blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
e88fd9c2254cf4a1054a10ef2f7e0b7b20d470a7
[ "MOD = 10 ** 9 + 7\nN = len(A)\nA.sort()\ndp = [1] * N\nindex = {x: i for i, x in enumerate(A)}\nfor i, x in enumerate(A):\n for j in range(i):\n if x % A[j] == 0:\n right = x // A[j]\n if right in index:\n dp[i] += dp[j] * dp[index[right]]\n dp[i] %= MO...
<|body_start_0|> MOD = 10 ** 9 + 7 N = len(A) A.sort() dp = [1] * N index = {x: i for i, x in enumerate(A)} for i, x in enumerate(A): for j in range(i): if x % A[j] == 0: right = x // A[j] if right in ind...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numFactoredBinaryTrees(self, A): """:type A: List[int] :rtype: int""" <|body_0|> def numFactoredBinaryTrees2(self, A): """:type A: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> MOD = 10 ** 9 + 7 N = len(...
stack_v2_sparse_classes_36k_train_016500
2,436
no_license
[ { "docstring": ":type A: List[int] :rtype: int", "name": "numFactoredBinaryTrees", "signature": "def numFactoredBinaryTrees(self, A)" }, { "docstring": ":type A: List[int] :rtype: int", "name": "numFactoredBinaryTrees2", "signature": "def numFactoredBinaryTrees2(self, A)" } ]
2
stack_v2_sparse_classes_30k_train_013610
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numFactoredBinaryTrees(self, A): :type A: List[int] :rtype: int - def numFactoredBinaryTrees2(self, A): :type A: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numFactoredBinaryTrees(self, A): :type A: List[int] :rtype: int - def numFactoredBinaryTrees2(self, A): :type A: List[int] :rtype: int <|skeleton|> class Solution: def ...
635af6e22aa8eef8e7920a585d43a45a891a8157
<|skeleton|> class Solution: def numFactoredBinaryTrees(self, A): """:type A: List[int] :rtype: int""" <|body_0|> def numFactoredBinaryTrees2(self, A): """:type A: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def numFactoredBinaryTrees(self, A): """:type A: List[int] :rtype: int""" MOD = 10 ** 9 + 7 N = len(A) A.sort() dp = [1] * N index = {x: i for i, x in enumerate(A)} for i, x in enumerate(A): for j in range(i): if x %...
the_stack_v2_python_sparse
code823BinaryTreesWithFactors.py
cybelewang/leetcode-python
train
0
06eb11827e74a37c25173a7865ba471d515bd90d
[ "k_indices = self._algo._k_indices\nif k_indices is None:\n return\ncurrentEvaluation = self._algo.getGlobalEvaluation()\nif currentEvaluation % self._every == 0:\n logging.info(f'Multi surrogate analysis checkpoint is done into {self._filepath}')\n line = str(currentEvaluation) + ';'\n for indices in k...
<|body_start_0|> k_indices = self._algo._k_indices if k_indices is None: return currentEvaluation = self._algo.getGlobalEvaluation() if currentEvaluation % self._every == 0: logging.info(f'Multi surrogate analysis checkpoint is done into {self._filepath}') ...
MultiSurrogateCheckpoint is used for keep track of sub-surrogate problem indices Attributes: algo: {Algorithm} -- main algorithm instance reference every: {int} -- checkpoint frequency used (based on number of evaluations) filepath: {str} -- file path where checkpoints will be saved
MultiSurrogateCheckpoint
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiSurrogateCheckpoint: """MultiSurrogateCheckpoint is used for keep track of sub-surrogate problem indices Attributes: algo: {Algorithm} -- main algorithm instance reference every: {int} -- checkpoint frequency used (based on number of evaluations) filepath: {str} -- file path where checkpoint...
stack_v2_sparse_classes_36k_train_016501
2,981
permissive
[ { "docstring": "Check if necessary to do backup based on `every` variable", "name": "run", "signature": "def run(self)" }, { "docstring": "Load nothing there, as we only log surrogate training information", "name": "load", "signature": "def load(self)" } ]
2
stack_v2_sparse_classes_30k_train_021337
Implement the Python class `MultiSurrogateCheckpoint` described below. Class description: MultiSurrogateCheckpoint is used for keep track of sub-surrogate problem indices Attributes: algo: {Algorithm} -- main algorithm instance reference every: {int} -- checkpoint frequency used (based on number of evaluations) filepa...
Implement the Python class `MultiSurrogateCheckpoint` described below. Class description: MultiSurrogateCheckpoint is used for keep track of sub-surrogate problem indices Attributes: algo: {Algorithm} -- main algorithm instance reference every: {int} -- checkpoint frequency used (based on number of evaluations) filepa...
a18c913871480999fd271cc0c361942d3d661499
<|skeleton|> class MultiSurrogateCheckpoint: """MultiSurrogateCheckpoint is used for keep track of sub-surrogate problem indices Attributes: algo: {Algorithm} -- main algorithm instance reference every: {int} -- checkpoint frequency used (based on number of evaluations) filepath: {str} -- file path where checkpoint...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiSurrogateCheckpoint: """MultiSurrogateCheckpoint is used for keep track of sub-surrogate problem indices Attributes: algo: {Algorithm} -- main algorithm instance reference every: {int} -- checkpoint frequency used (based on number of evaluations) filepath: {str} -- file path where checkpoints will be sav...
the_stack_v2_python_sparse
optimization/callbacks/MultiSurrogateCheckpoint.py
prise-3d/noise-detection-attributes-optimization
train
0
6bfbf95ba1d6f87a8a66fddb73de7414ce6db78d
[ "self.id = id\nself.consumer_id = consumer_id\nself.consumer_ssn = consumer_ssn\nself.requester_name = requester_name\nself.request_id = request_id\nself.constraints = constraints\nself.mtype = mtype\nself.status = status\nself.created_date = created_date\nself.additional_properties = additional_properties", "if ...
<|body_start_0|> self.id = id self.consumer_id = consumer_id self.consumer_ssn = consumer_ssn self.requester_name = requester_name self.request_id = request_id self.constraints = constraints self.mtype = mtype self.status = status self.created_date...
Implementation of the 'Report Summary' model. TODO: type model description here. Attributes: id (string): The Finicity report ID consumer_id (string): Finicity ID for the consumer consumer_ssn (string): Last 4 digits of the report consumer's Social Security number requester_name (string): Name of Finicity partner reque...
ReportSummary
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReportSummary: """Implementation of the 'Report Summary' model. TODO: type model description here. Attributes: id (string): The Finicity report ID consumer_id (string): Finicity ID for the consumer consumer_ssn (string): Last 4 digits of the report consumer's Social Security number requester_name...
stack_v2_sparse_classes_36k_train_016502
3,888
permissive
[ { "docstring": "Constructor for the ReportSummary class", "name": "__init__", "signature": "def __init__(self, id=None, consumer_id=None, consumer_ssn=None, requester_name=None, request_id=None, constraints=None, mtype=None, status=None, created_date=None, additional_properties={})" }, { "docstr...
2
stack_v2_sparse_classes_30k_train_002944
Implement the Python class `ReportSummary` described below. Class description: Implementation of the 'Report Summary' model. TODO: type model description here. Attributes: id (string): The Finicity report ID consumer_id (string): Finicity ID for the consumer consumer_ssn (string): Last 4 digits of the report consumer'...
Implement the Python class `ReportSummary` described below. Class description: Implementation of the 'Report Summary' model. TODO: type model description here. Attributes: id (string): The Finicity report ID consumer_id (string): Finicity ID for the consumer consumer_ssn (string): Last 4 digits of the report consumer'...
b2ab1ded435db75c78d42261f5e4acd2a3061487
<|skeleton|> class ReportSummary: """Implementation of the 'Report Summary' model. TODO: type model description here. Attributes: id (string): The Finicity report ID consumer_id (string): Finicity ID for the consumer consumer_ssn (string): Last 4 digits of the report consumer's Social Security number requester_name...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReportSummary: """Implementation of the 'Report Summary' model. TODO: type model description here. Attributes: id (string): The Finicity report ID consumer_id (string): Finicity ID for the consumer consumer_ssn (string): Last 4 digits of the report consumer's Social Security number requester_name (string): Na...
the_stack_v2_python_sparse
finicityapi/models/report_summary.py
monarchmoney/finicity-python
train
0
94dfbea49d648d211a72dbae07fb1d7a9f7e437c
[ "UserSim.__init__(self, error_evaluator)\nself.user_type = 'real'\nself.bool_undo = bool_undo\nself.undo_semantic_units = []", "self.questioned_pointers.append(pointer)\nif self.bool_undo:\n answer = input('Please enter yes(y)/no(n)/undo/exit: ').lower().strip()\n while answer not in {'yes', 'no', 'exit', '...
<|body_start_0|> UserSim.__init__(self, error_evaluator) self.user_type = 'real' self.bool_undo = bool_undo self.undo_semantic_units = [] <|end_body_0|> <|body_start_1|> self.questioned_pointers.append(pointer) if self.bool_undo: answer = input('Please enter ...
This is the class for real users (used in user study).
RealUser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RealUser: """This is the class for real users (used in user study).""" def __init__(self, error_evaluator, bool_undo=True): """Constructor of RealUser. :param error_evaluator: An instance of ErrorEvaluator.""" <|body_0|> def get_answer(self, pointer, *args): """R...
stack_v2_sparse_classes_36k_train_016503
9,856
permissive
[ { "docstring": "Constructor of RealUser. :param error_evaluator: An instance of ErrorEvaluator.", "name": "__init__", "signature": "def __init__(self, error_evaluator, bool_undo=True)" }, { "docstring": "Request for user answers. :param pointer: the pointer to the questioned semantic unit. :para...
3
stack_v2_sparse_classes_30k_train_000265
Implement the Python class `RealUser` described below. Class description: This is the class for real users (used in user study). Method signatures and docstrings: - def __init__(self, error_evaluator, bool_undo=True): Constructor of RealUser. :param error_evaluator: An instance of ErrorEvaluator. - def get_answer(sel...
Implement the Python class `RealUser` described below. Class description: This is the class for real users (used in user study). Method signatures and docstrings: - def __init__(self, error_evaluator, bool_undo=True): Constructor of RealUser. :param error_evaluator: An instance of ErrorEvaluator. - def get_answer(sel...
7870566ab6b9e121d648478968367bc79c12f7ef
<|skeleton|> class RealUser: """This is the class for real users (used in user study).""" def __init__(self, error_evaluator, bool_undo=True): """Constructor of RealUser. :param error_evaluator: An instance of ErrorEvaluator.""" <|body_0|> def get_answer(self, pointer, *args): """R...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RealUser: """This is the class for real users (used in user study).""" def __init__(self, error_evaluator, bool_undo=True): """Constructor of RealUser. :param error_evaluator: An instance of ErrorEvaluator.""" UserSim.__init__(self, error_evaluator) self.user_type = 'real' ...
the_stack_v2_python_sparse
MISP_SQL/environment.py
sunlab-osu/MISP
train
59
dfe7e039996e9e3c4bd85e808970c97ead2f0954
[ "if not root:\n return ''\nqueue = collections.deque([root])\nres = ''\nwhile queue:\n cur = queue.popleft()\n if cur is not None:\n res = res + ',' + str(cur.val)\n queue.append(cur.left)\n queue.append(cur.right)\n else:\n res = res + ',' + '-'\nreturn res[1:]", "tree_ls ...
<|body_start_0|> if not root: return '' queue = collections.deque([root]) res = '' while queue: cur = queue.popleft() if cur is not None: res = res + ',' + str(cur.val) queue.append(cur.left) queue.append...
Codec
[ "MIT" ]
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|> if not root: ...
stack_v2_sparse_classes_36k_train_016504
2,861
permissive
[ { "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
null
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...
3fd33092f53de25e8014c05af4ac3e6754f54e23
<|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_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" if not root: return '' queue = collections.deque([root]) res = '' while queue: cur = queue.popleft() if cur is not None: res =...
the_stack_v2_python_sparse
Python3/449.serialize-and-deserialize-bst.py
610yilingliu/leetcode
train
2
80c2eaddcd0ec49f6763834b695024faf6c9aa13
[ "response = self.client.get('/users/')\nself.assertEqual(response.status_code, 200)\ndatagrid = self._get_context_var(response, 'datagrid')\nself.assertTrue(datagrid)\nself.assertEqual(len(datagrid.rows), 4)\nself.assertEqual(datagrid.rows[0]['object'].username, 'admin')\nresponse = self.client.get('/users/?letter=...
<|body_start_0|> response = self.client.get('/users/') self.assertEqual(response.status_code, 200) datagrid = self._get_context_var(response, 'datagrid') self.assertTrue(datagrid) self.assertEqual(len(datagrid.rows), 4) self.assertEqual(datagrid.rows[0]['object'].username...
Unit tests for the users_list view.
SubmitterListViewTests
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubmitterListViewTests: """Unit tests for the users_list view.""" def test_with_access(self): """Testing users_list view""" <|body_0|> def test_as_anonymous_and_redirect(self): """Testing users_list view as anonymous with anonymous access disabled""" <|bo...
stack_v2_sparse_classes_36k_train_016505
49,494
permissive
[ { "docstring": "Testing users_list view", "name": "test_with_access", "signature": "def test_with_access(self)" }, { "docstring": "Testing users_list view as anonymous with anonymous access disabled", "name": "test_as_anonymous_and_redirect", "signature": "def test_as_anonymous_and_redir...
2
null
Implement the Python class `SubmitterListViewTests` described below. Class description: Unit tests for the users_list view. Method signatures and docstrings: - def test_with_access(self): Testing users_list view - def test_as_anonymous_and_redirect(self): Testing users_list view as anonymous with anonymous access dis...
Implement the Python class `SubmitterListViewTests` described below. Class description: Unit tests for the users_list view. Method signatures and docstrings: - def test_with_access(self): Testing users_list view - def test_as_anonymous_and_redirect(self): Testing users_list view as anonymous with anonymous access dis...
563c1e8d4dfd860f372281dc0f380a0809f6ae15
<|skeleton|> class SubmitterListViewTests: """Unit tests for the users_list view.""" def test_with_access(self): """Testing users_list view""" <|body_0|> def test_as_anonymous_and_redirect(self): """Testing users_list view as anonymous with anonymous access disabled""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubmitterListViewTests: """Unit tests for the users_list view.""" def test_with_access(self): """Testing users_list view""" response = self.client.get('/users/') self.assertEqual(response.status_code, 200) datagrid = self._get_context_var(response, 'datagrid') self...
the_stack_v2_python_sparse
reviewboard/datagrids/tests.py
LloydFinch/reviewboard
train
2
4c0e74e88a3e94548993ced7c581aa0d8b641769
[ "inp_data = all_inp_data[:BATCH_SIZE]\norig_out_data = all_orig_out_data[:BATCH_SIZE]\nrecons_err_hard, recons_err_soft = AdaroundOptimizer._eval_recons_err_metrics(wrapper, act_func, inp_data, orig_out_data)\nlogger.debug('Before opt, Recons. error metrics using soft rounding=%f and hard rounding=%f', recons_err_s...
<|body_start_0|> inp_data = all_inp_data[:BATCH_SIZE] orig_out_data = all_orig_out_data[:BATCH_SIZE] recons_err_hard, recons_err_soft = AdaroundOptimizer._eval_recons_err_metrics(wrapper, act_func, inp_data, orig_out_data) logger.debug('Before opt, Recons. error metrics using soft roundi...
Optimizes the weight rounding
AdaroundOptimizer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdaroundOptimizer: """Optimizes the weight rounding""" def adaround_wrapper(wrapper: AdaroundWrapper, act_func: Callable, all_inp_data: np.ndarray, all_orig_out_data: np.ndarray, opt_params: AdaroundHyperParameters) -> (np.ndarray, np.ndarray): """Adaround wrapper :param wrapper: Ada...
stack_v2_sparse_classes_36k_train_016506
10,909
permissive
[ { "docstring": "Adaround wrapper :param wrapper: Adaround wrapper :param act_func: Activation function :param all_inp_data: Input activation data :param all_orig_out_data: Original output activation data :param opt_params: Adaround hyper parameters :return: hard_rounded_weight, soft_rounded_weight", "name":...
3
null
Implement the Python class `AdaroundOptimizer` described below. Class description: Optimizes the weight rounding Method signatures and docstrings: - def adaround_wrapper(wrapper: AdaroundWrapper, act_func: Callable, all_inp_data: np.ndarray, all_orig_out_data: np.ndarray, opt_params: AdaroundHyperParameters) -> (np.n...
Implement the Python class `AdaroundOptimizer` described below. Class description: Optimizes the weight rounding Method signatures and docstrings: - def adaround_wrapper(wrapper: AdaroundWrapper, act_func: Callable, all_inp_data: np.ndarray, all_orig_out_data: np.ndarray, opt_params: AdaroundHyperParameters) -> (np.n...
5a406e657082b6a4f6e4bf48f0e46e085cb1e351
<|skeleton|> class AdaroundOptimizer: """Optimizes the weight rounding""" def adaround_wrapper(wrapper: AdaroundWrapper, act_func: Callable, all_inp_data: np.ndarray, all_orig_out_data: np.ndarray, opt_params: AdaroundHyperParameters) -> (np.ndarray, np.ndarray): """Adaround wrapper :param wrapper: Ada...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AdaroundOptimizer: """Optimizes the weight rounding""" def adaround_wrapper(wrapper: AdaroundWrapper, act_func: Callable, all_inp_data: np.ndarray, all_orig_out_data: np.ndarray, opt_params: AdaroundHyperParameters) -> (np.ndarray, np.ndarray): """Adaround wrapper :param wrapper: Adaround wrapper...
the_stack_v2_python_sparse
TrainingExtensions/tensorflow/src/python/aimet_tensorflow/keras/adaround/adaround_optimizer.py
quic/aimet
train
1,676
4e5482a04ac19e211e8a7243b39d011b11e367f1
[ "nginx_conf = self.GenerateNginxConfig(umpire_config, env)\nif not nginx_conf:\n return []\nproc_config = {'executable': HTTP_BIN, 'name': HTTP_SERVICE_NAME, 'args': ['-c', nginx_conf], 'path': '/tmp'}\nproc = umpire_service.ServiceProcess(self)\nproc.SetConfig(proc_config)\nreturn [proc]", "if 'services' not ...
<|body_start_0|> nginx_conf = self.GenerateNginxConfig(umpire_config, env) if not nginx_conf: return [] proc_config = {'executable': HTTP_BIN, 'name': HTTP_SERVICE_NAME, 'args': ['-c', nginx_conf], 'path': '/tmp'} proc = umpire_service.ServiceProcess(self) proc.SetCon...
HTTP service. Example: svc = SimpleService() procs = svc.CreateProcesses(umpire_config_dict) svc.Start(procs)
HTTPService
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HTTPService: """HTTP service. Example: svc = SimpleService() procs = svc.CreateProcesses(umpire_config_dict) svc.Start(procs)""" def CreateProcesses(self, umpire_config, env): """Creates list of processes via config. Args: umpire_config: Umpire config dict. env: UmpireEnv object. Ret...
stack_v2_sparse_classes_36k_train_016507
6,432
permissive
[ { "docstring": "Creates list of processes via config. Args: umpire_config: Umpire config dict. env: UmpireEnv object. Returns: A list of ServiceProcess.", "name": "CreateProcesses", "signature": "def CreateProcesses(self, umpire_config, env)" }, { "docstring": "Generates a nginx config. Args: um...
3
stack_v2_sparse_classes_30k_train_009989
Implement the Python class `HTTPService` described below. Class description: HTTP service. Example: svc = SimpleService() procs = svc.CreateProcesses(umpire_config_dict) svc.Start(procs) Method signatures and docstrings: - def CreateProcesses(self, umpire_config, env): Creates list of processes via config. Args: umpi...
Implement the Python class `HTTPService` described below. Class description: HTTP service. Example: svc = SimpleService() procs = svc.CreateProcesses(umpire_config_dict) svc.Start(procs) Method signatures and docstrings: - def CreateProcesses(self, umpire_config, env): Creates list of processes via config. Args: umpi...
a1b0fccd68987d8cd9c89710adc3c04b868347ec
<|skeleton|> class HTTPService: """HTTP service. Example: svc = SimpleService() procs = svc.CreateProcesses(umpire_config_dict) svc.Start(procs)""" def CreateProcesses(self, umpire_config, env): """Creates list of processes via config. Args: umpire_config: Umpire config dict. env: UmpireEnv object. Ret...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HTTPService: """HTTP service. Example: svc = SimpleService() procs = svc.CreateProcesses(umpire_config_dict) svc.Start(procs)""" def CreateProcesses(self, umpire_config, env): """Creates list of processes via config. Args: umpire_config: Umpire config dict. env: UmpireEnv object. Returns: A list ...
the_stack_v2_python_sparse
py/umpire/server/service/umpire_http.py
bridder/factory
train
0
cafe75024478031f3361e546f5ea9d9eba565a3b
[ "self.fpath = fpath\nif parent is not None and verbose and (not isinstance(parent, OpenEphysReader)):\n print('Warning, parent is not an OpenEphysReader instance')\nself.parent = parent\nself.load_kwd_info(verbose=verbose)\nfor rec in self.file_info.index:\n setattr(self, 'rec_%s' % rec, KwdRecording(self.fpa...
<|body_start_0|> self.fpath = fpath if parent is not None and verbose and (not isinstance(parent, OpenEphysReader)): print('Warning, parent is not an OpenEphysReader instance') self.parent = parent self.load_kwd_info(verbose=verbose) for rec in self.file_info.index: ...
Container for all the info related to a single .kwd file Should have a smart getter that opens and closes the kwd file and read from disc
KwdFile
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KwdFile: """Container for all the info related to a single .kwd file Should have a smart getter that opens and closes the kwd file and read from disc""" def __init__(self, fpath, verbose=True, parent=None): """:param fpath:str :param verbose:bool :param parent:OpenEphysReader instanc...
stack_v2_sparse_classes_36k_train_016508
13,322
no_license
[ { "docstring": ":param fpath:str :param verbose:bool :param parent:OpenEphysReader instance :return:KwdFile instance", "name": "__init__", "signature": "def __init__(self, fpath, verbose=True, parent=None)" }, { "docstring": "Read file infos Return a dict with all the attributes of the file: num...
3
null
Implement the Python class `KwdFile` described below. Class description: Container for all the info related to a single .kwd file Should have a smart getter that opens and closes the kwd file and read from disc Method signatures and docstrings: - def __init__(self, fpath, verbose=True, parent=None): :param fpath:str ...
Implement the Python class `KwdFile` described below. Class description: Container for all the info related to a single .kwd file Should have a smart getter that opens and closes the kwd file and read from disc Method signatures and docstrings: - def __init__(self, fpath, verbose=True, parent=None): :param fpath:str ...
a6ca9efb03c7966c1f6791755a1379333d6de359
<|skeleton|> class KwdFile: """Container for all the info related to a single .kwd file Should have a smart getter that opens and closes the kwd file and read from disc""" def __init__(self, fpath, verbose=True, parent=None): """:param fpath:str :param verbose:bool :param parent:OpenEphysReader instanc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KwdFile: """Container for all the info related to a single .kwd file Should have a smart getter that opens and closes the kwd file and read from disc""" def __init__(self, fpath, verbose=True, parent=None): """:param fpath:str :param verbose:bool :param parent:OpenEphysReader instance :return:Kwd...
the_stack_v2_python_sparse
openephys/OpenEphys/oe_reader.py
swc-pyclub/code_review
train
0
8dcf603a8016d5eb7ec10e8334888c1060320abe
[ "view = resolve(reverse(view_name, kwargs=kwargs))\nview = view.func.cls(action=action, format_kwarg=self.format_kwarg, kwargs=kwargs, request=self.request)\nview.check_permissions(self.request)\nreturn view", "context = {'request': self.request, 'view': self}\nfor backend in self.filter_backends:\n if issubcl...
<|body_start_0|> view = resolve(reverse(view_name, kwargs=kwargs)) view = view.func.cls(action=action, format_kwarg=self.format_kwarg, kwargs=kwargs, request=self.request) view.check_permissions(self.request) return view <|end_body_0|> <|body_start_1|> context = {'request': self...
DRF view mixin for the JSON API This mixin should be used in any view that wants to follow the JSON API specification for managing resources. This mixin will enforce spec compliance where applicable at the early request processing stage. Currently, it's limited to determining if the query params used have been enabled ...
JsonApiViewMixin
[ "ISC" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JsonApiViewMixin: """DRF view mixin for the JSON API This mixin should be used in any view that wants to follow the JSON API specification for managing resources. This mixin will enforce spec compliance where applicable at the early request processing stage. Currently, it's limited to determining...
stack_v2_sparse_classes_36k_train_016509
5,860
permissive
[ { "docstring": "Return the related view instance & check global perms", "name": "_get_related_view", "signature": "def _get_related_view(self, view_name, action, kwargs=None)" }, { "docstring": "Return the list of included resource objects", "name": "get_included", "signature": "def get_...
5
stack_v2_sparse_classes_30k_val_000953
Implement the Python class `JsonApiViewMixin` described below. Class description: DRF view mixin for the JSON API This mixin should be used in any view that wants to follow the JSON API specification for managing resources. This mixin will enforce spec compliance where applicable at the early request processing stage....
Implement the Python class `JsonApiViewMixin` described below. Class description: DRF view mixin for the JSON API This mixin should be used in any view that wants to follow the JSON API specification for managing resources. This mixin will enforce spec compliance where applicable at the early request processing stage....
46a9a1166695bb360271205b35fb2959f600510a
<|skeleton|> class JsonApiViewMixin: """DRF view mixin for the JSON API This mixin should be used in any view that wants to follow the JSON API specification for managing resources. This mixin will enforce spec compliance where applicable at the early request processing stage. Currently, it's limited to determining...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JsonApiViewMixin: """DRF view mixin for the JSON API This mixin should be used in any view that wants to follow the JSON API specification for managing resources. This mixin will enforce spec compliance where applicable at the early request processing stage. Currently, it's limited to determining if the query...
the_stack_v2_python_sparse
drfjsonapi/views.py
sassoo/drfjsonapi
train
2
2002eebc1d20a261311cd136ba55595f420039e2
[ "batch = batch.to(self.device)\nwavs, lens = batch.sig\nfeats = self.modules.compute_features(wavs)\nfeats = self.modules.mean_var_norm(feats, lens)\nembeddings = self.modules.embedding_model(feats)\noutputs = self.modules.classifier(embeddings)\nreturn outputs", "predictions = self.compute_forward(batch, sb.Stag...
<|body_start_0|> batch = batch.to(self.device) wavs, lens = batch.sig feats = self.modules.compute_features(wavs) feats = self.modules.mean_var_norm(feats, lens) embeddings = self.modules.embedding_model(feats) outputs = self.modules.classifier(embeddings) return ...
EmoIdBrain
[ "GPL-1.0-or-later", "LicenseRef-scancode-other-permissive", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmoIdBrain: def compute_forward(self, batch, stage): """Computation pipeline based on a encoder + emotion classifier.""" <|body_0|> def fit_batch(self, batch): """Trains the parameters given a single batch in input""" <|body_1|> def compute_objectives(se...
stack_v2_sparse_classes_36k_train_016510
12,801
permissive
[ { "docstring": "Computation pipeline based on a encoder + emotion classifier.", "name": "compute_forward", "signature": "def compute_forward(self, batch, stage)" }, { "docstring": "Trains the parameters given a single batch in input", "name": "fit_batch", "signature": "def fit_batch(self...
6
stack_v2_sparse_classes_30k_train_006559
Implement the Python class `EmoIdBrain` described below. Class description: Implement the EmoIdBrain class. Method signatures and docstrings: - def compute_forward(self, batch, stage): Computation pipeline based on a encoder + emotion classifier. - def fit_batch(self, batch): Trains the parameters given a single batc...
Implement the Python class `EmoIdBrain` described below. Class description: Implement the EmoIdBrain class. Method signatures and docstrings: - def compute_forward(self, batch, stage): Computation pipeline based on a encoder + emotion classifier. - def fit_batch(self, batch): Trains the parameters given a single batc...
d4c9a53773f13d5a2843f25bc7f89482936e2f17
<|skeleton|> class EmoIdBrain: def compute_forward(self, batch, stage): """Computation pipeline based on a encoder + emotion classifier.""" <|body_0|> def fit_batch(self, batch): """Trains the parameters given a single batch in input""" <|body_1|> def compute_objectives(se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EmoIdBrain: def compute_forward(self, batch, stage): """Computation pipeline based on a encoder + emotion classifier.""" batch = batch.to(self.device) wavs, lens = batch.sig feats = self.modules.compute_features(wavs) feats = self.modules.mean_var_norm(feats, lens) ...
the_stack_v2_python_sparse
recipes/IEMOCAP/emotion_recognition/train.py
zycv/speechbrain
train
2
08445ef5c3f35600aef22a4635b122e42f5d1a55
[ "try:\n user = User.objects.get(id=user_id)\n user_response = {'id': user_id, 'first_name': user.first_name, 'last_name': user.last_name, 'username': user.username, 'short_desc': user.short_desc, 'email': user.email, 'is_active': user.is_active}\n return Response(user_response, status.HTTP_200_OK)\nexcept ...
<|body_start_0|> try: user = User.objects.get(id=user_id) user_response = {'id': user_id, 'first_name': user.first_name, 'last_name': user.last_name, 'username': user.username, 'short_desc': user.short_desc, 'email': user.email, 'is_active': user.is_active} return Response(us...
API to get user details
UserDetailsView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserDetailsView: """API to get user details""" def get(self, request, user_id): """API to get User details""" <|body_0|> def post(self, request, user_id): """API to update User details""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: ...
stack_v2_sparse_classes_36k_train_016511
1,442
no_license
[ { "docstring": "API to get User details", "name": "get", "signature": "def get(self, request, user_id)" }, { "docstring": "API to update User details", "name": "post", "signature": "def post(self, request, user_id)" } ]
2
stack_v2_sparse_classes_30k_train_020651
Implement the Python class `UserDetailsView` described below. Class description: API to get user details Method signatures and docstrings: - def get(self, request, user_id): API to get User details - def post(self, request, user_id): API to update User details
Implement the Python class `UserDetailsView` described below. Class description: API to get user details Method signatures and docstrings: - def get(self, request, user_id): API to get User details - def post(self, request, user_id): API to update User details <|skeleton|> class UserDetailsView: """API to get us...
10189feace3cc6658917c3d121070f4893697e60
<|skeleton|> class UserDetailsView: """API to get user details""" def get(self, request, user_id): """API to get User details""" <|body_0|> def post(self, request, user_id): """API to update User details""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserDetailsView: """API to get user details""" def get(self, request, user_id): """API to get User details""" try: user = User.objects.get(id=user_id) user_response = {'id': user_id, 'first_name': user.first_name, 'last_name': user.last_name, 'username': user.usern...
the_stack_v2_python_sparse
backend/apps/users/views.py
mfsishweta/bibliophile
train
0
19b148f12858771fcc39dc8927699c33d3704316
[ "super(TextInput, self).__init__(attrs)\nif source is None:\n raise ValueError('A source url should be given')\nself.source = source\nself.min_length = int(min_length)\nself.result_limit = result_limit\nself.force_check = force_check", "if value is None:\n value = ''\nfinal_attrs = self.build_attrs(attrs, t...
<|body_start_0|> super(TextInput, self).__init__(attrs) if source is None: raise ValueError('A source url should be given') self.source = source self.min_length = int(min_length) self.result_limit = result_limit self.force_check = force_check <|end_body_0|> <...
A text input that autocompletes getting a json list
AutocompleteTextInput
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AutocompleteTextInput: """A text input that autocompletes getting a json list""" def __init__(self, attrs=None, source=None, min_length=3, result_limit=100, force_check=True): """It inits the widget. A source url for the json list should be given.""" <|body_0|> def rende...
stack_v2_sparse_classes_36k_train_016512
5,858
permissive
[ { "docstring": "It inits the widget. A source url for the json list should be given.", "name": "__init__", "signature": "def __init__(self, attrs=None, source=None, min_length=3, result_limit=100, force_check=True)" }, { "docstring": "It renders the html and the javascript", "name": "render"...
3
stack_v2_sparse_classes_30k_train_002061
Implement the Python class `AutocompleteTextInput` described below. Class description: A text input that autocompletes getting a json list Method signatures and docstrings: - def __init__(self, attrs=None, source=None, min_length=3, result_limit=100, force_check=True): It inits the widget. A source url for the json l...
Implement the Python class `AutocompleteTextInput` described below. Class description: A text input that autocompletes getting a json list Method signatures and docstrings: - def __init__(self, attrs=None, source=None, min_length=3, result_limit=100, force_check=True): It inits the widget. A source url for the json l...
7a50c9c4e65308fb51abf4f236457d12e9d028d6
<|skeleton|> class AutocompleteTextInput: """A text input that autocompletes getting a json list""" def __init__(self, attrs=None, source=None, min_length=3, result_limit=100, force_check=True): """It inits the widget. A source url for the json list should be given.""" <|body_0|> def rende...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AutocompleteTextInput: """A text input that autocompletes getting a json list""" def __init__(self, attrs=None, source=None, min_length=3, result_limit=100, force_check=True): """It inits the widget. A source url for the json list should be given.""" super(TextInput, self).__init__(attrs)...
the_stack_v2_python_sparse
goldenbraid/forms/widgets.py
bioinfcomav/goldebraid
train
0
a56badd282d51015f07c544942467839fcc69a30
[ "output = ''\nsummary = ''\nlogic = True\nfor bucket in result.keys():\n summary += '\\n +++++++++++++++++++++++++++++++++++++++++++++++++++'\n output += '\\n +++++++++++++++++++++++++++++++++++++++++++++++++++'\n output += '\\n Analyzing for Bucket {0}'.format(bucket)\n summary += '\\n Analyzing for Bu...
<|body_start_0|> output = '' summary = '' logic = True for bucket in result.keys(): summary += '\n +++++++++++++++++++++++++++++++++++++++++++++++++++' output += '\n +++++++++++++++++++++++++++++++++++++++++++++++++++' output += '\n Analyzing for Bucke...
Class containing methods to help analyze results for data analysis
DataAnalysisResultAnalyzer
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataAnalysisResultAnalyzer: """Class containing methods to help analyze results for data analysis""" def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False): """Method to Generate & analyze result AND output the logical and analysis result. This...
stack_v2_sparse_classes_36k_train_016513
41,540
permissive
[ { "docstring": "Method to Generate & analyze result AND output the logical and analysis result. This works on a bucket level only since we have already taken a union for all nodes", "name": "analyze_all_result", "signature": "def analyze_all_result(self, result, deletedItems=False, addedItems=False, upd...
3
null
Implement the Python class `DataAnalysisResultAnalyzer` described below. Class description: Class containing methods to help analyze results for data analysis Method signatures and docstrings: - def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False): Method to Generate & analyz...
Implement the Python class `DataAnalysisResultAnalyzer` described below. Class description: Class containing methods to help analyze results for data analysis Method signatures and docstrings: - def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False): Method to Generate & analyz...
4882e593be50cecbebb2e6bf7b95dcce82324ea1
<|skeleton|> class DataAnalysisResultAnalyzer: """Class containing methods to help analyze results for data analysis""" def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False): """Method to Generate & analyze result AND output the logical and analysis result. This...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataAnalysisResultAnalyzer: """Class containing methods to help analyze results for data analysis""" def analyze_all_result(self, result, deletedItems=False, addedItems=False, updatedItems=False): """Method to Generate & analyze result AND output the logical and analysis result. This works on a b...
the_stack_v2_python_sparse
lib/couchbase_helper/data_analysis_helper.py
couchbaselabs/TAF
train
16
a5b5e85c5d5312abed3fcdf4ab28cb20a0539635
[ "html = ET.Element('html')\nhead = ET.SubElement(html, 'head')\nbody = ET.SubElement(html, 'body')\nstyle = ET.SubElement(head, 'style')\nstyle.text = self.CSS\nreturn html", "template = self.get_template()\nbody = template.find('body')\ndiv = super(HTMLFormatter, self).transform_sheet(sheet)\nbody.append(div)\nr...
<|body_start_0|> html = ET.Element('html') head = ET.SubElement(html, 'head') body = ET.SubElement(html, 'body') style = ET.SubElement(head, 'style') style.text = self.CSS return html <|end_body_0|> <|body_start_1|> template = self.get_template() body = t...
Formatter for HTML sheets to a full HTML file.
HTMLFormatter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HTMLFormatter: """Formatter for HTML sheets to a full HTML file.""" def get_template(self): """Get a template element that represents the HTML file.""" <|body_0|> def transform_sheet(self, sheet): """Transform a <sheet> to a full <html> elemnt.""" <|body_...
stack_v2_sparse_classes_36k_train_016514
8,003
no_license
[ { "docstring": "Get a template element that represents the HTML file.", "name": "get_template", "signature": "def get_template(self)" }, { "docstring": "Transform a <sheet> to a full <html> elemnt.", "name": "transform_sheet", "signature": "def transform_sheet(self, sheet)" } ]
2
null
Implement the Python class `HTMLFormatter` described below. Class description: Formatter for HTML sheets to a full HTML file. Method signatures and docstrings: - def get_template(self): Get a template element that represents the HTML file. - def transform_sheet(self, sheet): Transform a <sheet> to a full <html> elemn...
Implement the Python class `HTMLFormatter` described below. Class description: Formatter for HTML sheets to a full HTML file. Method signatures and docstrings: - def get_template(self): Get a template element that represents the HTML file. - def transform_sheet(self, sheet): Transform a <sheet> to a full <html> elemn...
9b32089282c94c706d819333a3a2388179e99e86
<|skeleton|> class HTMLFormatter: """Formatter for HTML sheets to a full HTML file.""" def get_template(self): """Get a template element that represents the HTML file.""" <|body_0|> def transform_sheet(self, sheet): """Transform a <sheet> to a full <html> elemnt.""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HTMLFormatter: """Formatter for HTML sheets to a full HTML file.""" def get_template(self): """Get a template element that represents the HTML file.""" html = ET.Element('html') head = ET.SubElement(html, 'head') body = ET.SubElement(html, 'body') style = ET.SubEle...
the_stack_v2_python_sparse
google-rkern/trunk/notabene/html.py
minrk/ipython-svn-archive
train
0
c4f182e9f89e6aa86212bd5968deaf039337d427
[ "res = []\n\ndef preorder(root):\n if root == None:\n return\n res.append(str(root.val))\n if root.children == []:\n res.append('None')\n res.append('None')\n for child in root.children:\n preorder(child)\npreorder(root)\nprint(','.join(res))\nreturn ','.join(res)", "self.d...
<|body_start_0|> res = [] def preorder(root): if root == None: return res.append(str(root.val)) if root.children == []: res.append('None') res.append('None') for child in root.children: preor...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_36k_train_016515
2,063
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: Node :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node", "name": "deserialize", "signature": "def deserialize(self, ...
2
stack_v2_sparse_classes_30k_train_003468
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod...
f6df35359b223cdd1635c287455032ae1463906f
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: Node :rtype: str""" res = [] def preorder(root): if root == None: return res.append(str(root.val)) if root.children == []: res.append...
the_stack_v2_python_sparse
LeetCode/src/SerializeandDeserializeN-aryTree.py
jinwei15/java-PythonSyntax-Leetcode
train
0
bdf1de4f1ecb4b5c462a43a6b684a320d8a9db32
[ "def dp(s, i, p, j):\n m = len(s)\n n = len(p)\n if j == n:\n return i == m\n if i == m:\n if (n - j) % 2 == 1:\n return False\n for j in range(0, n - 1, 2):\n if p[j + 1] != '*':\n return False\n return True\n if s[i] == p[j] or p[j] =...
<|body_start_0|> def dp(s, i, p, j): m = len(s) n = len(p) if j == n: return i == m if i == m: if (n - j) % 2 == 1: return False for j in range(0, n - 1, 2): if p[j + 1] != '*'...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isMatch(self, s, p): """:type s: str :type p: str :rtype: bool""" <|body_0|> def isMatch(self, s, p): """:type s: str :type p: str :rtype: bool""" <|body_1|> def isMatch(self, s, p): """:type s: str :type p: str :rtype: bool""" ...
stack_v2_sparse_classes_36k_train_016516
2,919
no_license
[ { "docstring": ":type s: str :type p: str :rtype: bool", "name": "isMatch", "signature": "def isMatch(self, s, p)" }, { "docstring": ":type s: str :type p: str :rtype: bool", "name": "isMatch", "signature": "def isMatch(self, s, p)" }, { "docstring": ":type s: str :type p: str :r...
3
stack_v2_sparse_classes_30k_train_005664
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isMatch(self, s, p): :type s: str :type p: str :rtype: bool - def isMatch(self, s, p): :type s: str :type p: str :rtype: bool - def isMatch(self, s, p): :type s: str :type p:...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isMatch(self, s, p): :type s: str :type p: str :rtype: bool - def isMatch(self, s, p): :type s: str :type p: str :rtype: bool - def isMatch(self, s, p): :type s: str :type p:...
a509b383a42f54313970168d9faa11f088f18708
<|skeleton|> class Solution: def isMatch(self, s, p): """:type s: str :type p: str :rtype: bool""" <|body_0|> def isMatch(self, s, p): """:type s: str :type p: str :rtype: bool""" <|body_1|> def isMatch(self, s, p): """:type s: str :type p: str :rtype: bool""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isMatch(self, s, p): """:type s: str :type p: str :rtype: bool""" def dp(s, i, p, j): m = len(s) n = len(p) if j == n: return i == m if i == m: if (n - j) % 2 == 1: return False ...
the_stack_v2_python_sparse
0010_Regular_Expression_Matching.py
bingli8802/leetcode
train
0
8991b6fadad30d37a7d09b27b490612843014efc
[ "super().__init__(coordinator, device)\nself._mac = device.mac\nself._omada_client = coordinator.omada_client\nself._attr_unique_id = f'{device.mac}_firmware'", "status = self.coordinator.data[self._mac]\nif status.firmware:\n return status.firmware.release_notes\nreturn None", "try:\n await self._omada_c...
<|body_start_0|> super().__init__(coordinator, device) self._mac = device.mac self._omada_client = coordinator.omada_client self._attr_unique_id = f'{device.mac}_firmware' <|end_body_0|> <|body_start_1|> status = self.coordinator.data[self._mac] if status.firmware: ...
Firmware update status for Omada SDN devices.
OmadaDeviceUpdate
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OmadaDeviceUpdate: """Firmware update status for Omada SDN devices.""" def __init__(self, coordinator: OmadaFirmwareUpdateCoodinator, device: OmadaListDevice) -> None: """Initialize the update entity.""" <|body_0|> def release_notes(self) -> str | None: """Get th...
stack_v2_sparse_classes_36k_train_016517
5,250
permissive
[ { "docstring": "Initialize the update entity.", "name": "__init__", "signature": "def __init__(self, coordinator: OmadaFirmwareUpdateCoodinator, device: OmadaListDevice) -> None" }, { "docstring": "Get the release notes for the latest update.", "name": "release_notes", "signature": "def ...
4
stack_v2_sparse_classes_30k_train_017837
Implement the Python class `OmadaDeviceUpdate` described below. Class description: Firmware update status for Omada SDN devices. Method signatures and docstrings: - def __init__(self, coordinator: OmadaFirmwareUpdateCoodinator, device: OmadaListDevice) -> None: Initialize the update entity. - def release_notes(self) ...
Implement the Python class `OmadaDeviceUpdate` described below. Class description: Firmware update status for Omada SDN devices. Method signatures and docstrings: - def __init__(self, coordinator: OmadaFirmwareUpdateCoodinator, device: OmadaListDevice) -> None: Initialize the update entity. - def release_notes(self) ...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class OmadaDeviceUpdate: """Firmware update status for Omada SDN devices.""" def __init__(self, coordinator: OmadaFirmwareUpdateCoodinator, device: OmadaListDevice) -> None: """Initialize the update entity.""" <|body_0|> def release_notes(self) -> str | None: """Get th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OmadaDeviceUpdate: """Firmware update status for Omada SDN devices.""" def __init__(self, coordinator: OmadaFirmwareUpdateCoodinator, device: OmadaListDevice) -> None: """Initialize the update entity.""" super().__init__(coordinator, device) self._mac = device.mac self._om...
the_stack_v2_python_sparse
homeassistant/components/tplink_omada/update.py
home-assistant/core
train
35,501
99f413282752edd5f9a461ecfb592a11cf0e2cd8
[ "if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.DISABLE]:\n tango.Except.throw_exception(f'AssignResources() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke AssignResources command on mccsmasterleafnode.', 'mccsmasterleafnode.AssignResources()', tango....
<|body_start_0|> if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.DISABLE]: tango.Except.throw_exception(f'AssignResources() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke AssignResources command on mccsmasterleafnode.', 'mccsmasterleafnode...
A class for MccsMasterLeafNode's AssignResources() command. It accepts stationiDList list, channels and stationBeamiDList in JSON string format and invokes allocate command on MccsMaster with JSON string as an input argument.
AssignResources
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AssignResources: """A class for MccsMasterLeafNode's AssignResources() command. It accepts stationiDList list, channels and stationBeamiDList in JSON string format and invokes allocate command on MccsMaster with JSON string as an input argument.""" def check_allowed(self): """Checks ...
stack_v2_sparse_classes_36k_train_016518
5,925
permissive
[ { "docstring": "Checks whether the command is allowed to be run in the current 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": "def...
3
null
Implement the Python class `AssignResources` described below. Class description: A class for MccsMasterLeafNode's AssignResources() command. It accepts stationiDList list, channels and stationBeamiDList in JSON string format and invokes allocate command on MccsMaster with JSON string as an input argument. Method sign...
Implement the Python class `AssignResources` described below. Class description: A class for MccsMasterLeafNode's AssignResources() command. It accepts stationiDList list, channels and stationBeamiDList in JSON string format and invokes allocate command on MccsMaster with JSON string as an input argument. Method sign...
7ee65a9c8dada9b28893144b372a398bd0646195
<|skeleton|> class AssignResources: """A class for MccsMasterLeafNode's AssignResources() command. It accepts stationiDList list, channels and stationBeamiDList in JSON string format and invokes allocate command on MccsMaster with JSON string as an input argument.""" def check_allowed(self): """Checks ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AssignResources: """A class for MccsMasterLeafNode's AssignResources() command. It accepts stationiDList list, channels and stationBeamiDList in JSON string format and invokes allocate command on MccsMaster with JSON string as an input argument.""" def check_allowed(self): """Checks whether the c...
the_stack_v2_python_sparse
temp_src/ska_tmc_mccsmasterleafnode_low/assign_resources_command.py
ska-telescope/tmc-prototype
train
4
3aa79b9bf7fe7a891899d632804b20c8ddff48c7
[ "n = len(nums)\nif n == 0:\n return None\nelif n == 1:\n return TreeNode(nums[0])\nelif n == 2:\n return TreeNode(nums[1], TreeNode(nums[0]))\nelif n == 3:\n return TreeNode(nums[1], TreeNode(nums[0]), TreeNode(nums[2]))\nelse:\n mid = n // 2\n return TreeNode(nums[mid], self.sortedArrayToBST(nums...
<|body_start_0|> n = len(nums) if n == 0: return None elif n == 1: return TreeNode(nums[0]) elif n == 2: return TreeNode(nums[1], TreeNode(nums[0])) elif n == 3: return TreeNode(nums[1], TreeNode(nums[0]), TreeNode(nums[2])) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: """108 升序的整数数组nums 转换为一棵 高度平衡 二叉搜索树 【递归创建】""" <|body_0|> def levelOrder(self, root: TreeNode) -> List[List[int]]: """102 二叉树的层序遍历 用队列""" <|body_1|> def isSameTree(self, p: TreeNode, q: Tr...
stack_v2_sparse_classes_36k_train_016519
4,939
no_license
[ { "docstring": "108 升序的整数数组nums 转换为一棵 高度平衡 二叉搜索树 【递归创建】", "name": "sortedArrayToBST", "signature": "def sortedArrayToBST(self, nums: List[int]) -> TreeNode" }, { "docstring": "102 二叉树的层序遍历 用队列", "name": "levelOrder", "signature": "def levelOrder(self, root: TreeNode) -> List[List[int]]" ...
6
stack_v2_sparse_classes_30k_train_006853
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortedArrayToBST(self, nums: List[int]) -> TreeNode: 108 升序的整数数组nums 转换为一棵 高度平衡 二叉搜索树 【递归创建】 - def levelOrder(self, root: TreeNode) -> List[List[int]]: 102 二叉树的层序遍历 用队列 - def...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortedArrayToBST(self, nums: List[int]) -> TreeNode: 108 升序的整数数组nums 转换为一棵 高度平衡 二叉搜索树 【递归创建】 - def levelOrder(self, root: TreeNode) -> List[List[int]]: 102 二叉树的层序遍历 用队列 - def...
3fd69b85f52af861ff7e2c74d8aacc515b192615
<|skeleton|> class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: """108 升序的整数数组nums 转换为一棵 高度平衡 二叉搜索树 【递归创建】""" <|body_0|> def levelOrder(self, root: TreeNode) -> List[List[int]]: """102 二叉树的层序遍历 用队列""" <|body_1|> def isSameTree(self, p: TreeNode, q: Tr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: """108 升序的整数数组nums 转换为一棵 高度平衡 二叉搜索树 【递归创建】""" n = len(nums) if n == 0: return None elif n == 1: return TreeNode(nums[0]) elif n == 2: return TreeNode(nums[1], TreeNode...
the_stack_v2_python_sparse
DataStruct/BiTree/108_102_100_114.py
helloprogram6/leetcode_Cookbook_python
train
0
1d4357228742ad1466ad66fd061220eb76c5d59d
[ "readonly_fields = super(TincHostInline, self).get_readonly_fields(request, obj=obj)\nif obj and obj.tinc.pubkey and ('pubkey' not in readonly_fields):\n return ('pubkey',) + readonly_fields\nreturn readonly_fields", "if obj and obj.mgmt_net.backend == 'tinc' and (obj.tinc.pubkey is None) and (request.method =...
<|body_start_0|> readonly_fields = super(TincHostInline, self).get_readonly_fields(request, obj=obj) if obj and obj.tinc.pubkey and ('pubkey' not in readonly_fields): return ('pubkey',) + readonly_fields return readonly_fields <|end_body_0|> <|body_start_1|> if obj and obj.m...
TincHostInline
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TincHostInline: def get_readonly_fields(self, request, obj=None): """pubkey as readonly if exists""" <|body_0|> def get_formset(self, request, obj=None, **kwargs): """Warn user if the tinc host is not fully configured""" <|body_1|> def get_fieldsets(self...
stack_v2_sparse_classes_36k_train_016520
6,808
no_license
[ { "docstring": "pubkey as readonly if exists", "name": "get_readonly_fields", "signature": "def get_readonly_fields(self, request, obj=None)" }, { "docstring": "Warn user if the tinc host is not fully configured", "name": "get_formset", "signature": "def get_formset(self, request, obj=No...
3
null
Implement the Python class `TincHostInline` described below. Class description: Implement the TincHostInline class. Method signatures and docstrings: - def get_readonly_fields(self, request, obj=None): pubkey as readonly if exists - def get_formset(self, request, obj=None, **kwargs): Warn user if the tinc host is not...
Implement the Python class `TincHostInline` described below. Class description: Implement the TincHostInline class. Method signatures and docstrings: - def get_readonly_fields(self, request, obj=None): pubkey as readonly if exists - def get_formset(self, request, obj=None, **kwargs): Warn user if the tinc host is not...
dd798dc9bd3321b17007ff131e7b1288a2cd3c36
<|skeleton|> class TincHostInline: def get_readonly_fields(self, request, obj=None): """pubkey as readonly if exists""" <|body_0|> def get_formset(self, request, obj=None, **kwargs): """Warn user if the tinc host is not fully configured""" <|body_1|> def get_fieldsets(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TincHostInline: def get_readonly_fields(self, request, obj=None): """pubkey as readonly if exists""" readonly_fields = super(TincHostInline, self).get_readonly_fields(request, obj=obj) if obj and obj.tinc.pubkey and ('pubkey' not in readonly_fields): return ('pubkey',) + re...
the_stack_v2_python_sparse
controller/apps/tinc/admin.py
m00dy/vct-controller
train
2
d36379739d21f4870035e081f24802ac947d4e6b
[ "currSum, currMax = (0, float('-inf'))\nbst = BST(TreeNode(currSum))\nfor num in nums:\n currSum += num\n preSum = bst.ceiling(currSum - k)\n currMax = max(currMax, currSum - preSum)\n bst.insert(TreeNode(currSum))\nreturn currMax", "currMax, currSum = (float('-inf'), 0)\nfor num in nums:\n currSum...
<|body_start_0|> currSum, currMax = (0, float('-inf')) bst = BST(TreeNode(currSum)) for num in nums: currSum += num preSum = bst.ceiling(currSum - k) currMax = max(currMax, currSum - preSum) bst.insert(TreeNode(currSum)) return currMax <|en...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _get_limit_max_sub_sum(self, nums: List[int], k: int) -> int: """Try to find a contiguous sub list from nums whose summary <= k. The search process is accelarated by storing the pre calculated sub summaries to each node of a BST.""" <|body_0|> def _get_no_limit...
stack_v2_sparse_classes_36k_train_016521
3,575
no_license
[ { "docstring": "Try to find a contiguous sub list from nums whose summary <= k. The search process is accelarated by storing the pre calculated sub summaries to each node of a BST.", "name": "_get_limit_max_sub_sum", "signature": "def _get_limit_max_sub_sum(self, nums: List[int], k: int) -> int" }, ...
3
stack_v2_sparse_classes_30k_train_019365
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _get_limit_max_sub_sum(self, nums: List[int], k: int) -> int: Try to find a contiguous sub list from nums whose summary <= k. The search process is accelarated by storing the...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _get_limit_max_sub_sum(self, nums: List[int], k: int) -> int: Try to find a contiguous sub list from nums whose summary <= k. The search process is accelarated by storing the...
edb870f83f0c4568cce0cacec04ee70cf6b545bf
<|skeleton|> class Solution: def _get_limit_max_sub_sum(self, nums: List[int], k: int) -> int: """Try to find a contiguous sub list from nums whose summary <= k. The search process is accelarated by storing the pre calculated sub summaries to each node of a BST.""" <|body_0|> def _get_no_limit...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def _get_limit_max_sub_sum(self, nums: List[int], k: int) -> int: """Try to find a contiguous sub list from nums whose summary <= k. The search process is accelarated by storing the pre calculated sub summaries to each node of a BST.""" currSum, currMax = (0, float('-inf')) b...
the_stack_v2_python_sparse
2020/max_sum_of_rectangle_no_larger_than_k.py
eronekogin/leetcode
train
0
af03c3ac144e750fae8e35174d8b0dbdb3a45a6d
[ "string = 'select * from teacher_teacher where teacher1_id in (%s)'\nsql = string % ','.join(['?' for id in id_list])\nresults = db.select(sql, *id_list)\nreturn results", "string = 'select %s from es_teacher where ID in (%s)' % (','.join(keys) if keys is not None else '*', '%s')\nsql = string % ','.join(['?' for...
<|body_start_0|> string = 'select * from teacher_teacher where teacher1_id in (%s)' sql = string % ','.join(['?' for id in id_list]) results = db.select(sql, *id_list) return results <|end_body_0|> <|body_start_1|> string = 'select %s from es_teacher where ID in (%s)' % (','.joi...
TeacherDao
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TeacherDao: def get_relations_by_ids(self, id_list): """获取老师id对应的所有有联系的老师id :param id_list: 老师id数组 :return: 所有和该老师有联系的数组""" <|body_0|> def get_teachers_by_ids(self, id_list, keys=None): """根据老师id数组获取所有的老师 :param id_list: 老师id所组成的数组 :param keys: 要获得的键值数组 如['ID', 'NAME...
stack_v2_sparse_classes_36k_train_016522
5,061
permissive
[ { "docstring": "获取老师id对应的所有有联系的老师id :param id_list: 老师id数组 :return: 所有和该老师有联系的数组", "name": "get_relations_by_ids", "signature": "def get_relations_by_ids(self, id_list)" }, { "docstring": "根据老师id数组获取所有的老师 :param id_list: 老师id所组成的数组 :param keys: 要获得的键值数组 如['ID', 'NAME'] 为空则获取所有的键值对 :return: 查询成功的...
6
stack_v2_sparse_classes_30k_train_005495
Implement the Python class `TeacherDao` described below. Class description: Implement the TeacherDao class. Method signatures and docstrings: - def get_relations_by_ids(self, id_list): 获取老师id对应的所有有联系的老师id :param id_list: 老师id数组 :return: 所有和该老师有联系的数组 - def get_teachers_by_ids(self, id_list, keys=None): 根据老师id数组获取所有的老师...
Implement the Python class `TeacherDao` described below. Class description: Implement the TeacherDao class. Method signatures and docstrings: - def get_relations_by_ids(self, id_list): 获取老师id对应的所有有联系的老师id :param id_list: 老师id数组 :return: 所有和该老师有联系的数组 - def get_teachers_by_ids(self, id_list, keys=None): 根据老师id数组获取所有的老师...
8f03df509e796a5c37189cd8aae0c114d0fa5e90
<|skeleton|> class TeacherDao: def get_relations_by_ids(self, id_list): """获取老师id对应的所有有联系的老师id :param id_list: 老师id数组 :return: 所有和该老师有联系的数组""" <|body_0|> def get_teachers_by_ids(self, id_list, keys=None): """根据老师id数组获取所有的老师 :param id_list: 老师id所组成的数组 :param keys: 要获得的键值数组 如['ID', 'NAME...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TeacherDao: def get_relations_by_ids(self, id_list): """获取老师id对应的所有有联系的老师id :param id_list: 老师id数组 :return: 所有和该老师有联系的数组""" string = 'select * from teacher_teacher where teacher1_id in (%s)' sql = string % ','.join(['?' for id in id_list]) results = db.select(sql, *id_list) ...
the_stack_v2_python_sparse
websiteV2/dao/teacherdao.py
cnsoin/scholar_discovery_sys
train
0
08d63d9a573f23c0ae83b2507add617971dbbd47
[ "Model.__init__(self, data, verbose=verbose)\nself.α = α\nif G is None:\n self.G = stats.norm(loc=0, scale=10000)\nelse:\n self.G = G\nself.col_lookups = [{unique_val: count for unique_val, count in zip(*np.unique(self.X.data[:, d][~self.X.mask[:, d]], return_counts=True))} for d in range(self.D)]\nself._calc...
<|body_start_0|> Model.__init__(self, data, verbose=verbose) self.α = α if G is None: self.G = stats.norm(loc=0, scale=10000) else: self.G = G self.col_lookups = [{unique_val: count for unique_val, count in zip(*np.unique(self.X.data[:, d][~self.X.mask[:, ...
DP
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DP: def __init__(self, data, verbose=None, α=1, G=None): """Creates the model object. Args: data: The dataset with missing data as a numpy masked array. verbose: bool, indicating whether or not information should be written to std_err. α: floating point concentration parameter. G: prior ...
stack_v2_sparse_classes_36k_train_016523
7,946
permissive
[ { "docstring": "Creates the model object. Args: data: The dataset with missing data as a numpy masked array. verbose: bool, indicating whether or not information should be written to std_err. α: floating point concentration parameter. G: prior distribution: scipy.stats objects or other objects with similar inte...
6
stack_v2_sparse_classes_30k_train_012002
Implement the Python class `DP` described below. Class description: Implement the DP class. Method signatures and docstrings: - def __init__(self, data, verbose=None, α=1, G=None): Creates the model object. Args: data: The dataset with missing data as a numpy masked array. verbose: bool, indicating whether or not inf...
Implement the Python class `DP` described below. Class description: Implement the DP class. Method signatures and docstrings: - def __init__(self, data, verbose=None, α=1, G=None): Creates the model object. Args: data: The dataset with missing data as a numpy masked array. verbose: bool, indicating whether or not inf...
99aaa6364898e5e67a9fc7e21d8c5dc0052d9edc
<|skeleton|> class DP: def __init__(self, data, verbose=None, α=1, G=None): """Creates the model object. Args: data: The dataset with missing data as a numpy masked array. verbose: bool, indicating whether or not information should be written to std_err. α: floating point concentration parameter. G: prior ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DP: def __init__(self, data, verbose=None, α=1, G=None): """Creates the model object. Args: data: The dataset with missing data as a numpy masked array. verbose: bool, indicating whether or not information should be written to std_err. α: floating point concentration parameter. G: prior distribution: ...
the_stack_v2_python_sparse
auto_impute/dp.py
JamesAllingham/AutoImpute
train
1
fc0d6d958c34b9beeaf7f86695d049be16db6a3f
[ "if not is_all(eids):\n g = g.edge_subgraph(eids.long())\nn_nodes = g.number_of_nodes()\nn_edges = g.number_of_edges()\nscore_context = utils.to_dgl_context(score.device)\nif isinstance(g, DGLGraph):\n gidx = g._graph.get_immutable_gidx(score_context)\nelif isinstance(g, DGLHeteroGraph):\n assert g._graph....
<|body_start_0|> if not is_all(eids): g = g.edge_subgraph(eids.long()) n_nodes = g.number_of_nodes() n_edges = g.number_of_edges() score_context = utils.to_dgl_context(score.device) if isinstance(g, DGLGraph): gidx = g._graph.get_immutable_gidx(score_conte...
Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j\\rightarrow i`, also called logits in the context of softmax. :math:`\\mathca...
EdgeSoftmax
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EdgeSoftmax: """Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j\\rightarrow i`, also called logits in ...
stack_v2_sparse_classes_36k_train_016524
6,424
permissive
[ { "docstring": "Forward function. Pseudo-code: .. code:: python score = dgl.EData(g, score) score_max = score.dst_max() # of type dgl.NData score = score - score_max # edge_sub_dst, ret dgl.EData score_sum = score.dst_sum() # of type dgl.NData out = score / score_sum # edge_div_dst, ret dgl.EData return out.dat...
2
stack_v2_sparse_classes_30k_train_004251
Implement the Python class `EdgeSoftmax` described below. Class description: Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j...
Implement the Python class `EdgeSoftmax` described below. Class description: Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j...
170c2ed46fde29271246fe6600948b2864534ca3
<|skeleton|> class EdgeSoftmax: """Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j\\rightarrow i`, also called logits in ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EdgeSoftmax: """Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j\\rightarrow i`, also called logits in the context o...
the_stack_v2_python_sparse
python/dgl/nn/pytorch/softmax.py
Menooker/dgl
train
3
91a5d0fd8f12330432fe85224c7999d6a015f667
[ "self.dataset = dataset\nself.rl_task = rl_task\nself.policy = policy\nself.episode_length = episode_length if episode_length is not None else self.rl_task.max_episode_length", "i_tot_step = 0\nwhile True:\n i_step = 0\n terminal = False\n state = self.rl_task.reset()\n self.dataset.notify_new_traject...
<|body_start_0|> self.dataset = dataset self.rl_task = rl_task self.policy = policy self.episode_length = episode_length if episode_length is not None else self.rl_task.max_episode_length <|end_body_0|> <|body_start_1|> i_tot_step = 0 while True: i_step = 0 ...
RLCollector
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RLCollector: def __init__(self, dataset: RLDataset, rl_task: RLTask, policy: RLAgent, episode_length: int=None): """Class to collect data from the reinforcement learning task :param dataset: Dataset to fill with data :param rl_task: Reinforcement learning Task :type rl_task: RLTask :para...
stack_v2_sparse_classes_36k_train_016525
5,384
no_license
[ { "docstring": "Class to collect data from the reinforcement learning task :param dataset: Dataset to fill with data :param rl_task: Reinforcement learning Task :type rl_task: RLTask :param policy: The policy", "name": "__init__", "signature": "def __init__(self, dataset: RLDataset, rl_task: RLTask, pol...
3
stack_v2_sparse_classes_30k_val_001057
Implement the Python class `RLCollector` described below. Class description: Implement the RLCollector class. Method signatures and docstrings: - def __init__(self, dataset: RLDataset, rl_task: RLTask, policy: RLAgent, episode_length: int=None): Class to collect data from the reinforcement learning task :param datase...
Implement the Python class `RLCollector` described below. Class description: Implement the RLCollector class. Method signatures and docstrings: - def __init__(self, dataset: RLDataset, rl_task: RLTask, policy: RLAgent, episode_length: int=None): Class to collect data from the reinforcement learning task :param datase...
9f57dabd08e233882483db8728b7b1c2d83f6be8
<|skeleton|> class RLCollector: def __init__(self, dataset: RLDataset, rl_task: RLTask, policy: RLAgent, episode_length: int=None): """Class to collect data from the reinforcement learning task :param dataset: Dataset to fill with data :param rl_task: Reinforcement learning Task :type rl_task: RLTask :para...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RLCollector: def __init__(self, dataset: RLDataset, rl_task: RLTask, policy: RLAgent, episode_length: int=None): """Class to collect data from the reinforcement learning task :param dataset: Dataset to fill with data :param rl_task: Reinforcement learning Task :type rl_task: RLTask :param policy: The ...
the_stack_v2_python_sparse
herl/solver.py
SamuelePolimi/HeRL
train
3
0569255378885ca3711ea205c901574176e4e14e
[ "mapping = collections.defaultdict(int)\nlength = len(s)\nif length < minSize:\n return 0\nstart, end = (0, 0)\ncount = collections.defaultdict(int)\nwhile end < length:\n if end - start + 1 < minSize:\n count[s[end]] += 1\n end += 1\n else:\n count[s[end]] += 1\n c_len = len(co...
<|body_start_0|> mapping = collections.defaultdict(int) length = len(s) if length < minSize: return 0 start, end = (0, 0) count = collections.defaultdict(int) while end < length: if end - start + 1 < minSize: count[s[end]] += 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxFreq(self, s, maxLetters, minSize, maxSize): """:type s: str :type maxLetters: int :type minSize: int :type maxSize: int :rtype: int""" <|body_0|> def maxFreq_others(self, s, maxLetters, minSize, maxSize): """:type s: str :type maxLetters: int :type ...
stack_v2_sparse_classes_36k_train_016526
2,040
no_license
[ { "docstring": ":type s: str :type maxLetters: int :type minSize: int :type maxSize: int :rtype: int", "name": "maxFreq", "signature": "def maxFreq(self, s, maxLetters, minSize, maxSize)" }, { "docstring": ":type s: str :type maxLetters: int :type minSize: int :type maxSize: int :rtype: int", ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxFreq(self, s, maxLetters, minSize, maxSize): :type s: str :type maxLetters: int :type minSize: int :type maxSize: int :rtype: int - def maxFreq_others(self, s, maxLetters,...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxFreq(self, s, maxLetters, minSize, maxSize): :type s: str :type maxLetters: int :type minSize: int :type maxSize: int :rtype: int - def maxFreq_others(self, s, maxLetters,...
238995bd23c8a6c40c6035890e94baa2473d4bbc
<|skeleton|> class Solution: def maxFreq(self, s, maxLetters, minSize, maxSize): """:type s: str :type maxLetters: int :type minSize: int :type maxSize: int :rtype: int""" <|body_0|> def maxFreq_others(self, s, maxLetters, minSize, maxSize): """:type s: str :type maxLetters: int :type ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxFreq(self, s, maxLetters, minSize, maxSize): """:type s: str :type maxLetters: int :type minSize: int :type maxSize: int :rtype: int""" mapping = collections.defaultdict(int) length = len(s) if length < minSize: return 0 start, end = (0, 0) ...
the_stack_v2_python_sparse
problems/N1297_Maximum_Number_Of_Occurrences_Of_A_Substring.py
wan-catherine/Leetcode
train
5
3da6723fb2f328bd7eea061c2b5e8efa9adf23d6
[ "self.config_map = config_map\nself.downward_api = downward_api\nself.secret = secret\nself.service_account_token = service_account_token", "if dictionary is None:\n return None\nconfig_map = cohesity_management_sdk.models.pod_info_pod_spec_volume_info_projected_volume_projection_config_map_projection.PodInfo_...
<|body_start_0|> self.config_map = config_map self.downward_api = downward_api self.secret = secret self.service_account_token = service_account_token <|end_body_0|> <|body_start_1|> if dictionary is None: return None config_map = cohesity_management_sdk.mode...
Implementation of the 'PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection' model. TODO: type description here. Attributes: config_map (PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection): TODO: Type description here. downward_api (PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_DownwardA...
PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection: """Implementation of the 'PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection' model. TODO: type description here. Attributes: config_map (PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection): TODO: Type description he...
stack_v2_sparse_classes_36k_train_016527
3,966
permissive
[ { "docstring": "Constructor for the PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection class", "name": "__init__", "signature": "def __init__(self, config_map=None, downward_api=None, secret=None, service_account_token=None)" }, { "docstring": "Creates an instance of this model from a diction...
2
null
Implement the Python class `PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection` described below. Class description: Implementation of the 'PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection' model. TODO: type description here. Attributes: config_map (PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMa...
Implement the Python class `PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection` described below. Class description: Implementation of the 'PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection' model. TODO: type description here. Attributes: config_map (PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMa...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection: """Implementation of the 'PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection' model. TODO: type description here. Attributes: config_map (PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection): TODO: Type description he...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection: """Implementation of the 'PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection' model. TODO: type description here. Attributes: config_map (PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection): TODO: Type description here. downward_...
the_stack_v2_python_sparse
cohesity_management_sdk/models/pod_info_pod_spec_volume_info_projected_volume_projection.py
cohesity/management-sdk-python
train
24
f623d330bc2434b6db05fb1502767c48e2825722
[ "self.checks_and_handlers = list(self.base_checks_and_handlers) + list(self.checks_and_handlers)\nfor item in self.checks_and_handlers:\n if_check_falls = item.check(self.request, **self.kwargs)\n if if_check_falls:\n self.kwargs['failed_check'] = item\n return False\nreturn True", "if not sel...
<|body_start_0|> self.checks_and_handlers = list(self.base_checks_and_handlers) + list(self.checks_and_handlers) for item in self.checks_and_handlers: if_check_falls = item.check(self.request, **self.kwargs) if if_check_falls: self.kwargs['failed_check'] = item ...
Base view for all checks. There is a list of check functions in 'base_checks_and_handlers' and checks from child mixins in 'checks_and_handlers'.
BaseChecksMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseChecksMixin: """Base view for all checks. There is a list of check functions in 'base_checks_and_handlers' and checks from child mixins in 'checks_and_handlers'.""" def test_func(self): """Do all checks. At the start this function unites base checks and checks from child mixins. ...
stack_v2_sparse_classes_36k_train_016528
4,653
no_license
[ { "docstring": "Do all checks. At the start this function unites base checks and checks from child mixins. Then it iterates over the list of checks, calls it and, if check is failed, add the check in kwargs and returns False. If all checks are passed it returns True. When it returns False, 'dispatch' from UserP...
2
null
Implement the Python class `BaseChecksMixin` described below. Class description: Base view for all checks. There is a list of check functions in 'base_checks_and_handlers' and checks from child mixins in 'checks_and_handlers'. Method signatures and docstrings: - def test_func(self): Do all checks. At the start this f...
Implement the Python class `BaseChecksMixin` described below. Class description: Base view for all checks. There is a list of check functions in 'base_checks_and_handlers' and checks from child mixins in 'checks_and_handlers'. Method signatures and docstrings: - def test_func(self): Do all checks. At the start this f...
0879ade24685b628624dce06698f8a0afd042000
<|skeleton|> class BaseChecksMixin: """Base view for all checks. There is a list of check functions in 'base_checks_and_handlers' and checks from child mixins in 'checks_and_handlers'.""" def test_func(self): """Do all checks. At the start this function unites base checks and checks from child mixins. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseChecksMixin: """Base view for all checks. There is a list of check functions in 'base_checks_and_handlers' and checks from child mixins in 'checks_and_handlers'.""" def test_func(self): """Do all checks. At the start this function unites base checks and checks from child mixins. Then it itera...
the_stack_v2_python_sparse
camp-python-2021-find-me-develop/apps/core/mixins.py
rhanmar/oi_projects_summer_2021
train
0
59d5033b072e192a742ac0d46157c179abf87434
[ "get_logger().debug('Creating Configuration Service')\nConfigParser.ConfigParser.__init__(self)\nself.optionxform = str\nself.add_files(conf_files)", "for the_file in conf_files:\n get_logger().debug('Loading configuration from {0}'.format(the_file))\n self.read(the_file)\nincludes = self.get_active_section...
<|body_start_0|> get_logger().debug('Creating Configuration Service') ConfigParser.ConfigParser.__init__(self) self.optionxform = str self.add_files(conf_files) <|end_body_0|> <|body_start_1|> for the_file in conf_files: get_logger().debug('Loading configuration from...
Load and manage configuration information
Configuration
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Configuration: """Load and manage configuration information""" def __init__(self, conf_files): """Load the list of specified configuration files""" <|body_0|> def add_files(self, conf_files): """Read in conf files one by one""" <|body_1|> def get_act...
stack_v2_sparse_classes_36k_train_016529
4,198
no_license
[ { "docstring": "Load the list of specified configuration files", "name": "__init__", "signature": "def __init__(self, conf_files)" }, { "docstring": "Read in conf files one by one", "name": "add_files", "signature": "def add_files(self, conf_files)" }, { "docstring": "Get a list ...
4
null
Implement the Python class `Configuration` described below. Class description: Load and manage configuration information Method signatures and docstrings: - def __init__(self, conf_files): Load the list of specified configuration files - def add_files(self, conf_files): Read in conf files one by one - def get_active_...
Implement the Python class `Configuration` described below. Class description: Load and manage configuration information Method signatures and docstrings: - def __init__(self, conf_files): Load the list of specified configuration files - def add_files(self, conf_files): Read in conf files one by one - def get_active_...
eba6c1489b503fdcf040a126942643b355867bcd
<|skeleton|> class Configuration: """Load and manage configuration information""" def __init__(self, conf_files): """Load the list of specified configuration files""" <|body_0|> def add_files(self, conf_files): """Read in conf files one by one""" <|body_1|> def get_act...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Configuration: """Load and manage configuration information""" def __init__(self, conf_files): """Load the list of specified configuration files""" get_logger().debug('Creating Configuration Service') ConfigParser.ConfigParser.__init__(self) self.optionxform = str ...
the_stack_v2_python_sparse
src/ibm/teal/configuration.py
ppjsand/pyteal
train
1
093cb63b9bbe69ba7e87c92ff6cdc3111d86a772
[ "fields = list(super().get_fields(request, model_instance))\nordered_field_names = reversed(['notes', 'type', 'title', 'slug', 'summary', 'certainty', 'elaboration'])\nfor field_name in ordered_field_names:\n if field_name in fields:\n fields.remove(field_name)\n fields.insert(0, field_name)\nretur...
<|body_start_0|> fields = list(super().get_fields(request, model_instance)) ordered_field_names = reversed(['notes', 'type', 'title', 'slug', 'summary', 'certainty', 'elaboration']) for field_name in ordered_field_names: if field_name in fields: fields.remove(field_na...
Model admin for searchable models.
SearchableModelAdmin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SearchableModelAdmin: """Model admin for searchable models.""" def get_fields(self, request: 'HttpRequest', model_instance: Optional['SearchableModel']=None) -> list[str]: """Return reordered fields to be displayed in the admin.""" <|body_0|> def get_fieldsets(self, requ...
stack_v2_sparse_classes_36k_train_016530
4,473
no_license
[ { "docstring": "Return reordered fields to be displayed in the admin.", "name": "get_fields", "signature": "def get_fields(self, request: 'HttpRequest', model_instance: Optional['SearchableModel']=None) -> list[str]" }, { "docstring": "Return the fieldsets to be displayed in the admin form.", ...
3
stack_v2_sparse_classes_30k_train_014712
Implement the Python class `SearchableModelAdmin` described below. Class description: Model admin for searchable models. Method signatures and docstrings: - def get_fields(self, request: 'HttpRequest', model_instance: Optional['SearchableModel']=None) -> list[str]: Return reordered fields to be displayed in the admin...
Implement the Python class `SearchableModelAdmin` described below. Class description: Model admin for searchable models. Method signatures and docstrings: - def get_fields(self, request: 'HttpRequest', model_instance: Optional['SearchableModel']=None) -> list[str]: Return reordered fields to be displayed in the admin...
8bbdc8eec3622af22c17214051c34e36bea8e05a
<|skeleton|> class SearchableModelAdmin: """Model admin for searchable models.""" def get_fields(self, request: 'HttpRequest', model_instance: Optional['SearchableModel']=None) -> list[str]: """Return reordered fields to be displayed in the admin.""" <|body_0|> def get_fieldsets(self, requ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SearchableModelAdmin: """Model admin for searchable models.""" def get_fields(self, request: 'HttpRequest', model_instance: Optional['SearchableModel']=None) -> list[str]: """Return reordered fields to be displayed in the admin.""" fields = list(super().get_fields(request, model_instance)...
the_stack_v2_python_sparse
apps/search/admin.py
abdulwahed-mansour/modularhistory
train
1
f0c1be9dd0cbccd2de1e89a0dbc14f9e9b4fd08c
[ "import os\nimport subprocess\nself.info('call command: %s' % str(command))\np = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)\nstdout, stderr = p.communicate()\nif hasattr(stdout, 'decode'):\n stdout = stdout.decode('utf-8')\n stderr = stderr.decode('utf-8')\nself.info('...
<|body_start_0|> import os import subprocess self.info('call command: %s' % str(command)) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) stdout, stderr = p.communicate() if hasattr(stdout, 'decode'): stdout = stdout.dec...
GSS class to access FTP server using curl commands.
GSS_FTP
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GSS_FTP: """GSS class to access FTP server using curl commands.""" def _Call(self, command, **kwargs): """Execute curl command. Return values: * stdout line (incl newline characters) * stderr line (incl newline characters) * return code, 0 if no error, <0 indicates warning, >0 error"...
stack_v2_sparse_classes_36k_train_016531
40,935
no_license
[ { "docstring": "Execute curl command. Return values: * stdout line (incl newline characters) * stderr line (incl newline characters) * return code, 0 if no error, <0 indicates warning, >0 error", "name": "_Call", "signature": "def _Call(self, command, **kwargs)" }, { "docstring": "List directory...
5
null
Implement the Python class `GSS_FTP` described below. Class description: GSS class to access FTP server using curl commands. Method signatures and docstrings: - def _Call(self, command, **kwargs): Execute curl command. Return values: * stdout line (incl newline characters) * stderr line (incl newline characters) * re...
Implement the Python class `GSS_FTP` described below. Class description: GSS class to access FTP server using curl commands. Method signatures and docstrings: - def _Call(self, command, **kwargs): Execute curl command. Return values: * stdout line (incl newline characters) * stderr line (incl newline characters) * re...
1b6b8e42cd00d3490647aa90ca749b49551448a4
<|skeleton|> class GSS_FTP: """GSS class to access FTP server using curl commands.""" def _Call(self, command, **kwargs): """Execute curl command. Return values: * stdout line (incl newline characters) * stderr line (incl newline characters) * return code, 0 if no error, <0 indicates warning, >0 error"...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GSS_FTP: """GSS class to access FTP server using curl commands.""" def _Call(self, command, **kwargs): """Execute curl command. Return values: * stdout line (incl newline characters) * stderr line (incl newline characters) * return code, 0 if no error, <0 indicates warning, >0 error""" im...
the_stack_v2_python_sparse
lekf_4DEnVAR/lekf/v3.0.003-beta/proj/beta/003/py/gss.py
ayarceb/Version_WRF_04_2020
train
0
60b1c56d9b242ac1aed38b51f6bf8096bafed5c9
[ "queue = collections.deque([root])\nresult = ['#']\nwhile queue:\n node = queue.popleft()\n if node:\n queue.append(node.left)\n queue.append(node.right)\n result.append(str(node.val))\n else:\n result.append('#')\nreturn ' '.join(result)", "if data == '# #':\n return None\...
<|body_start_0|> queue = collections.deque([root]) result = ['#'] while queue: node = queue.popleft() if node: queue.append(node.left) queue.append(node.right) result.append(str(node.val)) else: r...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|b...
stack_v2_sparse_classes_36k_train_016532
3,026
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature"...
2
null
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. :type root: TreeNode :rtype: str - def deserialize(self, data: str) -> TreeNode: Decodes your encoded dat...
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. :type root: TreeNode :rtype: str - def deserialize(self, data: str) -> TreeNode: Decodes your encoded dat...
1c9528e26752b723e1d128b020f6c5291ed5ca19
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" queue = collections.deque([root]) result = ['#'] while queue: node = queue.popleft() if node: queue.append(node.l...
the_stack_v2_python_sparse
leetcode/most_liked/297_serialize_and_deserialize_binary_tree.py
eunjungchoi/algorithm
train
1
1c09e2ced8ed33aaf69f92e353bcdee1631818af
[ "self.github_repo_obj = github_repo_obj\nself.git_repo_obj = git_repo_obj\nself.run_id = run_id", "for pr in self.github_repo_obj.get_pulls(state='open', sort='created', base=BASE):\n print(f'{t.yellow}Looking on pr number [{pr.number}]: last updated: {str(pr.updated_at)}, branch={pr.head.ref}')\n condition...
<|body_start_0|> self.github_repo_obj = github_repo_obj self.git_repo_obj = git_repo_obj self.run_id = run_id <|end_body_0|> <|body_start_1|> for pr in self.github_repo_obj.get_pulls(state='open', sort='created', base=BASE): print(f'{t.yellow}Looking on pr number [{pr.number...
AutoBumperManager
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AutoBumperManager: def __init__(self, github_repo_obj: Repository, git_repo_obj: Repo, run_id: str): """Args: github_repo_obj: GitHub API repo object. git_repo_obj: Git API repo object. run_id: GitHub action run id.""" <|body_0|> def manage(self): """Iterates over al...
stack_v2_sparse_classes_36k_train_016533
11,815
permissive
[ { "docstring": "Args: github_repo_obj: GitHub API repo object. git_repo_obj: Git API repo object. run_id: GitHub action run id.", "name": "__init__", "signature": "def __init__(self, github_repo_obj: Repository, git_repo_obj: Repo, run_id: str)" }, { "docstring": "Iterates over all PR's in the r...
2
stack_v2_sparse_classes_30k_train_019219
Implement the Python class `AutoBumperManager` described below. Class description: Implement the AutoBumperManager class. Method signatures and docstrings: - def __init__(self, github_repo_obj: Repository, git_repo_obj: Repo, run_id: str): Args: github_repo_obj: GitHub API repo object. git_repo_obj: Git API repo obje...
Implement the Python class `AutoBumperManager` described below. Class description: Implement the AutoBumperManager class. Method signatures and docstrings: - def __init__(self, github_repo_obj: Repository, git_repo_obj: Repo, run_id: str): Args: github_repo_obj: GitHub API repo object. git_repo_obj: Git API repo obje...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class AutoBumperManager: def __init__(self, github_repo_obj: Repository, git_repo_obj: Repo, run_id: str): """Args: github_repo_obj: GitHub API repo object. git_repo_obj: Git API repo object. run_id: GitHub action run id.""" <|body_0|> def manage(self): """Iterates over al...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AutoBumperManager: def __init__(self, github_repo_obj: Repository, git_repo_obj: Repo, run_id: str): """Args: github_repo_obj: GitHub API repo object. git_repo_obj: Git API repo object. run_id: GitHub action run id.""" self.github_repo_obj = github_repo_obj self.git_repo_obj = git_repo...
the_stack_v2_python_sparse
Utils/github_workflow_scripts/autobump_release_notes/autobump_rn.py
demisto/content
train
1,023
5f0180f34007f7d3d7bc978f42c8da57a044cf10
[ "super().__init__()\nif aggregators is None:\n aggregators = ['sum', 'min', 'max', 'std']\nif scalers is None:\n scalers = ['identity', 'amplification', 'attenuation']\nself.convs = nn.ModuleList()\nself.activs = nn.ModuleList()\nself.dropouts = nn.ModuleList()\nif residual:\n self.residuals = nn.ModuleLis...
<|body_start_0|> super().__init__() if aggregators is None: aggregators = ['sum', 'min', 'max', 'std'] if scalers is None: scalers = ['identity', 'amplification', 'attenuation'] self.convs = nn.ModuleList() self.activs = nn.ModuleList() self.dropou...
Principal Neighborhood aggregation (PNA) Output activation is Identity
PNAModule
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PNAModule: """Principal Neighborhood aggregation (PNA) Output activation is Identity""" def __init__(self, c_list, deg, edge_dim=None, drop_rate=0.1, act_name=Cte.RELU, aggregators=None, scalers=None, residual=False): """Args: c_list: deg: In-degree histogram over training data edge_...
stack_v2_sparse_classes_36k_train_016534
2,669
permissive
[ { "docstring": "Args: c_list: deg: In-degree histogram over training data edge_dim: drop_rate: act_name: aggregators: scalers: residual:", "name": "__init__", "signature": "def __init__(self, c_list, deg, edge_dim=None, drop_rate=0.1, act_name=Cte.RELU, aggregators=None, scalers=None, residual=False)" ...
2
stack_v2_sparse_classes_30k_train_019397
Implement the Python class `PNAModule` described below. Class description: Principal Neighborhood aggregation (PNA) Output activation is Identity Method signatures and docstrings: - def __init__(self, c_list, deg, edge_dim=None, drop_rate=0.1, act_name=Cte.RELU, aggregators=None, scalers=None, residual=False): Args: ...
Implement the Python class `PNAModule` described below. Class description: Principal Neighborhood aggregation (PNA) Output activation is Identity Method signatures and docstrings: - def __init__(self, c_list, deg, edge_dim=None, drop_rate=0.1, act_name=Cte.RELU, aggregators=None, scalers=None, residual=False): Args: ...
5e552740338a3373d81245b8daa28399183b74cd
<|skeleton|> class PNAModule: """Principal Neighborhood aggregation (PNA) Output activation is Identity""" def __init__(self, c_list, deg, edge_dim=None, drop_rate=0.1, act_name=Cte.RELU, aggregators=None, scalers=None, residual=False): """Args: c_list: deg: In-degree histogram over training data edge_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PNAModule: """Principal Neighborhood aggregation (PNA) Output activation is Identity""" def __init__(self, c_list, deg, edge_dim=None, drop_rate=0.1, act_name=Cte.RELU, aggregators=None, scalers=None, residual=False): """Args: c_list: deg: In-degree histogram over training data edge_dim: drop_rat...
the_stack_v2_python_sparse
modules/pna.py
wanqiukong/VACA
train
0
fb4049d8db8793c5d605768946086fd310732a59
[ "adjacencies_list = []\nexpectedadj_list = [{1: (1, 0), 2: (0, 1), 5: (1, 1)}, {1: [(1, 0), (2, 0)], 2: [(0, 1), (0, 2)], 5: [(1, 1), (2, 2)]}, {5: [(1, 1), (2, 2)]}, {1: [(1, 0), (2, 0)], 2: [(0, 1), (0, 2)]}, {5: (1, 2), 6: (2, 1)}]\npiece_letters = ['K', 'Q', 'B', 'R', 'N']\nmatrix = [[0] * 3 for _ in itertools....
<|body_start_0|> adjacencies_list = [] expectedadj_list = [{1: (1, 0), 2: (0, 1), 5: (1, 1)}, {1: [(1, 0), (2, 0)], 2: [(0, 1), (0, 2)], 5: [(1, 1), (2, 2)]}, {5: [(1, 1), (2, 2)]}, {1: [(1, 0), (2, 0)], 2: [(0, 1), (0, 2)]}, {5: (1, 2), 6: (2, 1)}] piece_letters = ['K', 'Q', 'B', 'R', 'N'] ...
Class of chess main application - pieces module testing
PiecesApplicationTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PiecesApplicationTest: """Class of chess main application - pieces module testing""" def test_list_adjacencies(self): """Tests adjacencies listing""" <|body_0|> def test_adjacencies(self): """Tests adjacencies checking""" <|body_1|> def test_check_ad...
stack_v2_sparse_classes_36k_train_016535
6,418
permissive
[ { "docstring": "Tests adjacencies listing", "name": "test_list_adjacencies", "signature": "def test_list_adjacencies(self)" }, { "docstring": "Tests adjacencies checking", "name": "test_adjacencies", "signature": "def test_adjacencies(self)" }, { "docstring": "Tests check_adj bet...
3
stack_v2_sparse_classes_30k_train_016076
Implement the Python class `PiecesApplicationTest` described below. Class description: Class of chess main application - pieces module testing Method signatures and docstrings: - def test_list_adjacencies(self): Tests adjacencies listing - def test_adjacencies(self): Tests adjacencies checking - def test_check_adj(se...
Implement the Python class `PiecesApplicationTest` described below. Class description: Class of chess main application - pieces module testing Method signatures and docstrings: - def test_list_adjacencies(self): Tests adjacencies listing - def test_adjacencies(self): Tests adjacencies checking - def test_check_adj(se...
7470479e352bf6fa28215e745af8c42dc20d7a1f
<|skeleton|> class PiecesApplicationTest: """Class of chess main application - pieces module testing""" def test_list_adjacencies(self): """Tests adjacencies listing""" <|body_0|> def test_adjacencies(self): """Tests adjacencies checking""" <|body_1|> def test_check_ad...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PiecesApplicationTest: """Class of chess main application - pieces module testing""" def test_list_adjacencies(self): """Tests adjacencies listing""" adjacencies_list = [] expectedadj_list = [{1: (1, 0), 2: (0, 1), 5: (1, 1)}, {1: [(1, 0), (2, 0)], 2: [(0, 1), (0, 2)], 5: [(1, 1),...
the_stack_v2_python_sparse
challenges/chess/tests.py
williamlagos/python-coding
train
0
b675b047dea080792425c8c74b72abaf6ba42094
[ "dic = dict()\nm = n = head\nwhile m:\n dic[m] = Node(m.val)\n m = m.next\nwhile n:\n dic[n].next = dic.get(n.next)\n dic[n].random = dic.get(n.random)\n n = n.next\nreturn dic.get(head)", "map_new = collections.defaultdict(lambda: Node(0, None, None))\nmap_new[None] = None\nnd_old = head\nwhile nd...
<|body_start_0|> dic = dict() m = n = head while m: dic[m] = Node(m.val) m = m.next while n: dic[n].next = dic.get(n.next) dic[n].random = dic.get(n.random) n = n.next return dic.get(head) <|end_body_0|> <|body_start_1|...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def copyRandomList(self, head: 'Node') -> 'Node': """O(2n)""" <|body_0|> def copyRandomList(self, head: 'Node') -> 'Node': """dict with old Nodes as keys and new Nodes as values. Doing so allows us to create node's next and random as we iterate through the ...
stack_v2_sparse_classes_36k_train_016536
1,508
no_license
[ { "docstring": "O(2n)", "name": "copyRandomList", "signature": "def copyRandomList(self, head: 'Node') -> 'Node'" }, { "docstring": "dict with old Nodes as keys and new Nodes as values. Doing so allows us to create node's next and random as we iterate through the list from head to tail. Otherwis...
2
stack_v2_sparse_classes_30k_test_000467
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def copyRandomList(self, head: 'Node') -> 'Node': O(2n) - def copyRandomList(self, head: 'Node') -> 'Node': dict with old Nodes as keys and new Nodes as values. Doing so allows u...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def copyRandomList(self, head: 'Node') -> 'Node': O(2n) - def copyRandomList(self, head: 'Node') -> 'Node': dict with old Nodes as keys and new Nodes as values. Doing so allows u...
e50dc0642f087f37ab3234390be3d8a0ed48fe62
<|skeleton|> class Solution: def copyRandomList(self, head: 'Node') -> 'Node': """O(2n)""" <|body_0|> def copyRandomList(self, head: 'Node') -> 'Node': """dict with old Nodes as keys and new Nodes as values. Doing so allows us to create node's next and random as we iterate through the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def copyRandomList(self, head: 'Node') -> 'Node': """O(2n)""" dic = dict() m = n = head while m: dic[m] = Node(m.val) m = m.next while n: dic[n].next = dic.get(n.next) dic[n].random = dic.get(n.random) ...
the_stack_v2_python_sparse
Leetcode/138. Copy List with Random Pointer.py
brlala/Educative-Grokking-Coding-Exercise
train
3
ab8b688386f7eef00c3c953fef493f582875d632
[ "attributes = {'class': node.get_option_value('class'), 'id': node.get_option_value('id')}\nhtml = Html.generate_tag('table', attributes)\nhtml += TableHtmlFormatter._generate_caption(node)\nhtml += self._generate_table_body(node)\nhtml += '</table>'\nfile.write(html)", "if node.caption:\n table_number = node....
<|body_start_0|> attributes = {'class': node.get_option_value('class'), 'id': node.get_option_value('id')} html = Html.generate_tag('table', attributes) html += TableHtmlFormatter._generate_caption(node) html += self._generate_table_body(node) html += '</table>' file.writ...
HtmlFormatter for generating HTML code for table.
TableHtmlFormatter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TableHtmlFormatter: """HtmlFormatter for generating HTML code for table.""" def generate(self, node: TableNode, file: Any) -> None: """Generates the HTML code for a table node. :param TableNode node: The table node. :param any file: The output file.""" <|body_0|> def _ge...
stack_v2_sparse_classes_36k_train_016537
4,269
permissive
[ { "docstring": "Generates the HTML code for a table node. :param TableNode node: The table node. :param any file: The output file.", "name": "generate", "signature": "def generate(self, node: TableNode, file: Any) -> None" }, { "docstring": "Generates the caption for the table in HTML representa...
5
null
Implement the Python class `TableHtmlFormatter` described below. Class description: HtmlFormatter for generating HTML code for table. Method signatures and docstrings: - def generate(self, node: TableNode, file: Any) -> None: Generates the HTML code for a table node. :param TableNode node: The table node. :param any ...
Implement the Python class `TableHtmlFormatter` described below. Class description: HtmlFormatter for generating HTML code for table. Method signatures and docstrings: - def generate(self, node: TableNode, file: Any) -> None: Generates the HTML code for a table node. :param TableNode node: The table node. :param any ...
589c2a27eceebb7d96c14744c1632bdbdee9be52
<|skeleton|> class TableHtmlFormatter: """HtmlFormatter for generating HTML code for table.""" def generate(self, node: TableNode, file: Any) -> None: """Generates the HTML code for a table node. :param TableNode node: The table node. :param any file: The output file.""" <|body_0|> def _ge...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TableHtmlFormatter: """HtmlFormatter for generating HTML code for table.""" def generate(self, node: TableNode, file: Any) -> None: """Generates the HTML code for a table node. :param TableNode node: The table node. :param any file: The output file.""" attributes = {'class': node.get_opti...
the_stack_v2_python_sparse
sdoc/sdoc2/formatter/html/TableHtmlFormatter.py
SDoc/py-sdoc
train
2
b4ac27259ad7af6874515427006e7451acb122d1
[ "self.iterations = iterations\nself.graph = graph\nself.features = get_degrees(graph)\nself.nodes = self.graph.nodes()\nself.extracted_features = [str(v) for k, v in self.features.items()]\nself.per_stage = []", "new_features = {}\nfor node in self.nodes:\n nebs = self.graph.neighbors(node)\n degs = [self.f...
<|body_start_0|> self.iterations = iterations self.graph = graph self.features = get_degrees(graph) self.nodes = self.graph.nodes() self.extracted_features = [str(v) for k, v in self.features.items()] self.per_stage = [] <|end_body_0|> <|body_start_1|> new_featur...
Weisfeiler Lehman feature extractor class.
WeisfeilerLehmanMachine
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WeisfeilerLehmanMachine: """Weisfeiler Lehman feature extractor class.""" def __init__(self, graph, iterations): """Initialization method which also executes feature extraction. :param graph: The Nx graph object. :param iterations: Number of WL iterations.""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_016538
6,915
permissive
[ { "docstring": "Initialization method which also executes feature extraction. :param graph: The Nx graph object. :param iterations: Number of WL iterations.", "name": "__init__", "signature": "def __init__(self, graph, iterations)" }, { "docstring": "The method does a single WL recursion. :retur...
3
stack_v2_sparse_classes_30k_test_001062
Implement the Python class `WeisfeilerLehmanMachine` described below. Class description: Weisfeiler Lehman feature extractor class. Method signatures and docstrings: - def __init__(self, graph, iterations): Initialization method which also executes feature extraction. :param graph: The Nx graph object. :param iterati...
Implement the Python class `WeisfeilerLehmanMachine` described below. Class description: Weisfeiler Lehman feature extractor class. Method signatures and docstrings: - def __init__(self, graph, iterations): Initialization method which also executes feature extraction. :param graph: The Nx graph object. :param iterati...
e6e9db5a936e87a2adfdf81a1f00d952d800d1c8
<|skeleton|> class WeisfeilerLehmanMachine: """Weisfeiler Lehman feature extractor class.""" def __init__(self, graph, iterations): """Initialization method which also executes feature extraction. :param graph: The Nx graph object. :param iterations: Number of WL iterations.""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WeisfeilerLehmanMachine: """Weisfeiler Lehman feature extractor class.""" def __init__(self, graph, iterations): """Initialization method which also executes feature extraction. :param graph: The Nx graph object. :param iterations: Number of WL iterations.""" self.iterations = iterations ...
the_stack_v2_python_sparse
wl_sensibility.py
Yacnnn/GAT-Skip-Gram
train
0
9405c36a805f5bfdfec281cbf6a2fe806ea03a9f
[ "used_taxons = cls.get_all_taxons(company_id, taxon_slugs, taxonless_map, data_sources, include_aggregation_definition_taxons)\nraw_taxons = UsedTaxonsContainer()\nraw_taxons.required_taxons = {taxon.slug_expr: taxon for taxon in used_taxons.required_taxons.values() if not taxon.is_computed_metric}\nraw_taxons.opti...
<|body_start_0|> used_taxons = cls.get_all_taxons(company_id, taxon_slugs, taxonless_map, data_sources, include_aggregation_definition_taxons) raw_taxons = UsedTaxonsContainer() raw_taxons.required_taxons = {taxon.slug_expr: taxon for taxon in used_taxons.required_taxons.values() if not taxon.is...
Helper class containing getters working with UsedTaxonsContainer
UsedTaxons
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UsedTaxons: """Helper class containing getters working with UsedTaxonsContainer""" def get_raw_taxons(cls, company_id: str, taxon_slugs: Iterable[TaxonExpressionStr], taxonless_map: TaxonMap, data_sources: Optional[Iterable[str]]=None, include_aggregation_definition_taxons: bool=False) -> Us...
stack_v2_sparse_classes_36k_train_016539
17,816
permissive
[ { "docstring": "Returns raw (not computed) taxons required to get data for given taxon slugs.", "name": "get_raw_taxons", "signature": "def get_raw_taxons(cls, company_id: str, taxon_slugs: Iterable[TaxonExpressionStr], taxonless_map: TaxonMap, data_sources: Optional[Iterable[str]]=None, include_aggrega...
3
null
Implement the Python class `UsedTaxons` described below. Class description: Helper class containing getters working with UsedTaxonsContainer Method signatures and docstrings: - def get_raw_taxons(cls, company_id: str, taxon_slugs: Iterable[TaxonExpressionStr], taxonless_map: TaxonMap, data_sources: Optional[Iterable[...
Implement the Python class `UsedTaxons` described below. Class description: Helper class containing getters working with UsedTaxonsContainer Method signatures and docstrings: - def get_raw_taxons(cls, company_id: str, taxon_slugs: Iterable[TaxonExpressionStr], taxonless_map: TaxonMap, data_sources: Optional[Iterable[...
210f037280793d5cb3b6d9d3e7ba3e22ca9b8bbc
<|skeleton|> class UsedTaxons: """Helper class containing getters working with UsedTaxonsContainer""" def get_raw_taxons(cls, company_id: str, taxon_slugs: Iterable[TaxonExpressionStr], taxonless_map: TaxonMap, data_sources: Optional[Iterable[str]]=None, include_aggregation_definition_taxons: bool=False) -> Us...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UsedTaxons: """Helper class containing getters working with UsedTaxonsContainer""" def get_raw_taxons(cls, company_id: str, taxon_slugs: Iterable[TaxonExpressionStr], taxonless_map: TaxonMap, data_sources: Optional[Iterable[str]]=None, include_aggregation_definition_taxons: bool=False) -> UsedTaxonsConta...
the_stack_v2_python_sparse
src/panoramic/cli/husky/core/taxonomy/getters.py
panoramichq/panoramic-cli
train
5
d7c5cd49bcff63ee18401c43507d42a3b561f3ba
[ "self.result = list()\nend = n + 2 - k\nfor i in range(1, end):\n self.dfs(i + 1, end + 1, k - 1, [i])\nreturn self.result", "if k == 0:\n self.result.append(current)\n return\nfor i in range(start, n):\n temp = current[:]\n temp.append(i)\n self.dfs(i + 1, n + 1, k - 1, temp)" ]
<|body_start_0|> self.result = list() end = n + 2 - k for i in range(1, end): self.dfs(i + 1, end + 1, k - 1, [i]) return self.result <|end_body_0|> <|body_start_1|> if k == 0: self.result.append(current) return for i in range(start, n...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def combine(self, n, k): """:type n: int :type k: int :rtype: List[List[int]]""" <|body_0|> def dfs(self, start, n, k, current): """深度搜索 :type start: int :type n: int :param n: 该轮遍历的终点 :type k: int :param k: 第 k 轮遍历(倒序) :type current: List[int]""" <...
stack_v2_sparse_classes_36k_train_016540
1,355
no_license
[ { "docstring": ":type n: int :type k: int :rtype: List[List[int]]", "name": "combine", "signature": "def combine(self, n, k)" }, { "docstring": "深度搜索 :type start: int :type n: int :param n: 该轮遍历的终点 :type k: int :param k: 第 k 轮遍历(倒序) :type current: List[int]", "name": "dfs", "signature": ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combine(self, n, k): :type n: int :type k: int :rtype: List[List[int]] - def dfs(self, start, n, k, current): 深度搜索 :type start: int :type n: int :param n: 该轮遍历的终点 :type k: in...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combine(self, n, k): :type n: int :type k: int :rtype: List[List[int]] - def dfs(self, start, n, k, current): 深度搜索 :type start: int :type n: int :param n: 该轮遍历的终点 :type k: in...
f832227c4d0e0b1c0cc326561187004ef24e2a68
<|skeleton|> class Solution: def combine(self, n, k): """:type n: int :type k: int :rtype: List[List[int]]""" <|body_0|> def dfs(self, start, n, k, current): """深度搜索 :type start: int :type n: int :param n: 该轮遍历的终点 :type k: int :param k: 第 k 轮遍历(倒序) :type current: List[int]""" <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def combine(self, n, k): """:type n: int :type k: int :rtype: List[List[int]]""" self.result = list() end = n + 2 - k for i in range(1, end): self.dfs(i + 1, end + 1, k - 1, [i]) return self.result def dfs(self, start, n, k, current): ...
the_stack_v2_python_sparse
77.py
Gackle/leetcode_practice
train
0
ced2133b20cf83f9bfb59d7d6f4182d7cf10bdb5
[ "p = 1\nc_max = float('-inf')\nfor n in nums:\n p *= n\n c_max = max(c_max, p)\n if n == 0:\n p = 1\np = 1\nfor n in nums[::-1]:\n p *= n\n c_max = max(c_max, p)\n if n == 0:\n p = 1\nreturn c_max", "dp_min = [nums[0]] + [0] * (len(nums) - 1)\ndp_max = [nums[0]] + [0] * (len(nums) ...
<|body_start_0|> p = 1 c_max = float('-inf') for n in nums: p *= n c_max = max(c_max, p) if n == 0: p = 1 p = 1 for n in nums[::-1]: p *= n c_max = max(c_max, p) if n == 0: p =...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProduct(self, nums): """:type nums: List[int] :rtype: int 這個做法非常好懂 其實最重要的就是負數還有0 先討論負數,而且必須是奇數個負數,如果是偶數個負數的話會負負得正 假設數列中有3個負數,則最大值必定存在以三個負數的其中一個作為分割點的左數列或右數列其中一個 舉例來說 數列是 [2, 2, -3, 2, 2, -4, 2, 2, -5, 2, 2] 若取-3為分割點則左右分別為 [2 2] [-3] [2 2 -4 2 2 -5 2 2] 若取-4為分割點則左右分別為 [2 ...
stack_v2_sparse_classes_36k_train_016541
2,635
no_license
[ { "docstring": ":type nums: List[int] :rtype: int 這個做法非常好懂 其實最重要的就是負數還有0 先討論負數,而且必須是奇數個負數,如果是偶數個負數的話會負負得正 假設數列中有3個負數,則最大值必定存在以三個負數的其中一個作為分割點的左數列或右數列其中一個 舉例來說 數列是 [2, 2, -3, 2, 2, -4, 2, 2, -5, 2, 2] 若取-3為分割點則左右分別為 [2 2] [-3] [2 2 -4 2 2 -5 2 2] 若取-4為分割點則左右分別為 [2 2 -3 2 2] [-4] [2 2 -5 2 2] 若取-5為分割點則左右分別為 [2 2 -...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct(self, nums): :type nums: List[int] :rtype: int 這個做法非常好懂 其實最重要的就是負數還有0 先討論負數,而且必須是奇數個負數,如果是偶數個負數的話會負負得正 假設數列中有3個負數,則最大值必定存在以三個負數的其中一個作為分割點的左數列或右數列其中一個 舉例來說 數列是 [2, ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct(self, nums): :type nums: List[int] :rtype: int 這個做法非常好懂 其實最重要的就是負數還有0 先討論負數,而且必須是奇數個負數,如果是偶數個負數的話會負負得正 假設數列中有3個負數,則最大值必定存在以三個負數的其中一個作為分割點的左數列或右數列其中一個 舉例來說 數列是 [2, ...
ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd
<|skeleton|> class Solution: def maxProduct(self, nums): """:type nums: List[int] :rtype: int 這個做法非常好懂 其實最重要的就是負數還有0 先討論負數,而且必須是奇數個負數,如果是偶數個負數的話會負負得正 假設數列中有3個負數,則最大值必定存在以三個負數的其中一個作為分割點的左數列或右數列其中一個 舉例來說 數列是 [2, 2, -3, 2, 2, -4, 2, 2, -5, 2, 2] 若取-3為分割點則左右分別為 [2 2] [-3] [2 2 -4 2 2 -5 2 2] 若取-4為分割點則左右分別為 [2 ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProduct(self, nums): """:type nums: List[int] :rtype: int 這個做法非常好懂 其實最重要的就是負數還有0 先討論負數,而且必須是奇數個負數,如果是偶數個負數的話會負負得正 假設數列中有3個負數,則最大值必定存在以三個負數的其中一個作為分割點的左數列或右數列其中一個 舉例來說 數列是 [2, 2, -3, 2, 2, -4, 2, 2, -5, 2, 2] 若取-3為分割點則左右分別為 [2 2] [-3] [2 2 -4 2 2 -5 2 2] 若取-4為分割點則左右分別為 [2 2 -3 2 2] [-4]...
the_stack_v2_python_sparse
cs_notes/arrays/maximum_product_subarray.py
hwc1824/LeetCodeSolution
train
0
1d984788ae3589a2d046935cb6c54ae2c323784f
[ "customerId = kwargs['pk']\ndefaultAddress = get_object_or_404(CustomerAddress, customer_id=customerId, isDefault=True)\nserializer = CustomerAddressSerializer(defaultAddress)\nreturn Response(serializer.data)", "data = request.data\nnewDefaultAddress = get_object_or_404(CustomerAddress, id=data['address'])\nnewD...
<|body_start_0|> customerId = kwargs['pk'] defaultAddress = get_object_or_404(CustomerAddress, customer_id=customerId, isDefault=True) serializer = CustomerAddressSerializer(defaultAddress) return Response(serializer.data) <|end_body_0|> <|body_start_1|> data = request.data ...
DefaultAddress
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DefaultAddress: def get(self, request, *args, **kwargs): """获取用户默认地址""" <|body_0|> def patch(self, request, *args, **kwargs): """修改用户默认地址 :param request: address:新地址id :param args: :param kwargs: id:用户id :return:""" <|body_1|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_36k_train_016542
5,621
no_license
[ { "docstring": "获取用户默认地址", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "修改用户默认地址 :param request: address:新地址id :param args: :param kwargs: id:用户id :return:", "name": "patch", "signature": "def patch(self, request, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_005968
Implement the Python class `DefaultAddress` described below. Class description: Implement the DefaultAddress class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): 获取用户默认地址 - def patch(self, request, *args, **kwargs): 修改用户默认地址 :param request: address:新地址id :param args: :param kwargs: id:用...
Implement the Python class `DefaultAddress` described below. Class description: Implement the DefaultAddress class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): 获取用户默认地址 - def patch(self, request, *args, **kwargs): 修改用户默认地址 :param request: address:新地址id :param args: :param kwargs: id:用...
4510c5bb5b1a936dc881412b92518d01b5d5be13
<|skeleton|> class DefaultAddress: def get(self, request, *args, **kwargs): """获取用户默认地址""" <|body_0|> def patch(self, request, *args, **kwargs): """修改用户默认地址 :param request: address:新地址id :param args: :param kwargs: id:用户id :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DefaultAddress: def get(self, request, *args, **kwargs): """获取用户默认地址""" customerId = kwargs['pk'] defaultAddress = get_object_or_404(CustomerAddress, customer_id=customerId, isDefault=True) serializer = CustomerAddressSerializer(defaultAddress) return Response(serialize...
the_stack_v2_python_sparse
WeChat/views/customer.py
liuyucomeon/WeChatMall
train
1
ccc247171269bb43aaf90860faff08dcdddcdd43
[ "ds = 'ted_hrlr_translate/pt_to_en'\ntr = 'train'\nvl = 'validation'\nt_sample, v_sample = tfds.load(ds, with_info=True, as_supervised=True)\nself.data_train, self.data_valid = (t_sample[tr], t_sample[vl])\nportuguese, english = self.tokenize_dataset(self.data_train)\nself.tokenizer_pt, self.tokenizer_en = (portugu...
<|body_start_0|> ds = 'ted_hrlr_translate/pt_to_en' tr = 'train' vl = 'validation' t_sample, v_sample = tfds.load(ds, with_info=True, as_supervised=True) self.data_train, self.data_valid = (t_sample[tr], t_sample[vl]) portuguese, english = self.tokenize_dataset(self.data_...
[Loads and preps a dataset for machine translation] Returns: [type]: [description]
Dataset
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dataset: """[Loads and preps a dataset for machine translation] Returns: [type]: [description]""" def __init__(self): """[Class constructor. Creates the instance attributes] Attributes: data_train contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervi...
stack_v2_sparse_classes_36k_train_016543
2,359
no_license
[ { "docstring": "[Class constructor. Creates the instance attributes] Attributes: data_train contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided data_valid contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded as_supervided tokenizer_pt is the Port...
2
stack_v2_sparse_classes_30k_train_013948
Implement the Python class `Dataset` described below. Class description: [Loads and preps a dataset for machine translation] Returns: [type]: [description] Method signatures and docstrings: - def __init__(self): [Class constructor. Creates the instance attributes] Attributes: data_train contains the ted_hrlr_translat...
Implement the Python class `Dataset` described below. Class description: [Loads and preps a dataset for machine translation] Returns: [type]: [description] Method signatures and docstrings: - def __init__(self): [Class constructor. Creates the instance attributes] Attributes: data_train contains the ted_hrlr_translat...
eb47cd4d12e2f0627bb5e5af28cc0802ff13d0d9
<|skeleton|> class Dataset: """[Loads and preps a dataset for machine translation] Returns: [type]: [description]""" def __init__(self): """[Class constructor. Creates the instance attributes] Attributes: data_train contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Dataset: """[Loads and preps a dataset for machine translation] Returns: [type]: [description]""" def __init__(self): """[Class constructor. Creates the instance attributes] Attributes: data_train contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided data_vali...
the_stack_v2_python_sparse
supervised_learning/0x12-transformer_apps/0-dataset.py
rodrigocruz13/holbertonschool-machine_learning
train
4
ac1e14b9b048862935e1904e163fcab9eb8323cf
[ "dict.__init__(self)\nself[AI_ID] = event_id\nself[AI_COMP] = default_comp\nself[AI_NAME] = None\nself[AI_POOL_EXT_TIME] = pool_ext\nself[AI_MIN_TIME_IN_POOL] = min_time_in_pool\nreturn", "outstr = 'id=' + str(self['id'])\nif self[AI_COMP] is not None:\n outstr += ' comp=' + str(self[AI_COMP])\nif self[AI_NAME...
<|body_start_0|> dict.__init__(self) self[AI_ID] = event_id self[AI_COMP] = default_comp self[AI_NAME] = None self[AI_POOL_EXT_TIME] = pool_ext self[AI_MIN_TIME_IN_POOL] = min_time_in_pool return <|end_body_0|> <|body_start_1|> outstr = 'id=' + str(self['...
Event Analysis Info
AnalysisInfoEvent
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnalysisInfoEvent: """Event Analysis Info""" def __init__(self, event_id, default_comp, pool_ext=0, min_time_in_pool=0): """Construct the event info from the id and set defaults""" <|body_0|> def __str__(self): """Print out the event analysis info""" <|bo...
stack_v2_sparse_classes_36k_train_016544
12,915
no_license
[ { "docstring": "Construct the event info from the id and set defaults", "name": "__init__", "signature": "def __init__(self, event_id, default_comp, pool_ext=0, min_time_in_pool=0)" }, { "docstring": "Print out the event analysis info", "name": "__str__", "signature": "def __str__(self)"...
4
null
Implement the Python class `AnalysisInfoEvent` described below. Class description: Event Analysis Info Method signatures and docstrings: - def __init__(self, event_id, default_comp, pool_ext=0, min_time_in_pool=0): Construct the event info from the id and set defaults - def __str__(self): Print out the event analysis...
Implement the Python class `AnalysisInfoEvent` described below. Class description: Event Analysis Info Method signatures and docstrings: - def __init__(self, event_id, default_comp, pool_ext=0, min_time_in_pool=0): Construct the event info from the id and set defaults - def __str__(self): Print out the event analysis...
eba6c1489b503fdcf040a126942643b355867bcd
<|skeleton|> class AnalysisInfoEvent: """Event Analysis Info""" def __init__(self, event_id, default_comp, pool_ext=0, min_time_in_pool=0): """Construct the event info from the id and set defaults""" <|body_0|> def __str__(self): """Print out the event analysis info""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AnalysisInfoEvent: """Event Analysis Info""" def __init__(self, event_id, default_comp, pool_ext=0, min_time_in_pool=0): """Construct the event info from the id and set defaults""" dict.__init__(self) self[AI_ID] = event_id self[AI_COMP] = default_comp self[AI_NAME...
the_stack_v2_python_sparse
src/ibm/teal/analyzer/analysis_info.py
ppjsand/pyteal
train
1
80102f48947665632115655db00a3baea9f700f7
[ "lens = len(s)\nif len(s) == 0:\n return ''\nself.res = (1, (0, 0))\ndp = {}\n\ndef dps(i, j):\n if i > j:\n return False\n elif i == j:\n return True\n elif (i, j) in dp:\n return dp[i, j]\n else:\n if i == j - 1:\n now = s[i] == s[j]\n else:\n ...
<|body_start_0|> lens = len(s) if len(s) == 0: return '' self.res = (1, (0, 0)) dp = {} def dps(i, j): if i > j: return False elif i == j: return True elif (i, j) in dp: return dp[i, ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestPalindrome(self, s: str) -> str: """递归会超时间""" <|body_0|> def longestPalindrome(self, s: str) -> str: """斜向遍历""" <|body_1|> <|end_skeleton|> <|body_start_0|> lens = len(s) if len(s) == 0: return '' sel...
stack_v2_sparse_classes_36k_train_016545
1,865
no_license
[ { "docstring": "递归会超时间", "name": "longestPalindrome", "signature": "def longestPalindrome(self, s: str) -> str" }, { "docstring": "斜向遍历", "name": "longestPalindrome", "signature": "def longestPalindrome(self, s: str) -> str" } ]
2
stack_v2_sparse_classes_30k_train_001107
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestPalindrome(self, s: str) -> str: 递归会超时间 - def longestPalindrome(self, s: str) -> str: 斜向遍历
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestPalindrome(self, s: str) -> str: 递归会超时间 - def longestPalindrome(self, s: str) -> str: 斜向遍历 <|skeleton|> class Solution: def longestPalindrome(self, s: str) -> st...
cb3587242195bb3f2626231af2da13b90945a4d5
<|skeleton|> class Solution: def longestPalindrome(self, s: str) -> str: """递归会超时间""" <|body_0|> def longestPalindrome(self, s: str) -> str: """斜向遍历""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestPalindrome(self, s: str) -> str: """递归会超时间""" lens = len(s) if len(s) == 0: return '' self.res = (1, (0, 0)) dp = {} def dps(i, j): if i > j: return False elif i == j: retu...
the_stack_v2_python_sparse
leetcode/py36/最长回文子串.py
lionheartStark/sword_towards_offer
train
0
bccf7d464001b772c5ef5b2ae27506746b8ca710
[ "if packet.sender is None:\n db = SafeJsonFile(os.path.join(self.home_dir, TOPOLOGY_DB))\n data = db.read()\n if data:\n for item in data.values():\n item['old_data'] = 1\n db.write(data)\nreturn packet", "ret_params = {}\nupper_neighbours = self.operator.get_neighbours(NT_UPPER)...
<|body_start_0|> if packet.sender is None: db = SafeJsonFile(os.path.join(self.home_dir, TOPOLOGY_DB)) data = db.read() if data: for item in data.values(): item['old_data'] = 1 db.write(data) return packet <|end_body...
TopologyCognition
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TopologyCognition: def before_resend(self, packet): """In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketRequest class @return object of FabnetPacketRequest class or None for disabling packet resend to neigbours"...
stack_v2_sparse_classes_36k_train_016546
4,056
no_license
[ { "docstring": "In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketRequest class @return object of FabnetPacketRequest class or None for disabling packet resend to neigbours", "name": "before_resend", "signature": "def before_res...
3
stack_v2_sparse_classes_30k_train_015745
Implement the Python class `TopologyCognition` described below. Class description: Implement the TopologyCognition class. Method signatures and docstrings: - def before_resend(self, packet): In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketR...
Implement the Python class `TopologyCognition` described below. Class description: Implement the TopologyCognition class. Method signatures and docstrings: - def before_resend(self, packet): In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketR...
4d02a96e2c6e7f82cef03c7e808e390cdb1f6b6d
<|skeleton|> class TopologyCognition: def before_resend(self, packet): """In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketRequest class @return object of FabnetPacketRequest class or None for disabling packet resend to neigbours"...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TopologyCognition: def before_resend(self, packet): """In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketRequest class @return object of FabnetPacketRequest class or None for disabling packet resend to neigbours""" if ...
the_stack_v2_python_sparse
fabnet/operations/topology_cognition.py
fabregas/fabnet_core
train
0
028ee31e186cfe465f00c8969a46595e35492c60
[ "self.likelihoodObsDiff = []\nfor seq in trainSequences:\n for i in range(seq.shape[0] - 1):\n obsDiff = seq[i + 1] - seq[i]\n logLikelihood = hmmModel.score(np.expand_dims(seq[i], axis=0))\n self.likelihoodObsDiff.append((logLikelihood, obsDiff))\nself.likelihoodObsDiff.sort(key=lambda logL...
<|body_start_0|> self.likelihoodObsDiff = [] for seq in trainSequences: for i in range(seq.shape[0] - 1): obsDiff = seq[i + 1] - seq[i] logLikelihood = hmmModel.score(np.expand_dims(seq[i], axis=0)) self.likelihoodObsDiff.append((logLikelihood,...
Data Structure for finding the observation in the current dataset whose likelihood is closest to the provided input likelihood as a query. Actually, instead of outputting the observation, it outputs the difference between next and current observation found.
ClosestLikelihoodObsDiff
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClosestLikelihoodObsDiff: """Data Structure for finding the observation in the current dataset whose likelihood is closest to the provided input likelihood as a query. Actually, instead of outputting the observation, it outputs the difference between next and current observation found.""" de...
stack_v2_sparse_classes_36k_train_016547
8,041
no_license
[ { "docstring": "Constructs the data structure using the trained HMM model and training sequences :param hmmModel: The trained HMM model :param trainSequences: Training Sequences", "name": "__init__", "signature": "def __init__(self, hmmModel, trainSequences)" }, { "docstring": "Outputs the obser...
2
null
Implement the Python class `ClosestLikelihoodObsDiff` described below. Class description: Data Structure for finding the observation in the current dataset whose likelihood is closest to the provided input likelihood as a query. Actually, instead of outputting the observation, it outputs the difference between next an...
Implement the Python class `ClosestLikelihoodObsDiff` described below. Class description: Data Structure for finding the observation in the current dataset whose likelihood is closest to the provided input likelihood as a query. Actually, instead of outputting the observation, it outputs the difference between next an...
62f6fa0d5e832d2d1786eae729d9462b78d9b459
<|skeleton|> class ClosestLikelihoodObsDiff: """Data Structure for finding the observation in the current dataset whose likelihood is closest to the provided input likelihood as a query. Actually, instead of outputting the observation, it outputs the difference between next and current observation found.""" de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClosestLikelihoodObsDiff: """Data Structure for finding the observation in the current dataset whose likelihood is closest to the provided input likelihood as a query. Actually, instead of outputting the observation, it outputs the difference between next and current observation found.""" def __init__(se...
the_stack_v2_python_sparse
ts/model/gmm_hmm_likelihood_similarity.py
tedlaw09/time_series_forecaster
train
1
72a8908d0302e41f51afea90b02d1218cc78302b
[ "if torch.cuda.is_available():\n self.device = torch.device('cuda')\nelse:\n self.device = torch.device('cpu')\nself.model = BertForSequenceClassification.from_pretrained(path)\nself.tokenizer = BertTokenizer.from_pretrained(path)\nself.model.to(self.device)", "inputs = self.tokenizer(text, padding=True, tr...
<|body_start_0|> if torch.cuda.is_available(): self.device = torch.device('cuda') else: self.device = torch.device('cpu') self.model = BertForSequenceClassification.from_pretrained(path) self.tokenizer = BertTokenizer.from_pretrained(path) self.model.to(se...
Implements BertForSequenceClassification and BertTokenizer for binary classification from a saved model
FrankenBert
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FrankenBert: """Implements BertForSequenceClassification and BertTokenizer for binary classification from a saved model""" def __init__(self, path: str): """If there's a GPU available, tell PyTorch to use the GPU. Loads model and tokenizer from saved model directory (path)""" ...
stack_v2_sparse_classes_36k_train_016548
1,345
no_license
[ { "docstring": "If there's a GPU available, tell PyTorch to use the GPU. Loads model and tokenizer from saved model directory (path)", "name": "__init__", "signature": "def __init__(self, path: str)" }, { "docstring": "Makes a binary classification prediction based on saved model", "name": "...
2
null
Implement the Python class `FrankenBert` described below. Class description: Implements BertForSequenceClassification and BertTokenizer for binary classification from a saved model Method signatures and docstrings: - def __init__(self, path: str): If there's a GPU available, tell PyTorch to use the GPU. Loads model a...
Implement the Python class `FrankenBert` described below. Class description: Implements BertForSequenceClassification and BertTokenizer for binary classification from a saved model Method signatures and docstrings: - def __init__(self, path: str): If there's a GPU available, tell PyTorch to use the GPU. Loads model a...
ed957485c14aa8831e5a119d14849ddb0e1e6ec8
<|skeleton|> class FrankenBert: """Implements BertForSequenceClassification and BertTokenizer for binary classification from a saved model""" def __init__(self, path: str): """If there's a GPU available, tell PyTorch to use the GPU. Loads model and tokenizer from saved model directory (path)""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FrankenBert: """Implements BertForSequenceClassification and BertTokenizer for binary classification from a saved model""" def __init__(self, path: str): """If there's a GPU available, tell PyTorch to use the GPU. Loads model and tokenizer from saved model directory (path)""" if torch.cud...
the_stack_v2_python_sparse
LAMBDA_LABS/human-rights-first-police-ds-a/archive/old_app/frankenbert.py
Bryan-Guner-Backup/DOWN_ARCHIVE_V2
train
0
d24410b51d52fc0801c4a5e82a343c499991e556
[ "if not root:\n return ''\nret = []\n\ndef postSerialize(root):\n if not root:\n ret.append('# ')\n return\n ret.append(str(root.val) + ' ')\n postSerialize(root.left)\n postSerialize(root.right)\npostSerialize(root)\nreturn ''.join(ret)", "if not data:\n return None\nsplitData = d...
<|body_start_0|> if not root: return '' ret = [] def postSerialize(root): if not root: ret.append('# ') return ret.append(str(root.val) + ' ') postSerialize(root.left) postSerialize(root.right) p...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_016549
2,764
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_val_000597
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
af5b37e45c89028aad119b1bc2c684e26dafd6e0
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return '' ret = [] def postSerialize(root): if not root: ret.append('# ') return ret.app...
the_stack_v2_python_sparse
BFS/449.py
LuluFighting/leetCodeEveryday
train
2
b619a7b72efa631e21e4d8c16db8af8307a2a4b3
[ "args['epsilon'] = epsilon\nargs['gamma'] = gamma\nargs['alpha'] = alpha\nargs['numTraining'] = numTraining\nself.index = 0\nQLearningAgent.__init__(self, **args)", "action = QLearningAgent.getAction(self, state)\nself.doAction(state, action)\nreturn action" ]
<|body_start_0|> args['epsilon'] = epsilon args['gamma'] = gamma args['alpha'] = alpha args['numTraining'] = numTraining self.index = 0 QLearningAgent.__init__(self, **args) <|end_body_0|> <|body_start_1|> action = QLearningAgent.getAction(self, state) se...
Exactly the same as QLearningAgent, but with different default parameters
PacmanQAgent
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PacmanQAgent: """Exactly the same as QLearningAgent, but with different default parameters""" def __init__(self, epsilon=0.05, gamma=0.8, alpha=0.2, numTraining=0, **args): """These default parameters can be changed from the pacman.py command line. For example, to change the explorat...
stack_v2_sparse_classes_36k_train_016550
4,578
permissive
[ { "docstring": "These default parameters can be changed from the pacman.py command line. For example, to change the exploration rate, try: python pacman.py -p PacmanQLearningAgent -a epsilon=0.1 alpha - learning rate epsilon - exploration rate gamma - discount factor numTraining - number of training episodes, i...
2
stack_v2_sparse_classes_30k_train_006827
Implement the Python class `PacmanQAgent` described below. Class description: Exactly the same as QLearningAgent, but with different default parameters Method signatures and docstrings: - def __init__(self, epsilon=0.05, gamma=0.8, alpha=0.2, numTraining=0, **args): These default parameters can be changed from the pa...
Implement the Python class `PacmanQAgent` described below. Class description: Exactly the same as QLearningAgent, but with different default parameters Method signatures and docstrings: - def __init__(self, epsilon=0.05, gamma=0.8, alpha=0.2, numTraining=0, **args): These default parameters can be changed from the pa...
c598c63c16dba57639013a90086735377a2562b1
<|skeleton|> class PacmanQAgent: """Exactly the same as QLearningAgent, but with different default parameters""" def __init__(self, epsilon=0.05, gamma=0.8, alpha=0.2, numTraining=0, **args): """These default parameters can be changed from the pacman.py command line. For example, to change the explorat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PacmanQAgent: """Exactly the same as QLearningAgent, but with different default parameters""" def __init__(self, epsilon=0.05, gamma=0.8, alpha=0.2, numTraining=0, **args): """These default parameters can be changed from the pacman.py command line. For example, to change the exploration rate, try...
the_stack_v2_python_sparse
week03_model_free/crawler_and_pacman/seminar_py2/qlearningAgents.py
yandexdataschool/Practical_RL
train
5,932
53d6b2bc50929a36fde7bc7a14384dd58228c018
[ "super(Sqlite3DatabaseFile, self).__init__()\nself._connection = None\nself._cursor = None\nself.filename = None\nself.read_only = None", "if not self._connection:\n raise RuntimeError('Cannot close database not opened.')\nself._connection.commit()\nself._connection.close()\nself._connection = None\nself._curs...
<|body_start_0|> super(Sqlite3DatabaseFile, self).__init__() self._connection = None self._cursor = None self.filename = None self.read_only = None <|end_body_0|> <|body_start_1|> if not self._connection: raise RuntimeError('Cannot close database not opened.'...
Class that defines a sqlite3 database file.
Sqlite3DatabaseFile
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Sqlite3DatabaseFile: """Class that defines a sqlite3 database file.""" def __init__(self): """Initializes the database file object.""" <|body_0|> def Close(self): """Closes the database file. Raises: RuntimeError: if the database is not opened.""" <|body_...
stack_v2_sparse_classes_36k_train_016551
11,064
permissive
[ { "docstring": "Initializes the database file object.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Closes the database file. Raises: RuntimeError: if the database is not opened.", "name": "Close", "signature": "def Close(self)" }, { "docstring": "Det...
5
stack_v2_sparse_classes_30k_train_002268
Implement the Python class `Sqlite3DatabaseFile` described below. Class description: Class that defines a sqlite3 database file. Method signatures and docstrings: - def __init__(self): Initializes the database file object. - def Close(self): Closes the database file. Raises: RuntimeError: if the database is not opene...
Implement the Python class `Sqlite3DatabaseFile` described below. Class description: Class that defines a sqlite3 database file. Method signatures and docstrings: - def __init__(self): Initializes the database file object. - def Close(self): Closes the database file. Raises: RuntimeError: if the database is not opene...
c69b2952b608cfce47ff8fd0d1409d856be35cb1
<|skeleton|> class Sqlite3DatabaseFile: """Class that defines a sqlite3 database file.""" def __init__(self): """Initializes the database file object.""" <|body_0|> def Close(self): """Closes the database file. Raises: RuntimeError: if the database is not opened.""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Sqlite3DatabaseFile: """Class that defines a sqlite3 database file.""" def __init__(self): """Initializes the database file object.""" super(Sqlite3DatabaseFile, self).__init__() self._connection = None self._cursor = None self.filename = None self.read_onl...
the_stack_v2_python_sparse
plaso/formatters/winevt_rc.py
cyb3rfox/plaso
train
3
78770b6b37567a6395ad931814055c34d335e3c7
[ "self.cap = capacity\nself.cache = LinkedList(capacity)\nself.cachemap = {}", "if key in self.cachemap:\n node = self.cachemap[key]\n self.cache.modify_and_move(key, node.value, node)\n return node.value\nelse:\n return -1", "if key in self.cachemap:\n node = self.cachemap[key]\n node = self.c...
<|body_start_0|> self.cap = capacity self.cache = LinkedList(capacity) self.cachemap = {} <|end_body_0|> <|body_start_1|> if key in self.cachemap: node = self.cachemap[key] self.cache.modify_and_move(key, node.value, node) return node.value el...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_016552
3,111
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: nothing", "name": "set", "sig...
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): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing
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): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing <|skeleton|> cla...
9d2acde4c84265e25457e0ba88c0b0230188c42d
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.cap = capacity self.cache = LinkedList(capacity) self.cachemap = {} def get(self, key): """:rtype: int""" if key in self.cachemap: node = self.cachemap[key] self....
the_stack_v2_python_sparse
leetcode/lru_cache/sol.py
goelhardik/programming
train
0
4beef4d67f7c3db51aab01fad4f8dd44c18c4539
[ "if not self.data.get('tags'):\n raise PolicyValidationError('Must specify tags')\nreturn self", "params = {'Resource': self.manager.source.get_resource_qcs([resource])[0], 'ReplaceTags': []}\ntags = instances_tags.get(resource['InstanceId'])\nfor tag in tags:\n if tag['TagKey'] in self.data.get('tags'):\n ...
<|body_start_0|> if not self.data.get('tags'): raise PolicyValidationError('Must specify tags') return self <|end_body_0|> <|body_start_1|> params = {'Resource': self.manager.source.get_resource_qcs([resource])[0], 'ReplaceTags': []} tags = instances_tags.get(resource['Insta...
Action to copy tags from instance to cbs resources which are attached to it :example: .. code-block:: yaml policies: - name: copy_instance_tags resource: tencentcloud.cbs filters: - DiskState: ATTACHED - type: value key: 'InstanceIdList[0]' value: not-null actions: - type: copy-instance-tags tags: - test_pro_16 - test_...
CbsCopyInstanceTagsAction
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CbsCopyInstanceTagsAction: """Action to copy tags from instance to cbs resources which are attached to it :example: .. code-block:: yaml policies: - name: copy_instance_tags resource: tencentcloud.cbs filters: - DiskState: ATTACHED - type: value key: 'InstanceIdList[0]' value: not-null actions: -...
stack_v2_sparse_classes_36k_train_016553
4,415
permissive
[ { "docstring": "validate", "name": "validate", "signature": "def validate(self)" }, { "docstring": "get cbs tag request params,single resource operation https://cloud.tencent.com/document/api/651/35322", "name": "_get_tag_request_params", "signature": "def _get_tag_request_params(self, r...
4
null
Implement the Python class `CbsCopyInstanceTagsAction` described below. Class description: Action to copy tags from instance to cbs resources which are attached to it :example: .. code-block:: yaml policies: - name: copy_instance_tags resource: tencentcloud.cbs filters: - DiskState: ATTACHED - type: value key: 'Instan...
Implement the Python class `CbsCopyInstanceTagsAction` described below. Class description: Action to copy tags from instance to cbs resources which are attached to it :example: .. code-block:: yaml policies: - name: copy_instance_tags resource: tencentcloud.cbs filters: - DiskState: ATTACHED - type: value key: 'Instan...
27563cf4571040f923124e1acb2463f11e372225
<|skeleton|> class CbsCopyInstanceTagsAction: """Action to copy tags from instance to cbs resources which are attached to it :example: .. code-block:: yaml policies: - name: copy_instance_tags resource: tencentcloud.cbs filters: - DiskState: ATTACHED - type: value key: 'InstanceIdList[0]' value: not-null actions: -...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CbsCopyInstanceTagsAction: """Action to copy tags from instance to cbs resources which are attached to it :example: .. code-block:: yaml policies: - name: copy_instance_tags resource: tencentcloud.cbs filters: - DiskState: ATTACHED - type: value key: 'InstanceIdList[0]' value: not-null actions: - type: copy-i...
the_stack_v2_python_sparse
tools/c7n_tencentcloud/c7n_tencentcloud/resources/cbs.py
cloud-custodian/cloud-custodian
train
3,327
3287ae153ab25303162efed0416b0f17baa6d33d
[ "field = 'sql'\nvalue = '*'\nsql_steps = [step for step in self.all_steps if self.contains_value(step, field, value)]\nself.add_all_issues(sql_steps, self.WARNINGS, self.issue_messages.select_star)", "self.limits_set()\nself.select_star()\nself.lazy_conversion('lazy_conversion_active')\nreturn self.issues" ]
<|body_start_0|> field = 'sql' value = '*' sql_steps = [step for step in self.all_steps if self.contains_value(step, field, value)] self.add_all_issues(sql_steps, self.WARNINGS, self.issue_messages.select_star) <|end_body_0|> <|body_start_1|> self.limits_set() self.selec...
Models the TableInput step. Relies heavily on members created in parent class
TableInput
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TableInput: """Models the TableInput step. Relies heavily on members created in parent class""" def select_star(self): """Check if select * is used :return: None""" <|body_0|> def run_tests(self): """Run all tests in class :return: issues from test""" <|b...
stack_v2_sparse_classes_36k_train_016554
805
no_license
[ { "docstring": "Check if select * is used :return: None", "name": "select_star", "signature": "def select_star(self)" }, { "docstring": "Run all tests in class :return: issues from test", "name": "run_tests", "signature": "def run_tests(self)" } ]
2
stack_v2_sparse_classes_30k_train_003792
Implement the Python class `TableInput` described below. Class description: Models the TableInput step. Relies heavily on members created in parent class Method signatures and docstrings: - def select_star(self): Check if select * is used :return: None - def run_tests(self): Run all tests in class :return: issues fro...
Implement the Python class `TableInput` described below. Class description: Models the TableInput step. Relies heavily on members created in parent class Method signatures and docstrings: - def select_star(self): Check if select * is used :return: None - def run_tests(self): Run all tests in class :return: issues fro...
8ec68096770f26027d0f95600ce7cc53eb944603
<|skeleton|> class TableInput: """Models the TableInput step. Relies heavily on members created in parent class""" def select_star(self): """Check if select * is used :return: None""" <|body_0|> def run_tests(self): """Run all tests in class :return: issues from test""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TableInput: """Models the TableInput step. Relies heavily on members created in parent class""" def select_star(self): """Check if select * is used :return: None""" field = 'sql' value = '*' sql_steps = [step for step in self.all_steps if self.contains_value(step, field, v...
the_stack_v2_python_sparse
git/kettle_validation/classes/TableInputTrans.py
overtron/code-quality
train
1
edc0a786abb99111d9ff9abed7611cadbdbbf6e7
[ "self._title = turtle._CFG['title']\nself._root = turtle._Root()\nself._root.title(self._title)\nself._root.ondestroy(self._destroy)\ncanvwidth = turtle._CFG['canvwidth']\ncanvheight = turtle._CFG['canvheight']\nself._root.setupcanvas(width, height, canvwidth, canvheight)\nself._canvas = self._root._getcanvas()\ntu...
<|body_start_0|> self._title = turtle._CFG['title'] self._root = turtle._Root() self._root.title(self._title) self._root.ondestroy(self._destroy) canvwidth = turtle._CFG['canvwidth'] canvheight = turtle._CFG['canvheight'] self._root.setupcanvas(width, height, canv...
This is an nternal private class to emulate the Screen singleton :ivar _root: Reference to the turtle screen root :ivar _canvas: Reference to the internal drawing canvas :ivar _title: Reference to the window title bar
_Window
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _Window: """This is an nternal private class to emulate the Screen singleton :ivar _root: Reference to the turtle screen root :ivar _canvas: Reference to the internal drawing canvas :ivar _title: Reference to the window title bar""" def __init__(self, x=100, y=100, width=800, height=800): ...
stack_v2_sparse_classes_36k_train_016555
15,965
no_license
[ { "docstring": "Creates a copy of turtle.Screen, as a non-singleton :return: a copy of turtle.Screen, as a non-singleton :param x: initial x coordinate (default 0) :type x: ``int`` >= 0 :param y: initial y coordinate (default 0) :type y: ``int`` >= 0 :param width: initial window width (default 800) :type width:...
3
stack_v2_sparse_classes_30k_train_004296
Implement the Python class `_Window` described below. Class description: This is an nternal private class to emulate the Screen singleton :ivar _root: Reference to the turtle screen root :ivar _canvas: Reference to the internal drawing canvas :ivar _title: Reference to the window title bar Method signatures and docst...
Implement the Python class `_Window` described below. Class description: This is an nternal private class to emulate the Screen singleton :ivar _root: Reference to the turtle screen root :ivar _canvas: Reference to the internal drawing canvas :ivar _title: Reference to the window title bar Method signatures and docst...
1b85193ca611aeadabd5cc6d244fce699e924e72
<|skeleton|> class _Window: """This is an nternal private class to emulate the Screen singleton :ivar _root: Reference to the turtle screen root :ivar _canvas: Reference to the internal drawing canvas :ivar _title: Reference to the window title bar""" def __init__(self, x=100, y=100, width=800, height=800): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _Window: """This is an nternal private class to emulate the Screen singleton :ivar _root: Reference to the turtle screen root :ivar _canvas: Reference to the internal drawing canvas :ivar _title: Reference to the window title bar""" def __init__(self, x=100, y=100, width=800, height=800): """Crea...
the_stack_v2_python_sparse
data/addins/Lib/site-packages/cornell/tkturtle/window.py
Jasonh90/Invaders
train
0
73d6876ab2f4c693c3d9b527025b745ef7541097
[ "self._nodes = []\nself._edges = []\nself._num_nodes = 0", "self._num_nodes += 1\nname = 'node{number}'.format(number=self._num_nodes)\ncode = '{name} [label=\"{label}\"];'.format(name=name, label=label)\nself._nodes.append(code)\nreturn name", "template = '{from_node} -- {to_node};'\ncode = template.format(fro...
<|body_start_0|> self._nodes = [] self._edges = [] self._num_nodes = 0 <|end_body_0|> <|body_start_1|> self._num_nodes += 1 name = 'node{number}'.format(number=self._num_nodes) code = '{name} [label="{label}"];'.format(name=name, label=label) self._nodes.append(c...
Clase utilizada para la generación de grafos en formato Graphviz DOT.
DotGenerator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DotGenerator: """Clase utilizada para la generación de grafos en formato Graphviz DOT.""" def __init__(self): """Esta clase es utilizada en la generación de código Graphivz DOT a partir de un árbol de sintáxis abstracta de un programa Tiger.""" <|body_0|> def add_node(se...
stack_v2_sparse_classes_36k_train_016556
2,786
permissive
[ { "docstring": "Esta clase es utilizada en la generación de código Graphivz DOT a partir de un árbol de sintáxis abstracta de un programa Tiger.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Añade un nuevo nodo al grafo actualmente en creación. @type label: C{str} @p...
4
stack_v2_sparse_classes_30k_test_001071
Implement the Python class `DotGenerator` described below. Class description: Clase utilizada para la generación de grafos en formato Graphviz DOT. Method signatures and docstrings: - def __init__(self): Esta clase es utilizada en la generación de código Graphivz DOT a partir de un árbol de sintáxis abstracta de un p...
Implement the Python class `DotGenerator` described below. Class description: Clase utilizada para la generación de grafos en formato Graphviz DOT. Method signatures and docstrings: - def __init__(self): Esta clase es utilizada en la generación de código Graphivz DOT a partir de un árbol de sintáxis abstracta de un p...
35c44d14775bf69ed6689b708b98d6d1ca533ba0
<|skeleton|> class DotGenerator: """Clase utilizada para la generación de grafos en formato Graphviz DOT.""" def __init__(self): """Esta clase es utilizada en la generación de código Graphivz DOT a partir de un árbol de sintáxis abstracta de un programa Tiger.""" <|body_0|> def add_node(se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DotGenerator: """Clase utilizada para la generación de grafos en formato Graphviz DOT.""" def __init__(self): """Esta clase es utilizada en la generación de código Graphivz DOT a partir de un árbol de sintáxis abstracta de un programa Tiger.""" self._nodes = [] self._edges = [] ...
the_stack_v2_python_sparse
packages/pytiger2c/dot.py
yasserglez/pytiger2c
train
2
1e0d2d967370147c946c3c9a50f847b33de3a455
[ "logging.info('开始编译模拟器...')\ncompile_emu_cmd_list = settings.compile_emu_cmd.split(';')\nfor compile_emu_cmd in compile_emu_cmd_list:\n return_code = self.make_compile(compile_emu_cmd, settings.compile_emu_env)\n if not return_code:\n logging.error('编译模拟器失败。')\n return return_code\n else:\n ...
<|body_start_0|> logging.info('开始编译模拟器...') compile_emu_cmd_list = settings.compile_emu_cmd.split(';') for compile_emu_cmd in compile_emu_cmd_list: return_code = self.make_compile(compile_emu_cmd, settings.compile_emu_env) if not return_code: logging.error...
Compile_Emulator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Compile_Emulator: def compile_emulator(self): """Description: make compile emulator. Return: (tool)""" <|body_0|> def clean_emulator(self): """Description: make clean emulator. Return: (tool)""" <|body_1|> def install_sdk(self): """Description: i...
stack_v2_sparse_classes_36k_train_016557
2,665
no_license
[ { "docstring": "Description: make compile emulator. Return: (tool)", "name": "compile_emulator", "signature": "def compile_emulator(self)" }, { "docstring": "Description: make clean emulator. Return: (tool)", "name": "clean_emulator", "signature": "def clean_emulator(self)" }, { ...
3
null
Implement the Python class `Compile_Emulator` described below. Class description: Implement the Compile_Emulator class. Method signatures and docstrings: - def compile_emulator(self): Description: make compile emulator. Return: (tool) - def clean_emulator(self): Description: make clean emulator. Return: (tool) - def ...
Implement the Python class `Compile_Emulator` described below. Class description: Implement the Compile_Emulator class. Method signatures and docstrings: - def compile_emulator(self): Description: make compile emulator. Return: (tool) - def clean_emulator(self): Description: make clean emulator. Return: (tool) - def ...
9384b5cbe13a71e12fddfe952cd9c4e275917eeb
<|skeleton|> class Compile_Emulator: def compile_emulator(self): """Description: make compile emulator. Return: (tool)""" <|body_0|> def clean_emulator(self): """Description: make clean emulator. Return: (tool)""" <|body_1|> def install_sdk(self): """Description: i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Compile_Emulator: def compile_emulator(self): """Description: make compile emulator. Return: (tool)""" logging.info('开始编译模拟器...') compile_emu_cmd_list = settings.compile_emu_cmd.split(';') for compile_emu_cmd in compile_emu_cmd_list: return_code = self.make_compile(...
the_stack_v2_python_sparse
suntest/build/compile_emulator.py
berniehuang/autotest
train
0
01937e90e33bc2dd7dc01a0f4599458b8d7e76d2
[ "if self.settings.get('debug') is True:\n self.set_header('Access-Control-Allow-Origin', '*')\n self.set_header('Access-Control-Allow-Headers', 'duck-token')\n self.set_header('Access-Control-Allow-Methods', 'DELETE, PUT, POST, GET, OPTIONS')", "if self.settings.get('debug') is True:\n self.set_status...
<|body_start_0|> if self.settings.get('debug') is True: self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Access-Control-Allow-Headers', 'duck-token') self.set_header('Access-Control-Allow-Methods', 'DELETE, PUT, POST, GET, OPTIONS') <|end_body_0|> <|body_...
allow for development
BaseHandler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseHandler: """allow for development""" def set_default_headers(self): """allow access for development""" <|body_0|> def options(self, *args, **kwargs): """allow dev request""" <|body_1|> <|end_skeleton|> <|body_start_0|> if self.settings.get('...
stack_v2_sparse_classes_36k_train_016558
813
permissive
[ { "docstring": "allow access for development", "name": "set_default_headers", "signature": "def set_default_headers(self)" }, { "docstring": "allow dev request", "name": "options", "signature": "def options(self, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_016933
Implement the Python class `BaseHandler` described below. Class description: allow for development Method signatures and docstrings: - def set_default_headers(self): allow access for development - def options(self, *args, **kwargs): allow dev request
Implement the Python class `BaseHandler` described below. Class description: allow for development Method signatures and docstrings: - def set_default_headers(self): allow access for development - def options(self, *args, **kwargs): allow dev request <|skeleton|> class BaseHandler: """allow for development""" ...
e6d0e62d378bd2d9ed0cd5ce4bc7ab3476b86020
<|skeleton|> class BaseHandler: """allow for development""" def set_default_headers(self): """allow access for development""" <|body_0|> def options(self, *args, **kwargs): """allow dev request""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseHandler: """allow for development""" def set_default_headers(self): """allow access for development""" if self.settings.get('debug') is True: self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Access-Control-Allow-Headers', 'duck-token') ...
the_stack_v2_python_sparse
duckdown/handlers/base_handler.py
blueshed/duckdown
train
0
f0f7ebdd129fed0c1399de3884d9dbb04b007df9
[ "try:\n iter(obj)\n return True\nexcept TypeError:\n return False", "if not isinstance(obj, list) and cls.is_iterable(obj):\n obj = list(obj)\nreturn obj" ]
<|body_start_0|> try: iter(obj) return True except TypeError: return False <|end_body_0|> <|body_start_1|> if not isinstance(obj, list) and cls.is_iterable(obj): obj = list(obj) return obj <|end_body_1|>
TypeUtil
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TypeUtil: def is_iterable(cls, obj): """Determines if obj is iterable. Useful when writing functions that can accept multiple types of input (list, tuple, ndarray, iterator). Pairs well with convert_to_list.""" <|body_0|> def convert_to_list(cls, obj): """Converts ob...
stack_v2_sparse_classes_36k_train_016559
680
permissive
[ { "docstring": "Determines if obj is iterable. Useful when writing functions that can accept multiple types of input (list, tuple, ndarray, iterator). Pairs well with convert_to_list.", "name": "is_iterable", "signature": "def is_iterable(cls, obj)" }, { "docstring": "Converts obj to a list if i...
2
stack_v2_sparse_classes_30k_train_007522
Implement the Python class `TypeUtil` described below. Class description: Implement the TypeUtil class. Method signatures and docstrings: - def is_iterable(cls, obj): Determines if obj is iterable. Useful when writing functions that can accept multiple types of input (list, tuple, ndarray, iterator). Pairs well with ...
Implement the Python class `TypeUtil` described below. Class description: Implement the TypeUtil class. Method signatures and docstrings: - def is_iterable(cls, obj): Determines if obj is iterable. Useful when writing functions that can accept multiple types of input (list, tuple, ndarray, iterator). Pairs well with ...
1279d2ea65fa7bbeb4d18ab80f7f77685df553b8
<|skeleton|> class TypeUtil: def is_iterable(cls, obj): """Determines if obj is iterable. Useful when writing functions that can accept multiple types of input (list, tuple, ndarray, iterator). Pairs well with convert_to_list.""" <|body_0|> def convert_to_list(cls, obj): """Converts ob...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TypeUtil: def is_iterable(cls, obj): """Determines if obj is iterable. Useful when writing functions that can accept multiple types of input (list, tuple, ndarray, iterator). Pairs well with convert_to_list.""" try: iter(obj) return True except TypeError: ...
the_stack_v2_python_sparse
data-science-ipython-notebooks/python-data/type_util.py
amirothman/scikit-learn-course
train
2
c02c5e3b7a2546c91c6d0fa455f4163900f50a4d
[ "self.numiters = numiters\nself.damp = damp\nself.dist_thresh = dist_thresh", "if not isinstance(maps_pointclouds, Pointclouds):\n raise TypeError('Expected maps_pointclouds to be of type gradslam.Pointclouds. Got {0}.'.format(type(maps_pointclouds)))\nif not isinstance(frames_pointclouds, Pointclouds):\n r...
<|body_start_0|> self.numiters = numiters self.damp = damp self.dist_thresh = dist_thresh <|end_body_0|> <|body_start_1|> if not isinstance(maps_pointclouds, Pointclouds): raise TypeError('Expected maps_pointclouds to be of type gradslam.Pointclouds. Got {0}.'.format(type(ma...
ICP odometry provider using a point-to-plane error metric. Computes the relative transformation between a pair of `gradslam.Pointclouds` objects using ICP (Iterative Closest Point). Uses LM (Levenberg-Marquardt) solver.
ICPOdometryProvider
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ICPOdometryProvider: """ICP odometry provider using a point-to-plane error metric. Computes the relative transformation between a pair of `gradslam.Pointclouds` objects using ICP (Iterative Closest Point). Uses LM (Levenberg-Marquardt) solver.""" def __init__(self, numiters: int=20, damp: fl...
stack_v2_sparse_classes_36k_train_016560
3,691
permissive
[ { "docstring": "Initializes internal ICPOdometryProvider state. Args: numiters (int): Number of iterations to run the optimization for. Default: 20 damp (float or torch.Tensor): Damping coefficient for nonlinear least-squares. Default: 1e-8 dist_thresh (float or int or None): Distance threshold for removing `sr...
2
stack_v2_sparse_classes_30k_train_012206
Implement the Python class `ICPOdometryProvider` described below. Class description: ICP odometry provider using a point-to-plane error metric. Computes the relative transformation between a pair of `gradslam.Pointclouds` objects using ICP (Iterative Closest Point). Uses LM (Levenberg-Marquardt) solver. Method signat...
Implement the Python class `ICPOdometryProvider` described below. Class description: ICP odometry provider using a point-to-plane error metric. Computes the relative transformation between a pair of `gradslam.Pointclouds` objects using ICP (Iterative Closest Point). Uses LM (Levenberg-Marquardt) solver. Method signat...
7fb2891b8ad79dc3c89f576fdb80c9e09b5124ea
<|skeleton|> class ICPOdometryProvider: """ICP odometry provider using a point-to-plane error metric. Computes the relative transformation between a pair of `gradslam.Pointclouds` objects using ICP (Iterative Closest Point). Uses LM (Levenberg-Marquardt) solver.""" def __init__(self, numiters: int=20, damp: fl...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ICPOdometryProvider: """ICP odometry provider using a point-to-plane error metric. Computes the relative transformation between a pair of `gradslam.Pointclouds` objects using ICP (Iterative Closest Point). Uses LM (Levenberg-Marquardt) solver.""" def __init__(self, numiters: int=20, damp: float=1e-08, di...
the_stack_v2_python_sparse
gradslam/odometry/icp.py
saryazdi/gradslam
train
8
04b26dc0a3f3b1520a8361f9a086bebc8d3d6400
[ "self.name = name\nself.mime = mime\nhash_ = hashlib.sha256()\nhash_.update(content)\nself.hash = hash_.digest()\ndata_dir = app.config.get_path('data')\nhash_hex = binascii.hexlify(self.hash).decode('ascii')\ndir1 = os.path.join(data_dir, hash_hex[0])\ndir2 = os.path.join(dir1, hash_hex[1])\npath = os.path.join(di...
<|body_start_0|> self.name = name self.mime = mime hash_ = hashlib.sha256() hash_.update(content) self.hash = hash_.digest() data_dir = app.config.get_path('data') hash_hex = binascii.hexlify(self.hash).decode('ascii') dir1 = os.path.join(data_dir, hash_he...
Data model for a file stored in the file system. Files are stored in a content-addressable file system: a SHA-2 hash of the content determines the path where it is stored. For example, a file with hash e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 is stored in data/e/3/b0c44298fc1c149afbf4c8996fb9242...
File
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class File: """Data model for a file stored in the file system. Files are stored in a content-addressable file system: a SHA-2 hash of the content determines the path where it is stored. For example, a file with hash e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 is stored in data/e/3...
stack_v2_sparse_classes_36k_train_016561
1,873
no_license
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self, name, mime, content)" }, { "docstring": "Return path to the file relative to the data directory.", "name": "relpath", "signature": "def relpath(self)" } ]
2
stack_v2_sparse_classes_30k_train_010054
Implement the Python class `File` described below. Class description: Data model for a file stored in the file system. Files are stored in a content-addressable file system: a SHA-2 hash of the content determines the path where it is stored. For example, a file with hash e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934...
Implement the Python class `File` described below. Class description: Data model for a file stored in the file system. Files are stored in a content-addressable file system: a SHA-2 hash of the content determines the path where it is stored. For example, a file with hash e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934...
ded575313c0ef9b09640689f5af50a5a636e17a8
<|skeleton|> class File: """Data model for a file stored in the file system. Files are stored in a content-addressable file system: a SHA-2 hash of the content determines the path where it is stored. For example, a file with hash e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 is stored in data/e/3...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class File: """Data model for a file stored in the file system. Files are stored in a content-addressable file system: a SHA-2 hash of the content determines the path where it is stored. For example, a file with hash e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 is stored in data/e/3/b0c44298fc1c...
the_stack_v2_python_sparse
lib/model/file.py
TeamHG-Memex/quickpin
train
6
8cd9e5269e785ce6ce6e2d9b33840e85c1a2da2e
[ "PhongMaterial.__init__(self, baseColor, ambient, diffuse, specular, reflection, smoothness)\nself.otherColor = otherColor\nself.checkSize = checkSize", "coordinates = point.scale(1.0 / self.checkSize).coordinates\nif sum([int(abs(t) + 0.5) for t in coordinates]) % 2:\n return self.otherColor\nreturn self.colo...
<|body_start_0|> PhongMaterial.__init__(self, baseColor, ambient, diffuse, specular, reflection, smoothness) self.otherColor = otherColor self.checkSize = checkSize <|end_body_0|> <|body_start_1|> coordinates = point.scale(1.0 / self.checkSize).coordinates if sum([int(abs(t) + 0...
CheckerboardMaterial
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CheckerboardMaterial: def __init__(self, baseColor=Color(1, 1, 1), otherColor=Color(0.1, 0.1, 0.1), ambient=0.1, diffuse=0.8, specular=0.2, reflection=0.2, smoothness=0.5, checkSize=2.0): """@param baseColor: erste Farbe des Schachbretts @param otherColor: zweite Farbe des Schachbretts @...
stack_v2_sparse_classes_36k_train_016562
1,496
no_license
[ { "docstring": "@param baseColor: erste Farbe des Schachbretts @param otherColor: zweite Farbe des Schachbretts @param ambient: konstanter ambienter Anteil <= 1 @param diffuse: diffuser Anteil <= 1 @param specular: spekularer Anteil <= 1 specular + diffuse <= 1 @param reflection: reflection <= 1, hat einfluss a...
2
stack_v2_sparse_classes_30k_train_020051
Implement the Python class `CheckerboardMaterial` described below. Class description: Implement the CheckerboardMaterial class. Method signatures and docstrings: - def __init__(self, baseColor=Color(1, 1, 1), otherColor=Color(0.1, 0.1, 0.1), ambient=0.1, diffuse=0.8, specular=0.2, reflection=0.2, smoothness=0.5, chec...
Implement the Python class `CheckerboardMaterial` described below. Class description: Implement the CheckerboardMaterial class. Method signatures and docstrings: - def __init__(self, baseColor=Color(1, 1, 1), otherColor=Color(0.1, 0.1, 0.1), ambient=0.1, diffuse=0.8, specular=0.2, reflection=0.2, smoothness=0.5, chec...
2e4e93ad6c84326761da8cc78008cd185090faa6
<|skeleton|> class CheckerboardMaterial: def __init__(self, baseColor=Color(1, 1, 1), otherColor=Color(0.1, 0.1, 0.1), ambient=0.1, diffuse=0.8, specular=0.2, reflection=0.2, smoothness=0.5, checkSize=2.0): """@param baseColor: erste Farbe des Schachbretts @param otherColor: zweite Farbe des Schachbretts @...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CheckerboardMaterial: def __init__(self, baseColor=Color(1, 1, 1), otherColor=Color(0.1, 0.1, 0.1), ambient=0.1, diffuse=0.8, specular=0.2, reflection=0.2, smoothness=0.5, checkSize=2.0): """@param baseColor: erste Farbe des Schachbretts @param otherColor: zweite Farbe des Schachbretts @param ambient:...
the_stack_v2_python_sparse
renderer/material/checkerboard.py
ccaspers/RayTracer
train
2
584ef1e0ac294cc18b49d16f8eb1bf79236d01c8
[ "if value is None:\n return value\nif isinstance(value, datetime.datetime):\n if settings.USE_TZ and timezone.is_aware(value):\n default_timezone = timezone.get_default_timezone()\n value = timezone.make_naive(value, default_timezone)\n return value.date()\nif isinstance(value, datetime.date)...
<|body_start_0|> if value is None: return value if isinstance(value, datetime.datetime): if settings.USE_TZ and timezone.is_aware(value): default_timezone = timezone.get_default_timezone() value = timezone.make_naive(value, default_timezone) ...
EncryptedDateField
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EncryptedDateField: def to_python(self, value): """Returns the decrypted date IF the private key is found, otherwise returns the encrypted value. Value comes from DB as a hash (e.g. <hash_prefix><hashed_value>). If DB value is being acccessed for the first time, value is not an encrypted...
stack_v2_sparse_classes_36k_train_016563
3,108
no_license
[ { "docstring": "Returns the decrypted date IF the private key is found, otherwise returns the encrypted value. Value comes from DB as a hash (e.g. <hash_prefix><hashed_value>). If DB value is being acccessed for the first time, value is not an encrypted value (not a prefix+hashed_value).", "name": "to_pytho...
2
null
Implement the Python class `EncryptedDateField` described below. Class description: Implement the EncryptedDateField class. Method signatures and docstrings: - def to_python(self, value): Returns the decrypted date IF the private key is found, otherwise returns the encrypted value. Value comes from DB as a hash (e.g....
Implement the Python class `EncryptedDateField` described below. Class description: Implement the EncryptedDateField class. Method signatures and docstrings: - def to_python(self, value): Returns the decrypted date IF the private key is found, otherwise returns the encrypted value. Value comes from DB as a hash (e.g....
4f75336ff572babd39d431185677a65bece9e524
<|skeleton|> class EncryptedDateField: def to_python(self, value): """Returns the decrypted date IF the private key is found, otherwise returns the encrypted value. Value comes from DB as a hash (e.g. <hash_prefix><hashed_value>). If DB value is being acccessed for the first time, value is not an encrypted...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EncryptedDateField: def to_python(self, value): """Returns the decrypted date IF the private key is found, otherwise returns the encrypted value. Value comes from DB as a hash (e.g. <hash_prefix><hashed_value>). If DB value is being acccessed for the first time, value is not an encrypted value (not a ...
the_stack_v2_python_sparse
edc/core/crypto_fields/fields/encrypted_date_field.py
botswana-harvard/edc
train
0
44b9f5b2af9f84839387a7cf1f987bc5c4ca82a5
[ "self.ai_settings = ai_settings\nself.reset_stats()\nself.game_active = False\nself.high_score = 0", "self.ships_left = self.ai_settings.ship_limit\nself.score = 0\nself.level = 1" ]
<|body_start_0|> self.ai_settings = ai_settings self.reset_stats() self.game_active = False self.high_score = 0 <|end_body_0|> <|body_start_1|> self.ships_left = self.ai_settings.ship_limit self.score = 0 self.level = 1 <|end_body_1|>
跟踪游戏的统计信息
GameStats
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GameStats: """跟踪游戏的统计信息""" def __init__(self, ai_settings): """初始化统计信息""" <|body_0|> def reset_stats(self): """初始化在游戏运行期间可能变化的统计信息""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.ai_settings = ai_settings self.reset_stats() ...
stack_v2_sparse_classes_36k_train_016564
708
no_license
[ { "docstring": "初始化统计信息", "name": "__init__", "signature": "def __init__(self, ai_settings)" }, { "docstring": "初始化在游戏运行期间可能变化的统计信息", "name": "reset_stats", "signature": "def reset_stats(self)" } ]
2
null
Implement the Python class `GameStats` described below. Class description: 跟踪游戏的统计信息 Method signatures and docstrings: - def __init__(self, ai_settings): 初始化统计信息 - def reset_stats(self): 初始化在游戏运行期间可能变化的统计信息
Implement the Python class `GameStats` described below. Class description: 跟踪游戏的统计信息 Method signatures and docstrings: - def __init__(self, ai_settings): 初始化统计信息 - def reset_stats(self): 初始化在游戏运行期间可能变化的统计信息 <|skeleton|> class GameStats: """跟踪游戏的统计信息""" def __init__(self, ai_settings): """初始化统计信息""" ...
fb305cd6512a6ec410770c14e6121e7c6d4bd23a
<|skeleton|> class GameStats: """跟踪游戏的统计信息""" def __init__(self, ai_settings): """初始化统计信息""" <|body_0|> def reset_stats(self): """初始化在游戏运行期间可能变化的统计信息""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GameStats: """跟踪游戏的统计信息""" def __init__(self, ai_settings): """初始化统计信息""" self.ai_settings = ai_settings self.reset_stats() self.game_active = False self.high_score = 0 def reset_stats(self): """初始化在游戏运行期间可能变化的统计信息""" self.ships_left = self.ai_...
the_stack_v2_python_sparse
PythonCrashCourse/ch12/game_stats.py
hujiangong/Python_Study
train
3
69a7db37f552a29e804b6bdf8cd3878c590c8602
[ "_LOGGER.debug('Enable max range charging: %s', self.name)\nawait self.tesla_device.set_max()\nself.async_write_ha_state()", "_LOGGER.debug('Disable max range charging: %s', self.name)\nawait self.tesla_device.set_standard()\nself.async_write_ha_state()", "if self.tesla_device.is_maxrange() is None:\n return...
<|body_start_0|> _LOGGER.debug('Enable max range charging: %s', self.name) await self.tesla_device.set_max() self.async_write_ha_state() <|end_body_0|> <|body_start_1|> _LOGGER.debug('Disable max range charging: %s', self.name) await self.tesla_device.set_standard() self...
Representation of a Tesla max range charging switch.
RangeSwitch
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RangeSwitch: """Representation of a Tesla max range charging switch.""" async def async_turn_on(self, **kwargs): """Send the on command.""" <|body_0|> async def async_turn_off(self, **kwargs): """Send the off command.""" <|body_1|> def is_on(self): ...
stack_v2_sparse_classes_36k_train_016565
4,636
permissive
[ { "docstring": "Send the on command.", "name": "async_turn_on", "signature": "async def async_turn_on(self, **kwargs)" }, { "docstring": "Send the off command.", "name": "async_turn_off", "signature": "async def async_turn_off(self, **kwargs)" }, { "docstring": "Get whether the s...
3
stack_v2_sparse_classes_30k_train_000205
Implement the Python class `RangeSwitch` described below. Class description: Representation of a Tesla max range charging switch. Method signatures and docstrings: - async def async_turn_on(self, **kwargs): Send the on command. - async def async_turn_off(self, **kwargs): Send the off command. - def is_on(self): Get w...
Implement the Python class `RangeSwitch` described below. Class description: Representation of a Tesla max range charging switch. Method signatures and docstrings: - async def async_turn_on(self, **kwargs): Send the on command. - async def async_turn_off(self, **kwargs): Send the off command. - def is_on(self): Get w...
2fee32fce03bc49e86cf2e7b741a15621a97cce5
<|skeleton|> class RangeSwitch: """Representation of a Tesla max range charging switch.""" async def async_turn_on(self, **kwargs): """Send the on command.""" <|body_0|> async def async_turn_off(self, **kwargs): """Send the off command.""" <|body_1|> def is_on(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RangeSwitch: """Representation of a Tesla max range charging switch.""" async def async_turn_on(self, **kwargs): """Send the on command.""" _LOGGER.debug('Enable max range charging: %s', self.name) await self.tesla_device.set_max() self.async_write_ha_state() async de...
the_stack_v2_python_sparse
homeassistant/components/tesla/switch.py
BenWoodford/home-assistant
train
11
ee4d41cd44173eb8bf84b8d711eaad91045a711d
[ "if batch_dims < 0:\n raise ValueError('Batch dims must be non-negative.')\nself._batch_dims = batch_dims\nself._original_tensor_shape = None", "with tf.name_scope('batch_flatten'):\n if self._batch_dims == 1:\n return tensor\n self._original_tensor_shape = composite.shape(tensor)\n if tensor.s...
<|body_start_0|> if batch_dims < 0: raise ValueError('Batch dims must be non-negative.') self._batch_dims = batch_dims self._original_tensor_shape = None <|end_body_0|> <|body_start_1|> with tf.name_scope('batch_flatten'): if self._batch_dims == 1: ...
Facilitates flattening and unflattening batch dims of a tensor. Exposes a pair of matched faltten and unflatten methods. After flattening only 1 batch dimension will be left. This facilitates evaluating networks that expect inputs to have only 1 batch dimension.
BatchSquash
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BatchSquash: """Facilitates flattening and unflattening batch dims of a tensor. Exposes a pair of matched faltten and unflatten methods. After flattening only 1 batch dimension will be left. This facilitates evaluating networks that expect inputs to have only 1 batch dimension.""" def __init...
stack_v2_sparse_classes_36k_train_016566
9,002
permissive
[ { "docstring": "Create two tied ops to flatten and unflatten the front dimensions. Args: batch_dims: Number of batch dimensions the flatten/unflatten ops should handle. Raises: ValueError: if batch dims is negative.", "name": "__init__", "signature": "def __init__(self, batch_dims)" }, { "docstr...
3
stack_v2_sparse_classes_30k_train_020600
Implement the Python class `BatchSquash` described below. Class description: Facilitates flattening and unflattening batch dims of a tensor. Exposes a pair of matched faltten and unflatten methods. After flattening only 1 batch dimension will be left. This facilitates evaluating networks that expect inputs to have onl...
Implement the Python class `BatchSquash` described below. Class description: Facilitates flattening and unflattening batch dims of a tensor. Exposes a pair of matched faltten and unflatten methods. After flattening only 1 batch dimension will be left. This facilitates evaluating networks that expect inputs to have onl...
eca1093d3a047e538f17f6ab92ab4d8144284f23
<|skeleton|> class BatchSquash: """Facilitates flattening and unflattening batch dims of a tensor. Exposes a pair of matched faltten and unflatten methods. After flattening only 1 batch dimension will be left. This facilitates evaluating networks that expect inputs to have only 1 batch dimension.""" def __init...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BatchSquash: """Facilitates flattening and unflattening batch dims of a tensor. Exposes a pair of matched faltten and unflatten methods. After flattening only 1 batch dimension will be left. This facilitates evaluating networks that expect inputs to have only 1 batch dimension.""" def __init__(self, batc...
the_stack_v2_python_sparse
tf_agents/networks/utils.py
tensorflow/agents
train
2,755
9b84f235cb91ebc51cea151fa6501f07d999484e
[ "temp = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)\ncls._createdFiles.add(temp)\nreturn temp", "super(BaseUnitest, cls).tearDownClass()\nfor i in cls._createdFiles:\n if os.path.exists(i):\n if os.path.isdir(i):\n os.rmdir(i)\n else:\n os.remove(i)\ncls._created...
<|body_start_0|> temp = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir) cls._createdFiles.add(temp) return temp <|end_body_0|> <|body_start_1|> super(BaseUnitest, cls).tearDownClass() for i in cls._createdFiles: if os.path.exists(i): if os.pat...
This Class acts as the base for all unitests, supplies a helper method for creating tempfile which will be cleaned up once the class has been shutdown. If you override the tearDownClass method you must call super or at least clean up the _createFiles set
BaseUnitest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseUnitest: """This Class acts as the base for all unitests, supplies a helper method for creating tempfile which will be cleaned up once the class has been shutdown. If you override the tearDownClass method you must call super or at least clean up the _createFiles set""" def createTemp(cls...
stack_v2_sparse_classes_36k_train_016567
1,579
no_license
[ { "docstring": "Create's a temp file and stores it on the class :param suffix: str, the files name suffix :return: str, the temp file path", "name": "createTemp", "signature": "def createTemp(cls, suffix, prefix=None, dir=None)" }, { "docstring": "Cleans up all the temp files that have been crea...
2
stack_v2_sparse_classes_30k_train_020661
Implement the Python class `BaseUnitest` described below. Class description: This Class acts as the base for all unitests, supplies a helper method for creating tempfile which will be cleaned up once the class has been shutdown. If you override the tearDownClass method you must call super or at least clean up the _cre...
Implement the Python class `BaseUnitest` described below. Class description: This Class acts as the base for all unitests, supplies a helper method for creating tempfile which will be cleaned up once the class has been shutdown. If you override the tearDownClass method you must call super or at least clean up the _cre...
eda3105eb39a1e4bcd3757f2a24414831dc8fb13
<|skeleton|> class BaseUnitest: """This Class acts as the base for all unitests, supplies a helper method for creating tempfile which will be cleaned up once the class has been shutdown. If you override the tearDownClass method you must call super or at least clean up the _createFiles set""" def createTemp(cls...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseUnitest: """This Class acts as the base for all unitests, supplies a helper method for creating tempfile which will be cleaned up once the class has been shutdown. If you override the tearDownClass method you must call super or at least clean up the _createFiles set""" def createTemp(cls, suffix, pre...
the_stack_v2_python_sparse
slither/core/test.py
dsparrow27/slither
train
0
e62b74496c87aac076888d250cd87196b15b6f45
[ "selected_severities = self._parameter('severities')\nseverities: dict[str, set[Severity]] = {}\nnr_vulnerabilities: dict[str, int] = {}\nexample_vulnerability = {}\nvulnerabilities = cast(JSONDict, json).get('vulnerabilities', [])\nfor vulnerability in vulnerabilities:\n if (severity := vulnerability['severity'...
<|body_start_0|> selected_severities = self._parameter('severities') severities: dict[str, set[Severity]] = {} nr_vulnerabilities: dict[str, int] = {} example_vulnerability = {} vulnerabilities = cast(JSONDict, json).get('vulnerabilities', []) for vulnerability in vulnera...
Snyk collector for security warnings.
SnykSecurityWarnings
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SnykSecurityWarnings: """Snyk collector for security warnings.""" def _parse_json(self, json: JSON, filename: str) -> Entities: """Parse the direct dependencies with vulnerabilities from the JSON.""" <|body_0|> def __highest_severity(severities: Collection[Severity]) -> ...
stack_v2_sparse_classes_36k_train_016568
2,290
permissive
[ { "docstring": "Parse the direct dependencies with vulnerabilities from the JSON.", "name": "_parse_json", "signature": "def _parse_json(self, json: JSON, filename: str) -> Entities" }, { "docstring": "Return the highest severity from a collection of severities.", "name": "__highest_severity...
2
stack_v2_sparse_classes_30k_train_010888
Implement the Python class `SnykSecurityWarnings` described below. Class description: Snyk collector for security warnings. Method signatures and docstrings: - def _parse_json(self, json: JSON, filename: str) -> Entities: Parse the direct dependencies with vulnerabilities from the JSON. - def __highest_severity(sever...
Implement the Python class `SnykSecurityWarnings` described below. Class description: Snyk collector for security warnings. Method signatures and docstrings: - def _parse_json(self, json: JSON, filename: str) -> Entities: Parse the direct dependencies with vulnerabilities from the JSON. - def __highest_severity(sever...
5d9952bf0bd47895824fa78428d3e4f4d6b5d9b3
<|skeleton|> class SnykSecurityWarnings: """Snyk collector for security warnings.""" def _parse_json(self, json: JSON, filename: str) -> Entities: """Parse the direct dependencies with vulnerabilities from the JSON.""" <|body_0|> def __highest_severity(severities: Collection[Severity]) -> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SnykSecurityWarnings: """Snyk collector for security warnings.""" def _parse_json(self, json: JSON, filename: str) -> Entities: """Parse the direct dependencies with vulnerabilities from the JSON.""" selected_severities = self._parameter('severities') severities: dict[str, set[Sev...
the_stack_v2_python_sparse
components/collector/src/source_collectors/snyk/security_warnings.py
ICTU/quality-time
train
43
9510a83adeb81c80dd396e63d1d809a7368ae555
[ "scores = Scores.objects.all().values()\nothers = Other.objects.all().values()\nscore = [i for i in scores]\nother = [i for i in others]\nrs = score + other\nresult_dict = defaultdict(dict)\nfor d in rs:\n id_ = d['id']\n result_dict[id_].update(d)\nreturn result_dict.values()", "temp_id = params.get('id', ...
<|body_start_0|> scores = Scores.objects.all().values() others = Other.objects.all().values() score = [i for i in scores] other = [i for i in others] rs = score + other result_dict = defaultdict(dict) for d in rs: id_ = d['id'] result_dict[...
成绩页面处理逻辑
ScoreManage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScoreManage: """成绩页面处理逻辑""" def main_score(cls): """成绩显示的主页面""" <|body_0|> def mark_short(cls, params): """批改简答题部分""" <|body_1|> def save_short_score(cls, params): """传入分数并算总分""" <|body_2|> def record_page(cls, params): "...
stack_v2_sparse_classes_36k_train_016569
8,285
no_license
[ { "docstring": "成绩显示的主页面", "name": "main_score", "signature": "def main_score(cls)" }, { "docstring": "批改简答题部分", "name": "mark_short", "signature": "def mark_short(cls, params)" }, { "docstring": "传入分数并算总分", "name": "save_short_score", "signature": "def save_short_score(c...
4
null
Implement the Python class `ScoreManage` described below. Class description: 成绩页面处理逻辑 Method signatures and docstrings: - def main_score(cls): 成绩显示的主页面 - def mark_short(cls, params): 批改简答题部分 - def save_short_score(cls, params): 传入分数并算总分 - def record_page(cls, params): 回溯页面
Implement the Python class `ScoreManage` described below. Class description: 成绩页面处理逻辑 Method signatures and docstrings: - def main_score(cls): 成绩显示的主页面 - def mark_short(cls, params): 批改简答题部分 - def save_short_score(cls, params): 传入分数并算总分 - def record_page(cls, params): 回溯页面 <|skeleton|> class ScoreManage: """成绩页面...
4febccac57bfa5f7ef46f5f57e52206c8b0a57ac
<|skeleton|> class ScoreManage: """成绩页面处理逻辑""" def main_score(cls): """成绩显示的主页面""" <|body_0|> def mark_short(cls, params): """批改简答题部分""" <|body_1|> def save_short_score(cls, params): """传入分数并算总分""" <|body_2|> def record_page(cls, params): "...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScoreManage: """成绩页面处理逻辑""" def main_score(cls): """成绩显示的主页面""" scores = Scores.objects.all().values() others = Other.objects.all().values() score = [i for i in scores] other = [i for i in others] rs = score + other result_dict = defaultdict(dict) ...
the_stack_v2_python_sparse
item/interview/backend/utils.py
soulorman/Python
train
0
bb420c3ec2693ce5b78109d5345a5fd7bfe2935b
[ "shared = SharedObjects.get()\nself.flagmaterial = ba.Material()\nself.flagmaterial.add_actions(conditions=(('we_are_younger_than', 100), 'and', ('they_have_material', shared.object_material)), actions=('modify_node_collision', 'collide', False))\nself.flagmaterial.add_actions(conditions=('they_have_material', shar...
<|body_start_0|> shared = SharedObjects.get() self.flagmaterial = ba.Material() self.flagmaterial.add_actions(conditions=(('we_are_younger_than', 100), 'and', ('they_have_material', shared.object_material)), actions=('modify_node_collision', 'collide', False)) self.flagmaterial.add_actio...
Wraps up media and other resources used by ba.Flags. category: Gameplay Classes A single instance of this is shared between all flags and can be retrieved via bastd.actor.flag.get_factory(). Attributes: flagmaterial The ba.Material applied to all ba.Flags. impact_sound The ba.Sound used when a ba.Flag hits the ground. ...
FlagFactory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FlagFactory: """Wraps up media and other resources used by ba.Flags. category: Gameplay Classes A single instance of this is shared between all flags and can be retrieved via bastd.actor.flag.get_factory(). Attributes: flagmaterial The ba.Material applied to all ba.Flags. impact_sound The ba.Soun...
stack_v2_sparse_classes_36k_train_016570
13,816
permissive
[ { "docstring": "Instantiate a FlagFactory. You shouldn't need to do this; call bastd.actor.flag.get_factory() to get a shared instance.", "name": "__init__", "signature": "def __init__(self) -> None" }, { "docstring": "Get/create a shared FlagFactory instance.", "name": "get", "signature...
2
stack_v2_sparse_classes_30k_train_002719
Implement the Python class `FlagFactory` described below. Class description: Wraps up media and other resources used by ba.Flags. category: Gameplay Classes A single instance of this is shared between all flags and can be retrieved via bastd.actor.flag.get_factory(). Attributes: flagmaterial The ba.Material applied to...
Implement the Python class `FlagFactory` described below. Class description: Wraps up media and other resources used by ba.Flags. category: Gameplay Classes A single instance of this is shared between all flags and can be retrieved via bastd.actor.flag.get_factory(). Attributes: flagmaterial The ba.Material applied to...
3ffeff8ce401a00128363ff08b406471092adaa9
<|skeleton|> class FlagFactory: """Wraps up media and other resources used by ba.Flags. category: Gameplay Classes A single instance of this is shared between all flags and can be retrieved via bastd.actor.flag.get_factory(). Attributes: flagmaterial The ba.Material applied to all ba.Flags. impact_sound The ba.Soun...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FlagFactory: """Wraps up media and other resources used by ba.Flags. category: Gameplay Classes A single instance of this is shared between all flags and can be retrieved via bastd.actor.flag.get_factory(). Attributes: flagmaterial The ba.Material applied to all ba.Flags. impact_sound The ba.Sound used when a...
the_stack_v2_python_sparse
assets/src/ba_data/python/bastd/actor/flag.py
kakekakeka/ballistica
train
2
0ec9b615bcb7d1ec2f76f065e00fab27da08e0ae
[ "result = super().get_lookup_regex(viewset, lookup_prefix)\nlookup_fields = getattr(viewset, 'lookup_fields', None)\nif lookup_fields and (not self.multi):\n lookup_value = getattr(viewset, 'lookup_value_regex', '[^/.]+')\n for lookup_field in lookup_fields[1:]:\n result += f'/(?P<{lookup_field}>{looku...
<|body_start_0|> result = super().get_lookup_regex(viewset, lookup_prefix) lookup_fields = getattr(viewset, 'lookup_fields', None) if lookup_fields and (not self.multi): lookup_value = getattr(viewset, 'lookup_value_regex', '[^/.]+') for lookup_field in lookup_fields[1:]:...
Support multiple lookup keys e.g. /parent_pk/pk
MultiLookupRouter
[ "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiLookupRouter: """Support multiple lookup keys e.g. /parent_pk/pk""" def get_lookup_regex(self, viewset, lookup_prefix=''): """Returns a lookup regex, this extends the default to allow for multiple lookup keys as defined by a viewset.lookup_fields property.""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_016571
7,050
permissive
[ { "docstring": "Returns a lookup regex, this extends the default to allow for multiple lookup keys as defined by a viewset.lookup_fields property.", "name": "get_lookup_regex", "signature": "def get_lookup_regex(self, viewset, lookup_prefix='')" }, { "docstring": "Return a list of URL regexs, th...
2
stack_v2_sparse_classes_30k_train_003888
Implement the Python class `MultiLookupRouter` described below. Class description: Support multiple lookup keys e.g. /parent_pk/pk Method signatures and docstrings: - def get_lookup_regex(self, viewset, lookup_prefix=''): Returns a lookup regex, this extends the default to allow for multiple lookup keys as defined by...
Implement the Python class `MultiLookupRouter` described below. Class description: Support multiple lookup keys e.g. /parent_pk/pk Method signatures and docstrings: - def get_lookup_regex(self, viewset, lookup_prefix=''): Returns a lookup regex, this extends the default to allow for multiple lookup keys as defined by...
e5bdec91cb47179172b515bbcb91701262ff3377
<|skeleton|> class MultiLookupRouter: """Support multiple lookup keys e.g. /parent_pk/pk""" def get_lookup_regex(self, viewset, lookup_prefix=''): """Returns a lookup regex, this extends the default to allow for multiple lookup keys as defined by a viewset.lookup_fields property.""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiLookupRouter: """Support multiple lookup keys e.g. /parent_pk/pk""" def get_lookup_regex(self, viewset, lookup_prefix=''): """Returns a lookup regex, this extends the default to allow for multiple lookup keys as defined by a viewset.lookup_fields property.""" result = super().get_loo...
the_stack_v2_python_sparse
onadata/apps/api/urls/v1_urls.py
onaio/onadata
train
177
2a946758bd61981f99f5e101ac347df3a4096486
[ "def findPalindromeFrom(string, left, right):\n while left >= 0 and right < len(string) and (string[left] == string[right]):\n left -= 1\n right += 1\n return string[left + 1:right]\nif not s:\n return ''\nlongest = ''\nfor mid in range(len(s)):\n sub = findPalindromeFrom(s, mid, mid)\n ...
<|body_start_0|> def findPalindromeFrom(string, left, right): while left >= 0 and right < len(string) and (string[left] == string[right]): left -= 1 right += 1 return string[left + 1:right] if not s: return '' longest = '' ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestPalindrome_Recursive(self, s): """:type s: str :rtype: str""" <|body_0|> def longestPalindrome_TLE(self, s): """:type s: str :rtype: str""" <|body_1|> def longestPalindrome(self, s): """:type s: str :rtype: str""" <|b...
stack_v2_sparse_classes_36k_train_016572
2,160
no_license
[ { "docstring": ":type s: str :rtype: str", "name": "longestPalindrome_Recursive", "signature": "def longestPalindrome_Recursive(self, s)" }, { "docstring": ":type s: str :rtype: str", "name": "longestPalindrome_TLE", "signature": "def longestPalindrome_TLE(self, s)" }, { "docstri...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestPalindrome_Recursive(self, s): :type s: str :rtype: str - def longestPalindrome_TLE(self, s): :type s: str :rtype: str - def longestPalindrome(self, s): :type s: str :...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestPalindrome_Recursive(self, s): :type s: str :rtype: str - def longestPalindrome_TLE(self, s): :type s: str :rtype: str - def longestPalindrome(self, s): :type s: str :...
2d5fa4cd696d5035ea8859befeadc5cc436959c9
<|skeleton|> class Solution: def longestPalindrome_Recursive(self, s): """:type s: str :rtype: str""" <|body_0|> def longestPalindrome_TLE(self, s): """:type s: str :rtype: str""" <|body_1|> def longestPalindrome(self, s): """:type s: str :rtype: str""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestPalindrome_Recursive(self, s): """:type s: str :rtype: str""" def findPalindromeFrom(string, left, right): while left >= 0 and right < len(string) and (string[left] == string[right]): left -= 1 right += 1 return strin...
the_stack_v2_python_sparse
SourceCode/Python/Problem/00005.Longest Palindromic Substring.py
roger6blog/LeetCode
train
0
66c1032ec50d8353cc3b2814d70f4a22a4a40a28
[ "super(Cd, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)\nself.path = path\nself.ret_required = False\nself._re_expected_prompt = None\nif expected_prompt:\n self._re_expected_prompt = CommandTextualGeneric._calculate_prompt(expected_prompt)", "cmd = 'cd'\nif ...
<|body_start_0|> super(Cd, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner) self.path = path self.ret_required = False self._re_expected_prompt = None if expected_prompt: self._re_expected_prompt = CommandTextualGeneric....
Cd
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Cd: def __init__(self, connection, path=None, prompt=None, newline_chars=None, runner=None, expected_prompt=None): """:param connection: moler connection to device :param prompt: start prompt (on system where command cd starts) :param path: path to directory :param expected_prompt: Promp...
stack_v2_sparse_classes_36k_train_016573
3,352
permissive
[ { "docstring": ":param connection: moler connection to device :param prompt: start prompt (on system where command cd starts) :param path: path to directory :param expected_prompt: Prompt after change directory :param newline_chars: Characters to split lines :param runner: Runner to run command", "name": "_...
4
stack_v2_sparse_classes_30k_train_020027
Implement the Python class `Cd` described below. Class description: Implement the Cd class. Method signatures and docstrings: - def __init__(self, connection, path=None, prompt=None, newline_chars=None, runner=None, expected_prompt=None): :param connection: moler connection to device :param prompt: start prompt (on s...
Implement the Python class `Cd` described below. Class description: Implement the Cd class. Method signatures and docstrings: - def __init__(self, connection, path=None, prompt=None, newline_chars=None, runner=None, expected_prompt=None): :param connection: moler connection to device :param prompt: start prompt (on s...
5a7bb06807b6e0124c77040367d0c20f42849a4c
<|skeleton|> class Cd: def __init__(self, connection, path=None, prompt=None, newline_chars=None, runner=None, expected_prompt=None): """:param connection: moler connection to device :param prompt: start prompt (on system where command cd starts) :param path: path to directory :param expected_prompt: Promp...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Cd: def __init__(self, connection, path=None, prompt=None, newline_chars=None, runner=None, expected_prompt=None): """:param connection: moler connection to device :param prompt: start prompt (on system where command cd starts) :param path: path to directory :param expected_prompt: Prompt after change...
the_stack_v2_python_sparse
moler/cmd/unix/cd.py
nokia/moler
train
60
70fe5cb34093e5a9dc70f344c3fe4eae9bde64a6
[ "url = 'testurl.com'\noutput = split_url_for_query(url)\nself.assertEqual(output, ('com.testurl.%', '%'))", "url = 'testurl.com/test'\noutput = split_url_for_query(url)\nself.assertEqual(output, ('com.testurl.%', '%./test%'))", "url = '*.testurl.com/test'\noutput = split_url_for_query(url)\nself.assertEqual(out...
<|body_start_0|> url = 'testurl.com' output = split_url_for_query(url) self.assertEqual(output, ('com.testurl.%', '%')) <|end_body_0|> <|body_start_1|> url = 'testurl.com/test' output = split_url_for_query(url) self.assertEqual(output, ('com.testurl.%', '%./test%')) <|en...
LinksHelpersTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinksHelpersTest: def test_split_url_for_query_1(self): """Given a URL pattern, ensure that our helper function converts it to the expected format for querying replica databases""" <|body_0|> def test_split_url_for_query_2(self): """Given a URL pattern with a path, e...
stack_v2_sparse_classes_36k_train_016574
20,276
permissive
[ { "docstring": "Given a URL pattern, ensure that our helper function converts it to the expected format for querying replica databases", "name": "test_split_url_for_query_1", "signature": "def test_split_url_for_query_1(self)" }, { "docstring": "Given a URL pattern with a path, ensure that our h...
4
stack_v2_sparse_classes_30k_train_016450
Implement the Python class `LinksHelpersTest` described below. Class description: Implement the LinksHelpersTest class. Method signatures and docstrings: - def test_split_url_for_query_1(self): Given a URL pattern, ensure that our helper function converts it to the expected format for querying replica databases - def...
Implement the Python class `LinksHelpersTest` described below. Class description: Implement the LinksHelpersTest class. Method signatures and docstrings: - def test_split_url_for_query_1(self): Given a URL pattern, ensure that our helper function converts it to the expected format for querying replica databases - def...
e536b510482b522e0a804ba9424b58f56b113846
<|skeleton|> class LinksHelpersTest: def test_split_url_for_query_1(self): """Given a URL pattern, ensure that our helper function converts it to the expected format for querying replica databases""" <|body_0|> def test_split_url_for_query_2(self): """Given a URL pattern with a path, e...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinksHelpersTest: def test_split_url_for_query_1(self): """Given a URL pattern, ensure that our helper function converts it to the expected format for querying replica databases""" url = 'testurl.com' output = split_url_for_query(url) self.assertEqual(output, ('com.testurl.%', ...
the_stack_v2_python_sparse
extlinks/links/tests.py
WikipediaLibrary/externallinks
train
6
1c145999b8e07d52087afc7741082020510d35d6
[ "self.preSum = [0] * len(w)\nself.preSum[0] = w[0]\nfor i in range(1, len(w)):\n self.preSum[i] = self.preSum[i - 1] + w[i]", "total = self.preSum[-1]\nrand = random.randint(0, total - 1)\nleft, right = (0, len(self.preSum) - 1)\nwhile left + 1 < right:\n mid = (left + right) // 2\n if rand >= self.preSu...
<|body_start_0|> self.preSum = [0] * len(w) self.preSum[0] = w[0] for i in range(1, len(w)): self.preSum[i] = self.preSum[i - 1] + w[i] <|end_body_0|> <|body_start_1|> total = self.preSum[-1] rand = random.randint(0, total - 1) left, right = (0, len(self.preS...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def __init__(self, w): """:type w: List[int]""" <|body_0|> def pickIndex(self): """:rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.preSum = [0] * len(w) self.preSum[0] = w[0] for i in range(1, len(w)): ...
stack_v2_sparse_classes_36k_train_016575
3,072
no_license
[ { "docstring": ":type w: List[int]", "name": "__init__", "signature": "def __init__(self, w)" }, { "docstring": ":rtype: int", "name": "pickIndex", "signature": "def pickIndex(self)" } ]
2
stack_v2_sparse_classes_30k_train_005825
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def __init__(self, w): :type w: List[int] - def pickIndex(self): :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def __init__(self, w): :type w: List[int] - def pickIndex(self): :rtype: int <|skeleton|> class Solution: def __init__(self, w): """:type w: List[int]""" <|...
6350568d16b0f8c49a020f055bb6d72e2705ea56
<|skeleton|> class Solution: def __init__(self, w): """:type w: List[int]""" <|body_0|> def pickIndex(self): """:rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def __init__(self, w): """:type w: List[int]""" self.preSum = [0] * len(w) self.preSum[0] = w[0] for i in range(1, len(w)): self.preSum[i] = self.preSum[i - 1] + w[i] def pickIndex(self): """:rtype: int""" total = self.preSum[-1] ...
the_stack_v2_python_sparse
co_linkedin/528_Random_Pick_with_Weight.py
vsdrun/lc_public
train
6
c07a401830d632ef7bafa71e103416f0a42c3819
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UnifiedRoleManagementPolicy()", "from .entity import Entity\nfrom .identity import Identity\nfrom .unified_role_management_policy_rule import UnifiedRoleManagementPolicyRule\nfrom .entity import Entity\nfrom .identity import Identity\n...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return UnifiedRoleManagementPolicy() <|end_body_0|> <|body_start_1|> from .entity import Entity from .identity import Identity from .unified_role_management_policy_rule import UnifiedRo...
UnifiedRoleManagementPolicy
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UnifiedRoleManagementPolicy: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleManagementPolicy: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a...
stack_v2_sparse_classes_36k_train_016576
5,220
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UnifiedRoleManagementPolicy", "name": "create_from_discriminator_value", "signature": "def create_from_discr...
3
stack_v2_sparse_classes_30k_train_009438
Implement the Python class `UnifiedRoleManagementPolicy` described below. Class description: Implement the UnifiedRoleManagementPolicy class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleManagementPolicy: Creates a new instance of the appr...
Implement the Python class `UnifiedRoleManagementPolicy` described below. Class description: Implement the UnifiedRoleManagementPolicy class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleManagementPolicy: Creates a new instance of the appr...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class UnifiedRoleManagementPolicy: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleManagementPolicy: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UnifiedRoleManagementPolicy: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleManagementPolicy: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ...
the_stack_v2_python_sparse
msgraph/generated/models/unified_role_management_policy.py
microsoftgraph/msgraph-sdk-python
train
135
74c03562590cb1422291ab704e9c3c27c661cd2e
[ "self.kommunenr_field = kommunenr_field\nself.kommune_navn_field = kommune_navn_field\nself.gardnr_field = gardnr_field\nself.bruksnr_field = bruksnr_field\nself.festenr_field = festenr_field\nself.seksjonsnr_field = seksjonsnr_field\nself.type_field = type_field\nself.andel_field = andel_field\nself.additional_pro...
<|body_start_0|> self.kommunenr_field = kommunenr_field self.kommune_navn_field = kommune_navn_field self.gardnr_field = gardnr_field self.bruksnr_field = bruksnr_field self.festenr_field = festenr_field self.seksjonsnr_field = seksjonsnr_field self.type_field = t...
Implementation of the 'EiendomNorgeListe' model. TODO: type model description here. Attributes: kommunenr_field (int): TODO: type description here. kommune_navn_field (string): TODO: type description here. gardnr_field (int): TODO: type description here. bruksnr_field (int): TODO: type description here. festenr_field (...
EiendomNorgeListe
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EiendomNorgeListe: """Implementation of the 'EiendomNorgeListe' model. TODO: type model description here. Attributes: kommunenr_field (int): TODO: type description here. kommune_navn_field (string): TODO: type description here. gardnr_field (int): TODO: type description here. bruksnr_field (int):...
stack_v2_sparse_classes_36k_train_016577
3,823
permissive
[ { "docstring": "Constructor for the EiendomNorgeListe class", "name": "__init__", "signature": "def __init__(self, kommunenr_field=None, kommune_navn_field=None, gardnr_field=None, bruksnr_field=None, festenr_field=None, seksjonsnr_field=None, type_field=None, andel_field=None, additional_properties={})...
2
null
Implement the Python class `EiendomNorgeListe` described below. Class description: Implementation of the 'EiendomNorgeListe' model. TODO: type model description here. Attributes: kommunenr_field (int): TODO: type description here. kommune_navn_field (string): TODO: type description here. gardnr_field (int): TODO: type...
Implement the Python class `EiendomNorgeListe` described below. Class description: Implementation of the 'EiendomNorgeListe' model. TODO: type model description here. Attributes: kommunenr_field (int): TODO: type description here. kommune_navn_field (string): TODO: type description here. gardnr_field (int): TODO: type...
fa3918a6c54ea0eedb9146578645b7eb1755b642
<|skeleton|> class EiendomNorgeListe: """Implementation of the 'EiendomNorgeListe' model. TODO: type model description here. Attributes: kommunenr_field (int): TODO: type description here. kommune_navn_field (string): TODO: type description here. gardnr_field (int): TODO: type description here. bruksnr_field (int):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EiendomNorgeListe: """Implementation of the 'EiendomNorgeListe' model. TODO: type model description here. Attributes: kommunenr_field (int): TODO: type description here. kommune_navn_field (string): TODO: type description here. gardnr_field (int): TODO: type description here. bruksnr_field (int): TODO: type d...
the_stack_v2_python_sparse
idfy_rest_client/models/eiendom_norge_liste.py
dealflowteam/Idfy
train
0
1a0d689aeccd823dae14c1416e05bb11ce485ff6
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
A set of methods for managing Data Proc subclusters.
SubclusterServiceServicer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubclusterServiceServicer: """A set of methods for managing Data Proc subclusters.""" def Get(self, request, context): """Returns the specified subcluster. To get the list of all available subclusters, make a [SubclusterService.List] request.""" <|body_0|> def List(self,...
stack_v2_sparse_classes_36k_train_016578
10,405
permissive
[ { "docstring": "Returns the specified subcluster. To get the list of all available subclusters, make a [SubclusterService.List] request.", "name": "Get", "signature": "def Get(self, request, context)" }, { "docstring": "Retrieves a list of subclusters in the specified cluster.", "name": "Lis...
5
null
Implement the Python class `SubclusterServiceServicer` described below. Class description: A set of methods for managing Data Proc subclusters. Method signatures and docstrings: - def Get(self, request, context): Returns the specified subcluster. To get the list of all available subclusters, make a [SubclusterService...
Implement the Python class `SubclusterServiceServicer` described below. Class description: A set of methods for managing Data Proc subclusters. Method signatures and docstrings: - def Get(self, request, context): Returns the specified subcluster. To get the list of all available subclusters, make a [SubclusterService...
b906a014dd893e2697864e1e48e814a8d9fbc48c
<|skeleton|> class SubclusterServiceServicer: """A set of methods for managing Data Proc subclusters.""" def Get(self, request, context): """Returns the specified subcluster. To get the list of all available subclusters, make a [SubclusterService.List] request.""" <|body_0|> def List(self,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubclusterServiceServicer: """A set of methods for managing Data Proc subclusters.""" def Get(self, request, context): """Returns the specified subcluster. To get the list of all available subclusters, make a [SubclusterService.List] request.""" context.set_code(grpc.StatusCode.UNIMPLEMEN...
the_stack_v2_python_sparse
yandex/cloud/dataproc/v1/subcluster_service_pb2_grpc.py
yandex-cloud/python-sdk
train
63
dda2699e126b4644f3e29ce2daad5334ecc998b6
[ "self.subset = []\nself.level = level\nleng = 200.0 / 2 ** level\ny_diff = leng * sqrt(3) / 2\nx_diff = leng / 2\nself.x_pos = [x, x - x_diff, x + x_diff]\nself.y_pos = [y, y - y_diff, y - y_diff]", "if self.subset != []:\n for item in self.subset:\n item.add_subset()\nelse:\n leng = 200.0 / 2 ** (se...
<|body_start_0|> self.subset = [] self.level = level leng = 200.0 / 2 ** level y_diff = leng * sqrt(3) / 2 x_diff = leng / 2 self.x_pos = [x, x - x_diff, x + x_diff] self.y_pos = [y, y - y_diff, y - y_diff] <|end_body_0|> <|body_start_1|> if self.subset !...
Class that contains the Serpinski set
Serpinski
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Serpinski: """Class that contains the Serpinski set""" def __init__(self, x, y, level): """Initializer""" <|body_0|> def add_subset(self): """Create a subset of Serpinski""" <|body_1|> def draw_me(self): """Draw the set recursively""" ...
stack_v2_sparse_classes_36k_train_016579
1,836
permissive
[ { "docstring": "Initializer", "name": "__init__", "signature": "def __init__(self, x, y, level)" }, { "docstring": "Create a subset of Serpinski", "name": "add_subset", "signature": "def add_subset(self)" }, { "docstring": "Draw the set recursively", "name": "draw_me", "s...
3
null
Implement the Python class `Serpinski` described below. Class description: Class that contains the Serpinski set Method signatures and docstrings: - def __init__(self, x, y, level): Initializer - def add_subset(self): Create a subset of Serpinski - def draw_me(self): Draw the set recursively
Implement the Python class `Serpinski` described below. Class description: Class that contains the Serpinski set Method signatures and docstrings: - def __init__(self, x, y, level): Initializer - def add_subset(self): Create a subset of Serpinski - def draw_me(self): Draw the set recursively <|skeleton|> class Serpi...
737769d4a046b4ecea885cafeaf26e26075f7320
<|skeleton|> class Serpinski: """Class that contains the Serpinski set""" def __init__(self, x, y, level): """Initializer""" <|body_0|> def add_subset(self): """Create a subset of Serpinski""" <|body_1|> def draw_me(self): """Draw the set recursively""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Serpinski: """Class that contains the Serpinski set""" def __init__(self, x, y, level): """Initializer""" self.subset = [] self.level = level leng = 200.0 / 2 ** level y_diff = leng * sqrt(3) / 2 x_diff = leng / 2 self.x_pos = [x, x - x_diff, x + x_...
the_stack_v2_python_sparse
PSet2/P2/serpinski_class.py
ali-mahani/ComputationalPhysics-Fall2020
train
3
a954cbb5bb61284321a11f2f21c0d39ad5782d34
[ "pattern = re.compile('(\\\\s)|(,)|(\\\\.)|(-)')\nstring = re.sub(pattern, '', string)\nreturn string", "try:\n int(string)\n return True\nexcept ValueError:\n return False", "if re.search('[0-9@]+', string) is not None:\n return False\nreturn True", "regex = '^\\\\w+([\\\\.-]?\\\\w+)*@\\\\w+([\\\...
<|body_start_0|> pattern = re.compile('(\\s)|(,)|(\\.)|(-)') string = re.sub(pattern, '', string) return string <|end_body_0|> <|body_start_1|> try: int(string) return True except ValueError: return False <|end_body_1|> <|body_start_2|> ...
Helper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Helper: def clean_number(string): """String cleaning""" <|body_0|> def is_int(string): """Check if a string is an integer""" <|body_1|> def is_letters(string): """String cleaning""" <|body_2|> def email_regex(mail): """email ...
stack_v2_sparse_classes_36k_train_016580
849
no_license
[ { "docstring": "String cleaning", "name": "clean_number", "signature": "def clean_number(string)" }, { "docstring": "Check if a string is an integer", "name": "is_int", "signature": "def is_int(string)" }, { "docstring": "String cleaning", "name": "is_letters", "signature...
4
stack_v2_sparse_classes_30k_train_011125
Implement the Python class `Helper` described below. Class description: Implement the Helper class. Method signatures and docstrings: - def clean_number(string): String cleaning - def is_int(string): Check if a string is an integer - def is_letters(string): String cleaning - def email_regex(mail): email checking
Implement the Python class `Helper` described below. Class description: Implement the Helper class. Method signatures and docstrings: - def clean_number(string): String cleaning - def is_int(string): Check if a string is an integer - def is_letters(string): String cleaning - def email_regex(mail): email checking <|s...
e4a3ed154c6ca410e5832720854be26f2b035f1a
<|skeleton|> class Helper: def clean_number(string): """String cleaning""" <|body_0|> def is_int(string): """Check if a string is an integer""" <|body_1|> def is_letters(string): """String cleaning""" <|body_2|> def email_regex(mail): """email ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Helper: def clean_number(string): """String cleaning""" pattern = re.compile('(\\s)|(,)|(\\.)|(-)') string = re.sub(pattern, '', string) return string def is_int(string): """Check if a string is an integer""" try: int(string) return ...
the_stack_v2_python_sparse
RasaChatBot/helper.py
DanyalKhaliq/Machine-Learning-
train
1
5983b54aba73962c78575d99b22dca29054791bf
[ "super(LabelSmoothingLoss, self).__init__()\nself.criterion = nn.KLDivLoss(reduction='none')\nself.padding_idx = padding_idx\nself.confidence = 1.0 - smoothing\nself.smoothing = smoothing\nself.size = size\nself.normalize_length = normalize_length", "assert x.size(2) == self.size\nbatch_size = x.size(0)\nx = x.vi...
<|body_start_0|> super(LabelSmoothingLoss, self).__init__() self.criterion = nn.KLDivLoss(reduction='none') self.padding_idx = padding_idx self.confidence = 1.0 - smoothing self.smoothing = smoothing self.size = size self.normalize_length = normalize_length <|end_...
Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. e.g. smoothing=0.1 [0,1,2] -> [ [0.9, 0.05, 0....
LabelSmoothingLoss
[ "GPL-1.0-or-later", "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LabelSmoothingLoss: """Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. ...
stack_v2_sparse_classes_36k_train_016581
3,459
permissive
[ { "docstring": "Construct an LabelSmoothingLoss object.", "name": "__init__", "signature": "def __init__(self, size: int, padding_idx: int, smoothing: float, normalize_length: bool=False)" }, { "docstring": "Compute loss between x and target. The model outputs and data labels tensors are flatten...
2
stack_v2_sparse_classes_30k_train_009162
Implement the Python class `LabelSmoothingLoss` described below. Class description: Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1....
Implement the Python class `LabelSmoothingLoss` described below. Class description: Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1....
92acc188d3a0f634de58463b6676e70df83ef808
<|skeleton|> class LabelSmoothingLoss: """Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LabelSmoothingLoss: """Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. e.g. smoothin...
the_stack_v2_python_sparse
PyTorch/built-in/audio/Wenet_Conformer_for_Pytorch/wenet/transformer/label_smoothing_loss.py
Ascend/ModelZoo-PyTorch
train
23
c480d7f4bdcfa72d3a9b328a1b61bd3dce75ddf0
[ "enterprise_context = {'tpa_hint': enterprise_customer and enterprise_customer.identity_provider, 'enterprise_id': enterprise_customer and str(enterprise_customer.uuid)}\nenterprise_context.update(**kwargs)\ncourses = []\nfor course in self.data[course_container_key]:\n courses.append(self.update_course(course, ...
<|body_start_0|> enterprise_context = {'tpa_hint': enterprise_customer and enterprise_customer.identity_provider, 'enterprise_id': enterprise_customer and str(enterprise_customer.uuid)} enterprise_context.update(**kwargs) courses = [] for course in self.data[course_container_key]: ...
Serializer mixin for serializers that require Enterprise context in course data.
EnterpriseCourseContextSerializerMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnterpriseCourseContextSerializerMixin: """Serializer mixin for serializers that require Enterprise context in course data.""" def update_enterprise_courses(self, enterprise_customer, course_container_key='results', **kwargs): """This method adds enterprise specific metadata for each...
stack_v2_sparse_classes_36k_train_016582
4,147
no_license
[ { "docstring": "This method adds enterprise specific metadata for each course. We are adding following field in all the courses. tpa_hint: a string for identifying Identity Provider. enterprise_id: the UUID of the enterprise **kwargs: any additional data one would like to add on a per-use basis. Arguments: ente...
3
stack_v2_sparse_classes_30k_train_011052
Implement the Python class `EnterpriseCourseContextSerializerMixin` described below. Class description: Serializer mixin for serializers that require Enterprise context in course data. Method signatures and docstrings: - def update_enterprise_courses(self, enterprise_customer, course_container_key='results', **kwargs...
Implement the Python class `EnterpriseCourseContextSerializerMixin` described below. Class description: Serializer mixin for serializers that require Enterprise context in course data. Method signatures and docstrings: - def update_enterprise_courses(self, enterprise_customer, course_container_key='results', **kwargs...
73fec97eb2850e67e5f57e391641116465424d88
<|skeleton|> class EnterpriseCourseContextSerializerMixin: """Serializer mixin for serializers that require Enterprise context in course data.""" def update_enterprise_courses(self, enterprise_customer, course_container_key='results', **kwargs): """This method adds enterprise specific metadata for each...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EnterpriseCourseContextSerializerMixin: """Serializer mixin for serializers that require Enterprise context in course data.""" def update_enterprise_courses(self, enterprise_customer, course_container_key='results', **kwargs): """This method adds enterprise specific metadata for each course. We a...
the_stack_v2_python_sparse
edx/app/edxapp/venvs/edxapp/lib/python2.7/site-packages/enterprise/api/v1/mixins.py
AlaaSwedan/edx
train
0
24a3022c2a04ca99ce417f8f5caa4a7e790d29f9
[ "BaseXL20WorklistWriter.__init__(self, parent=parent)\nself.tube_transfers = tube_transfers\nself._tube_transfer_data = None", "if self._check_input_class('tube transfer list', self.tube_transfers, list):\n all_tt_data = []\n for tt in self.tube_transfers:\n if isinstance(tt, TubeTransferData):\n ...
<|body_start_0|> BaseXL20WorklistWriter.__init__(self, parent=parent) self.tube_transfers = tube_transfers self._tube_transfer_data = None <|end_body_0|> <|body_start_1|> if self._check_input_class('tube transfer list', self.tube_transfers, list): all_tt_data = [] ...
An XL20 worklist writer that generates a XL20 worklist file using a list of :class:`TubeTransfer` or :class:`TubeTransferData` items. The writer can be run without further adjustments. **Return Value:** the XL20 worklist as stream
XL20WorklistWriter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XL20WorklistWriter: """An XL20 worklist writer that generates a XL20 worklist file using a list of :class:`TubeTransfer` or :class:`TubeTransferData` items. The writer can be run without further adjustments. **Return Value:** the XL20 worklist as stream""" def __init__(self, tube_transfers, ...
stack_v2_sparse_classes_36k_train_016583
20,184
permissive
[ { "docstring": "Constructor. :param tube_transfer: A list of :class:`TubeTransfer` instances. :type tube_transfer: :class:`list`", "name": "__init__", "signature": "def __init__(self, tube_transfers, parent=None)" }, { "docstring": "Checks the initialization values.", "name": "_check_input",...
3
null
Implement the Python class `XL20WorklistWriter` described below. Class description: An XL20 worklist writer that generates a XL20 worklist file using a list of :class:`TubeTransfer` or :class:`TubeTransferData` items. The writer can be run without further adjustments. **Return Value:** the XL20 worklist as stream Met...
Implement the Python class `XL20WorklistWriter` described below. Class description: An XL20 worklist writer that generates a XL20 worklist file using a list of :class:`TubeTransfer` or :class:`TubeTransferData` items. The writer can be run without further adjustments. **Return Value:** the XL20 worklist as stream Met...
d2dc7a478ee5d24ccf3cc680888e712d482321d0
<|skeleton|> class XL20WorklistWriter: """An XL20 worklist writer that generates a XL20 worklist file using a list of :class:`TubeTransfer` or :class:`TubeTransferData` items. The writer can be run without further adjustments. **Return Value:** the XL20 worklist as stream""" def __init__(self, tube_transfers, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class XL20WorklistWriter: """An XL20 worklist writer that generates a XL20 worklist file using a list of :class:`TubeTransfer` or :class:`TubeTransferData` items. The writer can be run without further adjustments. **Return Value:** the XL20 worklist as stream""" def __init__(self, tube_transfers, parent=None):...
the_stack_v2_python_sparse
thelma/tools/worklists/tubehandler.py
papagr/TheLMA
train
1
96e828c3454d61a46519d130bcd8cd5bbc835677
[ "if not root:\n return '[]'\ndata = []\nqueue = [root]\nwhile queue:\n length = len(queue)\n for i in range(length):\n node = queue.pop(0)\n if node:\n data.append(node.val)\n queue.append(node.left)\n queue.append(node.right)\n else:\n data....
<|body_start_0|> if not root: return '[]' data = [] queue = [root] while queue: length = len(queue) for i in range(length): node = queue.pop(0) if node: data.append(node.val) queue...
Codec
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_016584
3,240
permissive
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_016145
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
f09e0aa3de081883b4a7ebfe4d31b5f86f24b64f
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return '[]' data = [] queue = [root] while queue: length = len(queue) for i in range(length): nod...
the_stack_v2_python_sparse
Leetcode/297. 二叉树的序列化与反序列化.py
QDylan/Learning-
train
0
79c893f627e0d13b1f25f704bfb18d46ec378a3c
[ "super(LabelBilinear, self).__init__()\nself.bilinear = nn.Bilinear(in1_features, in2_features, num_label, bias=bias)\nself.lin = nn.Linear(in1_features + in2_features, num_label, bias=False)", "output = self.bilinear(x1, x2)\noutput = output + self.lin(torch.cat([x1, x2], dim=2))\nreturn output" ]
<|body_start_0|> super(LabelBilinear, self).__init__() self.bilinear = nn.Bilinear(in1_features, in2_features, num_label, bias=bias) self.lin = nn.Linear(in1_features + in2_features, num_label, bias=False) <|end_body_0|> <|body_start_1|> output = self.bilinear(x1, x2) output = o...
Biaffine Dependency Parser 的子模块, 用于构建预测边类别的图
LabelBilinear
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LabelBilinear: """Biaffine Dependency Parser 的子模块, 用于构建预测边类别的图""" def __init__(self, in1_features, in2_features, num_label, bias=True): """:param in1_features: 输入的特征1维度 :param in2_features: 输入的特征2维度 :param num_label: 边类别的个数 :param bias: 是否使用bias. Default: ``True``""" <|body_0...
stack_v2_sparse_classes_36k_train_016585
22,013
permissive
[ { "docstring": ":param in1_features: 输入的特征1维度 :param in2_features: 输入的特征2维度 :param num_label: 边类别的个数 :param bias: 是否使用bias. Default: ``True``", "name": "__init__", "signature": "def __init__(self, in1_features, in2_features, num_label, bias=True)" }, { "docstring": ":param x1: [batch, seq_len, h...
2
null
Implement the Python class `LabelBilinear` described below. Class description: Biaffine Dependency Parser 的子模块, 用于构建预测边类别的图 Method signatures and docstrings: - def __init__(self, in1_features, in2_features, num_label, bias=True): :param in1_features: 输入的特征1维度 :param in2_features: 输入的特征2维度 :param num_label: 边类别的个数 :pa...
Implement the Python class `LabelBilinear` described below. Class description: Biaffine Dependency Parser 的子模块, 用于构建预测边类别的图 Method signatures and docstrings: - def __init__(self, in1_features, in2_features, num_label, bias=True): :param in1_features: 输入的特征1维度 :param in2_features: 输入的特征2维度 :param num_label: 边类别的个数 :pa...
dffc7a06cdbff2671a3ca73d2398159d91a4a7db
<|skeleton|> class LabelBilinear: """Biaffine Dependency Parser 的子模块, 用于构建预测边类别的图""" def __init__(self, in1_features, in2_features, num_label, bias=True): """:param in1_features: 输入的特征1维度 :param in2_features: 输入的特征2维度 :param num_label: 边类别的个数 :param bias: 是否使用bias. Default: ``True``""" <|body_0...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LabelBilinear: """Biaffine Dependency Parser 的子模块, 用于构建预测边类别的图""" def __init__(self, in1_features, in2_features, num_label, bias=True): """:param in1_features: 输入的特征1维度 :param in2_features: 输入的特征2维度 :param num_label: 边类别的个数 :param bias: 是否使用bias. Default: ``True``""" super(LabelBilinear, ...
the_stack_v2_python_sparse
phenobert/utils/fastNLP/models/biaffine_parser.py
TianlabTech/PhenoBERT
train
2
6d7a2eb11cf2f14d3092f0d9a0d0d4afd66740c3
[ "super().__init__()\nself.bn = nn.BatchNorm2d(nOut, eps=0.001)\nself.act = nn.PReLU(nOut)", "output = self.bn(input)\noutput = self.act(output)\nreturn output" ]
<|body_start_0|> super().__init__() self.bn = nn.BatchNorm2d(nOut, eps=0.001) self.act = nn.PReLU(nOut) <|end_body_0|> <|body_start_1|> output = self.bn(input) output = self.act(output) return output <|end_body_1|>
This class groups the batch normalization and PReLU activation
BR
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BR: """This class groups the batch normalization and PReLU activation""" def __init__(self, nOut): """:param nOut: output feature maps""" <|body_0|> def forward(self, input): """:param input: input feature map :return: normalized and thresholded feature map""" ...
stack_v2_sparse_classes_36k_train_016586
15,567
permissive
[ { "docstring": ":param nOut: output feature maps", "name": "__init__", "signature": "def __init__(self, nOut)" }, { "docstring": ":param input: input feature map :return: normalized and thresholded feature map", "name": "forward", "signature": "def forward(self, input)" } ]
2
null
Implement the Python class `BR` described below. Class description: This class groups the batch normalization and PReLU activation Method signatures and docstrings: - def __init__(self, nOut): :param nOut: output feature maps - def forward(self, input): :param input: input feature map :return: normalized and threshol...
Implement the Python class `BR` described below. Class description: This class groups the batch normalization and PReLU activation Method signatures and docstrings: - def __init__(self, nOut): :param nOut: output feature maps - def forward(self, input): :param input: input feature map :return: normalized and threshol...
f2993d3ce73a2f7ddba05da3891defb08547d504
<|skeleton|> class BR: """This class groups the batch normalization and PReLU activation""" def __init__(self, nOut): """:param nOut: output feature maps""" <|body_0|> def forward(self, input): """:param input: input feature map :return: normalized and thresholded feature map""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BR: """This class groups the batch normalization and PReLU activation""" def __init__(self, nOut): """:param nOut: output feature maps""" super().__init__() self.bn = nn.BatchNorm2d(nOut, eps=0.001) self.act = nn.PReLU(nOut) def forward(self, input): """:param...
the_stack_v2_python_sparse
pytorch/pytorchcv/models/others/oth_espnet.py
osmr/imgclsmob
train
3,017
4cdcd2254e219ca22f778cf162069424188aa01a
[ "super().__init__()\nself.in_dim = x_dim + y_dim\nself.x_dim = x_dim\nself.y_dim = y_dim\nself.r_dim = r_dim\nself.hidden_dims = hidden_dims\nself.self_att = self_att\nself.cross_attention_type = attention_type\nself.self_attentive_network = SelfAttentiveVanillaNN(in_dim=self.in_dim, out_dim=self.r_dim, hidden_dims...
<|body_start_0|> super().__init__() self.in_dim = x_dim + y_dim self.x_dim = x_dim self.y_dim = y_dim self.r_dim = r_dim self.hidden_dims = hidden_dims self.self_att = self_att self.cross_attention_type = attention_type self.self_attentive_network ...
Self and cross attentive deterministic encoder, as implemented in the ANP paper, where it is described as the Deterministic Encoder.
AttentiveDeterministicEncoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttentiveDeterministicEncoder: """Self and cross attentive deterministic encoder, as implemented in the ANP paper, where it is described as the Deterministic Encoder.""" def __init__(self, x_dim, y_dim, r_dim, hidden_dims, self_att=True, attention_type='uniform'): """:param input_siz...
stack_v2_sparse_classes_36k_train_016587
16,175
no_license
[ { "docstring": ":param input_size: An integer describing the dimensionality of the input to the encoder; in this case the sum of x_dim and y_dim :param r_dim: An integer describing the dimensionality of the embedding, r_i :param n_hidden: An integer describing the number of hidden layers in the neural network :...
2
stack_v2_sparse_classes_30k_train_009786
Implement the Python class `AttentiveDeterministicEncoder` described below. Class description: Self and cross attentive deterministic encoder, as implemented in the ANP paper, where it is described as the Deterministic Encoder. Method signatures and docstrings: - def __init__(self, x_dim, y_dim, r_dim, hidden_dims, s...
Implement the Python class `AttentiveDeterministicEncoder` described below. Class description: Self and cross attentive deterministic encoder, as implemented in the ANP paper, where it is described as the Deterministic Encoder. Method signatures and docstrings: - def __init__(self, x_dim, y_dim, r_dim, hidden_dims, s...
de60f831ee082ab2ae232c498cf2755da7c14c27
<|skeleton|> class AttentiveDeterministicEncoder: """Self and cross attentive deterministic encoder, as implemented in the ANP paper, where it is described as the Deterministic Encoder.""" def __init__(self, x_dim, y_dim, r_dim, hidden_dims, self_att=True, attention_type='uniform'): """:param input_siz...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AttentiveDeterministicEncoder: """Self and cross attentive deterministic encoder, as implemented in the ANP paper, where it is described as the Deterministic Encoder.""" def __init__(self, x_dim, y_dim, r_dim, hidden_dims, self_att=True, attention_type='uniform'): """:param input_size: An integer...
the_stack_v2_python_sparse
models/networks/np_networks.py
PenelopeJones/neural_processes
train
4
ac805d02c6376b67f36fb45c03319c709f5cd7da
[ "self._train_op = optimizer.minimize(loss)\nself._loss = loss\nself._predictions = predictions\nself._ds_train = ds_train\nself._ds_validation = ds_validation\nself._stop_patience = stop_patience\nself._evaluation = evaluation\nself._validation_losses = []\nself._model_inputs = inputs\nself._model_labels = labels\n...
<|body_start_0|> self._train_op = optimizer.minimize(loss) self._loss = loss self._predictions = predictions self._ds_train = ds_train self._ds_validation = ds_validation self._stop_patience = stop_patience self._evaluation = evaluation self._validation_lo...
Trainer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Trainer: def __init__(self, loss, predictions, optimizer, ds_train, ds_validation, stop_patience, evaluation, inputs, labels): """Initialize the trainer Args: loss an operation that computes the loss predictions an operation that computes the predictions for the current optimizer optimiz...
stack_v2_sparse_classes_36k_train_016588
6,508
permissive
[ { "docstring": "Initialize the trainer Args: loss an operation that computes the loss predictions an operation that computes the predictions for the current optimizer optimizer to use ds_train instance of Dataset that holds the training data ds_validation instance of Dataset that holds the validation data stop_...
5
stack_v2_sparse_classes_30k_train_009159
Implement the Python class `Trainer` described below. Class description: Implement the Trainer class. Method signatures and docstrings: - def __init__(self, loss, predictions, optimizer, ds_train, ds_validation, stop_patience, evaluation, inputs, labels): Initialize the trainer Args: loss an operation that computes t...
Implement the Python class `Trainer` described below. Class description: Implement the Trainer class. Method signatures and docstrings: - def __init__(self, loss, predictions, optimizer, ds_train, ds_validation, stop_patience, evaluation, inputs, labels): Initialize the trainer Args: loss an operation that computes t...
e66ca5b33645641426edac4da5aed0cb205a5aeb
<|skeleton|> class Trainer: def __init__(self, loss, predictions, optimizer, ds_train, ds_validation, stop_patience, evaluation, inputs, labels): """Initialize the trainer Args: loss an operation that computes the loss predictions an operation that computes the predictions for the current optimizer optimiz...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Trainer: def __init__(self, loss, predictions, optimizer, ds_train, ds_validation, stop_patience, evaluation, inputs, labels): """Initialize the trainer Args: loss an operation that computes the loss predictions an operation that computes the predictions for the current optimizer optimizer to use ds_t...
the_stack_v2_python_sparse
train/trainer.py
snowskysun/Classification-of-solar-cell-defects
train
0
67c697e2a82919a9469e2550ae43384f3adfe900
[ "conn = kpdb.connect(schema=self.schema_name, catalog='hive')\nself.assertTrue(isinstance(conn, Connection))\nself.assertEqual(conn.schema, self.schema_name)\nself.assertEqual(conn.catalog, 'hive')", "class SQLTest:\n\n def __init__(self, sql_test, params, sql_verify):\n self.sql_test = sql_test\n ...
<|body_start_0|> conn = kpdb.connect(schema=self.schema_name, catalog='hive') self.assertTrue(isinstance(conn, Connection)) self.assertEqual(conn.schema, self.schema_name) self.assertEqual(conn.catalog, 'hive') <|end_body_0|> <|body_start_1|> class SQLTest: def __in...
TestPrestoDatabaseUtils
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestPrestoDatabaseUtils: def test_connect(self): """Test connection to presto returns presto.dbapi.Connection instance""" <|body_0|> def test_sql_mogrify(self): """Test that sql_mogrify renders a syntactically correct SQL statement""" <|body_1|> def test...
stack_v2_sparse_classes_36k_train_016589
4,165
permissive
[ { "docstring": "Test connection to presto returns presto.dbapi.Connection instance", "name": "test_connect", "signature": "def test_connect(self)" }, { "docstring": "Test that sql_mogrify renders a syntactically correct SQL statement", "name": "test_sql_mogrify", "signature": "def test_s...
5
null
Implement the Python class `TestPrestoDatabaseUtils` described below. Class description: Implement the TestPrestoDatabaseUtils class. Method signatures and docstrings: - def test_connect(self): Test connection to presto returns presto.dbapi.Connection instance - def test_sql_mogrify(self): Test that sql_mogrify rende...
Implement the Python class `TestPrestoDatabaseUtils` described below. Class description: Implement the TestPrestoDatabaseUtils class. Method signatures and docstrings: - def test_connect(self): Test connection to presto returns presto.dbapi.Connection instance - def test_sql_mogrify(self): Test that sql_mogrify rende...
2979f03fbdd1c20c3abc365a963a1282b426f321
<|skeleton|> class TestPrestoDatabaseUtils: def test_connect(self): """Test connection to presto returns presto.dbapi.Connection instance""" <|body_0|> def test_sql_mogrify(self): """Test that sql_mogrify renders a syntactically correct SQL statement""" <|body_1|> def test...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestPrestoDatabaseUtils: def test_connect(self): """Test connection to presto returns presto.dbapi.Connection instance""" conn = kpdb.connect(schema=self.schema_name, catalog='hive') self.assertTrue(isinstance(conn, Connection)) self.assertEqual(conn.schema, self.schema_name) ...
the_stack_v2_python_sparse
koku/koku/test_presto_db_utils.py
luisfdez/koku
train
0
944c7b5b3302b6150a605ce79bcd528f259f9db1
[ "super().__init__()\nself.cin = CINLayer(embed_size=embed_size, num_fields=num_fields, output_size=1, layer_sizes=cin_layer_sizes, is_direct=cin_is_direct, use_bias=cin_use_bias, use_batchnorm=cin_use_batchnorm, activation=cin_activation)\nself.deep = DNNLayer(inputs_size=embed_size * num_fields, output_size=1, lay...
<|body_start_0|> super().__init__() self.cin = CINLayer(embed_size=embed_size, num_fields=num_fields, output_size=1, layer_sizes=cin_layer_sizes, is_direct=cin_is_direct, use_bias=cin_use_bias, use_batchnorm=cin_use_batchnorm, activation=cin_activation) self.deep = DNNLayer(inputs_size=embed_siz...
Model class of eXtreme Deep Factorization Machine (xDeepFM). eXtreme Deep Factorization Machine is a variant of DeepFM by replacing FM part with a Convolutional Neural Network (CNN) based model, called Compress Interaction Network (CIN), to calculate element-wise cross-features tensors by outer product, and compress th...
XDeepFactorizationMachineModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XDeepFactorizationMachineModel: """Model class of eXtreme Deep Factorization Machine (xDeepFM). eXtreme Deep Factorization Machine is a variant of DeepFM by replacing FM part with a Convolutional Neural Network (CNN) based model, called Compress Interaction Network (CIN), to calculate element-wis...
stack_v2_sparse_classes_36k_train_016590
5,016
permissive
[ { "docstring": "Initialize XDeepFactorizationMachineModel Args: embed_size (int): size of embedding tensor num_fields (int): number of inputs' fields cin_layer_sizes (List[int]): layer sizes of compress interaction network deep_layer_sizes (List[int]): layer sizes of DNN cin_is_direct (bool, optional): whether ...
2
stack_v2_sparse_classes_30k_train_014738
Implement the Python class `XDeepFactorizationMachineModel` described below. Class description: Model class of eXtreme Deep Factorization Machine (xDeepFM). eXtreme Deep Factorization Machine is a variant of DeepFM by replacing FM part with a Convolutional Neural Network (CNN) based model, called Compress Interaction ...
Implement the Python class `XDeepFactorizationMachineModel` described below. Class description: Model class of eXtreme Deep Factorization Machine (xDeepFM). eXtreme Deep Factorization Machine is a variant of DeepFM by replacing FM part with a Convolutional Neural Network (CNN) based model, called Compress Interaction ...
751a43b9cd35e951d81c0d9cf46507b1777bb7ff
<|skeleton|> class XDeepFactorizationMachineModel: """Model class of eXtreme Deep Factorization Machine (xDeepFM). eXtreme Deep Factorization Machine is a variant of DeepFM by replacing FM part with a Convolutional Neural Network (CNN) based model, called Compress Interaction Network (CIN), to calculate element-wis...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class XDeepFactorizationMachineModel: """Model class of eXtreme Deep Factorization Machine (xDeepFM). eXtreme Deep Factorization Machine is a variant of DeepFM by replacing FM part with a Convolutional Neural Network (CNN) based model, called Compress Interaction Network (CIN), to calculate element-wise cross-featu...
the_stack_v2_python_sparse
torecsys/models/ctr/xdeep_fm.py
p768lwy3/torecsys
train
98
5ebefc01e80cdd571928bceeb277005ef622e265
[ "args = request.args.to_dict()\nvalidator.validate(args, validator.USER_CONTENT)\nusername = get_jwt_identity()\nuser_titles = user_controller.get_user_titles(username, args)\nif not user_titles:\n return ('', 404)\nuser_titles_dto = user_schema.serialize_user_titles(username, user_titles)\nresponse = Response(r...
<|body_start_0|> args = request.args.to_dict() validator.validate(args, validator.USER_CONTENT) username = get_jwt_identity() user_titles = user_controller.get_user_titles(username, args) if not user_titles: return ('', 404) user_titles_dto = user_schema.seria...
UserTitlesResource
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserTitlesResource: def get(self): """Get user related titles""" <|body_0|> def post(self, title_id): """Add a title to user's watchlist""" <|body_1|> def delete(self, title_id): """Remove a title from a watchlist""" <|body_2|> <|end_ske...
stack_v2_sparse_classes_36k_train_016591
4,871
no_license
[ { "docstring": "Get user related titles", "name": "get", "signature": "def get(self)" }, { "docstring": "Add a title to user's watchlist", "name": "post", "signature": "def post(self, title_id)" }, { "docstring": "Remove a title from a watchlist", "name": "delete", "signa...
3
stack_v2_sparse_classes_30k_train_017229
Implement the Python class `UserTitlesResource` described below. Class description: Implement the UserTitlesResource class. Method signatures and docstrings: - def get(self): Get user related titles - def post(self, title_id): Add a title to user's watchlist - def delete(self, title_id): Remove a title from a watchli...
Implement the Python class `UserTitlesResource` described below. Class description: Implement the UserTitlesResource class. Method signatures and docstrings: - def get(self): Get user related titles - def post(self, title_id): Add a title to user's watchlist - def delete(self, title_id): Remove a title from a watchli...
e0c8ea99886f10aea14b9ca95af8a4f42f2af493
<|skeleton|> class UserTitlesResource: def get(self): """Get user related titles""" <|body_0|> def post(self, title_id): """Add a title to user's watchlist""" <|body_1|> def delete(self, title_id): """Remove a title from a watchlist""" <|body_2|> <|end_ske...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserTitlesResource: def get(self): """Get user related titles""" args = request.args.to_dict() validator.validate(args, validator.USER_CONTENT) username = get_jwt_identity() user_titles = user_controller.get_user_titles(username, args) if not user_titles: ...
the_stack_v2_python_sparse
imdb_api/resources/user_resources.py
Matiasmoratti7/imdb
train
0
0d81fc9b6e18818183d352510202b9634a78a5b0
[ "developer = Developer.query.filter_by(id=id).first()\nif developer is None:\n return ({'message': 'Developer does not exist'}, 404)\nreturn developer_schema.dump(developer)", "req = api.payload\ndeveloper = Developer.query.filter_by(id=id).first()\nif developer is None:\n return ({'message': 'Developer doe...
<|body_start_0|> developer = Developer.query.filter_by(id=id).first() if developer is None: return ({'message': 'Developer does not exist'}, 404) return developer_schema.dump(developer) <|end_body_0|> <|body_start_1|> req = api.payload developer = Developer.query.fil...
SingleDeveloper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SingleDeveloper: def get(self, id): """Get Developer by id""" <|body_0|> def put(self, id): """Update a Developer""" <|body_1|> def delete(self, id): """Delete a Developer by id""" <|body_2|> <|end_skeleton|> <|body_start_0|> de...
stack_v2_sparse_classes_36k_train_016592
3,376
no_license
[ { "docstring": "Get Developer by id", "name": "get", "signature": "def get(self, id)" }, { "docstring": "Update a Developer", "name": "put", "signature": "def put(self, id)" }, { "docstring": "Delete a Developer by id", "name": "delete", "signature": "def delete(self, id)...
3
stack_v2_sparse_classes_30k_train_010631
Implement the Python class `SingleDeveloper` described below. Class description: Implement the SingleDeveloper class. Method signatures and docstrings: - def get(self, id): Get Developer by id - def put(self, id): Update a Developer - def delete(self, id): Delete a Developer by id
Implement the Python class `SingleDeveloper` described below. Class description: Implement the SingleDeveloper class. Method signatures and docstrings: - def get(self, id): Get Developer by id - def put(self, id): Update a Developer - def delete(self, id): Delete a Developer by id <|skeleton|> class SingleDeveloper:...
ae78fff9888b0f68d9403d7f65cba086dabb3802
<|skeleton|> class SingleDeveloper: def get(self, id): """Get Developer by id""" <|body_0|> def put(self, id): """Update a Developer""" <|body_1|> def delete(self, id): """Delete a Developer by id""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SingleDeveloper: def get(self, id): """Get Developer by id""" developer = Developer.query.filter_by(id=id).first() if developer is None: return ({'message': 'Developer does not exist'}, 404) return developer_schema.dump(developer) def put(self, id): """...
the_stack_v2_python_sparse
api/v1/developers.py
mythril-io/flask-api
train
0
e6d5218a66f5b347a24d5aa965291a53dbed19c0
[ "algorithm.Algorithm.__init__(self, 50)\nself.n_inputs = n_inputs\nself.n_outputs = n_outputs\nself.n_hidden_layers = n_hidden_layers\nself.n_neurons = n_neurons\nself.n_genes = self.n_inputs + self.n_hidden_layers * self.n_neurons * self.n_inputs + self.n_outputs * self.n_neurons\n_i = self.population_size\nwhile ...
<|body_start_0|> algorithm.Algorithm.__init__(self, 50) self.n_inputs = n_inputs self.n_outputs = n_outputs self.n_hidden_layers = n_hidden_layers self.n_neurons = n_neurons self.n_genes = self.n_inputs + self.n_hidden_layers * self.n_neurons * self.n_inputs + self.n_outp...
Population of ANNs.
AnnPopulation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnnPopulation: """Population of ANNs.""" def __init__(self, n_inputs, n_outputs, n_hidden_layers, n_neurons): """Constructor.""" <|body_0|> def evolve(self, training_set): """Train the neural network, by evolving the weights.""" <|body_1|> <|end_skeleton...
stack_v2_sparse_classes_36k_train_016593
5,211
no_license
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self, n_inputs, n_outputs, n_hidden_layers, n_neurons)" }, { "docstring": "Train the neural network, by evolving the weights.", "name": "evolve", "signature": "def evolve(self, training_set)" } ]
2
stack_v2_sparse_classes_30k_train_001912
Implement the Python class `AnnPopulation` described below. Class description: Population of ANNs. Method signatures and docstrings: - def __init__(self, n_inputs, n_outputs, n_hidden_layers, n_neurons): Constructor. - def evolve(self, training_set): Train the neural network, by evolving the weights.
Implement the Python class `AnnPopulation` described below. Class description: Population of ANNs. Method signatures and docstrings: - def __init__(self, n_inputs, n_outputs, n_hidden_layers, n_neurons): Constructor. - def evolve(self, training_set): Train the neural network, by evolving the weights. <|skeleton|> cl...
227466e6ae9b0a1adcfd2bd191c746b3e09b8edb
<|skeleton|> class AnnPopulation: """Population of ANNs.""" def __init__(self, n_inputs, n_outputs, n_hidden_layers, n_neurons): """Constructor.""" <|body_0|> def evolve(self, training_set): """Train the neural network, by evolving the weights.""" <|body_1|> <|end_skeleton...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AnnPopulation: """Population of ANNs.""" def __init__(self, n_inputs, n_outputs, n_hidden_layers, n_neurons): """Constructor.""" algorithm.Algorithm.__init__(self, 50) self.n_inputs = n_inputs self.n_outputs = n_outputs self.n_hidden_layers = n_hidden_layers ...
the_stack_v2_python_sparse
ANNbug/main.py
deadbok/ANNbug
train
0
fc14563588ec33bdd5bb748aa94972856517d4b7
[ "for bn in self.batch_names:\n a, a_err = get_lattice_spacing(self.beta_values[bn])\n V = float(self.lattice_sizes[bn][0] ** 3)\n self.chi_const[bn] = self.hbarc / a / V ** 0.25\n self.chi_const_err[bn] = self.hbarc * a_err / a ** 2 / V ** 0.25", "try:\n return '$t_e/a=%d$' % int(label)\nexcept Val...
<|body_start_0|> for bn in self.batch_names: a, a_err = get_lattice_spacing(self.beta_values[bn]) V = float(self.lattice_sizes[bn][0] ** 3) self.chi_const[bn] = self.hbarc / a / V ** 0.25 self.chi_const_err[bn] = self.hbarc * a_err / a ** 2 / V ** 0.25 <|end_body_...
Post-analysis of the topsus with with one Q at fixed euclidean time.
TopsustPostAnalysis
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TopsustPostAnalysis: """Post-analysis of the topsus with with one Q at fixed euclidean time.""" def _initialize_topsus_func_const(self): """Sets the constant in the topsus function for found batch beta values.""" <|body_0|> def _convert_label(self, label): """Sho...
stack_v2_sparse_classes_36k_train_016594
1,497
permissive
[ { "docstring": "Sets the constant in the topsus function for found batch beta values.", "name": "_initialize_topsus_func_const", "signature": "def _initialize_topsus_func_const(self)" }, { "docstring": "Short method for formatting time in labels.", "name": "_convert_label", "signature": ...
2
stack_v2_sparse_classes_30k_train_013634
Implement the Python class `TopsustPostAnalysis` described below. Class description: Post-analysis of the topsus with with one Q at fixed euclidean time. Method signatures and docstrings: - def _initialize_topsus_func_const(self): Sets the constant in the topsus function for found batch beta values. - def _convert_la...
Implement the Python class `TopsustPostAnalysis` described below. Class description: Post-analysis of the topsus with with one Q at fixed euclidean time. Method signatures and docstrings: - def _initialize_topsus_func_const(self): Sets the constant in the topsus function for found batch beta values. - def _convert_la...
6c3e69ab7af893f23934d1c3ce8355ac7514c0fe
<|skeleton|> class TopsustPostAnalysis: """Post-analysis of the topsus with with one Q at fixed euclidean time.""" def _initialize_topsus_func_const(self): """Sets the constant in the topsus function for found batch beta values.""" <|body_0|> def _convert_label(self, label): """Sho...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TopsustPostAnalysis: """Post-analysis of the topsus with with one Q at fixed euclidean time.""" def _initialize_topsus_func_const(self): """Sets the constant in the topsus function for found batch beta values.""" for bn in self.batch_names: a, a_err = get_lattice_spacing(self....
the_stack_v2_python_sparse
post_analysis/observable_analysis/topsustpostanalysis.py
hmvege/LatticeAnalyser
train
0
59fc9fc694531d6db268d0c6ab66198e306b1a0e
[ "game = small.BiasedGame(seed)\nrandom = np.random.RandomState(seed)\nsuccesses = []\nfor _ in range(trials):\n dirichlet_alpha = np.ones(game.num_strategies()[0])\n dist = random.dirichlet(dirichlet_alpha)\n sample_best_responses = np.argmax(game.payoff_tensor()[0], axis=0)\n estimated_best_response = ...
<|body_start_0|> game = small.BiasedGame(seed) random = np.random.RandomState(seed) successes = [] for _ in range(trials): dirichlet_alpha = np.ones(game.num_strategies()[0]) dist = random.dirichlet(dirichlet_alpha) sample_best_responses = np.argmax(ga...
SmallTest
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SmallTest: def test_biased_game(self, trials=100, atol=1e-05, rtol=1e-05, seed=1234): """Test best responses to sampled opp. actions in BiasedGame are biased.""" <|body_0|> def simp_to_euc(a, b, center): """Transforms a point [a, b] on the simplex to Euclidean space....
stack_v2_sparse_classes_36k_train_016595
3,917
permissive
[ { "docstring": "Test best responses to sampled opp. actions in BiasedGame are biased.", "name": "test_biased_game", "signature": "def test_biased_game(self, trials=100, atol=1e-05, rtol=1e-05, seed=1234)" }, { "docstring": "Transforms a point [a, b] on the simplex to Euclidean space. /\\\\ ^ b /...
3
null
Implement the Python class `SmallTest` described below. Class description: Implement the SmallTest class. Method signatures and docstrings: - def test_biased_game(self, trials=100, atol=1e-05, rtol=1e-05, seed=1234): Test best responses to sampled opp. actions in BiasedGame are biased. - def simp_to_euc(a, b, center)...
Implement the Python class `SmallTest` described below. Class description: Implement the SmallTest class. Method signatures and docstrings: - def test_biased_game(self, trials=100, atol=1e-05, rtol=1e-05, seed=1234): Test best responses to sampled opp. actions in BiasedGame are biased. - def simp_to_euc(a, b, center)...
ee149736f7d85e16c119a463eee338c6d4c2ceb0
<|skeleton|> class SmallTest: def test_biased_game(self, trials=100, atol=1e-05, rtol=1e-05, seed=1234): """Test best responses to sampled opp. actions in BiasedGame are biased.""" <|body_0|> def simp_to_euc(a, b, center): """Transforms a point [a, b] on the simplex to Euclidean space....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SmallTest: def test_biased_game(self, trials=100, atol=1e-05, rtol=1e-05, seed=1234): """Test best responses to sampled opp. actions in BiasedGame are biased.""" game = small.BiasedGame(seed) random = np.random.RandomState(seed) successes = [] for _ in range(trials): ...
the_stack_v2_python_sparse
open_spiel/python/algorithms/adidas_utils/games/small_test.py
lanctot/open_spiel
train
1
0c8f9999eac88bb26a4c9ead02351c342f64d540
[ "self.pos = np.asarray(pos, dtype=float)\nself.vel = np.asarray(vel, dtype=float)\nself.n = self.pos.shape[0]\nself.r = r\nself.m = m\nself.nsteps = 0", "self.nsteps += 1\nself.pos += self.vel * dt\ndist = squareform(pdist(self.pos))\niarr, jarr = np.where(dist < 2 * self.r)\nk = iarr < jarr\niarr, jarr = (iarr[k...
<|body_start_0|> self.pos = np.asarray(pos, dtype=float) self.vel = np.asarray(vel, dtype=float) self.n = self.pos.shape[0] self.r = r self.m = m self.nsteps = 0 <|end_body_0|> <|body_start_1|> self.nsteps += 1 self.pos += self.vel * dt dist = squ...
MDSimulation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MDSimulation: def __init__(self, pos, vel, r, m): """Initialize the simulation with identical, circular particles of radius r and mass m. The n x 2 state arrays pos and vel hold the n particles' positions in their rows as (x_i, y_i) and (vx_i, vy_i).""" <|body_0|> def advanc...
stack_v2_sparse_classes_36k_train_016596
5,499
no_license
[ { "docstring": "Initialize the simulation with identical, circular particles of radius r and mass m. The n x 2 state arrays pos and vel hold the n particles' positions in their rows as (x_i, y_i) and (vx_i, vy_i).", "name": "__init__", "signature": "def __init__(self, pos, vel, r, m)" }, { "docs...
2
stack_v2_sparse_classes_30k_val_000672
Implement the Python class `MDSimulation` described below. Class description: Implement the MDSimulation class. Method signatures and docstrings: - def __init__(self, pos, vel, r, m): Initialize the simulation with identical, circular particles of radius r and mass m. The n x 2 state arrays pos and vel hold the n par...
Implement the Python class `MDSimulation` described below. Class description: Implement the MDSimulation class. Method signatures and docstrings: - def __init__(self, pos, vel, r, m): Initialize the simulation with identical, circular particles of radius r and mass m. The n x 2 state arrays pos and vel hold the n par...
af24407f75d930e06f02ce25942c222112f33761
<|skeleton|> class MDSimulation: def __init__(self, pos, vel, r, m): """Initialize the simulation with identical, circular particles of radius r and mass m. The n x 2 state arrays pos and vel hold the n particles' positions in their rows as (x_i, y_i) and (vx_i, vy_i).""" <|body_0|> def advanc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MDSimulation: def __init__(self, pos, vel, r, m): """Initialize the simulation with identical, circular particles of radius r and mass m. The n x 2 state arrays pos and vel hold the n particles' positions in their rows as (x_i, y_i) and (vx_i, vy_i).""" self.pos = np.asarray(pos, dtype=float) ...
the_stack_v2_python_sparse
effusion.py
paniash/progs
train
0
285b7087fb18311a04510e123e05ec35856026c7
[ "try:\n session = ndb.Key(sessions.Session, self._en(id)).get()\n assert session != None\nexcept AssertionError:\n self.logging.info('Session not found at encoded ID \"%s\".' % id)\n pass\nexcept Exception:\n self.logging.error('Error encountered building datastore key for session at encoded ID \"%s\...
<|body_start_0|> try: session = ndb.Key(sessions.Session, self._en(id)).get() assert session != None except AssertionError: self.logging.info('Session not found at encoded ID "%s".' % id) pass except Exception: self.logging.error('Error...
Session loader that loads and saves sessions with NDB and the AppEngine Datastore
PersistentSessionLoader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PersistentSessionLoader: """Session loader that loads and saves sessions with NDB and the AppEngine Datastore""" def get_session(self, id): """Returns a session from the datastore, given a session ID.""" <|body_0|> def put_session(self, id, struct, handler): """S...
stack_v2_sparse_classes_36k_train_016597
4,626
no_license
[ { "docstring": "Returns a session from the datastore, given a session ID.", "name": "get_session", "signature": "def get_session(self, id)" }, { "docstring": "Saves a session to the datastore, from a generated response.", "name": "put_session", "signature": "def put_session(self, id, str...
2
null
Implement the Python class `PersistentSessionLoader` described below. Class description: Session loader that loads and saves sessions with NDB and the AppEngine Datastore Method signatures and docstrings: - def get_session(self, id): Returns a session from the datastore, given a session ID. - def put_session(self, id...
Implement the Python class `PersistentSessionLoader` described below. Class description: Session loader that loads and saves sessions with NDB and the AppEngine Datastore Method signatures and docstrings: - def get_session(self, id): Returns a session from the datastore, given a session ID. - def put_session(self, id...
b0ea12ff7b56ea86179a97b08055d6ff1b57355c
<|skeleton|> class PersistentSessionLoader: """Session loader that loads and saves sessions with NDB and the AppEngine Datastore""" def get_session(self, id): """Returns a session from the datastore, given a session ID.""" <|body_0|> def put_session(self, id, struct, handler): """S...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PersistentSessionLoader: """Session loader that loads and saves sessions with NDB and the AppEngine Datastore""" def get_session(self, id): """Returns a session from the datastore, given a session ID.""" try: session = ndb.Key(sessions.Session, self._en(id)).get() ...
the_stack_v2_python_sparse
app/openfire/core/sessions/loader.py
openfire/openfire_old
train
0
1654eb691f3a97b85f4dada06ac471d6c1bcf6ac
[ "self.res = float('inf')\n\ndef help(triangle, level, index, t):\n if level == len(triangle):\n self.res = min(self.res, t)\n if level < len(triangle):\n if index + 1 < len(triangle[level]):\n help(triangle, level + 1, index, t + triangle[level][index])\n help(triangle, lev...
<|body_start_0|> self.res = float('inf') def help(triangle, level, index, t): if level == len(triangle): self.res = min(self.res, t) if level < len(triangle): if index + 1 < len(triangle[level]): help(triangle, level + 1, index...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minimumTotal1(self, triangle): """:type triangle: List[List[int]] :rtype: int""" <|body_0|> def minimumTotal(self, triangle): """:type triangle: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.res = flo...
stack_v2_sparse_classes_36k_train_016598
1,142
no_license
[ { "docstring": ":type triangle: List[List[int]] :rtype: int", "name": "minimumTotal1", "signature": "def minimumTotal1(self, triangle)" }, { "docstring": ":type triangle: List[List[int]] :rtype: int", "name": "minimumTotal", "signature": "def minimumTotal(self, triangle)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumTotal1(self, triangle): :type triangle: List[List[int]] :rtype: int - def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumTotal1(self, triangle): :type triangle: List[List[int]] :rtype: int - def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int <|skeleton|> class...
e5b018493bbd12edcdcd0434f35d9c358106d391
<|skeleton|> class Solution: def minimumTotal1(self, triangle): """:type triangle: List[List[int]] :rtype: int""" <|body_0|> def minimumTotal(self, triangle): """:type triangle: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minimumTotal1(self, triangle): """:type triangle: List[List[int]] :rtype: int""" self.res = float('inf') def help(triangle, level, index, t): if level == len(triangle): self.res = min(self.res, t) if level < len(triangle): ...
the_stack_v2_python_sparse
py/leetcode/120.py
wfeng1991/learnpy
train
0
f8c5bafe26962e4e994163f7294589111b8c327e
[ "raw = cls.validate_payload(payload)\nx_axis_int = raw[0] << 8 | raw[1]\ny_axis_int = raw[2] << 8 | raw[3]\nbrightness = raw[4]\ncolor_valid = raw[5] >> 1 & 1\nbrightness_valid = raw[5] & 1\nreturn XYYColor(color=(round(x_axis_int / 65535, 5), round(y_axis_int / 65535, 5)) if color_valid else None, brightness=brigh...
<|body_start_0|> raw = cls.validate_payload(payload) x_axis_int = raw[0] << 8 | raw[1] y_axis_int = raw[2] << 8 | raw[3] brightness = raw[4] color_valid = raw[5] >> 1 & 1 brightness_valid = raw[5] & 1 return XYYColor(color=(round(x_axis_int / 65535, 5), round(y_ax...
Abstraction for KNX 6 octet color xyY (DPT 242.600).
DPTColorXYY
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DPTColorXYY: """Abstraction for KNX 6 octet color xyY (DPT 242.600).""" def from_knx(cls, payload: DPTArray | DPTBinary) -> XYYColor: """Parse/deserialize from KNX/IP raw data.""" <|body_0|> def to_knx(cls, value: XYYColor | tuple[tuple[float, float] | None, int | None])...
stack_v2_sparse_classes_36k_train_016599
2,776
permissive
[ { "docstring": "Parse/deserialize from KNX/IP raw data.", "name": "from_knx", "signature": "def from_knx(cls, payload: DPTArray | DPTBinary) -> XYYColor" }, { "docstring": "Serialize to KNX/IP raw data.", "name": "to_knx", "signature": "def to_knx(cls, value: XYYColor | tuple[tuple[float...
2
stack_v2_sparse_classes_30k_train_013179
Implement the Python class `DPTColorXYY` described below. Class description: Abstraction for KNX 6 octet color xyY (DPT 242.600). Method signatures and docstrings: - def from_knx(cls, payload: DPTArray | DPTBinary) -> XYYColor: Parse/deserialize from KNX/IP raw data. - def to_knx(cls, value: XYYColor | tuple[tuple[fl...
Implement the Python class `DPTColorXYY` described below. Class description: Abstraction for KNX 6 octet color xyY (DPT 242.600). Method signatures and docstrings: - def from_knx(cls, payload: DPTArray | DPTBinary) -> XYYColor: Parse/deserialize from KNX/IP raw data. - def to_knx(cls, value: XYYColor | tuple[tuple[fl...
48d4e31365c15e632b275f0d129cd9f2b2b5717d
<|skeleton|> class DPTColorXYY: """Abstraction for KNX 6 octet color xyY (DPT 242.600).""" def from_knx(cls, payload: DPTArray | DPTBinary) -> XYYColor: """Parse/deserialize from KNX/IP raw data.""" <|body_0|> def to_knx(cls, value: XYYColor | tuple[tuple[float, float] | None, int | None])...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DPTColorXYY: """Abstraction for KNX 6 octet color xyY (DPT 242.600).""" def from_knx(cls, payload: DPTArray | DPTBinary) -> XYYColor: """Parse/deserialize from KNX/IP raw data.""" raw = cls.validate_payload(payload) x_axis_int = raw[0] << 8 | raw[1] y_axis_int = raw[2] << ...
the_stack_v2_python_sparse
xknx/dpt/dpt_color.py
XKNX/xknx
train
248