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
7c7a0f6f19cbdbfc2f15745a2c4c407ced3b3d8d
[ "if self.is_classifier():\n preds = self._predict(X)\n pred_col = self._get_custom_param('predictions_col', 0)\n selector = [c for c in range(preds.ncol) if c != pred_col]\n return preds[:, selector]\nraise AttributeError(\"{} attribute 'predict_proba' is supported only for classification.\".format(self...
<|body_start_0|> if self.is_classifier(): preds = self._predict(X) pred_col = self._get_custom_param('predictions_col', 0) selector = [c for c in range(preds.ncol) if c != pred_col] return preds[:, selector] raise AttributeError("{} attribute 'predict_prob...
H2OEstimatorPredictProbabilitiesSupport
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class H2OEstimatorPredictProbabilitiesSupport: def predict_proba(self, X): """Predicts on the data. :param iterable X: data to predict on (array-like or :class:`h2o.H2OFrame`). :return: the predictions probabilities, shape=[n_samples, n_classes] (array-like or :class:`h2o.H2OFrame`).""" ...
stack_v2_sparse_classes_36k_train_017900
36,832
permissive
[ { "docstring": "Predicts on the data. :param iterable X: data to predict on (array-like or :class:`h2o.H2OFrame`). :return: the predictions probabilities, shape=[n_samples, n_classes] (array-like or :class:`h2o.H2OFrame`).", "name": "predict_proba", "signature": "def predict_proba(self, X)" }, { ...
2
null
Implement the Python class `H2OEstimatorPredictProbabilitiesSupport` described below. Class description: Implement the H2OEstimatorPredictProbabilitiesSupport class. Method signatures and docstrings: - def predict_proba(self, X): Predicts on the data. :param iterable X: data to predict on (array-like or :class:`h2o.H...
Implement the Python class `H2OEstimatorPredictProbabilitiesSupport` described below. Class description: Implement the H2OEstimatorPredictProbabilitiesSupport class. Method signatures and docstrings: - def predict_proba(self, X): Predicts on the data. :param iterable X: data to predict on (array-like or :class:`h2o.H...
d817ab90c8c47f6787604a0b9639b66234158228
<|skeleton|> class H2OEstimatorPredictProbabilitiesSupport: def predict_proba(self, X): """Predicts on the data. :param iterable X: data to predict on (array-like or :class:`h2o.H2OFrame`). :return: the predictions probabilities, shape=[n_samples, n_classes] (array-like or :class:`h2o.H2OFrame`).""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class H2OEstimatorPredictProbabilitiesSupport: def predict_proba(self, X): """Predicts on the data. :param iterable X: data to predict on (array-like or :class:`h2o.H2OFrame`). :return: the predictions probabilities, shape=[n_samples, n_classes] (array-like or :class:`h2o.H2OFrame`).""" if self.is_c...
the_stack_v2_python_sparse
h2o-py/h2o/sklearn/wrapper.py
h2oai/h2o-3
train
6,872
bac021f94f2e11735c86c690c60800a8c16a2fd2
[ "queue = self.messages.Queue(name=queue_ref.RelativeName(), retryConfig=retry_config, rateLimits=rate_limits, appEngineHttpQueue=app_engine_http_queue, stackdriverLoggingConfig=stackdriver_logging_config)\nrequest = self.messages.CloudtasksProjectsLocationsQueuesCreateRequest(parent=parent_ref.RelativeName(), queue...
<|body_start_0|> queue = self.messages.Queue(name=queue_ref.RelativeName(), retryConfig=retry_config, rateLimits=rate_limits, appEngineHttpQueue=app_engine_http_queue, stackdriverLoggingConfig=stackdriver_logging_config) request = self.messages.CloudtasksProjectsLocationsQueuesCreateRequest(parent=paren...
Client for queues service in the Cloud Tasks API.
BetaQueues
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BetaQueues: """Client for queues service in the Cloud Tasks API.""" def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_http_queue=None, stackdriver_logging_config=None): """Prepares and sends a Create request for creating a queue.""" <|bod...
stack_v2_sparse_classes_36k_train_017901
9,305
permissive
[ { "docstring": "Prepares and sends a Create request for creating a queue.", "name": "Create", "signature": "def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_http_queue=None, stackdriver_logging_config=None)" }, { "docstring": "Prepares and sends a Patch req...
2
stack_v2_sparse_classes_30k_train_019530
Implement the Python class `BetaQueues` described below. Class description: Client for queues service in the Cloud Tasks API. Method signatures and docstrings: - def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_http_queue=None, stackdriver_logging_config=None): Prepares and send...
Implement the Python class `BetaQueues` described below. Class description: Client for queues service in the Cloud Tasks API. Method signatures and docstrings: - def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_http_queue=None, stackdriver_logging_config=None): Prepares and send...
85bb264e273568b5a0408f733b403c56373e2508
<|skeleton|> class BetaQueues: """Client for queues service in the Cloud Tasks API.""" def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_http_queue=None, stackdriver_logging_config=None): """Prepares and sends a Create request for creating a queue.""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BetaQueues: """Client for queues service in the Cloud Tasks API.""" def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_http_queue=None, stackdriver_logging_config=None): """Prepares and sends a Create request for creating a queue.""" queue = self.messa...
the_stack_v2_python_sparse
google-cloud-sdk/lib/googlecloudsdk/api_lib/tasks/queues.py
bopopescu/socialliteapp
train
0
146bdf8e2adb3efcd7e785903d1552757e82abba
[ "m = defaultdict(int)\nn = len(nums)\nres = 1\nfor i in range(n):\n for j in range(i):\n diff = nums[i] - nums[j]\n m[i, diff] = m[j, diff] + 1\n res = max(res, m[i, diff])\nreturn res + 1", "n = len(nums)\ndp = [[0] * 2000 for _ in range(n)]\nres = 1\nfor i in range(n):\n for j in rang...
<|body_start_0|> m = defaultdict(int) n = len(nums) res = 1 for i in range(n): for j in range(i): diff = nums[i] - nums[j] m[i, diff] = m[j, diff] + 1 res = max(res, m[i, diff]) return res + 1 <|end_body_0|> <|body_star...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestArithSeqLength(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def longestArithSeqLengthDP(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> m = defaultdict(int) ...
stack_v2_sparse_classes_36k_train_017902
2,814
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "longestArithSeqLength", "signature": "def longestArithSeqLength(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "longestArithSeqLengthDP", "signature": "def longestArithSeqLengthDP(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_017398
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestArithSeqLength(self, nums): :type nums: List[int] :rtype: int - def longestArithSeqLengthDP(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestArithSeqLength(self, nums): :type nums: List[int] :rtype: int - def longestArithSeqLengthDP(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def longestArithSeqLength(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def longestArithSeqLengthDP(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestArithSeqLength(self, nums): """:type nums: List[int] :rtype: int""" m = defaultdict(int) n = len(nums) res = 1 for i in range(n): for j in range(i): diff = nums[i] - nums[j] m[i, diff] = m[j, diff] + 1 ...
the_stack_v2_python_sparse
L/LongestArithmeticSubsequence.py
bssrdf/pyleet
train
2
d97521b9ec229ea78a601836c046fe35cff85d0b
[ "worker = SysupdateWorker(router, firmware_config)\nworker.start()\nworker.join()", "worker = SysupgradeWorker(router, n)\nworker.start()\nworker.join()" ]
<|body_start_0|> worker = SysupdateWorker(router, firmware_config) worker.start() worker.join() <|end_body_0|> <|body_start_1|> worker = SysupgradeWorker(router, n) worker.start() worker.join() <|end_body_1|>
RouterFlashFirmware
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RouterFlashFirmware: def sysupdate(router: Router, firmware_config): """Instantiate a NetworkCtrl and copy the firmware via SSH to the Router(/tmp/<firmware_name>.bin) :param router: :param firmware_config:""" <|body_0|> def sysupgrade(router: Router, n: bool): """In...
stack_v2_sparse_classes_36k_train_017903
3,026
no_license
[ { "docstring": "Instantiate a NetworkCtrl and copy the firmware via SSH to the Router(/tmp/<firmware_name>.bin) :param router: :param firmware_config:", "name": "sysupdate", "signature": "def sysupdate(router: Router, firmware_config)" }, { "docstring": "Instantiate a NetworkCtrl, proves if the ...
2
stack_v2_sparse_classes_30k_train_002437
Implement the Python class `RouterFlashFirmware` described below. Class description: Implement the RouterFlashFirmware class. Method signatures and docstrings: - def sysupdate(router: Router, firmware_config): Instantiate a NetworkCtrl and copy the firmware via SSH to the Router(/tmp/<firmware_name>.bin) :param route...
Implement the Python class `RouterFlashFirmware` described below. Class description: Implement the RouterFlashFirmware class. Method signatures and docstrings: - def sysupdate(router: Router, firmware_config): Instantiate a NetworkCtrl and copy the firmware via SSH to the Router(/tmp/<firmware_name>.bin) :param route...
5dbe21f47552097441601b881aa47ff66625b211
<|skeleton|> class RouterFlashFirmware: def sysupdate(router: Router, firmware_config): """Instantiate a NetworkCtrl and copy the firmware via SSH to the Router(/tmp/<firmware_name>.bin) :param router: :param firmware_config:""" <|body_0|> def sysupgrade(router: Router, n: bool): """In...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RouterFlashFirmware: def sysupdate(router: Router, firmware_config): """Instantiate a NetworkCtrl and copy the firmware via SSH to the Router(/tmp/<firmware_name>.bin) :param router: :param firmware_config:""" worker = SysupdateWorker(router, firmware_config) worker.start() wor...
the_stack_v2_python_sparse
util/router_flash_firmware.py
freifunk-darmstadt/TestFramework
train
1
188405ec2c5c2996c0bdbc9c4df5fbeace808420
[ "n = len(citations)\nll, r = (0, n - 1)\nwhile ll <= r:\n mid = (ll + r) / 2\n if citations[mid] > n - mid:\n r = mid - 1\n elif citations[mid] < n - mid:\n ll = mid + 1\n else:\n return n - mid\nreturn n - ll", "if not citations:\n return 0\nlength = len(citations)\nleft = 0\n...
<|body_start_0|> n = len(citations) ll, r = (0, n - 1) while ll <= r: mid = (ll + r) / 2 if citations[mid] > n - mid: r = mid - 1 elif citations[mid] < n - mid: ll = mid + 1 else: return n - mid ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def hIndex(self, citations): """:type citations: List[int] :rtype: int""" <|body_0|> def hIndex_2(self, citations): """:type citations: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(citations) ll, r ...
stack_v2_sparse_classes_36k_train_017904
2,466
no_license
[ { "docstring": ":type citations: List[int] :rtype: int", "name": "hIndex", "signature": "def hIndex(self, citations)" }, { "docstring": ":type citations: List[int] :rtype: int", "name": "hIndex_2", "signature": "def hIndex_2(self, citations)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hIndex(self, citations): :type citations: List[int] :rtype: int - def hIndex_2(self, citations): :type citations: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hIndex(self, citations): :type citations: List[int] :rtype: int - def hIndex_2(self, citations): :type citations: List[int] :rtype: int <|skeleton|> class Solution: def...
6350568d16b0f8c49a020f055bb6d72e2705ea56
<|skeleton|> class Solution: def hIndex(self, citations): """:type citations: List[int] :rtype: int""" <|body_0|> def hIndex_2(self, citations): """:type citations: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def hIndex(self, citations): """:type citations: List[int] :rtype: int""" n = len(citations) ll, r = (0, n - 1) while ll <= r: mid = (ll + r) / 2 if citations[mid] > n - mid: r = mid - 1 elif citations[mid] < n - mid...
the_stack_v2_python_sparse
binary_search_tree/275_H-Index2.py
vsdrun/lc_public
train
6
f6685bed4bc88d88b0d647e9f8c34c3ac75bec7f
[ "low = high = 0\nfor c in s:\n low += 1 if c == '(' else -1\n high += 1 if c in '(*' else -1\n if high < 0:\n break\n low = max(low, 0)\nreturn low == 0", "def go(s, stack):\n for i in range(len(s)):\n if s[i] == '(':\n stack.append(s[i])\n elif s[i] == ')':\n ...
<|body_start_0|> low = high = 0 for c in s: low += 1 if c == '(' else -1 high += 1 if c in '(*' else -1 if high < 0: break low = max(low, 0) return low == 0 <|end_body_0|> <|body_start_1|> def go(s, stack): for ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def checkValidString(self, s): """:type s: str :rtype: bool 這個 greedy 的解法的想法是在 pass 整個字串的過程中 去計算當前的 `balance`, 所謂的 balance 就是把'('當成+1, 把')'當成-1, 把字串轉換成一個數字的意思 一個合法的括號方式,從 0 開始的子字串之 balance 必定大於 0 (balance 大於 0 的意思其實就是左括號比右括號多的意思) 而這題又多了一個萬能字元 - 星號,所以我們不能只計算 balance 要考慮 balance ...
stack_v2_sparse_classes_36k_train_017905
2,740
no_license
[ { "docstring": ":type s: str :rtype: bool 這個 greedy 的解法的想法是在 pass 整個字串的過程中 去計算當前的 `balance`, 所謂的 balance 就是把'('當成+1, 把')'當成-1, 把字串轉換成一個數字的意思 一個合法的括號方式,從 0 開始的子字串之 balance 必定大於 0 (balance 大於 0 的意思其實就是左括號比右括號多的意思) 而這題又多了一個萬能字元 - 星號,所以我們不能只計算 balance 要考慮 balance 可能的最大值及最小值 也就是說 '(' 會使 最大值跟最小值都 +1 ')' 會使 最大值跟最小值都 -...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def checkValidString(self, s): :type s: str :rtype: bool 這個 greedy 的解法的想法是在 pass 整個字串的過程中 去計算當前的 `balance`, 所謂的 balance 就是把'('當成+1, 把')'當成-1, 把字串轉換成一個數字的意思 一個合法的括號方式,從 0 開始的子字串之 ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def checkValidString(self, s): :type s: str :rtype: bool 這個 greedy 的解法的想法是在 pass 整個字串的過程中 去計算當前的 `balance`, 所謂的 balance 就是把'('當成+1, 把')'當成-1, 把字串轉換成一個數字的意思 一個合法的括號方式,從 0 開始的子字串之 ...
ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd
<|skeleton|> class Solution: def checkValidString(self, s): """:type s: str :rtype: bool 這個 greedy 的解法的想法是在 pass 整個字串的過程中 去計算當前的 `balance`, 所謂的 balance 就是把'('當成+1, 把')'當成-1, 把字串轉換成一個數字的意思 一個合法的括號方式,從 0 開始的子字串之 balance 必定大於 0 (balance 大於 0 的意思其實就是左括號比右括號多的意思) 而這題又多了一個萬能字元 - 星號,所以我們不能只計算 balance 要考慮 balance ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def checkValidString(self, s): """:type s: str :rtype: bool 這個 greedy 的解法的想法是在 pass 整個字串的過程中 去計算當前的 `balance`, 所謂的 balance 就是把'('當成+1, 把')'當成-1, 把字串轉換成一個數字的意思 一個合法的括號方式,從 0 開始的子字串之 balance 必定大於 0 (balance 大於 0 的意思其實就是左括號比右括號多的意思) 而這題又多了一個萬能字元 - 星號,所以我們不能只計算 balance 要考慮 balance 可能的最大值及最小值 也就是...
the_stack_v2_python_sparse
cs_notes/string/valid_parenthesis_string.py
hwc1824/LeetCodeSolution
train
0
5460024c542c2e0e26b846a7031d467ba27d96c4
[ "summ = nums[0]\nfor bIndex in range(len(nums)):\n for eIndex in range(1, len(nums[bIndex:]) + 1):\n tmp = sum(nums[bIndex:bIndex + eIndex])\n if tmp > summ:\n summ = tmp\nreturn summ", "curIndex = 0\ncurSum = maxSum = nums[0]\nfor index, num in enumerate(nums[1:]):\n if num > curSu...
<|body_start_0|> summ = nums[0] for bIndex in range(len(nums)): for eIndex in range(1, len(nums[bIndex:]) + 1): tmp = sum(nums[bIndex:bIndex + eIndex]) if tmp > summ: summ = tmp return summ <|end_body_0|> <|body_start_1|> c...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxSubArray1(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def maxSubArray(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> summ = nums[0] for bIndex in range(l...
stack_v2_sparse_classes_36k_train_017906
1,045
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "maxSubArray1", "signature": "def maxSubArray1(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "maxSubArray", "signature": "def maxSubArray(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_009196
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSubArray1(self, nums): :type nums: List[int] :rtype: int - def maxSubArray(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSubArray1(self, nums): :type nums: List[int] :rtype: int - def maxSubArray(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def maxSubArra...
1315727d68fc3e0c47376604b3f7d4807607e2c7
<|skeleton|> class Solution: def maxSubArray1(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def maxSubArray(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxSubArray1(self, nums): """:type nums: List[int] :rtype: int""" summ = nums[0] for bIndex in range(len(nums)): for eIndex in range(1, len(nums[bIndex:]) + 1): tmp = sum(nums[bIndex:bIndex + eIndex]) if tmp > summ: ...
the_stack_v2_python_sparse
maxSubArray.py
4ier/LeetCode
train
4
aaa47a1e25dbdad3c170a595e5c34a346d9a0d80
[ "input_data = {}\ninput_data['name'] = kwargs.get('name', None)\ninput_data['sort_by_date'] = kwargs.get('sort_by_date', None)\ninput_data['podcast_type'] = kwargs.get('podcast_type', None)\ninput_data['duration'] = kwargs.get('duration', None)\ninput_data['published'] = kwargs.get('published', None)\ninput_data['l...
<|body_start_0|> input_data = {} input_data['name'] = kwargs.get('name', None) input_data['sort_by_date'] = kwargs.get('sort_by_date', None) input_data['podcast_type'] = kwargs.get('podcast_type', None) input_data['duration'] = kwargs.get('duration', None) input_data['pub...
Validations for theclient information
PodcastValidations
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PodcastValidations: """Validations for theclient information""" def validate_podcast_data(self, kwargs): """Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: input_data (dict): validated data""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_017907
2,198
permissive
[ { "docstring": "Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: input_data (dict): validated data", "name": "validate_podcast_data", "signature": "def validate_podcast_data(self, kwargs)" }, { "docstring": "Runs all the corp...
2
stack_v2_sparse_classes_30k_test_000520
Implement the Python class `PodcastValidations` described below. Class description: Validations for theclient information Method signatures and docstrings: - def validate_podcast_data(self, kwargs): Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns:...
Implement the Python class `PodcastValidations` described below. Class description: Validations for theclient information Method signatures and docstrings: - def validate_podcast_data(self, kwargs): Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns:...
04ff9ebb5da482e5b2642a89654a5b5f0128eaaa
<|skeleton|> class PodcastValidations: """Validations for theclient information""" def validate_podcast_data(self, kwargs): """Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: input_data (dict): validated data""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PodcastValidations: """Validations for theclient information""" def validate_podcast_data(self, kwargs): """Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: input_data (dict): validated data""" input_data = {} ...
the_stack_v2_python_sparse
app/api/podcast/validators/validate_input.py
lunyamwis/laylinks-bend
train
0
990e44e8601b8ba7e548d3a958d933dd56527ec9
[ "odic = OrderedDict()\nodic['abc'] = 123\nodic['defg'] = 4567\nodic['xyz'] = 980\nodic['fhg'] = 456\nprint(odic)\ncollection_name = 'Hello'\nwith self.assertRaises(DuplicateKeyError):\n for n in range(2):\n time.sleep(2)\n with_mongo_collection(lambda col: col.insert_one(odic), collection_name)\nwi...
<|body_start_0|> odic = OrderedDict() odic['abc'] = 123 odic['defg'] = 4567 odic['xyz'] = 980 odic['fhg'] = 456 print(odic) collection_name = 'Hello' with self.assertRaises(DuplicateKeyError): for n in range(2): time.sleep(2) ...
config.py 的自动化测试案例
MongoTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MongoTest: """config.py 的自动化测试案例""" def test_deal_with_mongo_collection(self): """mongodb 连续插入重复数据会报错,原因不详 :return:""" <|body_0|> def test_deal_with_mongo_collection(self): """插入mongodb中记录字段的顺序,无关,都可以被find出来 :return:""" <|body_1|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_36k_train_017908
8,886
permissive
[ { "docstring": "mongodb 连续插入重复数据会报错,原因不详 :return:", "name": "test_deal_with_mongo_collection", "signature": "def test_deal_with_mongo_collection(self)" }, { "docstring": "插入mongodb中记录字段的顺序,无关,都可以被find出来 :return:", "name": "test_deal_with_mongo_collection", "signature": "def test_deal_wit...
2
stack_v2_sparse_classes_30k_train_012438
Implement the Python class `MongoTest` described below. Class description: config.py 的自动化测试案例 Method signatures and docstrings: - def test_deal_with_mongo_collection(self): mongodb 连续插入重复数据会报错,原因不详 :return: - def test_deal_with_mongo_collection(self): 插入mongodb中记录字段的顺序,无关,都可以被find出来 :return:
Implement the Python class `MongoTest` described below. Class description: config.py 的自动化测试案例 Method signatures and docstrings: - def test_deal_with_mongo_collection(self): mongodb 连续插入重复数据会报错,原因不详 :return: - def test_deal_with_mongo_collection(self): 插入mongodb中记录字段的顺序,无关,都可以被find出来 :return: <|skeleton|> class Mongo...
d6f20d926de047af6857e466cf28084d0ba69993
<|skeleton|> class MongoTest: """config.py 的自动化测试案例""" def test_deal_with_mongo_collection(self): """mongodb 连续插入重复数据会报错,原因不详 :return:""" <|body_0|> def test_deal_with_mongo_collection(self): """插入mongodb中记录字段的顺序,无关,都可以被find出来 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MongoTest: """config.py 的自动化测试案例""" def test_deal_with_mongo_collection(self): """mongodb 连续插入重复数据会报错,原因不详 :return:""" odic = OrderedDict() odic['abc'] = 123 odic['defg'] = 4567 odic['xyz'] = 980 odic['fhg'] = 456 print(odic) collection_name...
the_stack_v2_python_sparse
test_case/test_config_base_utils.py
mmmaaaggg/QABAT
train
4
9e6635cb59bd73a2f7b0812c705bffed39ee8d8f
[ "self.f = f\nself.gp = GP(X_init, Y_init, l, sigma_f)\naux = np.linspace(bounds[0], bounds[1], num=ac_samples)\nself.X_s = aux.reshape(-1, 1)\nself.xsi = xsi\nself.minimize = minimize", "mu_s, sigma_s = self.gp.predict(self.X_s)\nif self.minimize is True:\n Y_s_opt = np.min(self.gp.Y)\n imp = Y_s_opt - mu_s...
<|body_start_0|> self.f = f self.gp = GP(X_init, Y_init, l, sigma_f) aux = np.linspace(bounds[0], bounds[1], num=ac_samples) self.X_s = aux.reshape(-1, 1) self.xsi = xsi self.minimize = minimize <|end_body_0|> <|body_start_1|> mu_s, sigma_s = self.gp.predict(self...
Represents a noiseless 1D Gaussian process
BayesianOptimization
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BayesianOptimization: """Represents a noiseless 1D Gaussian process""" def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): """Class constructor :param f: is the black-box function to be optimized :param X_init: is a numpy.ndarray of sha...
stack_v2_sparse_classes_36k_train_017909
3,331
no_license
[ { "docstring": "Class constructor :param f: is the black-box function to be optimized :param X_init: is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function :param Y_init: is a numpy.ndarray of shape (t, 1) representing the outputs of the black-box function for eac...
3
stack_v2_sparse_classes_30k_train_008463
Implement the Python class `BayesianOptimization` described below. Class description: Represents a noiseless 1D Gaussian process Method signatures and docstrings: - def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): Class constructor :param f: is the black-box function...
Implement the Python class `BayesianOptimization` described below. Class description: Represents a noiseless 1D Gaussian process Method signatures and docstrings: - def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): Class constructor :param f: is the black-box function...
975f7e23906b7416e78489f6ad6331ea408c8709
<|skeleton|> class BayesianOptimization: """Represents a noiseless 1D Gaussian process""" def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): """Class constructor :param f: is the black-box function to be optimized :param X_init: is a numpy.ndarray of sha...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BayesianOptimization: """Represents a noiseless 1D Gaussian process""" def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): """Class constructor :param f: is the black-box function to be optimized :param X_init: is a numpy.ndarray of shape (t, 1) rep...
the_stack_v2_python_sparse
unsupervised_learning/0x03-hyperparameter_tuning/5-bayes_opt.py
julgachancipa/holbertonschool-machine_learning
train
1
28b03e2d1e9a9e2c1d3f112d060475886d4f0ed5
[ "def preorder(root):\n if root:\n vals.append(root.val)\n preorder(root.left)\n preorder(root.right)\nvals = []\npreorder(root)\nreturn ' '.join(map(str, vals))", "preorder = list(map(int, data.split()))\ninorder = sorted(preorder)\n\ndef buildBST(preorder, inorder):\n if not preorder:\...
<|body_start_0|> def preorder(root): if root: vals.append(root.val) preorder(root.left) preorder(root.right) vals = [] preorder(root) return ' '.join(map(str, vals)) <|end_body_0|> <|body_start_1|> preorder = list(map(i...
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_017910
1,414
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
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
3719f5cb059eefd66b83eb8ae990652f4b7fd124
<|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""" def preorder(root): if root: vals.append(root.val) preorder(root.left) preorder(root.right) vals = [] preorder...
the_stack_v2_python_sparse
Python3/0449-Serialize-and-Deserialize-BST/soln.py
wyaadarsh/LeetCode-Solutions
train
0
dd77732ee6da980ad247f90dc3b7c9cfeddda268
[ "log.dev_info('Mask file path: {}'.format(mask_fp))\nif not os.path.isfile(mask_fp):\n log.dev_error('Path {} is not a mask file')\n return None\nmask = cio.read_image(mask_fp)\nmask.from_numpy(mask.to_numpy(), np.uint8)\nsize_x, size_y, slice_count = mask.size()\nslices = mask.to_numpy()\nrst = {}\nfor index...
<|body_start_0|> log.dev_info('Mask file path: {}'.format(mask_fp)) if not os.path.isfile(mask_fp): log.dev_error('Path {} is not a mask file') return None mask = cio.read_image(mask_fp) mask.from_numpy(mask.to_numpy(), np.uint8) size_x, size_y, slice_coun...
SegmentationHelper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SegmentationHelper: def mask_to_contours(mask_fp): """Convert mask to contours :param mask_fp: Mask file path :return: Array of contours""" <|body_0|> def contours_to_mask(mask_fp, contours): """Convert contour to mask(.nii.gz) :param contours: dictionary of contours...
stack_v2_sparse_classes_36k_train_017911
3,104
no_license
[ { "docstring": "Convert mask to contours :param mask_fp: Mask file path :return: Array of contours", "name": "mask_to_contours", "signature": "def mask_to_contours(mask_fp)" }, { "docstring": "Convert contour to mask(.nii.gz) :param contours: dictionary of contours :param size: mask shape :retur...
2
null
Implement the Python class `SegmentationHelper` described below. Class description: Implement the SegmentationHelper class. Method signatures and docstrings: - def mask_to_contours(mask_fp): Convert mask to contours :param mask_fp: Mask file path :return: Array of contours - def contours_to_mask(mask_fp, contours): C...
Implement the Python class `SegmentationHelper` described below. Class description: Implement the SegmentationHelper class. Method signatures and docstrings: - def mask_to_contours(mask_fp): Convert mask to contours :param mask_fp: Mask file path :return: Array of contours - def contours_to_mask(mask_fp, contours): C...
d3206f29d37735b5cc393744faaa55295fe7d6b1
<|skeleton|> class SegmentationHelper: def mask_to_contours(mask_fp): """Convert mask to contours :param mask_fp: Mask file path :return: Array of contours""" <|body_0|> def contours_to_mask(mask_fp, contours): """Convert contour to mask(.nii.gz) :param contours: dictionary of contours...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SegmentationHelper: def mask_to_contours(mask_fp): """Convert mask to contours :param mask_fp: Mask file path :return: Array of contours""" log.dev_info('Mask file path: {}'.format(mask_fp)) if not os.path.isfile(mask_fp): log.dev_error('Path {} is not a mask file') ...
the_stack_v2_python_sparse
back_end/utils/segmentation_helper.py
yongweili1/portal
train
0
31bcd12cd23bee6d5051a7efec095ac49dee96eb
[ "self.agent = agent\nself.env = env\nself.replay = replay\nself.replay.shuffle = shuffle\nself._obs = None", "rollouts = self.replay.sample()\nwith torch.no_grad():\n actions, output = self.agent.explore_on_batch(rollouts.obs_next)\n expected_values = output['value'].cpu().numpy().squeeze(-1)\nrollouts.disc...
<|body_start_0|> self.agent = agent self.env = env self.replay = replay self.replay.shuffle = shuffle self._obs = None <|end_body_0|> <|body_start_1|> rollouts = self.replay.sample() with torch.no_grad(): actions, output = self.agent.explore_on_batch(...
ReplayRunner
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReplayRunner: def __init__(self, agent, env, replay, shuffle=False): """Adapter for batch sampling from environments and replays. Args: agent (Agent): Learning agent. env (gym.Env): Environment with gym-like interface. replay (Replay): Replay for training. To disable training from replay...
stack_v2_sparse_classes_36k_train_017912
3,782
permissive
[ { "docstring": "Adapter for batch sampling from environments and replays. Args: agent (Agent): Learning agent. env (gym.Env): Environment with gym-like interface. replay (Replay): Replay for training. To disable training from replay, pass None.", "name": "__init__", "signature": "def __init__(self, agen...
2
stack_v2_sparse_classes_30k_train_001799
Implement the Python class `ReplayRunner` described below. Class description: Implement the ReplayRunner class. Method signatures and docstrings: - def __init__(self, agent, env, replay, shuffle=False): Adapter for batch sampling from environments and replays. Args: agent (Agent): Learning agent. env (gym.Env): Envir...
Implement the Python class `ReplayRunner` described below. Class description: Implement the ReplayRunner class. Method signatures and docstrings: - def __init__(self, agent, env, replay, shuffle=False): Adapter for batch sampling from environments and replays. Args: agent (Agent): Learning agent. env (gym.Env): Envir...
b6447491250c1d41da704b989c751ff2c8a045e6
<|skeleton|> class ReplayRunner: def __init__(self, agent, env, replay, shuffle=False): """Adapter for batch sampling from environments and replays. Args: agent (Agent): Learning agent. env (gym.Env): Environment with gym-like interface. replay (Replay): Replay for training. To disable training from replay...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReplayRunner: def __init__(self, agent, env, replay, shuffle=False): """Adapter for batch sampling from environments and replays. Args: agent (Agent): Learning agent. env (gym.Env): Environment with gym-like interface. replay (Replay): Replay for training. To disable training from replay, pass None.""...
the_stack_v2_python_sparse
receptor/core/runner.py
dbobrenko/receptor
train
0
59f8929e9997f773d66b33b2a31589b184a6e062
[ "from beartype._util.py.utilpyweakref import make_obj_weakref_and_repr\nsuper().__init__(message)\nif not isinstance(culprits, tuple):\n raise _BeartypeUtilExceptionException(f'Culprits {repr(culprits)} not tuple.')\nelif not culprits:\n raise _BeartypeUtilExceptionException('Culprits tuple empty.')\nself._cu...
<|body_start_0|> from beartype._util.py.utilpyweakref import make_obj_weakref_and_repr super().__init__(message) if not isinstance(culprits, tuple): raise _BeartypeUtilExceptionException(f'Culprits {repr(culprits)} not tuple.') elif not culprits: raise _BeartypeUt...
Abstract base class of all **beartype type-checking violations.** Instances of subclasses of this exception are raised by :mod:`beartype` when an object to be type-checked violates the type hint annotating that object. This includes wrapper functions generated by the :func:`beartype.beartype` decorator when either pass...
BeartypeCallHintViolation
[ "MIT", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BeartypeCallHintViolation: """Abstract base class of all **beartype type-checking violations.** Instances of subclasses of this exception are raised by :mod:`beartype` when an object to be type-checked violates the type hint annotating that object. This includes wrapper functions generated by the...
stack_v2_sparse_classes_36k_train_017913
49,857
permissive
[ { "docstring": "Initialize this type-checking exception. Parameters ---------- message : str Human-readable message describing this exception. culprits : Tuple[object, ...] Tuple of one or more **culprits** (i.e., user-defined objects directly responsible for this exception, typically due to violating a type hi...
2
null
Implement the Python class `BeartypeCallHintViolation` described below. Class description: Abstract base class of all **beartype type-checking violations.** Instances of subclasses of this exception are raised by :mod:`beartype` when an object to be type-checked violates the type hint annotating that object. This incl...
Implement the Python class `BeartypeCallHintViolation` described below. Class description: Abstract base class of all **beartype type-checking violations.** Instances of subclasses of this exception are raised by :mod:`beartype` when an object to be type-checked violates the type hint annotating that object. This incl...
0cfd53391eb4de2f8297a4632aa5895b8d82a5b7
<|skeleton|> class BeartypeCallHintViolation: """Abstract base class of all **beartype type-checking violations.** Instances of subclasses of this exception are raised by :mod:`beartype` when an object to be type-checked violates the type hint annotating that object. This includes wrapper functions generated by the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BeartypeCallHintViolation: """Abstract base class of all **beartype type-checking violations.** Instances of subclasses of this exception are raised by :mod:`beartype` when an object to be type-checked violates the type hint annotating that object. This includes wrapper functions generated by the :func:`beart...
the_stack_v2_python_sparse
beartype/roar/_roarexc.py
beartype/beartype
train
1,992
2201e31140c9e94ce7f3e49d1f38c0e6fdda19f3
[ "eva = board.evaluate()\nif eva != 999 and eva != 998:\n return eva\nif board.isEnded():\n return 0\nif beta <= alpha:\n return 0\nif isMax:\n for i in range(board.sizeofX):\n for j in range(board.sizeofY):\n if board.get(i, j) == 0:\n board.move(i, j, 'X')\n ...
<|body_start_0|> eva = board.evaluate() if eva != 999 and eva != 998: return eva if board.isEnded(): return 0 if beta <= alpha: return 0 if isMax: for i in range(board.sizeofX): for j in range(board.sizeofY): ...
Computer for hard difficulty
SmartestComputer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SmartestComputer: """Computer for hard difficulty""" def minmax(self, board, depth, isMax, alpha, beta): """minmax Function that finds the best value of a move Arguments: board {Board} -- Game board depth {int} -- depth of the tree isMax {bool} -- check if is max or min alpha {int} -...
stack_v2_sparse_classes_36k_train_017914
3,019
no_license
[ { "docstring": "minmax Function that finds the best value of a move Arguments: board {Board} -- Game board depth {int} -- depth of the tree isMax {bool} -- check if is max or min alpha {int} -- value of max function beta {int} -- value of min function Returns: int -- value of moveset", "name": "minmax", ...
2
stack_v2_sparse_classes_30k_train_001275
Implement the Python class `SmartestComputer` described below. Class description: Computer for hard difficulty Method signatures and docstrings: - def minmax(self, board, depth, isMax, alpha, beta): minmax Function that finds the best value of a move Arguments: board {Board} -- Game board depth {int} -- depth of the ...
Implement the Python class `SmartestComputer` described below. Class description: Computer for hard difficulty Method signatures and docstrings: - def minmax(self, board, depth, isMax, alpha, beta): minmax Function that finds the best value of a move Arguments: board {Board} -- Game board depth {int} -- depth of the ...
9fbbb20a63813073ca1abcb73f0c1639bd9f5a76
<|skeleton|> class SmartestComputer: """Computer for hard difficulty""" def minmax(self, board, depth, isMax, alpha, beta): """minmax Function that finds the best value of a move Arguments: board {Board} -- Game board depth {int} -- depth of the tree isMax {bool} -- check if is max or min alpha {int} -...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SmartestComputer: """Computer for hard difficulty""" def minmax(self, board, depth, isMax, alpha, beta): """minmax Function that finds the best value of a move Arguments: board {Board} -- Game board depth {int} -- depth of the tree isMax {bool} -- check if is max or min alpha {int} -- value of ma...
the_stack_v2_python_sparse
Assignment 10/Computer.py
Taveeh/Fundamentals-of-Programming
train
2
3b2d844358edfa8f87ccbb40f7f3b7a178157d99
[ "a = 'AGC'\nb = 'AC'\ncomputedMatrix = [[0 for i in range(len(b) + 1)] for j in range(len(a) + 1)]\nfor i in range(1, len(a) + 1):\n computedMatrix[i][0] = computedMatrix[i - 1][0] + pah().weightFunctionDifference('', a[i - 1])\nfor i in range(1, len(b) + 1):\n computedMatrix[0][i] = computedMatrix[0][i - 1] ...
<|body_start_0|> a = 'AGC' b = 'AC' computedMatrix = [[0 for i in range(len(b) + 1)] for j in range(len(a) + 1)] for i in range(1, len(a) + 1): computedMatrix[i][0] = computedMatrix[i - 1][0] + pah().weightFunctionDifference('', a[i - 1]) for i in range(1, len(b) + 1)...
Class to test the correctness of the computation for the class NeedlemanWunsch.
NeedlemanWunschTestClass
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NeedlemanWunschTestClass: """Class to test the correctness of the computation for the class NeedlemanWunsch.""" def test_computeMatrix(self): """Test of the computation of the matrix.""" <|body_0|> def test_traceback(self): """Test of the traceback computation.""...
stack_v2_sparse_classes_36k_train_017915
2,597
no_license
[ { "docstring": "Test of the computation of the matrix.", "name": "test_computeMatrix", "signature": "def test_computeMatrix(self)" }, { "docstring": "Test of the traceback computation.", "name": "test_traceback", "signature": "def test_traceback(self)" } ]
2
stack_v2_sparse_classes_30k_train_009615
Implement the Python class `NeedlemanWunschTestClass` described below. Class description: Class to test the correctness of the computation for the class NeedlemanWunsch. Method signatures and docstrings: - def test_computeMatrix(self): Test of the computation of the matrix. - def test_traceback(self): Test of the tra...
Implement the Python class `NeedlemanWunschTestClass` described below. Class description: Class to test the correctness of the computation for the class NeedlemanWunsch. Method signatures and docstrings: - def test_computeMatrix(self): Test of the computation of the matrix. - def test_traceback(self): Test of the tra...
20d8df6172906337f81583dabb841d66b8f31857
<|skeleton|> class NeedlemanWunschTestClass: """Class to test the correctness of the computation for the class NeedlemanWunsch.""" def test_computeMatrix(self): """Test of the computation of the matrix.""" <|body_0|> def test_traceback(self): """Test of the traceback computation.""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NeedlemanWunschTestClass: """Class to test the correctness of the computation for the class NeedlemanWunsch.""" def test_computeMatrix(self): """Test of the computation of the matrix.""" a = 'AGC' b = 'AC' computedMatrix = [[0 for i in range(len(b) + 1)] for j in range(len...
the_stack_v2_python_sparse
new_algs/Sequence+algorithms/Needleman-Wunsch+algorithm/needlemanWunschTest.py
coolsnake/JupyterNotebook
train
0
e8f7cbbde808a8878f904bf9f211dad0917ca9a6
[ "assert isinstance(parameters, ChannelThresholderParameters)\nself.args = args = parameters\nself.channel = ChannelEncoder(input_shape, args.num_samples, args.sparsity, dtype=dtype, drange=drange, wrap=wrap)\nself.output_shape = self.channel.output_shape\nself.thresholds = np.random.normal(args.mean, args.stddev, s...
<|body_start_0|> assert isinstance(parameters, ChannelThresholderParameters) self.args = args = parameters self.channel = ChannelEncoder(input_shape, args.num_samples, args.sparsity, dtype=dtype, drange=drange, wrap=wrap) self.output_shape = self.channel.output_shape self.thresho...
Creates a channel encoder with an additional activation threshold. A bit becomes active if and only if the underlying channel encoder activates it and its magnitude is not less than its threshold. Activation thresholds are normally distributed.
ChannelThresholder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChannelThresholder: """Creates a channel encoder with an additional activation threshold. A bit becomes active if and only if the underlying channel encoder activates it and its magnitude is not less than its threshold. Activation thresholds are normally distributed.""" def __init__(self, pa...
stack_v2_sparse_classes_36k_train_017916
38,944
permissive
[ { "docstring": "Argument parameters is an instance of ChannelThresholderParameters. Argument input_shape is tuple of dimensions of each input frame. Arguments dtype, drange, and wrap are passed through to the underlying channel encoder.", "name": "__init__", "signature": "def __init__(self, parameters, ...
2
stack_v2_sparse_classes_30k_train_013947
Implement the Python class `ChannelThresholder` described below. Class description: Creates a channel encoder with an additional activation threshold. A bit becomes active if and only if the underlying channel encoder activates it and its magnitude is not less than its threshold. Activation thresholds are normally dis...
Implement the Python class `ChannelThresholder` described below. Class description: Creates a channel encoder with an additional activation threshold. A bit becomes active if and only if the underlying channel encoder activates it and its magnitude is not less than its threshold. Activation thresholds are normally dis...
367f8701ec18226029d7ef070e70e9a8248a1374
<|skeleton|> class ChannelThresholder: """Creates a channel encoder with an additional activation threshold. A bit becomes active if and only if the underlying channel encoder activates it and its magnitude is not less than its threshold. Activation thresholds are normally distributed.""" def __init__(self, pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChannelThresholder: """Creates a channel encoder with an additional activation threshold. A bit becomes active if and only if the underlying channel encoder activates it and its magnitude is not less than its threshold. Activation thresholds are normally distributed.""" def __init__(self, parameters, inp...
the_stack_v2_python_sparse
encoders.py
ctrl-z-9000-times/HTM_experiments
train
15
ca64c8db1f0e15754a752cf24a18a6c36f63885d
[ "candidate = 0\nfor i in xrange(n):\n if knows(candidate, i):\n candidate = i\nfor i in xrange(candidate):\n if knows(candidate, i):\n return -1\nfor i in xrange(candidate + 1, n):\n if not knows(i, candidate):\n return -1\nreturn candidate", "candidates = [True] * n\ncount = 0\nfor ...
<|body_start_0|> candidate = 0 for i in xrange(n): if knows(candidate, i): candidate = i for i in xrange(candidate): if knows(candidate, i): return -1 for i in xrange(candidate + 1, n): if not knows(i, candidate): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findCelebrity(self, n): """:type n: int :rtype: int""" <|body_0|> def findCelebrity_slow(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> candidate = 0 for i in xrange(n): if kno...
stack_v2_sparse_classes_36k_train_017917
1,145
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "findCelebrity", "signature": "def findCelebrity(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "findCelebrity_slow", "signature": "def findCelebrity_slow(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_017599
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findCelebrity(self, n): :type n: int :rtype: int - def findCelebrity_slow(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findCelebrity(self, n): :type n: int :rtype: int - def findCelebrity_slow(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def findCelebrity(self, n): ...
ed15eb27936b39980d4cb5fb61cd937ec7ddcb6a
<|skeleton|> class Solution: def findCelebrity(self, n): """:type n: int :rtype: int""" <|body_0|> def findCelebrity_slow(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findCelebrity(self, n): """:type n: int :rtype: int""" candidate = 0 for i in xrange(n): if knows(candidate, i): candidate = i for i in xrange(candidate): if knows(candidate, i): return -1 for i in xr...
the_stack_v2_python_sparse
alice/LC277.py
AliceTTXu/LeetCode
train
0
e3f1e91a022165a526299378047d7249c65a6eaa
[ "username = request.GET.get('username', None)\nif username is not None:\n pm = get_object_or_404(PM, user__username=username)\n serializer = CMSerializer(pm)\n return JsonResponse({'pms': [serializer.data]}, safe=False)\nelse:\n pms = PM.objects.all()\n serializer = PMSerializer(pms, many=True)\n ...
<|body_start_0|> username = request.GET.get('username', None) if username is not None: pm = get_object_or_404(PM, user__username=username) serializer = CMSerializer(pm) return JsonResponse({'pms': [serializer.data]}, safe=False) else: pms = PM.obje...
专业负责人view
PMs
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PMs: """专业负责人view""" def get(self, request): """查询专业负责人""" <|body_0|> def post(self, request): """增加专业负责人""" <|body_1|> def delete(self, request): """删除导员""" <|body_2|> <|end_skeleton|> <|body_start_0|> username = request.GE...
stack_v2_sparse_classes_36k_train_017918
16,053
permissive
[ { "docstring": "查询专业负责人", "name": "get", "signature": "def get(self, request)" }, { "docstring": "增加专业负责人", "name": "post", "signature": "def post(self, request)" }, { "docstring": "删除导员", "name": "delete", "signature": "def delete(self, request)" } ]
3
stack_v2_sparse_classes_30k_train_010225
Implement the Python class `PMs` described below. Class description: 专业负责人view Method signatures and docstrings: - def get(self, request): 查询专业负责人 - def post(self, request): 增加专业负责人 - def delete(self, request): 删除导员
Implement the Python class `PMs` described below. Class description: 专业负责人view Method signatures and docstrings: - def get(self, request): 查询专业负责人 - def post(self, request): 增加专业负责人 - def delete(self, request): 删除导员 <|skeleton|> class PMs: """专业负责人view""" def get(self, request): """查询专业负责人""" ...
7aaa1be773718de1beb3ce0080edca7c4114b7ad
<|skeleton|> class PMs: """专业负责人view""" def get(self, request): """查询专业负责人""" <|body_0|> def post(self, request): """增加专业负责人""" <|body_1|> def delete(self, request): """删除导员""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PMs: """专业负责人view""" def get(self, request): """查询专业负责人""" username = request.GET.get('username', None) if username is not None: pm = get_object_or_404(PM, user__username=username) serializer = CMSerializer(pm) return JsonResponse({'pms': [seria...
the_stack_v2_python_sparse
user/views.py
MIXISAMA/MIS-backend
train
0
1738ed8d4580f1107dfbee9373698fe766ade0ac
[ "ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(self._build_enforcement_target_attr, role_id=role_id, project_id=project_id, group_id=group_id))\ninherited = self._check_if_inherited()\nPROVIDERS.assignment_api.get_grant(role_id=role_id, group_id=group_id, project_id=project_id,...
<|body_start_0|> ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(self._build_enforcement_target_attr, role_id=role_id, project_id=project_id, group_id=group_id)) inherited = self._check_if_inherited() PROVIDERS.assignment_api.get_grant(role_id=role_id, group_i...
ProjectGroupGrantResource
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectGroupGrantResource: def get(self, project_id, group_id, role_id): """Check grant for project, group, role. GET/HEAD /v3/projects/{project_id/groups/{group_id}/roles/{role_id}""" <|body_0|> def put(self, project_id, group_id, role_id): """Grant role for group o...
stack_v2_sparse_classes_36k_train_017919
22,149
permissive
[ { "docstring": "Check grant for project, group, role. GET/HEAD /v3/projects/{project_id/groups/{group_id}/roles/{role_id}", "name": "get", "signature": "def get(self, project_id, group_id, role_id)" }, { "docstring": "Grant role for group on project. PUT /v3/projects/{project_id}/groups/{group_i...
3
stack_v2_sparse_classes_30k_train_008062
Implement the Python class `ProjectGroupGrantResource` described below. Class description: Implement the ProjectGroupGrantResource class. Method signatures and docstrings: - def get(self, project_id, group_id, role_id): Check grant for project, group, role. GET/HEAD /v3/projects/{project_id/groups/{group_id}/roles/{r...
Implement the Python class `ProjectGroupGrantResource` described below. Class description: Implement the ProjectGroupGrantResource class. Method signatures and docstrings: - def get(self, project_id, group_id, role_id): Check grant for project, group, role. GET/HEAD /v3/projects/{project_id/groups/{group_id}/roles/{r...
03a0a8146a78682ede9eca12a5a7fdacde2035c8
<|skeleton|> class ProjectGroupGrantResource: def get(self, project_id, group_id, role_id): """Check grant for project, group, role. GET/HEAD /v3/projects/{project_id/groups/{group_id}/roles/{role_id}""" <|body_0|> def put(self, project_id, group_id, role_id): """Grant role for group o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProjectGroupGrantResource: def get(self, project_id, group_id, role_id): """Check grant for project, group, role. GET/HEAD /v3/projects/{project_id/groups/{group_id}/roles/{role_id}""" ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(self._build_enforcement_t...
the_stack_v2_python_sparse
keystone/api/projects.py
sapcc/keystone
train
0
89a1c295989ea29028690fe55dcfb797285e968f
[ "self._config = config\nself._log = log\nlog.info('Pulsar Search Interface Initialisation')", "self._log.info('Starting Pulsar Search Interface')\nauthorizer = DummyAuthorizer()\nauthorizer.add_user(self._config['login']['user'], self._config['login']['psswd'], '.', perm=self._config['login']['perm'])\nauthorizer...
<|body_start_0|> self._config = config self._log = log log.info('Pulsar Search Interface Initialisation') <|end_body_0|> <|body_start_1|> self._log.info('Starting Pulsar Search Interface') authorizer = DummyAuthorizer() authorizer.add_user(self._config['login']['user'], ...
Add docstring!
PulsarStart
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PulsarStart: """Add docstring!""" def __init__(self, config, log): """Constructor. The supplied configuration dictionary must contain all parameters needed to define new user See pulsar_receiver_config.json for an example. Args: config (dict): Dictionary containing JSON configuration...
stack_v2_sparse_classes_36k_train_017920
5,054
permissive
[ { "docstring": "Constructor. The supplied configuration dictionary must contain all parameters needed to define new user See pulsar_receiver_config.json for an example. Args: config (dict): Dictionary containing JSON configuration file. log: Logger.", "name": "__init__", "signature": "def __init__(self,...
2
stack_v2_sparse_classes_30k_train_010389
Implement the Python class `PulsarStart` described below. Class description: Add docstring! Method signatures and docstrings: - def __init__(self, config, log): Constructor. The supplied configuration dictionary must contain all parameters needed to define new user See pulsar_receiver_config.json for an example. Args...
Implement the Python class `PulsarStart` described below. Class description: Add docstring! Method signatures and docstrings: - def __init__(self, config, log): Constructor. The supplied configuration dictionary must contain all parameters needed to define new user See pulsar_receiver_config.json for an example. Args...
5875dc0489f707232534ce75daf3707f909bcd15
<|skeleton|> class PulsarStart: """Add docstring!""" def __init__(self, config, log): """Constructor. The supplied configuration dictionary must contain all parameters needed to define new user See pulsar_receiver_config.json for an example. Args: config (dict): Dictionary containing JSON configuration...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PulsarStart: """Add docstring!""" def __init__(self, config, log): """Constructor. The supplied configuration dictionary must contain all parameters needed to define new user See pulsar_receiver_config.json for an example. Args: config (dict): Dictionary containing JSON configuration file. log: L...
the_stack_v2_python_sparse
sip/science_pipeline_workflows/receive_pss/pulsar_search.py
SKA-ScienceDataProcessor/integration-prototype
train
3
9edda2526ddac0aef5e4df6e38d8d83f70b775ed
[ "self.img_size = img_size\nself.conf_thres = conf_thres\nself.nms_thres = nms_thres\nsuper(Yolov3Detector, self).__init__(model=get_yolov3(img_size=img_size), device=device, batch_size=batch_size)", "imgs = super().preprocessing(imgs)\nimgs = [self.__yolov3_img_pre(img) for img in imgs]\nimgs = [torch.unsqueeze(i...
<|body_start_0|> self.img_size = img_size self.conf_thres = conf_thres self.nms_thres = nms_thres super(Yolov3Detector, self).__init__(model=get_yolov3(img_size=img_size), device=device, batch_size=batch_size) <|end_body_0|> <|body_start_1|> imgs = super().preprocessing(imgs) ...
Yolov3Detector
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Yolov3Detector: def __init__(self, device, conf_thres=0.8, nms_thres=0.4, img_size=416, batch_size=1): """Yolov3目标探测网络 Args: device (torch.device): 模型运行硬件 cuda or cpu conf_thres (float, optional): 目标置信度阈值. Defaults to 0.8. nms_thres (float, optional): 非极大值抑制阈值. Defaults to 0.4. img_size ...
stack_v2_sparse_classes_36k_train_017921
16,869
no_license
[ { "docstring": "Yolov3目标探测网络 Args: device (torch.device): 模型运行硬件 cuda or cpu conf_thres (float, optional): 目标置信度阈值. Defaults to 0.8. nms_thres (float, optional): 非极大值抑制阈值. Defaults to 0.4. img_size (int, optional): 网络输入大小. Defaults to 416. batch_size (int, optional): 批处理大小. Defaults to 1.", "name": "__init_...
5
null
Implement the Python class `Yolov3Detector` described below. Class description: Implement the Yolov3Detector class. Method signatures and docstrings: - def __init__(self, device, conf_thres=0.8, nms_thres=0.4, img_size=416, batch_size=1): Yolov3目标探测网络 Args: device (torch.device): 模型运行硬件 cuda or cpu conf_thres (float,...
Implement the Python class `Yolov3Detector` described below. Class description: Implement the Yolov3Detector class. Method signatures and docstrings: - def __init__(self, device, conf_thres=0.8, nms_thres=0.4, img_size=416, batch_size=1): Yolov3目标探测网络 Args: device (torch.device): 模型运行硬件 cuda or cpu conf_thres (float,...
3a0a7faab7049199312604e47f820b189973717e
<|skeleton|> class Yolov3Detector: def __init__(self, device, conf_thres=0.8, nms_thres=0.4, img_size=416, batch_size=1): """Yolov3目标探测网络 Args: device (torch.device): 模型运行硬件 cuda or cpu conf_thres (float, optional): 目标置信度阈值. Defaults to 0.8. nms_thres (float, optional): 非极大值抑制阈值. Defaults to 0.4. img_size ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Yolov3Detector: def __init__(self, device, conf_thres=0.8, nms_thres=0.4, img_size=416, batch_size=1): """Yolov3目标探测网络 Args: device (torch.device): 模型运行硬件 cuda or cpu conf_thres (float, optional): 目标置信度阈值. Defaults to 0.8. nms_thres (float, optional): 非极大值抑制阈值. Defaults to 0.4. img_size (int, optional...
the_stack_v2_python_sparse
components/detector/objectdetector.py
SDGLBL/ITrafficSceneApplication
train
3
8cd089e5fe8ac3149330de8c17073ee2b4a187c4
[ "super(BinaryComposition, self).__init__(operator, left, right)\nself.operator = operator\nself.left = left\nself.right = right\nself.validate()", "_validate_operator_name(self.operator, BinaryComposition.SUPPORTED_OPERATORS)\nif not isinstance(self.left, Expression):\n raise TypeError(u'Expected Expression le...
<|body_start_0|> super(BinaryComposition, self).__init__(operator, left, right) self.operator = operator self.left = left self.right = right self.validate() <|end_body_0|> <|body_start_1|> _validate_operator_name(self.operator, BinaryComposition.SUPPORTED_OPERATORS) ...
An expression created by composing two expressions together.
BinaryComposition
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinaryComposition: """An expression created by composing two expressions together.""" def __init__(self, operator, left, right): """Construct an expression that connects two expressions with an operator. Args: operator: unicode, specifying where the field was declared left: Expressio...
stack_v2_sparse_classes_36k_train_017922
41,432
permissive
[ { "docstring": "Construct an expression that connects two expressions with an operator. Args: operator: unicode, specifying where the field was declared left: Expression on the left side of the binary operator right: Expression on the right side of the binary operator Returns: new BinaryComposition object", ...
5
stack_v2_sparse_classes_30k_train_003924
Implement the Python class `BinaryComposition` described below. Class description: An expression created by composing two expressions together. Method signatures and docstrings: - def __init__(self, operator, left, right): Construct an expression that connects two expressions with an operator. Args: operator: unicode...
Implement the Python class `BinaryComposition` described below. Class description: An expression created by composing two expressions together. Method signatures and docstrings: - def __init__(self, operator, left, right): Construct an expression that connects two expressions with an operator. Args: operator: unicode...
4511793281698bd55e63fd7a3f25f9cb094084d4
<|skeleton|> class BinaryComposition: """An expression created by composing two expressions together.""" def __init__(self, operator, left, right): """Construct an expression that connects two expressions with an operator. Args: operator: unicode, specifying where the field was declared left: Expressio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinaryComposition: """An expression created by composing two expressions together.""" def __init__(self, operator, left, right): """Construct an expression that connects two expressions with an operator. Args: operator: unicode, specifying where the field was declared left: Expression on the left...
the_stack_v2_python_sparse
graphql_compiler/compiler/expressions.py
jb-kensho/graphql-compiler
train
0
985c1981365a5c9e7c886a5077741b078bd2fca3
[ "self.var = var\nself.con = con\nself.var_descr = var_descr\nself.con_descr = con_descr", "r = 'L-System Variables:\\n'\nfor i in range(0, len(self.var)):\n r += '{}: {}\\n'.format(self.var[i], self.var_descr[i])\nr += 'L-System Constants:\\n'\nfor i in range(0, len(self.con)):\n r += '{}: {}\\n'.format(sel...
<|body_start_0|> self.var = var self.con = con self.var_descr = var_descr self.con_descr = con_descr <|end_body_0|> <|body_start_1|> r = 'L-System Variables:\n' for i in range(0, len(self.var)): r += '{}: {}\n'.format(self.var[i], self.var_descr[i]) r...
The L-system vocabulary
vocabulary
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class vocabulary: """The L-system vocabulary""" def __init__(self, var: list, con: list, var_descr: list, con_descr: list) -> None: """Vocabulary parameters Parameters ---------- vocab : list The vocabulary members descr : list The description of the vocabulary members""" <|body_0|...
stack_v2_sparse_classes_36k_train_017923
18,172
permissive
[ { "docstring": "Vocabulary parameters Parameters ---------- vocab : list The vocabulary members descr : list The description of the vocabulary members", "name": "__init__", "signature": "def __init__(self, var: list, con: list, var_descr: list, con_descr: list) -> None" }, { "docstring": "Format...
2
stack_v2_sparse_classes_30k_test_000323
Implement the Python class `vocabulary` described below. Class description: The L-system vocabulary Method signatures and docstrings: - def __init__(self, var: list, con: list, var_descr: list, con_descr: list) -> None: Vocabulary parameters Parameters ---------- vocab : list The vocabulary members descr : list The d...
Implement the Python class `vocabulary` described below. Class description: The L-system vocabulary Method signatures and docstrings: - def __init__(self, var: list, con: list, var_descr: list, con_descr: list) -> None: Vocabulary parameters Parameters ---------- vocab : list The vocabulary members descr : list The d...
b47e951cc465f1d2d6ca4384b2bce05c6e96e2a0
<|skeleton|> class vocabulary: """The L-system vocabulary""" def __init__(self, var: list, con: list, var_descr: list, con_descr: list) -> None: """Vocabulary parameters Parameters ---------- vocab : list The vocabulary members descr : list The description of the vocabulary members""" <|body_0|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class vocabulary: """The L-system vocabulary""" def __init__(self, var: list, con: list, var_descr: list, con_descr: list) -> None: """Vocabulary parameters Parameters ---------- vocab : list The vocabulary members descr : list The description of the vocabulary members""" self.var = var ...
the_stack_v2_python_sparse
Models/MarcMentat/evolve_soft_2d/evolve/lsystems.py
martinventer/Naude_Masters-Project
train
0
c652428851eb81eab8ea3fa740d3fb1f52b51bfc
[ "K = len(probs)\nself.q = torch.zeros(K).cuda()\nself.J = torch.LongTensor([0] * K).cuda()\nsmaller = []\nlarger = []\nfor kk, prob in enumerate(probs):\n self.q[kk] = K * prob\n if self.q[kk] < 1.0:\n smaller.append(kk)\n else:\n larger.append(kk)\nwhile len(smaller) > 0 and len(larger) > 0:...
<|body_start_0|> K = len(probs) self.q = torch.zeros(K).cuda() self.J = torch.LongTensor([0] * K).cuda() smaller = [] larger = [] for kk, prob in enumerate(probs): self.q[kk] = K * prob if self.q[kk] < 1.0: smaller.append(kk) ...
Fast sampling from a multinomial distribution. https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/
AliasMultinomial
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AliasMultinomial: """Fast sampling from a multinomial distribution. https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/""" def __init__(self, probs): """probs: a float tensor with shape [K]. It represents probabilities of dif...
stack_v2_sparse_classes_36k_train_017924
29,814
no_license
[ { "docstring": "probs: a float tensor with shape [K]. It represents probabilities of different outcomes. There are K outcomes. Probabilities sum to one.", "name": "__init__", "signature": "def __init__(self, probs)" }, { "docstring": "Draw N samples from the distribution.", "name": "draw", ...
2
stack_v2_sparse_classes_30k_train_016198
Implement the Python class `AliasMultinomial` described below. Class description: Fast sampling from a multinomial distribution. https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/ Method signatures and docstrings: - def __init__(self, probs): probs: a float ...
Implement the Python class `AliasMultinomial` described below. Class description: Fast sampling from a multinomial distribution. https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/ Method signatures and docstrings: - def __init__(self, probs): probs: a float ...
82d3e9808073f2145b039ccf464c526cb85274e3
<|skeleton|> class AliasMultinomial: """Fast sampling from a multinomial distribution. https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/""" def __init__(self, probs): """probs: a float tensor with shape [K]. It represents probabilities of dif...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AliasMultinomial: """Fast sampling from a multinomial distribution. https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/""" def __init__(self, probs): """probs: a float tensor with shape [K]. It represents probabilities of different outcom...
the_stack_v2_python_sparse
business/p201908/3507_750/lda2vec_model.py
Alvin2580du/alvin_py
train
12
488191c352f647b27d8df2026e5f4fbc6622f390
[ "username = 'admin'\npassword = 'szx0982'\ncls.db = cls.connect_db(username, password)\nlogging.info('DBManager init success')", "client = MongoClient(cls.HOST, cls.PORT)\ndbAuth = client.szx_admin\ndbAuth.authenticate(username, password)\nreturn client.szx_admin" ]
<|body_start_0|> username = 'admin' password = 'szx0982' cls.db = cls.connect_db(username, password) logging.info('DBManager init success') <|end_body_0|> <|body_start_1|> client = MongoClient(cls.HOST, cls.PORT) dbAuth = client.szx_admin dbAuth.authenticate(user...
数据库管理
DBManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DBManager: """数据库管理""" def init(cls): """数据库初始化""" <|body_0|> def connect_db(cls, username, password): """连接数据库""" <|body_1|> <|end_skeleton|> <|body_start_0|> username = 'admin' password = 'szx0982' cls.db = cls.connect_db(usern...
stack_v2_sparse_classes_36k_train_017925
906
no_license
[ { "docstring": "数据库初始化", "name": "init", "signature": "def init(cls)" }, { "docstring": "连接数据库", "name": "connect_db", "signature": "def connect_db(cls, username, password)" } ]
2
stack_v2_sparse_classes_30k_val_000356
Implement the Python class `DBManager` described below. Class description: 数据库管理 Method signatures and docstrings: - def init(cls): 数据库初始化 - def connect_db(cls, username, password): 连接数据库
Implement the Python class `DBManager` described below. Class description: 数据库管理 Method signatures and docstrings: - def init(cls): 数据库初始化 - def connect_db(cls, username, password): 连接数据库 <|skeleton|> class DBManager: """数据库管理""" def init(cls): """数据库初始化""" <|body_0|> def connect_db(cls...
5feaf8b466c125e93fd08f31cc0eed99c9b4d164
<|skeleton|> class DBManager: """数据库管理""" def init(cls): """数据库初始化""" <|body_0|> def connect_db(cls, username, password): """连接数据库""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DBManager: """数据库管理""" def init(cls): """数据库初始化""" username = 'admin' password = 'szx0982' cls.db = cls.connect_db(username, password) logging.info('DBManager init success') def connect_db(cls, username, password): """连接数据库""" client = MongoCli...
the_stack_v2_python_sparse
base/db/DBManger.py
goodcan/financial-system-backend
train
1
cdff1d96ff767a993a1b3b35bb86b417dad60690
[ "if n == 1:\n return True\nelif n == 0:\n return False\nelse:\n c = 0\n for i in bin(n):\n if c < 3:\n c += 1\n continue\n elif i == '1':\n return False\n return True", "if n > 0 and n & n - 1 == 0:\n return True\nelse:\n return False", "if n <...
<|body_start_0|> if n == 1: return True elif n == 0: return False else: c = 0 for i in bin(n): if c < 3: c += 1 continue elif i == '1': return False ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPowerOfTwo_0(self, n: int) -> bool: """笨办法.遍历二进制码. 如果整数是2的幂次方,则其二进制数除了最高位是1,其余为都为0 :param n: :return:""" <|body_0|> def isPowerOfTwo_1(self, n: int) -> bool: """如果n是2的幂次方,则 n&n-1=0 举例: 8=>100 7=>111 8&7=0 :param n: :return:""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_017926
1,578
permissive
[ { "docstring": "笨办法.遍历二进制码. 如果整数是2的幂次方,则其二进制数除了最高位是1,其余为都为0 :param n: :return:", "name": "isPowerOfTwo_0", "signature": "def isPowerOfTwo_0(self, n: int) -> bool" }, { "docstring": "如果n是2的幂次方,则 n&n-1=0 举例: 8=>100 7=>111 8&7=0 :param n: :return:", "name": "isPowerOfTwo_1", "signature": "d...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPowerOfTwo_0(self, n: int) -> bool: 笨办法.遍历二进制码. 如果整数是2的幂次方,则其二进制数除了最高位是1,其余为都为0 :param n: :return: - def isPowerOfTwo_1(self, n: int) -> bool: 如果n是2的幂次方,则 n&n-1=0 举例: 8=>10...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPowerOfTwo_0(self, n: int) -> bool: 笨办法.遍历二进制码. 如果整数是2的幂次方,则其二进制数除了最高位是1,其余为都为0 :param n: :return: - def isPowerOfTwo_1(self, n: int) -> bool: 如果n是2的幂次方,则 n&n-1=0 举例: 8=>10...
60e9ef1051a1d0441ab1c5484a51ab77a306bf5b
<|skeleton|> class Solution: def isPowerOfTwo_0(self, n: int) -> bool: """笨办法.遍历二进制码. 如果整数是2的幂次方,则其二进制数除了最高位是1,其余为都为0 :param n: :return:""" <|body_0|> def isPowerOfTwo_1(self, n: int) -> bool: """如果n是2的幂次方,则 n&n-1=0 举例: 8=>100 7=>111 8&7=0 :param n: :return:""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPowerOfTwo_0(self, n: int) -> bool: """笨办法.遍历二进制码. 如果整数是2的幂次方,则其二进制数除了最高位是1,其余为都为0 :param n: :return:""" if n == 1: return True elif n == 0: return False else: c = 0 for i in bin(n): if c < 3: ...
the_stack_v2_python_sparse
Week 7/id_710/LeetCode_231_710.py
chenlei65368/algorithm004-05
train
1
4565c7b8b4dbc2832519dd865eb1f6c386495adb
[ "if applyTransform:\n boundPts = [obj.matrix_world * Vector(corner) for corner in obj.bound_box]\nelse:\n boundPts = obj.bound_box\nxmin = min([pt[0] for pt in boundPts])\nxmax = max([pt[0] for pt in boundPts])\nymin = min([pt[1] for pt in boundPts])\nymax = max([pt[1] for pt in boundPts])\nzmin = min([pt[2] ...
<|body_start_0|> if applyTransform: boundPts = [obj.matrix_world * Vector(corner) for corner in obj.bound_box] else: boundPts = obj.bound_box xmin = min([pt[0] for pt in boundPts]) xmax = max([pt[0] for pt in boundPts]) ymin = min([pt[1] for pt in boundPts...
Utilities to build BBOX object from various Blender context
getBBOX
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class getBBOX: """Utilities to build BBOX object from various Blender context""" def fromObj(obj, applyTransform=True): """Create a 3D BBOX from Blender object""" <|body_0|> def fromScn(cls, scn): """Create a 3D BBOX from Blender Scene union of bounding box of all obje...
stack_v2_sparse_classes_36k_train_017927
7,516
no_license
[ { "docstring": "Create a 3D BBOX from Blender object", "name": "fromObj", "signature": "def fromObj(obj, applyTransform=True)" }, { "docstring": "Create a 3D BBOX from Blender Scene union of bounding box of all objects containing in the scene", "name": "fromScn", "signature": "def fromSc...
4
stack_v2_sparse_classes_30k_train_003817
Implement the Python class `getBBOX` described below. Class description: Utilities to build BBOX object from various Blender context Method signatures and docstrings: - def fromObj(obj, applyTransform=True): Create a 3D BBOX from Blender object - def fromScn(cls, scn): Create a 3D BBOX from Blender Scene union of bou...
Implement the Python class `getBBOX` described below. Class description: Utilities to build BBOX object from various Blender context Method signatures and docstrings: - def fromObj(obj, applyTransform=True): Create a 3D BBOX from Blender object - def fromScn(cls, scn): Create a 3D BBOX from Blender Scene union of bou...
c3469272f0775ca8c9ad98e74465e16610ef0983
<|skeleton|> class getBBOX: """Utilities to build BBOX object from various Blender context""" def fromObj(obj, applyTransform=True): """Create a 3D BBOX from Blender object""" <|body_0|> def fromScn(cls, scn): """Create a 3D BBOX from Blender Scene union of bounding box of all obje...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class getBBOX: """Utilities to build BBOX object from various Blender context""" def fromObj(obj, applyTransform=True): """Create a 3D BBOX from Blender object""" if applyTransform: boundPts = [obj.matrix_world * Vector(corner) for corner in obj.bound_box] else: ...
the_stack_v2_python_sparse
operators/utils/bgis_utils.py
blendergis/BlenderGIS
train
3
33139806453009cc9cadda8583218f6cc7d28f13
[ "errors = []\nif not HAS_XMLTODICT:\n errors.append(missing_required_lib('xmltodict'))\nreturn errors", "errors = self._check_reqs()\nif errors:\n return {'errors': errors}\ncli_output = self._task_args.get('text')\nnetwork_os = self._task_args.get('parser').get('os') or self._task_vars.get('ansible_network...
<|body_start_0|> errors = [] if not HAS_XMLTODICT: errors.append(missing_required_lib('xmltodict')) return errors <|end_body_0|> <|body_start_1|> errors = self._check_reqs() if errors: return {'errors': errors} cli_output = self._task_args.get('te...
The xml parser class Convert an xml string to structured data using xmltodict
CliParser
[ "MIT", "GPL-3.0-or-later", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CliParser: """The xml parser class Convert an xml string to structured data using xmltodict""" def _check_reqs(): """Check the prerequisites for the xml parser""" <|body_0|> def parse(self, *_args, **_kwargs): """Std entry point for a cli_parse parse execution :r...
stack_v2_sparse_classes_36k_train_017928
2,153
permissive
[ { "docstring": "Check the prerequisites for the xml parser", "name": "_check_reqs", "signature": "def _check_reqs()" }, { "docstring": "Std entry point for a cli_parse parse execution :return: Errors or parsed text as structured data :rtype: dict :example: The parse function of a parser should r...
2
stack_v2_sparse_classes_30k_test_000552
Implement the Python class `CliParser` described below. Class description: The xml parser class Convert an xml string to structured data using xmltodict Method signatures and docstrings: - def _check_reqs(): Check the prerequisites for the xml parser - def parse(self, *_args, **_kwargs): Std entry point for a cli_par...
Implement the Python class `CliParser` described below. Class description: The xml parser class Convert an xml string to structured data using xmltodict Method signatures and docstrings: - def _check_reqs(): Check the prerequisites for the xml parser - def parse(self, *_args, **_kwargs): Std entry point for a cli_par...
2ea7d4f00212f502bc684ac257371ada73da1ca9
<|skeleton|> class CliParser: """The xml parser class Convert an xml string to structured data using xmltodict""" def _check_reqs(): """Check the prerequisites for the xml parser""" <|body_0|> def parse(self, *_args, **_kwargs): """Std entry point for a cli_parse parse execution :r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CliParser: """The xml parser class Convert an xml string to structured data using xmltodict""" def _check_reqs(): """Check the prerequisites for the xml parser""" errors = [] if not HAS_XMLTODICT: errors.append(missing_required_lib('xmltodict')) return errors ...
the_stack_v2_python_sparse
intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/ansible/netcommon/plugins/cli_parsers/xml_parser.py
SimonFangCisco/dne-dna-code
train
0
6163f0a1adb85a9fe56b50b3065461837c654ae9
[ "if device in cls.warned_devices:\n return\ncls.warned_devices.add(device)\nif fstype is None:\n logger.warning(f'Failed to determine filesystem type for {path} (device id: {device}). Using soft file locks to avoid potential data corruption.')\n return\nlogger.warning(f'The lock file {path} is on a filesys...
<|body_start_0|> if device in cls.warned_devices: return cls.warned_devices.add(device) if fstype is None: logger.warning(f'Failed to determine filesystem type for {path} (device id: {device}). Using soft file locks to avoid potential data corruption.') return...
This class is used to inspect the file system state and determine if the file being created can use `fcntl` / `flock` or should use soft file locks. This can be achieved by finding the device owning the parent directory and mapping it to the partition and finally checking the filesystem type. We prefer using soft file ...
FileSystemInspector
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileSystemInspector: """This class is used to inspect the file system state and determine if the file being created can use `fcntl` / `flock` or should use soft file locks. This can be achieved by finding the device owning the parent directory and mapping it to the partition and finally checking ...
stack_v2_sparse_classes_36k_train_017929
7,858
permissive
[ { "docstring": "Warn only once per device. This is used to avoid spamming the logs with the same message.", "name": "_warn_only_once", "signature": "def _warn_only_once(cls, path: str, device: int, fstype: Optional[str]) -> None" }, { "docstring": "Returns a mapping of device numbers to filesyst...
4
null
Implement the Python class `FileSystemInspector` described below. Class description: This class is used to inspect the file system state and determine if the file being created can use `fcntl` / `flock` or should use soft file locks. This can be achieved by finding the device owning the parent directory and mapping it...
Implement the Python class `FileSystemInspector` described below. Class description: This class is used to inspect the file system state and determine if the file being created can use `fcntl` / `flock` or should use soft file locks. This can be achieved by finding the device owning the parent directory and mapping it...
34e5c2c29abe9b26699760074adcadfe8fd4cfe0
<|skeleton|> class FileSystemInspector: """This class is used to inspect the file system state and determine if the file being created can use `fcntl` / `flock` or should use soft file locks. This can be achieved by finding the device owning the parent directory and mapping it to the partition and finally checking ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FileSystemInspector: """This class is used to inspect the file system state and determine if the file being created can use `fcntl` / `flock` or should use soft file locks. This can be achieved by finding the device owning the parent directory and mapping it to the partition and finally checking the filesyste...
the_stack_v2_python_sparse
src/python/aim/_core/storage/locking.py
aimhubio/aim
train
4,091
4e9098d394baadbf5e1be6f80dfe0384f89b8690
[ "super(CreateCuttlefishActionTest, self).setUp()\nself.build_client = mock.MagicMock()\nself.Patch(android_build_client, 'AndroidBuildClient', return_value=self.build_client)\nself.compute_client = mock.MagicMock()\nself.Patch(cvd_compute_client, 'CvdComputeClient', return_value=self.compute_client)\nself.Patch(cvd...
<|body_start_0|> super(CreateCuttlefishActionTest, self).setUp() self.build_client = mock.MagicMock() self.Patch(android_build_client, 'AndroidBuildClient', return_value=self.build_client) self.compute_client = mock.MagicMock() self.Patch(cvd_compute_client, 'CvdComputeClient', r...
Test create_cuttlefish_action.
CreateCuttlefishActionTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateCuttlefishActionTest: """Test create_cuttlefish_action.""" def setUp(self): """Set up the test.""" <|body_0|> def _CreateCfg(self): """A helper method that creates a mock configuration object.""" <|body_1|> def testCreateDevices(self): ...
stack_v2_sparse_classes_36k_train_017930
7,513
permissive
[ { "docstring": "Set up the test.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "A helper method that creates a mock configuration object.", "name": "_CreateCfg", "signature": "def _CreateCfg(self)" }, { "docstring": "Test CreateDevices.", "name": "testCr...
3
null
Implement the Python class `CreateCuttlefishActionTest` described below. Class description: Test create_cuttlefish_action. Method signatures and docstrings: - def setUp(self): Set up the test. - def _CreateCfg(self): A helper method that creates a mock configuration object. - def testCreateDevices(self): Test CreateD...
Implement the Python class `CreateCuttlefishActionTest` described below. Class description: Test create_cuttlefish_action. Method signatures and docstrings: - def setUp(self): Set up the test. - def _CreateCfg(self): A helper method that creates a mock configuration object. - def testCreateDevices(self): Test CreateD...
78a61ca023cbf1a0cecfef8b97df2b274ac3a988
<|skeleton|> class CreateCuttlefishActionTest: """Test create_cuttlefish_action.""" def setUp(self): """Set up the test.""" <|body_0|> def _CreateCfg(self): """A helper method that creates a mock configuration object.""" <|body_1|> def testCreateDevices(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateCuttlefishActionTest: """Test create_cuttlefish_action.""" def setUp(self): """Set up the test.""" super(CreateCuttlefishActionTest, self).setUp() self.build_client = mock.MagicMock() self.Patch(android_build_client, 'AndroidBuildClient', return_value=self.build_clie...
the_stack_v2_python_sparse
tools/acloud/public/actions/create_cuttlefish_action_test.py
ZYHGOD-1/Aosp11
train
0
9796b6b007d6c0cfe68ac39cb8d29628b4836f51
[ "self.csv_features = {}\nself.meta_features = []\nself.logger = fmeobjects.FMELogFile()\nself.session = FME_utils.create_session()", "order = feature.getAttribute(ORDER)\nif order == 1:\n default_key = feature.getAttribute('default_key')\n default_value = feature.getAttribute('default_value')\n self.csv_...
<|body_start_0|> self.csv_features = {} self.meta_features = [] self.logger = fmeobjects.FMELogFile() self.session = FME_utils.create_session() <|end_body_0|> <|body_start_1|> order = feature.getAttribute(ORDER) if order == 1: default_key = feature.getAttribu...
This class implement the design pattern: *Processing Composite Data*
FeatureProcessor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeatureProcessor: """This class implement the design pattern: *Processing Composite Data*""" def __init__(self): """This constructor method created a dictionary and a list to store the features.""" <|body_0|> def input(self, feature): """Load the incoming feature...
stack_v2_sparse_classes_36k_train_017931
6,105
permissive
[ { "docstring": "This constructor method created a dictionary and a list to store the features.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Load the incoming features. The features from the CSV (_order=1) are stored in a dictionary according to the unique format nam...
4
null
Implement the Python class `FeatureProcessor` described below. Class description: This class implement the design pattern: *Processing Composite Data* Method signatures and docstrings: - def __init__(self): This constructor method created a dictionary and a list to store the features. - def input(self, feature): Load...
Implement the Python class `FeatureProcessor` described below. Class description: This class implement the design pattern: *Processing Composite Data* Method signatures and docstrings: - def __init__(self): This constructor method created a dictionary and a list to store the features. - def input(self, feature): Load...
82368614a2658260c0f09a1b5d341918310626e5
<|skeleton|> class FeatureProcessor: """This class implement the design pattern: *Processing Composite Data*""" def __init__(self): """This constructor method created a dictionary and a list to store the features.""" <|body_0|> def input(self, feature): """Load the incoming feature...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeatureProcessor: """This class implement the design pattern: *Processing Composite Data*""" def __init__(self): """This constructor method created a dictionary and a list to store the features.""" self.csv_features = {} self.meta_features = [] self.logger = fmeobjects.FME...
the_stack_v2_python_sparse
FME_files/FME_Custom_Transformers/Python/GEOPORTAL_WEBLINK_ADDER_NG.py
federal-geospatial-platform/fgp-metadata-proxy
train
10
396fd021d2a349856c3822a0a3d6b26428400bf7
[ "url = await SourceCollector._api_url(self)\ncomponent = self._parameter('component')\nbranch = self._parameter('branch')\nreturn URL(f'{url}/project/issues?id={component}&branch={branch}')", "url = await SourceCollector._api_url(self)\ncomponent = self._parameter('component')\nbranch = self._parameter('branch')\...
<|body_start_0|> url = await SourceCollector._api_url(self) component = self._parameter('component') branch = self._parameter('branch') return URL(f'{url}/project/issues?id={component}&branch={branch}') <|end_body_0|> <|body_start_1|> url = await SourceCollector._api_url(self) ...
SonarQube suppressed violations collector.
SonarQubeSuppressedViolations
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SonarQubeSuppressedViolations: """SonarQube suppressed violations collector.""" async def _landing_url(self, responses: SourceResponses) -> URL: """Override to not include the rules parameter in the landing URL. This collector uses two SonarQube endpoints to get the suppressed violat...
stack_v2_sparse_classes_36k_train_017932
2,824
permissive
[ { "docstring": "Override to not include the rules parameter in the landing URL. This collector uses two SonarQube endpoints to get the suppressed violations. As we can't include both URLs in the landing URL, we use the overview of all issues as landing page.", "name": "_landing_url", "signature": "async...
4
null
Implement the Python class `SonarQubeSuppressedViolations` described below. Class description: SonarQube suppressed violations collector. Method signatures and docstrings: - async def _landing_url(self, responses: SourceResponses) -> URL: Override to not include the rules parameter in the landing URL. This collector ...
Implement the Python class `SonarQubeSuppressedViolations` described below. Class description: SonarQube suppressed violations collector. Method signatures and docstrings: - async def _landing_url(self, responses: SourceResponses) -> URL: Override to not include the rules parameter in the landing URL. This collector ...
5d9952bf0bd47895824fa78428d3e4f4d6b5d9b3
<|skeleton|> class SonarQubeSuppressedViolations: """SonarQube suppressed violations collector.""" async def _landing_url(self, responses: SourceResponses) -> URL: """Override to not include the rules parameter in the landing URL. This collector uses two SonarQube endpoints to get the suppressed violat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SonarQubeSuppressedViolations: """SonarQube suppressed violations collector.""" async def _landing_url(self, responses: SourceResponses) -> URL: """Override to not include the rules parameter in the landing URL. This collector uses two SonarQube endpoints to get the suppressed violations. As we c...
the_stack_v2_python_sparse
components/collector/src/source_collectors/sonarqube/suppressed_violations.py
ICTU/quality-time
train
43
142bc8a0fe3973592e486549f618261f42c5f9dc
[ "self.project = project\nself.date = date\nself.dest = dest", "pattern = 'cat /home/logs/vm-lnx-idpdm*/httpd/{project}.ncep.noaa.gov/access.{year}{month:02d}{day:02}'\nif self.date != dt.date.today():\n pattern += '.gz'\nkwargs = {'project': self.project, 'year': self.date.year, 'month': self.date.month, 'day'...
<|body_start_0|> self.project = project self.date = date self.dest = dest <|end_body_0|> <|body_start_1|> pattern = 'cat /home/logs/vm-lnx-idpdm*/httpd/{project}.ncep.noaa.gov/access.{year}{month:02d}{day:02}' if self.date != dt.date.today(): pattern += '.gz' ...
Download and count log file hits for a single day. Attributes ---------- project : str Specifies the project to process. date : datetime.date Defines year and month for log file merging. logfiles : list List of log files for the given month.
DailyApacheLogCount
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DailyApacheLogCount: """Download and count log file hits for a single day. Attributes ---------- project : str Specifies the project to process. date : datetime.date Defines year and month for log file merging. logfiles : list List of log files for the given month.""" def __init__(self, proj...
stack_v2_sparse_classes_36k_train_017933
2,546
no_license
[ { "docstring": "Parameters ---------- date : datetime.date Defines date for daily log file hits counting. dest : str CSV file", "name": "__init__", "signature": "def __init__(self, project, date, dest)" }, { "docstring": "Count the number of items in the files", "name": "run", "signature...
2
stack_v2_sparse_classes_30k_test_000994
Implement the Python class `DailyApacheLogCount` described below. Class description: Download and count log file hits for a single day. Attributes ---------- project : str Specifies the project to process. date : datetime.date Defines year and month for log file merging. logfiles : list List of log files for the given...
Implement the Python class `DailyApacheLogCount` described below. Class description: Download and count log file hits for a single day. Attributes ---------- project : str Specifies the project to process. date : datetime.date Defines year and month for log file merging. logfiles : list List of log files for the given...
8002cd4822a61075b365b3823d574f3c0ecc3b45
<|skeleton|> class DailyApacheLogCount: """Download and count log file hits for a single day. Attributes ---------- project : str Specifies the project to process. date : datetime.date Defines year and month for log file merging. logfiles : list List of log files for the given month.""" def __init__(self, proj...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DailyApacheLogCount: """Download and count log file hits for a single day. Attributes ---------- project : str Specifies the project to process. date : datetime.date Defines year and month for log file merging. logfiles : list List of log files for the given month.""" def __init__(self, project, date, de...
the_stack_v2_python_sparse
abusive-user-detection/gis_utilities/daily_log_merge.py
quintusdias/gis-monitoring
train
0
612dc6af577ba900d27d448d62eb286d4a04b347
[ "format_file = 'csv'\nkwargs = locals()\nkwargs['schema'] = _check_schema(kwargs['schema'])\ntmp = _apply_datareader(format_file, kwargs)\nreturn tmp", "format_file = 'json'\nkwargs = locals()\nkwargs['schema'] = _check_schema(kwargs['schema'])\ntmp = _apply_datareader(format_file, kwargs)\nreturn tmp", "format...
<|body_start_0|> format_file = 'csv' kwargs = locals() kwargs['schema'] = _check_schema(kwargs['schema']) tmp = _apply_datareader(format_file, kwargs) return tmp <|end_body_0|> <|body_start_1|> format_file = 'json' kwargs = locals() kwargs['schema'] = _ch...
DataReader
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataReader: def csv(filepath, num_of_parts='*', schema='str', sep=',', header=True, delimiter=None, na_filter=True, usecols=None, prefix=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, na_values=None, keep_default_na=True, skip_blank_lines=True, p...
stack_v2_sparse_classes_36k_train_017934
7,699
permissive
[ { "docstring": "Reads a csv file. :param filepath: :param num_of_parts: :param schema: :param sep: :param header: :param delimiter: :param na_filter: :param usecols: :param prefix: :param engine: :param converters: :param true_values: :param false_values: :param skipinitialspace: :param na_values: :param keep_d...
4
stack_v2_sparse_classes_30k_train_018123
Implement the Python class `DataReader` described below. Class description: Implement the DataReader class. Method signatures and docstrings: - def csv(filepath, num_of_parts='*', schema='str', sep=',', header=True, delimiter=None, na_filter=True, usecols=None, prefix=None, engine=None, converters=None, true_values=N...
Implement the Python class `DataReader` described below. Class description: Implement the DataReader class. Method signatures and docstrings: - def csv(filepath, num_of_parts='*', schema='str', sep=',', header=True, delimiter=None, na_filter=True, usecols=None, prefix=None, engine=None, converters=None, true_values=N...
09ab7c474c8badc9932de3e1148f62ffba16b0b2
<|skeleton|> class DataReader: def csv(filepath, num_of_parts='*', schema='str', sep=',', header=True, delimiter=None, na_filter=True, usecols=None, prefix=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, na_values=None, keep_default_na=True, skip_blank_lines=True, p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataReader: def csv(filepath, num_of_parts='*', schema='str', sep=',', header=True, delimiter=None, na_filter=True, usecols=None, prefix=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, na_values=None, keep_default_na=True, skip_blank_lines=True, parse_dates=Fal...
the_stack_v2_python_sparse
ddf_library/bases/data_reader.py
eubr-bigsea/Compss-Python
train
3
2f3a397abb79415922ead343d429dc1111c7d23a
[ "self._sensors = sensors\nself._const = const\nself.firmware = {}\nself.requested = {}\nself.started = {}\nself.unstarted = {}", "fw_type = None\nfw_ver = None\nif not isinstance(updates, tuple):\n updates = (updates,)\nfor store in updates:\n fw_id = store.pop(msg.node_id, None)\n if fw_id is not None:\...
<|body_start_0|> self._sensors = sensors self._const = const self.firmware = {} self.requested = {} self.started = {} self.unstarted = {} <|end_body_0|> <|body_start_1|> fw_type = None fw_ver = None if not isinstance(updates, tuple): u...
Organize OTAFirmware updates.
OTAFirmware
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OTAFirmware: """Organize OTAFirmware updates.""" def __init__(self, sensors, const): """Set up OTA firmware instance.""" <|body_0|> def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None): """Get firmware type, version and a dict holding binary data.""...
stack_v2_sparse_classes_36k_train_017935
6,845
permissive
[ { "docstring": "Set up OTA firmware instance.", "name": "__init__", "signature": "def __init__(self, sensors, const)" }, { "docstring": "Get firmware type, version and a dict holding binary data.", "name": "_get_fw", "signature": "def _get_fw(self, msg, updates, req_fw_type=None, req_fw_...
5
stack_v2_sparse_classes_30k_train_013616
Implement the Python class `OTAFirmware` described below. Class description: Organize OTAFirmware updates. Method signatures and docstrings: - def __init__(self, sensors, const): Set up OTA firmware instance. - def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None): Get firmware type, version and a dict h...
Implement the Python class `OTAFirmware` described below. Class description: Organize OTAFirmware updates. Method signatures and docstrings: - def __init__(self, sensors, const): Set up OTA firmware instance. - def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None): Get firmware type, version and a dict h...
f7264321986a66193192a10f3261fe268eeb7601
<|skeleton|> class OTAFirmware: """Organize OTAFirmware updates.""" def __init__(self, sensors, const): """Set up OTA firmware instance.""" <|body_0|> def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None): """Get firmware type, version and a dict holding binary data.""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OTAFirmware: """Organize OTAFirmware updates.""" def __init__(self, sensors, const): """Set up OTA firmware instance.""" self._sensors = sensors self._const = const self.firmware = {} self.requested = {} self.started = {} self.unstarted = {} de...
the_stack_v2_python_sparse
mysensors/ota.py
theolind/pymysensors
train
68
656256fb8189a363ae884d547f42ee47acf4f06b
[ "matrix = copy.deepcopy(grid)\nxLength = len(grid)\nyLength = xLength and len(grid[0])\nfor i in range(1, xLength):\n matrix[i][0] += matrix[i - 1][0]\nfor i in range(1, yLength):\n matrix[0][i] += matrix[0][i - 1]\nfor i in range(1, xLength):\n for j in range(1, yLength):\n matrix[i][j] += min(matr...
<|body_start_0|> matrix = copy.deepcopy(grid) xLength = len(grid) yLength = xLength and len(grid[0]) for i in range(1, xLength): matrix[i][0] += matrix[i - 1][0] for i in range(1, yLength): matrix[0][i] += matrix[0][i - 1] for i in range(1, xLength...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minPathSum(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_0|> def minPathSum2(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> matrix = copy.deepcopy(grid) ...
stack_v2_sparse_classes_36k_train_017936
1,207
permissive
[ { "docstring": ":type grid: List[List[int]] :rtype: int", "name": "minPathSum", "signature": "def minPathSum(self, grid)" }, { "docstring": ":type grid: List[List[int]] :rtype: int", "name": "minPathSum2", "signature": "def minPathSum2(self, grid)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int - def minPathSum2(self, grid): :type grid: List[List[int]] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int - def minPathSum2(self, grid): :type grid: List[List[int]] :rtype: int <|skeleton|> class Solution: def ...
c8bf33af30569177c5276ffcd72a8d93ba4c402a
<|skeleton|> class Solution: def minPathSum(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_0|> def minPathSum2(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minPathSum(self, grid): """:type grid: List[List[int]] :rtype: int""" matrix = copy.deepcopy(grid) xLength = len(grid) yLength = xLength and len(grid[0]) for i in range(1, xLength): matrix[i][0] += matrix[i - 1][0] for i in range(1, yLe...
the_stack_v2_python_sparse
1-100/61-70/64-minimumPathSum/minimumPathSum.py
xuychen/Leetcode
train
0
100bf4227863d859549157f6294da31fa184ab24
[ "self.parameters = parameters\nself._tree = None\nself._paths = None\nreturn", "if self._tree is None:\n parameters = self.parameters[:]\n leaves = parameters.pop()\n parameters.reverse()\n tree = [TreeNode(Parameters(leaves.name, leaf)) for leaf in leaves.parameters]\n for level in parameters:\n ...
<|body_start_0|> self.parameters = parameters self._tree = None self._paths = None return <|end_body_0|> <|body_start_1|> if self._tree is None: parameters = self.parameters[:] leaves = parameters.pop() parameters.reverse() tree = ...
A class to build a tree from iterative parameters The main product is the `paths` attribute which can be iterated over to get the parameters for a test.
ParameterTree
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParameterTree: """A class to build a tree from iterative parameters The main product is the `paths` attribute which can be iterated over to get the parameters for a test.""" def __init__(self, parameters): """:param: - `parameters`: list of parameter objects with a `name` property"""...
stack_v2_sparse_classes_36k_train_017937
3,506
permissive
[ { "docstring": ":param: - `parameters`: list of parameter objects with a `name` property", "name": "__init__", "signature": "def __init__(self, parameters)" }, { "docstring": "builds the tree bottoms-up from the parameters :return: list of trees (highest nodes are parameters[0], leaves are param...
4
stack_v2_sparse_classes_30k_train_012207
Implement the Python class `ParameterTree` described below. Class description: A class to build a tree from iterative parameters The main product is the `paths` attribute which can be iterated over to get the parameters for a test. Method signatures and docstrings: - def __init__(self, parameters): :param: - `paramet...
Implement the Python class `ParameterTree` described below. Class description: A class to build a tree from iterative parameters The main product is the `paths` attribute which can be iterated over to get the parameters for a test. Method signatures and docstrings: - def __init__(self, parameters): :param: - `paramet...
b4d1c77e1d611fe2b30768b42bdc7493afb0ea95
<|skeleton|> class ParameterTree: """A class to build a tree from iterative parameters The main product is the `paths` attribute which can be iterated over to get the parameters for a test.""" def __init__(self, parameters): """:param: - `parameters`: list of parameter objects with a `name` property"""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ParameterTree: """A class to build a tree from iterative parameters The main product is the `paths` attribute which can be iterated over to get the parameters for a test.""" def __init__(self, parameters): """:param: - `parameters`: list of parameter objects with a `name` property""" self...
the_stack_v2_python_sparse
apetools/lexicographers/parametertree.py
russell-n/oldape
train
0
75064ee9a463a109fc0d4c9876edce92211b627d
[ "user = request.user\nway = Way.get_by_id(way_id)\nif not way:\n return RESPONSE_400_OBJECT_NOT_FOUND\nif not user == way.user:\n return RESPONSE_403_ACCESS_DENIED\nif not notification_id:\n data = [notification.to_dict() for notification in way.notifications.all().order_by('week_day')]\n return JsonRes...
<|body_start_0|> user = request.user way = Way.get_by_id(way_id) if not way: return RESPONSE_400_OBJECT_NOT_FOUND if not user == way.user: return RESPONSE_403_ACCESS_DENIED if not notification_id: data = [notification.to_dict() for notification...
Notification view that handles GET, POST, PUT, DELETE requests and provides appropriate operations with notification model.
NotificationView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NotificationView: """Notification view that handles GET, POST, PUT, DELETE requests and provides appropriate operations with notification model.""" def get(self, request, way_id, notification_id=None): """Method that handles GET request.""" <|body_0|> def put(self, reque...
stack_v2_sparse_classes_36k_train_017938
4,575
no_license
[ { "docstring": "Method that handles GET request.", "name": "get", "signature": "def get(self, request, way_id, notification_id=None)" }, { "docstring": "Method that handles PUT request.", "name": "put", "signature": "def put(self, request, way_id, notification_id=None)" }, { "doc...
4
stack_v2_sparse_classes_30k_train_000561
Implement the Python class `NotificationView` described below. Class description: Notification view that handles GET, POST, PUT, DELETE requests and provides appropriate operations with notification model. Method signatures and docstrings: - def get(self, request, way_id, notification_id=None): Method that handles GE...
Implement the Python class `NotificationView` described below. Class description: Notification view that handles GET, POST, PUT, DELETE requests and provides appropriate operations with notification model. Method signatures and docstrings: - def get(self, request, way_id, notification_id=None): Method that handles GE...
c5f533bd049f6939037b14045e2aa2550aaac36a
<|skeleton|> class NotificationView: """Notification view that handles GET, POST, PUT, DELETE requests and provides appropriate operations with notification model.""" def get(self, request, way_id, notification_id=None): """Method that handles GET request.""" <|body_0|> def put(self, reque...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NotificationView: """Notification view that handles GET, POST, PUT, DELETE requests and provides appropriate operations with notification model.""" def get(self, request, way_id, notification_id=None): """Method that handles GET request.""" user = request.user way = Way.get_by_id(...
the_stack_v2_python_sparse
way_to_home/notification/views.py
Lv-365python/wayToHome
train
1
34b3ec9886ea5db9563fc67b1d7d9ae3031b15a5
[ "node_list = response.xpath(\"//tr[@class='even'] | //tr[@class='odd']\")\nfor node in node_list:\n item = TencentItem()\n item['position_name'] = node.xpath('./td[1]/a/text()').extract_first()\n item['position_link'] = 'https://hr.tencent.com/' + node.xpath('./td[1]/a/@href').extract_first()\n item['po...
<|body_start_0|> node_list = response.xpath("//tr[@class='even'] | //tr[@class='odd']") for node in node_list: item = TencentItem() item['position_name'] = node.xpath('./td[1]/a/text()').extract_first() item['position_link'] = 'https://hr.tencent.com/' + node.xpath('....
TencentCrawlSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TencentCrawlSpider: def parse_page(self, response): """默认列表页的解析方法""" <|body_0|> def parse_detail(self, response): """解析详情页的响应内容""" <|body_1|> <|end_skeleton|> <|body_start_0|> node_list = response.xpath("//tr[@class='even'] | //tr[@class='odd']") ...
stack_v2_sparse_classes_36k_train_017939
2,542
no_license
[ { "docstring": "默认列表页的解析方法", "name": "parse_page", "signature": "def parse_page(self, response)" }, { "docstring": "解析详情页的响应内容", "name": "parse_detail", "signature": "def parse_detail(self, response)" } ]
2
null
Implement the Python class `TencentCrawlSpider` described below. Class description: Implement the TencentCrawlSpider class. Method signatures and docstrings: - def parse_page(self, response): 默认列表页的解析方法 - def parse_detail(self, response): 解析详情页的响应内容
Implement the Python class `TencentCrawlSpider` described below. Class description: Implement the TencentCrawlSpider class. Method signatures and docstrings: - def parse_page(self, response): 默认列表页的解析方法 - def parse_detail(self, response): 解析详情页的响应内容 <|skeleton|> class TencentCrawlSpider: def parse_page(self, re...
a51e31acff41292e568ac22b0e213e6cb48218fa
<|skeleton|> class TencentCrawlSpider: def parse_page(self, response): """默认列表页的解析方法""" <|body_0|> def parse_detail(self, response): """解析详情页的响应内容""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TencentCrawlSpider: def parse_page(self, response): """默认列表页的解析方法""" node_list = response.xpath("//tr[@class='even'] | //tr[@class='odd']") for node in node_list: item = TencentItem() item['position_name'] = node.xpath('./td[1]/a/text()').extract_first() ...
the_stack_v2_python_sparse
爬虫项目/code10/2.Spider类多级页面数据采集/Tencent2/Tencent2/spiders/tencent_crawl.py
byst4nder/his_spider
train
1
de16b5d3e4695e00c3c38680f1151f0318ba91a5
[ "if not nums:\n return 0\nif val not in nums:\n return len(nums)\npos = 0\nwhile True:\n if pos == len(nums) or not len(nums):\n break\n if nums[pos] == val:\n del nums[pos]\n else:\n pos += 1\nreturn len(nums)", "if not nums:\n return 0\ni = 0\nwhile i < len(nums):\n if ...
<|body_start_0|> if not nums: return 0 if val not in nums: return len(nums) pos = 0 while True: if pos == len(nums) or not len(nums): break if nums[pos] == val: del nums[pos] else: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def removeElement_old(self, nums: List[int], val: int) -> int: """老方法 48 ms 13.9 MB Python3""" <|body_0|> def removeElement(self, nums: List[int], val: int) -> int: """20191021 40 ms 13.6 MB Python3""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_017940
1,167
no_license
[ { "docstring": "老方法 48 ms 13.9 MB Python3", "name": "removeElement_old", "signature": "def removeElement_old(self, nums: List[int], val: int) -> int" }, { "docstring": "20191021 40 ms 13.6 MB Python3", "name": "removeElement", "signature": "def removeElement(self, nums: List[int], val: i...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeElement_old(self, nums: List[int], val: int) -> int: 老方法 48 ms 13.9 MB Python3 - def removeElement(self, nums: List[int], val: int) -> int: 20191021 40 ms 13.6 MB Pytho...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeElement_old(self, nums: List[int], val: int) -> int: 老方法 48 ms 13.9 MB Python3 - def removeElement(self, nums: List[int], val: int) -> int: 20191021 40 ms 13.6 MB Pytho...
99a3abf1774933af73a8405f9b59e5e64906bca4
<|skeleton|> class Solution: def removeElement_old(self, nums: List[int], val: int) -> int: """老方法 48 ms 13.9 MB Python3""" <|body_0|> def removeElement(self, nums: List[int], val: int) -> int: """20191021 40 ms 13.6 MB Python3""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def removeElement_old(self, nums: List[int], val: int) -> int: """老方法 48 ms 13.9 MB Python3""" if not nums: return 0 if val not in nums: return len(nums) pos = 0 while True: if pos == len(nums) or not len(nums): ...
the_stack_v2_python_sparse
leetcode/27.remove_element.py
iamkissg/leetcode
train
0
907b81588ab02d14608e7dddba7c100b9aaf33a7
[ "super().__init__(entry, controller, poolObject, **kwargs)\nself._attr_device_class = device_class\nself._rounding_factor = rounding_factor\nself._attr_state_class = SensorStateClass.MEASUREMENT", "value = str(self._poolObject[self._attribute_key])\nif self._rounding_factor:\n value = str(int(round(int(value) ...
<|body_start_0|> super().__init__(entry, controller, poolObject, **kwargs) self._attr_device_class = device_class self._rounding_factor = rounding_factor self._attr_state_class = SensorStateClass.MEASUREMENT <|end_body_0|> <|body_start_1|> value = str(self._poolObject[self._attr...
Representation of an Pentair sensor.
PoolSensor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PoolSensor: """Representation of an Pentair sensor.""" def __init__(self, entry: ConfigEntry, controller: ModelController, poolObject: PoolObject, device_class: Optional[SensorDeviceClass], rounding_factor: int=0, **kwargs): """Initialize.""" <|body_0|> def state(self) -...
stack_v2_sparse_classes_36k_train_017941
7,986
no_license
[ { "docstring": "Initialize.", "name": "__init__", "signature": "def __init__(self, entry: ConfigEntry, controller: ModelController, poolObject: PoolObject, device_class: Optional[SensorDeviceClass], rounding_factor: int=0, **kwargs)" }, { "docstring": "Return the state of the sensor.", "name...
3
stack_v2_sparse_classes_30k_train_006163
Implement the Python class `PoolSensor` described below. Class description: Representation of an Pentair sensor. Method signatures and docstrings: - def __init__(self, entry: ConfigEntry, controller: ModelController, poolObject: PoolObject, device_class: Optional[SensorDeviceClass], rounding_factor: int=0, **kwargs):...
Implement the Python class `PoolSensor` described below. Class description: Representation of an Pentair sensor. Method signatures and docstrings: - def __init__(self, entry: ConfigEntry, controller: ModelController, poolObject: PoolObject, device_class: Optional[SensorDeviceClass], rounding_factor: int=0, **kwargs):...
625290c164c60611f501ee773583c06a85281300
<|skeleton|> class PoolSensor: """Representation of an Pentair sensor.""" def __init__(self, entry: ConfigEntry, controller: ModelController, poolObject: PoolObject, device_class: Optional[SensorDeviceClass], rounding_factor: int=0, **kwargs): """Initialize.""" <|body_0|> def state(self) -...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PoolSensor: """Representation of an Pentair sensor.""" def __init__(self, entry: ConfigEntry, controller: ModelController, poolObject: PoolObject, device_class: Optional[SensorDeviceClass], rounding_factor: int=0, **kwargs): """Initialize.""" super().__init__(entry, controller, poolObject...
the_stack_v2_python_sparse
custom_components/intellicenter/sensor.py
ntalekt/homeassistant
train
213
91c9e47fe12440e5c5c9e766820f87cf132199b3
[ "abort_if_product_doesnt_exist(product_id)\nproduct = ProductModel.query.get(product_id)\nreturn product.serialize", "abort_if_product_doesnt_exist(product_id)\nproduct = ProductModel.query.get(product_id)\ndb.session.delete(product)\ndb.session.commit()\nreturn ('', 204)", "args = parser.parse_args()\nproduct ...
<|body_start_0|> abort_if_product_doesnt_exist(product_id) product = ProductModel.query.get(product_id) return product.serialize <|end_body_0|> <|body_start_1|> abort_if_product_doesnt_exist(product_id) product = ProductModel.query.get(product_id) db.session.delete(produ...
Flask-Restful Implementation of API for Product.
Product
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Product: """Flask-Restful Implementation of API for Product.""" def get(self, product_id): """Checks to see if Product record with id={product_id} exist, and if so serialize and return it. Args: product_id(int): Id of product to retrieve. Returns: Serialized dict/json data containing...
stack_v2_sparse_classes_36k_train_017942
4,455
no_license
[ { "docstring": "Checks to see if Product record with id={product_id} exist, and if so serialize and return it. Args: product_id(int): Id of product to retrieve. Returns: Serialized dict/json data containing the information for one product and a status code of 200.", "name": "get", "signature": "def get(...
3
stack_v2_sparse_classes_30k_train_014840
Implement the Python class `Product` described below. Class description: Flask-Restful Implementation of API for Product. Method signatures and docstrings: - def get(self, product_id): Checks to see if Product record with id={product_id} exist, and if so serialize and return it. Args: product_id(int): Id of product t...
Implement the Python class `Product` described below. Class description: Flask-Restful Implementation of API for Product. Method signatures and docstrings: - def get(self, product_id): Checks to see if Product record with id={product_id} exist, and if so serialize and return it. Args: product_id(int): Id of product t...
15c675b997da64d3b2c6d7fcae147edcdd55858d
<|skeleton|> class Product: """Flask-Restful Implementation of API for Product.""" def get(self, product_id): """Checks to see if Product record with id={product_id} exist, and if so serialize and return it. Args: product_id(int): Id of product to retrieve. Returns: Serialized dict/json data containing...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Product: """Flask-Restful Implementation of API for Product.""" def get(self, product_id): """Checks to see if Product record with id={product_id} exist, and if so serialize and return it. Args: product_id(int): Id of product to retrieve. Returns: Serialized dict/json data containing the informat...
the_stack_v2_python_sparse
DiamondCaseWeb/api/product.py
engineering-diamondcasehair/diamonds
train
0
5b13fffd940cacac656b8504e7f9c5c0d540b991
[ "available_cars = []\nall_cars = self.get_full_content()\nfor car in all_cars:\n if not car.is_booked():\n available_cars.append(car)\nreturn available_cars", "booked_cars = []\nall_cars = self.get_full_content()\nfor car in all_cars:\n if car.is_booked():\n booked_cars.append(car)\nreturn boo...
<|body_start_0|> available_cars = [] all_cars = self.get_full_content() for car in all_cars: if not car.is_booked(): available_cars.append(car) return available_cars <|end_body_0|> <|body_start_1|> booked_cars = [] all_cars = self.get_full_con...
CarService
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CarService: def get_available_cars(self): """Saekir alla bila sem eru ekki i leigu og skilar theim""" <|body_0|> def get_booked_cars(self): """Saekir alla bila sem eru i leigu og skilar theim""" <|body_1|> <|end_skeleton|> <|body_start_0|> available...
stack_v2_sparse_classes_36k_train_017943
836
no_license
[ { "docstring": "Saekir alla bila sem eru ekki i leigu og skilar theim", "name": "get_available_cars", "signature": "def get_available_cars(self)" }, { "docstring": "Saekir alla bila sem eru i leigu og skilar theim", "name": "get_booked_cars", "signature": "def get_booked_cars(self)" } ...
2
stack_v2_sparse_classes_30k_train_001192
Implement the Python class `CarService` described below. Class description: Implement the CarService class. Method signatures and docstrings: - def get_available_cars(self): Saekir alla bila sem eru ekki i leigu og skilar theim - def get_booked_cars(self): Saekir alla bila sem eru i leigu og skilar theim
Implement the Python class `CarService` described below. Class description: Implement the CarService class. Method signatures and docstrings: - def get_available_cars(self): Saekir alla bila sem eru ekki i leigu og skilar theim - def get_booked_cars(self): Saekir alla bila sem eru i leigu og skilar theim <|skeleton|...
c9533d91081ab5ac34467e367d10efc1c1c75746
<|skeleton|> class CarService: def get_available_cars(self): """Saekir alla bila sem eru ekki i leigu og skilar theim""" <|body_0|> def get_booked_cars(self): """Saekir alla bila sem eru i leigu og skilar theim""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CarService: def get_available_cars(self): """Saekir alla bila sem eru ekki i leigu og skilar theim""" available_cars = [] all_cars = self.get_full_content() for car in all_cars: if not car.is_booked(): available_cars.append(car) return availa...
the_stack_v2_python_sparse
services/CarService.py
superhetja/verkefni1
train
0
bb9b51346698c76cb60c28b9861b494958c59a6e
[ "self.app = createApp(TestConfig)\nself.appContext = self.app.app_context()\nself.appContext.push()\nself.testApp = self.app.test_client()\nself._savepointContext = transactionContext(self)\nself._savepointContext.__enter__()", "self._savepointContext.__exit__(None, None, None)\nself.appContext.pop()\nself.appCon...
<|body_start_0|> self.app = createApp(TestConfig) self.appContext = self.app.app_context() self.appContext.push() self.testApp = self.app.test_client() self._savepointContext = transactionContext(self) self._savepointContext.__enter__() <|end_body_0|> <|body_start_1|> ...
Basic class for testcase
TestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCase: """Basic class for testcase""" def setUp(self): """Set up application for the tests""" <|body_0|> def tearDown(self): """Close application for the tests""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.app = createApp(TestConfig) ...
stack_v2_sparse_classes_36k_train_017944
1,330
no_license
[ { "docstring": "Set up application for the tests", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Close application for the tests", "name": "tearDown", "signature": "def tearDown(self)" } ]
2
stack_v2_sparse_classes_30k_train_019071
Implement the Python class `TestCase` described below. Class description: Basic class for testcase Method signatures and docstrings: - def setUp(self): Set up application for the tests - def tearDown(self): Close application for the tests
Implement the Python class `TestCase` described below. Class description: Basic class for testcase Method signatures and docstrings: - def setUp(self): Set up application for the tests - def tearDown(self): Close application for the tests <|skeleton|> class TestCase: """Basic class for testcase""" def setUp...
3afb4012b515e471f29dc5c0e0aae1501aea7ce7
<|skeleton|> class TestCase: """Basic class for testcase""" def setUp(self): """Set up application for the tests""" <|body_0|> def tearDown(self): """Close application for the tests""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestCase: """Basic class for testcase""" def setUp(self): """Set up application for the tests""" self.app = createApp(TestConfig) self.appContext = self.app.app_context() self.appContext.push() self.testApp = self.app.test_client() self._savepointContext = ...
the_stack_v2_python_sparse
backend/tests1/testCase.py
YuyaoZhong/4156-team-project
train
2
0d905c70ba5f2281bdd791133b5f2758b3a9279d
[ "if not matrix or not matrix[0]:\n return 0\nrow = len(matrix)\ncol = len(matrix[0])\ncur = [0 for _ in xrange(row + 1)]\nmaxw = pre = 0\nfor j in xrange(1, col + 1):\n for i in xrange(1, row + 1):\n tmp = cur[i]\n if matrix[i - 1][j - 1] == '1':\n cur[i] = min(cur[i - 1], cur[i], pre...
<|body_start_0|> if not matrix or not matrix[0]: return 0 row = len(matrix) col = len(matrix[0]) cur = [0 for _ in xrange(row + 1)] maxw = pre = 0 for j in xrange(1, col + 1): for i in xrange(1, row + 1): tmp = cur[i] ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maximalSquareON(self, matrix): """:type matrix: List[List[str]] :rtype: int""" <|body_0|> def maximalSquare(self, matrix): """:type matrix: List[List[str]] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not matrix or no...
stack_v2_sparse_classes_36k_train_017945
1,941
permissive
[ { "docstring": ":type matrix: List[List[str]] :rtype: int", "name": "maximalSquareON", "signature": "def maximalSquareON(self, matrix)" }, { "docstring": ":type matrix: List[List[str]] :rtype: int", "name": "maximalSquare", "signature": "def maximalSquare(self, matrix)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maximalSquareON(self, matrix): :type matrix: List[List[str]] :rtype: int - def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maximalSquareON(self, matrix): :type matrix: List[List[str]] :rtype: int - def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int <|skeleton|> class Solu...
86f1cb98de801f58c39d9a48ce9de12df7303d20
<|skeleton|> class Solution: def maximalSquareON(self, matrix): """:type matrix: List[List[str]] :rtype: int""" <|body_0|> def maximalSquare(self, matrix): """:type matrix: List[List[str]] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maximalSquareON(self, matrix): """:type matrix: List[List[str]] :rtype: int""" if not matrix or not matrix[0]: return 0 row = len(matrix) col = len(matrix[0]) cur = [0 for _ in xrange(row + 1)] maxw = pre = 0 for j in xrange(1, ...
the_stack_v2_python_sparse
221-Maximal-Square/solution.py
Tanych/CodeTracking
train
0
348918ea500e26ca921123b5bec04b70873037cd
[ "for draggable in self.excess_draggables:\n if self.excess_draggables[draggable]:\n return False\nfor index, draggable_ids in enumerate(self.correct_groups):\n current_rule = list(self.correct_positions[index].keys())[0]\n if 'number' in current_rule:\n rule_values = self.correct_positions[in...
<|body_start_0|> for draggable in self.excess_draggables: if self.excess_draggables[draggable]: return False for index, draggable_ids in enumerate(self.correct_groups): current_rule = list(self.correct_positions[index].keys())[0] if 'number' in current...
Grader class for drag and drop inputtype.
DragAndDrop
[ "MIT", "AGPL-3.0-only", "AGPL-3.0-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DragAndDrop: """Grader class for drag and drop inputtype.""" def grade(self): """Grader user answer. Checks if every draggable isplaced on proper target or on proper coordinates within radius of forgiveness (default is 10). Returns: bool.""" <|body_0|> def compare_positi...
stack_v2_sparse_classes_36k_train_017946
15,253
permissive
[ { "docstring": "Grader user answer. Checks if every draggable isplaced on proper target or on proper coordinates within radius of forgiveness (default is 10). Returns: bool.", "name": "grade", "signature": "def grade(self)" }, { "docstring": "Compares two lists of positions with flag rules. Orde...
3
null
Implement the Python class `DragAndDrop` described below. Class description: Grader class for drag and drop inputtype. Method signatures and docstrings: - def grade(self): Grader user answer. Checks if every draggable isplaced on proper target or on proper coordinates within radius of forgiveness (default is 10). Ret...
Implement the Python class `DragAndDrop` described below. Class description: Grader class for drag and drop inputtype. Method signatures and docstrings: - def grade(self): Grader user answer. Checks if every draggable isplaced on proper target or on proper coordinates within radius of forgiveness (default is 10). Ret...
5809eaca7079a15ee56b0b7fcfea425337046c97
<|skeleton|> class DragAndDrop: """Grader class for drag and drop inputtype.""" def grade(self): """Grader user answer. Checks if every draggable isplaced on proper target or on proper coordinates within radius of forgiveness (default is 10). Returns: bool.""" <|body_0|> def compare_positi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DragAndDrop: """Grader class for drag and drop inputtype.""" def grade(self): """Grader user answer. Checks if every draggable isplaced on proper target or on proper coordinates within radius of forgiveness (default is 10). Returns: bool.""" for draggable in self.excess_draggables: ...
the_stack_v2_python_sparse
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/lib/sandbox-packages/verifiers/draganddrop.py
luque/better-ways-of-thinking-about-software
train
3
330c746b8fc75b8d698c83bbbbae41a9a077c913
[ "if type(self) != type(other):\n return False\nreturn True", "shape = x.shape\nparties = x.parties\nnr_parties = len(parties)\nkwargs = {'seed_id_locations': secrets.randbits(64)}\ndecomposed_shares = [share.bit_decomposition(share, ring_size, False, **kwargs) for share in x.child]\nres_shares: List[MPCTensor]...
<|body_start_0|> if type(self) != type(other): return False return True <|end_body_0|> <|body_start_1|> shape = x.shape parties = x.parties nr_parties = len(parties) kwargs = {'seed_id_locations': secrets.randbits(64)} decomposed_shares = [share.bit_d...
ABY3 Protocol Implementation.
ABY3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ABY3: """ABY3 Protocol Implementation.""" def __eq__(self, other: Any) -> bool: """Check if "self" is equal with another object given a set of attributes to compare. Args: other (Any): Object to compare Returns: bool: True if equal False if not.""" <|body_0|> def bit_inj...
stack_v2_sparse_classes_36k_train_017947
4,866
permissive
[ { "docstring": "Check if \"self\" is equal with another object given a set of attributes to compare. Args: other (Any): Object to compare Returns: bool: True if equal False if not.", "name": "__eq__", "signature": "def __eq__(self, other: Any) -> bool" }, { "docstring": "Perform ABY3 bit injecti...
4
stack_v2_sparse_classes_30k_train_010558
Implement the Python class `ABY3` described below. Class description: ABY3 Protocol Implementation. Method signatures and docstrings: - def __eq__(self, other: Any) -> bool: Check if "self" is equal with another object given a set of attributes to compare. Args: other (Any): Object to compare Returns: bool: True if e...
Implement the Python class `ABY3` described below. Class description: ABY3 Protocol Implementation. Method signatures and docstrings: - def __eq__(self, other: Any) -> bool: Check if "self" is equal with another object given a set of attributes to compare. Args: other (Any): Object to compare Returns: bool: True if e...
1d2c6928b95a2f8164167a8c53f350b188e4533c
<|skeleton|> class ABY3: """ABY3 Protocol Implementation.""" def __eq__(self, other: Any) -> bool: """Check if "self" is equal with another object given a set of attributes to compare. Args: other (Any): Object to compare Returns: bool: True if equal False if not.""" <|body_0|> def bit_inj...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ABY3: """ABY3 Protocol Implementation.""" def __eq__(self, other: Any) -> bool: """Check if "self" is equal with another object given a set of attributes to compare. Args: other (Any): Object to compare Returns: bool: True if equal False if not.""" if type(self) != type(other): ...
the_stack_v2_python_sparse
packages/syft/src/syft/core/smpc/protocol/aby3/aby3.py
aanurraj/PySyft
train
0
6e956b186c71c9e6b26a60596aa9c3942ca5494b
[ "self.info_for_layers_dict = info_for_layers_dict\nself.gpmap_type = gpmap_type\nself.gpmap_kwargs = gpmap_kwargs\nself.alphabet = validate_alphabet(alphabet)\nself.C = len(self.alphabet)\nself.theta_regularization = theta_regularization\nself.eta_regularization = eta_regularization\nself.ohe_batch_size = ohe_batch...
<|body_start_0|> self.info_for_layers_dict = info_for_layers_dict self.gpmap_type = gpmap_type self.gpmap_kwargs = gpmap_kwargs self.alphabet = validate_alphabet(alphabet) self.C = len(self.alphabet) self.theta_regularization = theta_regularization self.eta_regula...
Represents a measurement process agnostic model. Parameters ---------- sequence_length: (int) Integer specifying the length of a single training sequence. number_of_bins: (int) Integer specifying the number of bins. (Only used for MPA regression). alphabet: (str) Specifies the type of input sequences. Three possible ch...
MeasurementProcessAgnosticModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MeasurementProcessAgnosticModel: """Represents a measurement process agnostic model. Parameters ---------- sequence_length: (int) Integer specifying the length of a single training sequence. number_of_bins: (int) Integer specifying the number of bins. (Only used for MPA regression). alphabet: (st...
stack_v2_sparse_classes_36k_train_017948
21,053
permissive
[ { "docstring": "Construct class instance.", "name": "__init__", "signature": "def __init__(self, info_for_layers_dict, sequence_length, number_of_bins, gpmap_type, gpmap_kwargs, alphabet, theta_regularization, eta_regularization, ohe_batch_size, custom_gpmap, initial_weights)" }, { "docstring": ...
2
stack_v2_sparse_classes_30k_train_012690
Implement the Python class `MeasurementProcessAgnosticModel` described below. Class description: Represents a measurement process agnostic model. Parameters ---------- sequence_length: (int) Integer specifying the length of a single training sequence. number_of_bins: (int) Integer specifying the number of bins. (Only ...
Implement the Python class `MeasurementProcessAgnosticModel` described below. Class description: Represents a measurement process agnostic model. Parameters ---------- sequence_length: (int) Integer specifying the length of a single training sequence. number_of_bins: (int) Integer specifying the number of bins. (Only ...
f83f6e94d3d6ceeb7f19401d369da1908cfac31d
<|skeleton|> class MeasurementProcessAgnosticModel: """Represents a measurement process agnostic model. Parameters ---------- sequence_length: (int) Integer specifying the length of a single training sequence. number_of_bins: (int) Integer specifying the number of bins. (Only used for MPA regression). alphabet: (st...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MeasurementProcessAgnosticModel: """Represents a measurement process agnostic model. Parameters ---------- sequence_length: (int) Integer specifying the length of a single training sequence. number_of_bins: (int) Integer specifying the number of bins. (Only used for MPA regression). alphabet: (str) Specifies ...
the_stack_v2_python_sparse
mavenn/src/regression_types.py
jbkinney/mavenn
train
21
9152fa8a73a1f448bb6a9b67bf3a535b3188f67b
[ "self.methods = [method() for method in args]\nself.method_arguments = arguments\nif list(self.method_arguments.keys()) != [method._designation for method in self.methods]:\n print(list(self.method_arguments.keys()))\n print([method._designation for method in self.methods])\n raise ValueError('The keys of ...
<|body_start_0|> self.methods = [method() for method in args] self.method_arguments = arguments if list(self.method_arguments.keys()) != [method._designation for method in self.methods]: print(list(self.method_arguments.keys())) print([method._designation for method in se...
Workflow class that aggregates all the steps of the analysis and the corresponding functions.
Workflow
[ "GPL-2.0-only", "GPL-1.0-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Workflow: """Workflow class that aggregates all the steps of the analysis and the corresponding functions.""" def __init__(self, *args, arguments: dict) -> None: """Initialize the Workflow args: list of functions that will be executed in the order they are passed kwargs: dict of argu...
stack_v2_sparse_classes_36k_train_017949
2,859
permissive
[ { "docstring": "Initialize the Workflow args: list of functions that will be executed in the order they are passed kwargs: dict of arguments that will be passed to the functions, the keys must match the function names, the values must be list of len 2 [*args, **kwargs] ARGUMENTS OR KEYWORD ARGUMENTS ARE \"METHO...
2
null
Implement the Python class `Workflow` described below. Class description: Workflow class that aggregates all the steps of the analysis and the corresponding functions. Method signatures and docstrings: - def __init__(self, *args, arguments: dict) -> None: Initialize the Workflow args: list of functions that will be e...
Implement the Python class `Workflow` described below. Class description: Workflow class that aggregates all the steps of the analysis and the corresponding functions. Method signatures and docstrings: - def __init__(self, *args, arguments: dict) -> None: Initialize the Workflow args: list of functions that will be e...
3139e5d45e1433a56481dcd00a3031c658089b73
<|skeleton|> class Workflow: """Workflow class that aggregates all the steps of the analysis and the corresponding functions.""" def __init__(self, *args, arguments: dict) -> None: """Initialize the Workflow args: list of functions that will be executed in the order they are passed kwargs: dict of argu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Workflow: """Workflow class that aggregates all the steps of the analysis and the corresponding functions.""" def __init__(self, *args, arguments: dict) -> None: """Initialize the Workflow args: list of functions that will be executed in the order they are passed kwargs: dict of arguments that wi...
the_stack_v2_python_sparse
src/nanopyx/methods/old_workflow.py
HenriquesLab/NanoPyx
train
33
9b427360d67190f16d7c4d34fef9e8ec80624fb8
[ "self.active_user = User.objects.create_user(username='active_user', email='activeuser@gmail.com', password='p@55words')\nself.inactive_user = User.objects.create_user(username='inactive_user', email='inactiveuser@gmail.com', password='p@55words')\nself.inactive_user.is_active = False\nself.inactive_user.save()\nse...
<|body_start_0|> self.active_user = User.objects.create_user(username='active_user', email='activeuser@gmail.com', password='p@55words') self.inactive_user = User.objects.create_user(username='inactive_user', email='inactiveuser@gmail.com', password='p@55words') self.inactive_user.is_active = Fa...
A class containing generic tests that are utilised throughout the different view tests.
ViewsTestCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ViewsTestCase: """A class containing generic tests that are utilised throughout the different view tests.""" def setUp(self): """Set up users to be used throughout testing.""" <|body_0|> def only_active_user_access_test(self, view_url, template_name): """Tests th...
stack_v2_sparse_classes_36k_train_017950
2,779
permissive
[ { "docstring": "Set up users to be used throughout testing.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Tests that only active users have access to this view. :param view_url: The url of the view being tested. :param template_name: The name of the template for the view b...
3
stack_v2_sparse_classes_30k_train_016199
Implement the Python class `ViewsTestCase` described below. Class description: A class containing generic tests that are utilised throughout the different view tests. Method signatures and docstrings: - def setUp(self): Set up users to be used throughout testing. - def only_active_user_access_test(self, view_url, tem...
Implement the Python class `ViewsTestCase` described below. Class description: A class containing generic tests that are utilised throughout the different view tests. Method signatures and docstrings: - def setUp(self): Set up users to be used throughout testing. - def only_active_user_access_test(self, view_url, tem...
85b450d7f6d0313c5e5ef53a262a850b7e93c3d6
<|skeleton|> class ViewsTestCase: """A class containing generic tests that are utilised throughout the different view tests.""" def setUp(self): """Set up users to be used throughout testing.""" <|body_0|> def only_active_user_access_test(self, view_url, template_name): """Tests th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ViewsTestCase: """A class containing generic tests that are utilised throughout the different view tests.""" def setUp(self): """Set up users to be used throughout testing.""" self.active_user = User.objects.create_user(username='active_user', email='activeuser@gmail.com', password='p@55w...
the_stack_v2_python_sparse
communique/utils/utils_tests.py
michael-xander/communique-webapp
train
0
b3e87335321a0c174c1b4b4df70db2fb0f231d1b
[ "if not prices:\n return 0\nnum_i0 = 0\nnum_i1 = -prices[0]\nfor price in prices:\n tmp = num_i0\n num_i0 = max(num_i0, num_i1 + price)\n num_i1 = max(num_i1, tmp - price)\nreturn num_i0", "if not prices:\n return 0\nn = len(prices)\nif k > n // 2:\n return self.maxProfit_inf(prices)\ndp = [[[0 ...
<|body_start_0|> if not prices: return 0 num_i0 = 0 num_i1 = -prices[0] for price in prices: tmp = num_i0 num_i0 = max(num_i0, num_i1 + price) num_i1 = max(num_i1, tmp - price) return num_i0 <|end_body_0|> <|body_start_1|> ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit_inf(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfit(self, k, prices): """:type prices: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not prices: return ...
stack_v2_sparse_classes_36k_train_017951
4,994
no_license
[ { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfit_inf", "signature": "def maxProfit_inf(self, prices)" }, { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfit", "signature": "def maxProfit(self, k, prices)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit_inf(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, k, prices): :type prices: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit_inf(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, k, prices): :type prices: List[int] :rtype: int <|skeleton|> class Solution: def ...
013f6f222c6c2a617787b258f8a37003a9f51526
<|skeleton|> class Solution: def maxProfit_inf(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfit(self, k, prices): """:type prices: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit_inf(self, prices): """:type prices: List[int] :rtype: int""" if not prices: return 0 num_i0 = 0 num_i1 = -prices[0] for price in prices: tmp = num_i0 num_i0 = max(num_i0, num_i1 + price) num_i1 = ma...
the_stack_v2_python_sparse
sub_seq.py
terrifyzhao/leetcode
train
0
cc34c81e7d6790392b7ada67954ba0ab86307af1
[ "dp = [0, 1, 2, 3]\nif n < 2:\n return -1\nelif n == 2:\n return 1\nelif n == 3:\n return 2\nfor i in range(4, n + 1):\n temp = 0\n for j in range(1, i // 2 + 1):\n temp = max(temp, dp[j] * dp[i - j])\n dp.append(temp)\nreturn dp[n]", "if n < 2:\n return -1\nelif n == 2:\n return 1\...
<|body_start_0|> dp = [0, 1, 2, 3] if n < 2: return -1 elif n == 2: return 1 elif n == 3: return 2 for i in range(4, n + 1): temp = 0 for j in range(1, i // 2 + 1): temp = max(temp, dp[j] * dp[i - j]) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def integerBreak(self, n: int) -> int: """dp[i] 代表整数i的最大积拆分 dp[i] = max(dp[i-j] * dp[j]) j=1_最短回文串.py,...,i-1_最短回文串.py. dp[0-3] = 0, 1_最短回文串.py, 2, 3 res = dp[-1_最短回文串.py]""" <|body_0|> def integerBreak(self, n: int) -> int: """贪心: 多分3 尾为1分2,2""" <|...
stack_v2_sparse_classes_36k_train_017952
1,039
no_license
[ { "docstring": "dp[i] 代表整数i的最大积拆分 dp[i] = max(dp[i-j] * dp[j]) j=1_最短回文串.py,...,i-1_最短回文串.py. dp[0-3] = 0, 1_最短回文串.py, 2, 3 res = dp[-1_最短回文串.py]", "name": "integerBreak", "signature": "def integerBreak(self, n: int) -> int" }, { "docstring": "贪心: 多分3 尾为1分2,2", "name": "integerBreak", "s...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def integerBreak(self, n: int) -> int: dp[i] 代表整数i的最大积拆分 dp[i] = max(dp[i-j] * dp[j]) j=1_最短回文串.py,...,i-1_最短回文串.py. dp[0-3] = 0, 1_最短回文串.py, 2, 3 res = dp[-1_最短回文串.py] - def int...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def integerBreak(self, n: int) -> int: dp[i] 代表整数i的最大积拆分 dp[i] = max(dp[i-j] * dp[j]) j=1_最短回文串.py,...,i-1_最短回文串.py. dp[0-3] = 0, 1_最短回文串.py, 2, 3 res = dp[-1_最短回文串.py] - def int...
57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb
<|skeleton|> class Solution: def integerBreak(self, n: int) -> int: """dp[i] 代表整数i的最大积拆分 dp[i] = max(dp[i-j] * dp[j]) j=1_最短回文串.py,...,i-1_最短回文串.py. dp[0-3] = 0, 1_最短回文串.py, 2, 3 res = dp[-1_最短回文串.py]""" <|body_0|> def integerBreak(self, n: int) -> int: """贪心: 多分3 尾为1分2,2""" <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def integerBreak(self, n: int) -> int: """dp[i] 代表整数i的最大积拆分 dp[i] = max(dp[i-j] * dp[j]) j=1_最短回文串.py,...,i-1_最短回文串.py. dp[0-3] = 0, 1_最短回文串.py, 2, 3 res = dp[-1_最短回文串.py]""" dp = [0, 1, 2, 3] if n < 2: return -1 elif n == 2: return 1 e...
the_stack_v2_python_sparse
4_LEETCODE/9_Greedy/343_整数拆分.py
fzingithub/SwordRefers2Offer
train
1
9f992bb06b34efc444921a3d7780eca52dfc8c41
[ "self.words_dict = defaultdict(list)\nfor w_index, word in enumerate(words):\n self.words_dict[word].append(w_index)", "distance_candidate = None\nlen_s = len(self.words_dict[word1])\nlen_b = len(self.words_dict[word2])\nj_init = 0\nfor i in range(0, len_s):\n for j in range(j_init, len_b):\n distanc...
<|body_start_0|> self.words_dict = defaultdict(list) for w_index, word in enumerate(words): self.words_dict[word].append(w_index) <|end_body_0|> <|body_start_1|> distance_candidate = None len_s = len(self.words_dict[word1]) len_b = len(self.words_dict[word2]) ...
WordDistance
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordDistance: def __init__(self, words): """:type words: List[str]""" <|body_0|> def shortest(self, word1, word2): """:type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.words_dict = defaultdict(list) ...
stack_v2_sparse_classes_36k_train_017953
2,062
no_license
[ { "docstring": ":type words: List[str]", "name": "__init__", "signature": "def __init__(self, words)" }, { "docstring": ":type word1: str :type word2: str :rtype: int", "name": "shortest", "signature": "def shortest(self, word1, word2)" } ]
2
stack_v2_sparse_classes_30k_train_015840
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int <|skeleton|> class WordDistance: ...
9387c1cbf1cac2db1aebf5ad196230705ab0fcc7
<|skeleton|> class WordDistance: def __init__(self, words): """:type words: List[str]""" <|body_0|> def shortest(self, word1, word2): """:type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordDistance: def __init__(self, words): """:type words: List[str]""" self.words_dict = defaultdict(list) for w_index, word in enumerate(words): self.words_dict[word].append(w_index) def shortest(self, word1, word2): """:type word1: str :type word2: str :rtype:...
the_stack_v2_python_sparse
shortest_world_distance_II.py
lightening0907/algorithm
train
0
d93627371e20c333b86cfa8532f8c8a80e175a71
[ "try:\n data_conf_frm().put_step_source(nnid, ver, node, request.data)\n return Response(json.dumps(request.data))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(return_data))", "try:\n return_data = data_conf_frm().get_data_conf(nnid, ver, ...
<|body_start_0|> try: data_conf_frm().put_step_source(nnid, ver, node, request.data) return Response(json.dumps(request.data)) except Exception as e: return_data = {'status': '404', 'result': str(e)} return Response(json.dumps(return_data)) <|end_body_0|> ...
WorkFlowDataConfFrame
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WorkFlowDataConfFrame: def post(self, request, nnid, ver, node): """- desc : insert cnn configuration data completed""" <|body_0|> def get(self, request, nnid, ver, node): """- desc : get cnn configuration data""" <|body_1|> def put(self, request, nnid, ...
stack_v2_sparse_classes_36k_train_017954
2,412
permissive
[ { "docstring": "- desc : insert cnn configuration data completed", "name": "post", "signature": "def post(self, request, nnid, ver, node)" }, { "docstring": "- desc : get cnn configuration data", "name": "get", "signature": "def get(self, request, nnid, ver, node)" }, { "docstrin...
4
stack_v2_sparse_classes_30k_test_000317
Implement the Python class `WorkFlowDataConfFrame` described below. Class description: Implement the WorkFlowDataConfFrame class. Method signatures and docstrings: - def post(self, request, nnid, ver, node): - desc : insert cnn configuration data completed - def get(self, request, nnid, ver, node): - desc : get cnn c...
Implement the Python class `WorkFlowDataConfFrame` described below. Class description: Implement the WorkFlowDataConfFrame class. Method signatures and docstrings: - def post(self, request, nnid, ver, node): - desc : insert cnn configuration data completed - def get(self, request, nnid, ver, node): - desc : get cnn c...
6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f
<|skeleton|> class WorkFlowDataConfFrame: def post(self, request, nnid, ver, node): """- desc : insert cnn configuration data completed""" <|body_0|> def get(self, request, nnid, ver, node): """- desc : get cnn configuration data""" <|body_1|> def put(self, request, nnid, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WorkFlowDataConfFrame: def post(self, request, nnid, ver, node): """- desc : insert cnn configuration data completed""" try: data_conf_frm().put_step_source(nnid, ver, node, request.data) return Response(json.dumps(request.data)) except Exception as e: ...
the_stack_v2_python_sparse
api/views/workflow_dataconf_frame.py
yurimkoo/tensormsa
train
1
30040e46f6612422c1fc0ef6f18b770859b94e18
[ "super().__init__(flatten_flag=flatten_flag, n_pca_components=n_pca_components, extract_hog_flag=extract_hog_flag, type_cnn=type_cnn)\nself.segment_lungs_flag = segment_lungs_flag\nself.u_net_model_path = u_net_model_path\nself.u_net_weights_path = u_net_weights_path\nself.segment_lungs_method = segment_lungs_metho...
<|body_start_0|> super().__init__(flatten_flag=flatten_flag, n_pca_components=n_pca_components, extract_hog_flag=extract_hog_flag, type_cnn=type_cnn) self.segment_lungs_flag = segment_lungs_flag self.u_net_model_path = u_net_model_path self.u_net_weights_path = u_net_weights_path ...
Children Class of ImagePreProcessor. Used to transform 2D X-Ray Images only of the chest cavity.
ChestXRayPreProcessor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChestXRayPreProcessor: """Children Class of ImagePreProcessor. Used to transform 2D X-Ray Images only of the chest cavity.""" def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn='', segment_lungs_flag=False, segment_lungs_method='', u_net_model_path=''...
stack_v2_sparse_classes_36k_train_017955
17,079
no_license
[ { "docstring": "Constructor of the class. :param flatten_flag: (bool) whether to express the numpy array of data with shape [n_samples, n_features] :param n_pca_components: (int) number of principal components that will be computed from the data \"x\". Must be an integer between 2 and 3. :param extract_hog_flag...
3
stack_v2_sparse_classes_30k_train_005489
Implement the Python class `ChestXRayPreProcessor` described below. Class description: Children Class of ImagePreProcessor. Used to transform 2D X-Ray Images only of the chest cavity. Method signatures and docstrings: - def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn='', se...
Implement the Python class `ChestXRayPreProcessor` described below. Class description: Children Class of ImagePreProcessor. Used to transform 2D X-Ray Images only of the chest cavity. Method signatures and docstrings: - def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn='', se...
c46f4b2ba7762420186cb710d2932adf00829d6f
<|skeleton|> class ChestXRayPreProcessor: """Children Class of ImagePreProcessor. Used to transform 2D X-Ray Images only of the chest cavity.""" def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn='', segment_lungs_flag=False, segment_lungs_method='', u_net_model_path=''...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChestXRayPreProcessor: """Children Class of ImagePreProcessor. Used to transform 2D X-Ray Images only of the chest cavity.""" def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn='', segment_lungs_flag=False, segment_lungs_method='', u_net_model_path='', u_net_weigh...
the_stack_v2_python_sparse
pre_processors.py
jonathand94/ML-Classifiers-Library
train
0
dba1f422578fff268508c6c25e5ac10c38b5696d
[ "self.modelPath = inputPath\nif os.path.exists('/'.join([self.modelPath, 'checkpoints'])):\n self.modelPath = '/'.join([self.modelPath, 'checkpoints'])\nconfigFile = self.modelPath + '/net_config.json'\nif not os.path.exists(configFile):\n sys.exit('could not find config file {}, cannot load DNN'.format(confi...
<|body_start_0|> self.modelPath = inputPath if os.path.exists('/'.join([self.modelPath, 'checkpoints'])): self.modelPath = '/'.join([self.modelPath, 'checkpoints']) configFile = self.modelPath + '/net_config.json' if not os.path.exists(configFile): sys.exit('could...
Model
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Model: def __init__(self, inputPath): """load dnn model with Keras""" <|body_0|> def setVariables(self): """read list of variables used for DNN evaluation read norm table with mean and std.dev values for all of theses variables""" <|body_1|> def findBest...
stack_v2_sparse_classes_36k_train_017956
3,217
no_license
[ { "docstring": "load dnn model with Keras", "name": "__init__", "signature": "def __init__(self, inputPath)" }, { "docstring": "read list of variables used for DNN evaluation read norm table with mean and std.dev values for all of theses variables", "name": "setVariables", "signature": "...
4
null
Implement the Python class `Model` described below. Class description: Implement the Model class. Method signatures and docstrings: - def __init__(self, inputPath): load dnn model with Keras - def setVariables(self): read list of variables used for DNN evaluation read norm table with mean and std.dev values for all o...
Implement the Python class `Model` described below. Class description: Implement the Model class. Method signatures and docstrings: - def __init__(self, inputPath): load dnn model with Keras - def setVariables(self): read list of variables used for DNN evaluation read norm table with mean and std.dev values for all o...
79f4b883eec1ea335edba28ddb1444fb2e693ea6
<|skeleton|> class Model: def __init__(self, inputPath): """load dnn model with Keras""" <|body_0|> def setVariables(self): """read list of variables used for DNN evaluation read norm table with mean and std.dev values for all of theses variables""" <|body_1|> def findBest...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Model: def __init__(self, inputPath): """load dnn model with Keras""" self.modelPath = inputPath if os.path.exists('/'.join([self.modelPath, 'checkpoints'])): self.modelPath = '/'.join([self.modelPath, 'checkpoints']) configFile = self.modelPath + '/net_config.json'...
the_stack_v2_python_sparse
karim/load/model.py
kit-cn-cms/karim
train
0
31f2f7b2fc882c821de580c8f5ed3c977501cec6
[ "self.ParticleInstanceIn = ParticleInstanceIn\nself.bar_angle = bar_angle\nself.data = dict()\nif self.bar_angle == None:\n self.bar_angle = -1.0 * BarTransform.bar_fourier_compute(self, self.ParticleInstanceIn.data['x'], self.ParticleInstanceIn.data['y'], maxr=maxr)\nself.bar_angle += rel_bar_angle\nself.calcul...
<|body_start_0|> self.ParticleInstanceIn = ParticleInstanceIn self.bar_angle = bar_angle self.data = dict() if self.bar_angle == None: self.bar_angle = -1.0 * BarTransform.bar_fourier_compute(self, self.ParticleInstanceIn.data['x'], self.ParticleInstanceIn.data['y'], maxr=max...
BarTransform : class to do the work to calculate the bar position and transform particles on it's own, BarTransform will reset the particles to be in the bar frame (planar transformation) inputs ----------------------- ParticleInstanceIn : the input PSP instance bar_angle : (default=None) the known bar angle rel_bar_an...
BarTransform
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BarTransform: """BarTransform : class to do the work to calculate the bar position and transform particles on it's own, BarTransform will reset the particles to be in the bar frame (planar transformation) inputs ----------------------- ParticleInstanceIn : the input PSP instance bar_angle : (defa...
stack_v2_sparse_classes_36k_train_017957
20,224
permissive
[ { "docstring": "see documentation above", "name": "__init__", "signature": "def __init__(self, ParticleInstanceIn, bar_angle=None, rel_bar_angle=0.0, minr=0.0, maxr=1.0)" }, { "docstring": "calculate_transform_and_return do the modification of the input PSP instance to be in the bar frame. input...
3
stack_v2_sparse_classes_30k_train_013187
Implement the Python class `BarTransform` described below. Class description: BarTransform : class to do the work to calculate the bar position and transform particles on it's own, BarTransform will reset the particles to be in the bar frame (planar transformation) inputs ----------------------- ParticleInstanceIn : t...
Implement the Python class `BarTransform` described below. Class description: BarTransform : class to do the work to calculate the bar position and transform particles on it's own, BarTransform will reset the particles to be in the bar frame (planar transformation) inputs ----------------------- ParticleInstanceIn : t...
189ed0b94b08309badde5da9b31f233cc2ec1765
<|skeleton|> class BarTransform: """BarTransform : class to do the work to calculate the bar position and transform particles on it's own, BarTransform will reset the particles to be in the bar frame (planar transformation) inputs ----------------------- ParticleInstanceIn : the input PSP instance bar_angle : (defa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BarTransform: """BarTransform : class to do the work to calculate the bar position and transform particles on it's own, BarTransform will reset the particles to be in the bar frame (planar transformation) inputs ----------------------- ParticleInstanceIn : the input PSP instance bar_angle : (default=None) the...
the_stack_v2_python_sparse
exptool/analysis/pattern.py
michael-petersen/exptool
train
5
e195f16ebd106c69a875618646cbfb476c7f46d2
[ "self.root = Path(__file__).parent.absolute()\nif not args:\n return\nself.build = Path(args.build_dir).resolve()\nif args.install_prefix:\n self.installed = Path(args.install_prefix).resolve()\nelse:\n self.installed = self.build.parent / (self.build.stem + '-install')\nif sys.platform == 'win32' and sys....
<|body_start_0|> self.root = Path(__file__).parent.absolute() if not args: return self.build = Path(args.build_dir).resolve() if args.install_prefix: self.installed = Path(args.install_prefix).resolve() else: self.installed = self.build.parent ...
root: Directory where scr, build config and tools are located (and this file) build: Directory where build output files (i.e. *.o) are saved install: Directory where .so from build and .py from src are put together. site: Directory where the built SciPy version was installed. This is a custom prefix, followed by a rela...
Dirs
[ "BSL-1.0", "BSD-2-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference", "Qhull", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dirs: """root: Directory where scr, build config and tools are located (and this file) build: Directory where build output files (i.e. *.o) are saved install: Directory where .so from build and .py from src are put together. site: Directory where the built SciPy version was installed. This is a c...
stack_v2_sparse_classes_36k_train_017958
49,632
permissive
[ { "docstring": ":params args: object like Context(build_dir, install_prefix)", "name": "__init__", "signature": "def __init__(self, args=None)" }, { "docstring": "Add site dir to sys.path / PYTHONPATH", "name": "add_sys_path", "signature": "def add_sys_path(self)" }, { "docstring...
3
stack_v2_sparse_classes_30k_train_016790
Implement the Python class `Dirs` described below. Class description: root: Directory where scr, build config and tools are located (and this file) build: Directory where build output files (i.e. *.o) are saved install: Directory where .so from build and .py from src are put together. site: Directory where the built S...
Implement the Python class `Dirs` described below. Class description: root: Directory where scr, build config and tools are located (and this file) build: Directory where build output files (i.e. *.o) are saved install: Directory where .so from build and .py from src are put together. site: Directory where the built S...
bae3476b8a245866f5f7f1b824a0a7919f3880a9
<|skeleton|> class Dirs: """root: Directory where scr, build config and tools are located (and this file) build: Directory where build output files (i.e. *.o) are saved install: Directory where .so from build and .py from src are put together. site: Directory where the built SciPy version was installed. This is a c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Dirs: """root: Directory where scr, build config and tools are located (and this file) build: Directory where build output files (i.e. *.o) are saved install: Directory where .so from build and .py from src are put together. site: Directory where the built SciPy version was installed. This is a custom prefix,...
the_stack_v2_python_sparse
dev.py
rgommers/scipy
train
17
67f067459fe6c6af550ee61aa817dd18e4a0e3bf
[ "plt.rcParams['figure.figsize'] = figsize\nself.fig = plt.figure()\nframe_axes = self.fig.add_subplot(111, frameon=False, xticklabels=(), yticklabels=())\nframe_axes.set_title(title)\nself.shape = shape\nself.num_subplots = 0", "self.num_subplots += 1\nself.fig.add_subplot(self.shape[0], self.shape[1], self.num_s...
<|body_start_0|> plt.rcParams['figure.figsize'] = figsize self.fig = plt.figure() frame_axes = self.fig.add_subplot(111, frameon=False, xticklabels=(), yticklabels=()) frame_axes.set_title(title) self.shape = shape self.num_subplots = 0 <|end_body_0|> <|body_start_1|> ...
Class to manage subplotting of histograms.
HistArray
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HistArray: """Class to manage subplotting of histograms.""" def __init__(self, title='', figsize=(12, 12), shape=(4, 3)): """Parameters ---------- title: str [''] Overall title of the figure. figsize: tuple [(12, 12)] Figure dimensions in x, y inches shape: tuple [(4, 3)] Number of s...
stack_v2_sparse_classes_36k_train_017959
6,100
permissive
[ { "docstring": "Parameters ---------- title: str [''] Overall title of the figure. figsize: tuple [(12, 12)] Figure dimensions in x, y inches shape: tuple [(4, 3)] Number of subplots in the y and x dimensions, respectively.", "name": "__init__", "signature": "def __init__(self, title='', figsize=(12, 12...
2
null
Implement the Python class `HistArray` described below. Class description: Class to manage subplotting of histograms. Method signatures and docstrings: - def __init__(self, title='', figsize=(12, 12), shape=(4, 3)): Parameters ---------- title: str [''] Overall title of the figure. figsize: tuple [(12, 12)] Figure di...
Implement the Python class `HistArray` described below. Class description: Class to manage subplotting of histograms. Method signatures and docstrings: - def __init__(self, title='', figsize=(12, 12), shape=(4, 3)): Parameters ---------- title: str [''] Overall title of the figure. figsize: tuple [(12, 12)] Figure di...
320ddc07432bcaa05723944738a6e02b6841b69e
<|skeleton|> class HistArray: """Class to manage subplotting of histograms.""" def __init__(self, title='', figsize=(12, 12), shape=(4, 3)): """Parameters ---------- title: str [''] Overall title of the figure. figsize: tuple [(12, 12)] Figure dimensions in x, y inches shape: tuple [(4, 3)] Number of s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HistArray: """Class to manage subplotting of histograms.""" def __init__(self, title='', figsize=(12, 12), shape=(4, 3)): """Parameters ---------- title: str [''] Overall title of the figure. figsize: tuple [(12, 12)] Figure dimensions in x, y inches shape: tuple [(4, 3)] Number of subplots in th...
the_stack_v2_python_sparse
bin.src/plot_instcat_dists.py
LSSTDESC/sims_GCRCatSimInterface
train
1
65a76d43a704f9997a10fd449e81db4a18dc6ff4
[ "order = get_object_or_404(Order, id=id)\nform = OrderForm(instance=order)\nreturn render(request, 'order/add-order.html', {'form': form, 'func': 'Update', 'order': order})", "order = get_object_or_404(Order, id=id)\nclient = get_object_or_404(Client, id=order.client.id)\nform = OrderForm(request.POST, instance=o...
<|body_start_0|> order = get_object_or_404(Order, id=id) form = OrderForm(instance=order) return render(request, 'order/add-order.html', {'form': form, 'func': 'Update', 'order': order}) <|end_body_0|> <|body_start_1|> order = get_object_or_404(Order, id=id) client = get_object_...
Class based view for updating new order.
OrderUpdateView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrderUpdateView: """Class based view for updating new order.""" def get(self, request, id): """Return add new order form.""" <|body_0|> def post(self, request, id): """Save order and redirect to order list.""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_36k_train_017960
3,127
no_license
[ { "docstring": "Return add new order form.", "name": "get", "signature": "def get(self, request, id)" }, { "docstring": "Save order and redirect to order list.", "name": "post", "signature": "def post(self, request, id)" } ]
2
null
Implement the Python class `OrderUpdateView` described below. Class description: Class based view for updating new order. Method signatures and docstrings: - def get(self, request, id): Return add new order form. - def post(self, request, id): Save order and redirect to order list.
Implement the Python class `OrderUpdateView` described below. Class description: Class based view for updating new order. Method signatures and docstrings: - def get(self, request, id): Return add new order form. - def post(self, request, id): Save order and redirect to order list. <|skeleton|> class OrderUpdateView...
93c3106ab90fb9aed85658f93f51686ba4734091
<|skeleton|> class OrderUpdateView: """Class based view for updating new order.""" def get(self, request, id): """Return add new order form.""" <|body_0|> def post(self, request, id): """Save order and redirect to order list.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OrderUpdateView: """Class based view for updating new order.""" def get(self, request, id): """Return add new order form.""" order = get_object_or_404(Order, id=id) form = OrderForm(instance=order) return render(request, 'order/add-order.html', {'form': form, 'func': 'Upda...
the_stack_v2_python_sparse
order/views/order_views.py
saadali5997/tms
train
0
887cf4cde1ba4f7cc89f78b6ee44b0603b867ddf
[ "self.sensors = sensors\nself.last_state = None\nself.wrapper = wrapper\nself.attribute = attribute\nself.block = block\nself.description = description\nself._unit = self.description.unit\nif block is not None:\n if callable(self._unit):\n self._unit = self._unit(block.info(attribute))\n self._unique_i...
<|body_start_0|> self.sensors = sensors self.last_state = None self.wrapper = wrapper self.attribute = attribute self.block = block self.description = description self._unit = self.description.unit if block is not None: if callable(self._unit):...
Represent a shelly sleeping block attribute entity.
ShellySleepingBlockAttributeEntity
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ShellySleepingBlockAttributeEntity: """Represent a shelly sleeping block attribute entity.""" def __init__(self, wrapper: ShellyDeviceWrapper, block: aioshelly.Block, attribute: str, description: BlockAttributeDescription, entry: entity_registry.RegistryEntry | None=None, sensors: set | None...
stack_v2_sparse_classes_36k_train_017961
13,987
permissive
[ { "docstring": "Initialize the sleeping sensor.", "name": "__init__", "signature": "def __init__(self, wrapper: ShellyDeviceWrapper, block: aioshelly.Block, attribute: str, description: BlockAttributeDescription, entry: entity_registry.RegistryEntry | None=None, sensors: set | None=None) -> None" }, ...
3
stack_v2_sparse_classes_30k_train_012755
Implement the Python class `ShellySleepingBlockAttributeEntity` described below. Class description: Represent a shelly sleeping block attribute entity. Method signatures and docstrings: - def __init__(self, wrapper: ShellyDeviceWrapper, block: aioshelly.Block, attribute: str, description: BlockAttributeDescription, e...
Implement the Python class `ShellySleepingBlockAttributeEntity` described below. Class description: Represent a shelly sleeping block attribute entity. Method signatures and docstrings: - def __init__(self, wrapper: ShellyDeviceWrapper, block: aioshelly.Block, attribute: str, description: BlockAttributeDescription, e...
2fee32fce03bc49e86cf2e7b741a15621a97cce5
<|skeleton|> class ShellySleepingBlockAttributeEntity: """Represent a shelly sleeping block attribute entity.""" def __init__(self, wrapper: ShellyDeviceWrapper, block: aioshelly.Block, attribute: str, description: BlockAttributeDescription, entry: entity_registry.RegistryEntry | None=None, sensors: set | None...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ShellySleepingBlockAttributeEntity: """Represent a shelly sleeping block attribute entity.""" def __init__(self, wrapper: ShellyDeviceWrapper, block: aioshelly.Block, attribute: str, description: BlockAttributeDescription, entry: entity_registry.RegistryEntry | None=None, sensors: set | None=None) -> Non...
the_stack_v2_python_sparse
homeassistant/components/shelly/entity.py
BenWoodford/home-assistant
train
11
abd3c58f36126962cba2e37147fd986969b8c24e
[ "g1 = GeoIP()\npath = settings.GEOIP_PATH\ng2 = GeoIP(path, 0)\ng3 = GeoIP.open(path, 0)\nfor g in (g1, g2, g3):\n self.assertEqual(True, bool(g._country))\n self.assertEqual(True, bool(g._city))\ncity = os.path.join(path, 'GeoLiteCity.dat')\ncntry = os.path.join(path, 'GeoIP.dat')\ng4 = GeoIP(city, country='...
<|body_start_0|> g1 = GeoIP() path = settings.GEOIP_PATH g2 = GeoIP(path, 0) g3 = GeoIP.open(path, 0) for g in (g1, g2, g3): self.assertEqual(True, bool(g._country)) self.assertEqual(True, bool(g._city)) city = os.path.join(path, 'GeoLiteCity.dat')...
GeoIPTest
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GeoIPTest: def test01_init(self): """Testing GeoIP initialization.""" <|body_0|> def test02_bad_query(self): """Testing GeoIP query parameter checking.""" <|body_1|> def test03_country(self): """Testing GeoIP country querying methods.""" ...
stack_v2_sparse_classes_36k_train_017962
4,706
permissive
[ { "docstring": "Testing GeoIP initialization.", "name": "test01_init", "signature": "def test01_init(self)" }, { "docstring": "Testing GeoIP query parameter checking.", "name": "test02_bad_query", "signature": "def test02_bad_query(self)" }, { "docstring": "Testing GeoIP country ...
6
stack_v2_sparse_classes_30k_train_011147
Implement the Python class `GeoIPTest` described below. Class description: Implement the GeoIPTest class. Method signatures and docstrings: - def test01_init(self): Testing GeoIP initialization. - def test02_bad_query(self): Testing GeoIP query parameter checking. - def test03_country(self): Testing GeoIP country que...
Implement the Python class `GeoIPTest` described below. Class description: Implement the GeoIPTest class. Method signatures and docstrings: - def test01_init(self): Testing GeoIP initialization. - def test02_bad_query(self): Testing GeoIP query parameter checking. - def test03_country(self): Testing GeoIP country que...
fa182e8ae82f33764d5e1f70bcd45899e1bf17e6
<|skeleton|> class GeoIPTest: def test01_init(self): """Testing GeoIP initialization.""" <|body_0|> def test02_bad_query(self): """Testing GeoIP query parameter checking.""" <|body_1|> def test03_country(self): """Testing GeoIP country querying methods.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GeoIPTest: def test01_init(self): """Testing GeoIP initialization.""" g1 = GeoIP() path = settings.GEOIP_PATH g2 = GeoIP(path, 0) g3 = GeoIP.open(path, 0) for g in (g1, g2, g3): self.assertEqual(True, bool(g._country)) self.assertEqual(Tr...
the_stack_v2_python_sparse
django/contrib/gis/geoip/tests.py
gregmuellegger/django
train
22
6e7feb7a628fd0bd9f46fae49b7ad23e21bf9aff
[ "c = []\nself.dfs(c, '', digits)\nreturn c", "if not r:\n return cmbs.append(s) if s else None\nfor ch in self.d[r[0]]:\n self.dfs(cmbs, s + ch, r[1:])", "if not digits:\n return []\nif len(digits) == 1:\n return [x for x in self.d[digits[0]]]\nreturn [x + y for x in self.d[digits[0]] for y in self....
<|body_start_0|> c = [] self.dfs(c, '', digits) return c <|end_body_0|> <|body_start_1|> if not r: return cmbs.append(s) if s else None for ch in self.d[r[0]]: self.dfs(cmbs, s + ch, r[1:]) <|end_body_1|> <|body_start_2|> if not digits: ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def letterCombinations(self, digits): """:type digits: str :rtype: List[str]""" <|body_0|> def dfs(self, cmbs, s, r): """:type cmbs: List[str] :type s: str :type r: str""" <|body_1|> def letterCombinations_pre1(self, digits): """:type d...
stack_v2_sparse_classes_36k_train_017963
1,029
permissive
[ { "docstring": ":type digits: str :rtype: List[str]", "name": "letterCombinations", "signature": "def letterCombinations(self, digits)" }, { "docstring": ":type cmbs: List[str] :type s: str :type r: str", "name": "dfs", "signature": "def dfs(self, cmbs, s, r)" }, { "docstring": "...
3
stack_v2_sparse_classes_30k_train_000976
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def letterCombinations(self, digits): :type digits: str :rtype: List[str] - def dfs(self, cmbs, s, r): :type cmbs: List[str] :type s: str :type r: str - def letterCombinations_pr...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def letterCombinations(self, digits): :type digits: str :rtype: List[str] - def dfs(self, cmbs, s, r): :type cmbs: List[str] :type s: str :type r: str - def letterCombinations_pr...
cb70ca87aa4604d1aec83d4224b3489eacebba75
<|skeleton|> class Solution: def letterCombinations(self, digits): """:type digits: str :rtype: List[str]""" <|body_0|> def dfs(self, cmbs, s, r): """:type cmbs: List[str] :type s: str :type r: str""" <|body_1|> def letterCombinations_pre1(self, digits): """:type d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def letterCombinations(self, digits): """:type digits: str :rtype: List[str]""" c = [] self.dfs(c, '', digits) return c def dfs(self, cmbs, s, r): """:type cmbs: List[str] :type s: str :type r: str""" if not r: return cmbs.append(s) if...
the_stack_v2_python_sparse
LeetCode/Python3/0017._Letter_Combinations_of_a_Phone_Number.py
icgw/practice
train
1
1bb69a91efb77ee151f70f2ba35860b4a4cbaaea
[ "dirpath_test_tree = os.path.join(dirpath_testdata, 'dir_with_folders_for_filtering')\ndetect_nothing_exp = '^$'\nactual_output = tuple(da.lwc.search._dirname_filtered_os_walk_gen(root=dirpath_test_tree, direxcl=[detect_nothing_exp]))\nexpected_output = ((os.path.join(dirpath_test_tree), ['dir_to_be_filtered', 'dir...
<|body_start_0|> dirpath_test_tree = os.path.join(dirpath_testdata, 'dir_with_folders_for_filtering') detect_nothing_exp = '^$' actual_output = tuple(da.lwc.search._dirname_filtered_os_walk_gen(root=dirpath_test_tree, direxcl=[detect_nothing_exp])) expected_output = ((os.path.join(dirpat...
Specify the da.lwc.search._dirname_filtered_os_walk_gen() function.
Specify_DirnameFilteredOsWalkGen
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Specify_DirnameFilteredOsWalkGen: """Specify the da.lwc.search._dirname_filtered_os_walk_gen() function.""" def it_filtering_nothing_at_all(self, dirpath_testdata): """Test the use of an expression that matches nothing to exclude.""" <|body_0|> def it_filter_something_by...
stack_v2_sparse_classes_36k_train_017964
29,518
permissive
[ { "docstring": "Test the use of an expression that matches nothing to exclude.", "name": "it_filtering_nothing_at_all", "signature": "def it_filtering_nothing_at_all(self, dirpath_testdata)" }, { "docstring": "Test that we may filter items using its' full name.", "name": "it_filter_something...
2
null
Implement the Python class `Specify_DirnameFilteredOsWalkGen` described below. Class description: Specify the da.lwc.search._dirname_filtered_os_walk_gen() function. Method signatures and docstrings: - def it_filtering_nothing_at_all(self, dirpath_testdata): Test the use of an expression that matches nothing to exclu...
Implement the Python class `Specify_DirnameFilteredOsWalkGen` described below. Class description: Specify the da.lwc.search._dirname_filtered_os_walk_gen() function. Method signatures and docstrings: - def it_filtering_nothing_at_all(self, dirpath_testdata): Test the use of an expression that matches nothing to exclu...
04a13be2792323e3f9fdb83fd236a8e9cfe6aa2d
<|skeleton|> class Specify_DirnameFilteredOsWalkGen: """Specify the da.lwc.search._dirname_filtered_os_walk_gen() function.""" def it_filtering_nothing_at_all(self, dirpath_testdata): """Test the use of an expression that matches nothing to exclude.""" <|body_0|> def it_filter_something_by...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Specify_DirnameFilteredOsWalkGen: """Specify the da.lwc.search._dirname_filtered_os_walk_gen() function.""" def it_filtering_nothing_at_all(self, dirpath_testdata): """Test the use of an expression that matches nothing to exclude.""" dirpath_test_tree = os.path.join(dirpath_testdata, 'dir...
the_stack_v2_python_sparse
a3_src/h70_internal/da/lwc/spec/spec_search.py
wtpayne/hiai
train
5
e088a3e8bba98315e09e0a13a25074ca6c3c1d32
[ "if n < 1 or n > 7:\n raise ValueError('Not a valid period. Must be 1-7')\nreturn np.array([elem for elem in cls.table[n - 1, :] if elem != ''])", "if n < 1 or n > 18:\n raise ValueError('Not a valid group. Must be 1-18')\nreturn np.array([elem for elem in cls.table[:, n - 1] if elem != ''])", "try:\n ...
<|body_start_0|> if n < 1 or n > 7: raise ValueError('Not a valid period. Must be 1-7') return np.array([elem for elem in cls.table[n - 1, :] if elem != '']) <|end_body_0|> <|body_start_1|> if n < 1 or n > 18: raise ValueError('Not a valid group. Must be 1-18') r...
PeriodicTable
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PeriodicTable: def period(cls, n: int): """Period of the periodic table, with 1 being the first period Arguments: n (int): Returns: (np.ndarray(str)): Raises: (ValueError): If n is not valid period index""" <|body_0|> def group(cls, n: int): """Group of the periodic ...
stack_v2_sparse_classes_36k_train_017965
35,279
permissive
[ { "docstring": "Period of the periodic table, with 1 being the first period Arguments: n (int): Returns: (np.ndarray(str)): Raises: (ValueError): If n is not valid period index", "name": "period", "signature": "def period(cls, n: int)" }, { "docstring": "Group of the periodic table, with 1 being...
4
stack_v2_sparse_classes_30k_train_019306
Implement the Python class `PeriodicTable` described below. Class description: Implement the PeriodicTable class. Method signatures and docstrings: - def period(cls, n: int): Period of the periodic table, with 1 being the first period Arguments: n (int): Returns: (np.ndarray(str)): Raises: (ValueError): If n is not v...
Implement the Python class `PeriodicTable` described below. Class description: Implement the PeriodicTable class. Method signatures and docstrings: - def period(cls, n: int): Period of the periodic table, with 1 being the first period Arguments: n (int): Returns: (np.ndarray(str)): Raises: (ValueError): If n is not v...
6505d5bbbd1906f57e4102e13f177510f166bbed
<|skeleton|> class PeriodicTable: def period(cls, n: int): """Period of the periodic table, with 1 being the first period Arguments: n (int): Returns: (np.ndarray(str)): Raises: (ValueError): If n is not valid period index""" <|body_0|> def group(cls, n: int): """Group of the periodic ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PeriodicTable: def period(cls, n: int): """Period of the periodic table, with 1 being the first period Arguments: n (int): Returns: (np.ndarray(str)): Raises: (ValueError): If n is not valid period index""" if n < 1 or n > 7: raise ValueError('Not a valid period. Must be 1-7') ...
the_stack_v2_python_sparse
autode/atoms.py
jdelev/autodE
train
0
ffe564834733640b6ff36c8b4b668289a9d11558
[ "def canSplit(target):\n sm = 0\n cnt = 0\n for n in nums:\n if sm + n > target:\n sm = n\n cnt += 1\n else:\n sm += n\n cnt += 1\n return cnt <= m\nl = 1\nr = 0\nfor i in nums:\n l = max(l, i)\n r += i\nwhile l + 1 < r:\n mid = l + (r - l) // 2...
<|body_start_0|> def canSplit(target): sm = 0 cnt = 0 for n in nums: if sm + n > target: sm = n cnt += 1 else: sm += n cnt += 1 return cnt <= m l = 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def splitArray(self, nums, m): """:type nums: List[int] :type m: int :rtype: int""" <|body_0|> def splitArrayBetterCode(self, nums, m): """:type nums: List[int] :type m: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> def c...
stack_v2_sparse_classes_36k_train_017966
2,394
no_license
[ { "docstring": ":type nums: List[int] :type m: int :rtype: int", "name": "splitArray", "signature": "def splitArray(self, nums, m)" }, { "docstring": ":type nums: List[int] :type m: int :rtype: int", "name": "splitArrayBetterCode", "signature": "def splitArrayBetterCode(self, nums, m)" ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtype: int - def splitArrayBetterCode(self, nums, m): :type nums: List[int] :type m: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtype: int - def splitArrayBetterCode(self, nums, m): :type nums: List[int] :type m: int :rtype: int <|skeleto...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def splitArray(self, nums, m): """:type nums: List[int] :type m: int :rtype: int""" <|body_0|> def splitArrayBetterCode(self, nums, m): """:type nums: List[int] :type m: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def splitArray(self, nums, m): """:type nums: List[int] :type m: int :rtype: int""" def canSplit(target): sm = 0 cnt = 0 for n in nums: if sm + n > target: sm = n cnt += 1 else...
the_stack_v2_python_sparse
S/SplitArrayLargestSum.py
bssrdf/pyleet
train
2
e89cf719cbee9ae8e5a17e318946c6c7fe9d74ce
[ "self.X_train, self.X_val, self.X_test = (None, None, None)\nself.y_train, self.y_val, self.y_test = (None, None, None)\nself.idx_train, self.idx_val, self.idx_test = (0, 0, 0)\nself.X_train, self.y_train = self.load(train, data_folder)\nif isinstance(val, str):\n self.X_val, self.y_val = self.load(val, data_fol...
<|body_start_0|> self.X_train, self.X_val, self.X_test = (None, None, None) self.y_train, self.y_val, self.y_test = (None, None, None) self.idx_train, self.idx_val, self.idx_test = (0, 0, 0) self.X_train, self.y_train = self.load(train, data_folder) if isinstance(val, str): ...
Load image data that has only a single label. Example: line OCR images. # Arguments data_folder [str]: the path that contain data train [str]: the path to train version file val [str]: the path to validation version file test [str]: the path to test version file helper [Helper object]: the helper that customize the out...
SingleLabelLoader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SingleLabelLoader: """Load image data that has only a single label. Example: line OCR images. # Arguments data_folder [str]: the path that contain data train [str]: the path to train version file val [str]: the path to validation version file test [str]: the path to test version file helper [Help...
stack_v2_sparse_classes_36k_train_017967
4,631
no_license
[ { "docstring": "Initialize the object", "name": "__init__", "signature": "def __init__(self, data_folder, train, val=None, test=None, helper=None)" }, { "docstring": "Load filepath and label from version text file # Arguments version_path [str]: the path to version file data_folder [str]: the pa...
4
stack_v2_sparse_classes_30k_train_017524
Implement the Python class `SingleLabelLoader` described below. Class description: Load image data that has only a single label. Example: line OCR images. # Arguments data_folder [str]: the path that contain data train [str]: the path to train version file val [str]: the path to validation version file test [str]: the...
Implement the Python class `SingleLabelLoader` described below. Class description: Load image data that has only a single label. Example: line OCR images. # Arguments data_folder [str]: the path that contain data train [str]: the path to train version file val [str]: the path to validation version file test [str]: the...
825ea87508b4d107b2425f37be89597cce5e0484
<|skeleton|> class SingleLabelLoader: """Load image data that has only a single label. Example: line OCR images. # Arguments data_folder [str]: the path that contain data train [str]: the path to train version file val [str]: the path to validation version file test [str]: the path to test version file helper [Help...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SingleLabelLoader: """Load image data that has only a single label. Example: line OCR images. # Arguments data_folder [str]: the path that contain data train [str]: the path to train version file val [str]: the path to validation version file test [str]: the path to test version file helper [Helper object]: t...
the_stack_v2_python_sparse
text_normalizer/cinnamon/versioning/loader.py
lionelcinnamon/AnsonOCR
train
0
f5aeacbf3509ee7c4a8ec0445f76c7bd00ac0551
[ "roman_int = {'I': 1, 'IV': 4, 'V': 5, 'IX': 9, 'X': 10, 'XL': 40, 'L': 50, 'XC': 90, 'C': 100, 'CD': 400, 'D': 500, 'CM': 900, 'M': 1000}\nresult = 0\ni = 0\nn = len(string)\nwhile i < n:\n if i < n - 1 and roman_int[string[i]] < roman_int[string[i + 1]]:\n result += roman_int[string[i:i + 2]]\n i...
<|body_start_0|> roman_int = {'I': 1, 'IV': 4, 'V': 5, 'IX': 9, 'X': 10, 'XL': 40, 'L': 50, 'XC': 90, 'C': 100, 'CD': 400, 'D': 500, 'CM': 900, 'M': 1000} result = 0 i = 0 n = len(string) while i < n: if i < n - 1 and roman_int[string[i]] < roman_int[string[i + 1]]: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def roman_to_int(self, string): """Converts Roman numerals to decimal integer. Intuitive algorithm. Algorithm description: 1) Scan the string from left to right. 2) If the value of current Roman character is less than the value of next Roman character, it means that we need to ...
stack_v2_sparse_classes_36k_train_017968
2,904
no_license
[ { "docstring": "Converts Roman numerals to decimal integer. Intuitive algorithm. Algorithm description: 1) Scan the string from left to right. 2) If the value of current Roman character is less than the value of next Roman character, it means that we need to take 2 characters to evaluate number. 3) Otherwise, w...
2
stack_v2_sparse_classes_30k_train_017107
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def roman_to_int(self, string): Converts Roman numerals to decimal integer. Intuitive algorithm. Algorithm description: 1) Scan the string from left to right. 2) If the value of ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def roman_to_int(self, string): Converts Roman numerals to decimal integer. Intuitive algorithm. Algorithm description: 1) Scan the string from left to right. 2) If the value of ...
71b722ddfe8da04572e527b055cf8723d5c87bbf
<|skeleton|> class Solution: def roman_to_int(self, string): """Converts Roman numerals to decimal integer. Intuitive algorithm. Algorithm description: 1) Scan the string from left to right. 2) If the value of current Roman character is less than the value of next Roman character, it means that we need to ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def roman_to_int(self, string): """Converts Roman numerals to decimal integer. Intuitive algorithm. Algorithm description: 1) Scan the string from left to right. 2) If the value of current Roman character is less than the value of next Roman character, it means that we need to take 2 charact...
the_stack_v2_python_sparse
Strings/roman_numerals/roman_to_integer.py
vladn90/Algorithms
train
0
8cb2df592dccc89c46eb895bfe4c05ec1b405819
[ "self.item_code = item_code\nself.description = description\nself.market_price = market_price\nself.rental_price = rental_price", "output_dict = {}\noutput_dict['item_code'] = self.item_code\noutput_dict['description'] = self.description\noutput_dict['market_price'] = self.market_price\noutput_dict['rental_price'...
<|body_start_0|> self.item_code = item_code self.description = description self.market_price = market_price self.rental_price = rental_price <|end_body_0|> <|body_start_1|> output_dict = {} output_dict['item_code'] = self.item_code output_dict['description'] = se...
Contains inventory class methods and attributes.
Inventory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Inventory: """Contains inventory class methods and attributes.""" def __init__(self, item_code, description, market_price, rental_price): """Create inventory item.""" <|body_0|> def return_as_dictionary(self): """Return inventory item information as dictionary.""...
stack_v2_sparse_classes_36k_train_017969
751
no_license
[ { "docstring": "Create inventory item.", "name": "__init__", "signature": "def __init__(self, item_code, description, market_price, rental_price)" }, { "docstring": "Return inventory item information as dictionary.", "name": "return_as_dictionary", "signature": "def return_as_dictionary(...
2
null
Implement the Python class `Inventory` described below. Class description: Contains inventory class methods and attributes. Method signatures and docstrings: - def __init__(self, item_code, description, market_price, rental_price): Create inventory item. - def return_as_dictionary(self): Return inventory item informa...
Implement the Python class `Inventory` described below. Class description: Contains inventory class methods and attributes. Method signatures and docstrings: - def __init__(self, item_code, description, market_price, rental_price): Create inventory item. - def return_as_dictionary(self): Return inventory item informa...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class Inventory: """Contains inventory class methods and attributes.""" def __init__(self, item_code, description, market_price, rental_price): """Create inventory item.""" <|body_0|> def return_as_dictionary(self): """Return inventory item information as dictionary.""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Inventory: """Contains inventory class methods and attributes.""" def __init__(self, item_code, description, market_price, rental_price): """Create inventory item.""" self.item_code = item_code self.description = description self.market_price = market_price self.re...
the_stack_v2_python_sparse
students/Reem_Alqaysi/Lesson_01/inventory_management/inventory_class.py
JavaRod/SP_Python220B_2019
train
1
21acedd6f3a72f7dccbded54ea59267487054d26
[ "self.vector_size = vector_size\nself.item_vectors = {}\nself.embeddings_model = None\nself.id_index_dict = None", "self.id_index_dict, _ = Utils.build_item_indices(list(train_seqs.values()), id_index_dict_file)\nvocab_size = len(self.id_index_dict)\nprint('building context and negative sampling pairs')\ndata_cou...
<|body_start_0|> self.vector_size = vector_size self.item_vectors = {} self.embeddings_model = None self.id_index_dict = None <|end_body_0|> <|body_start_1|> self.id_index_dict, _ = Utils.build_item_indices(list(train_seqs.values()), id_index_dict_file) vocab_size = len(...
Model to train embedding network on product sequences. Neural network is trained and resulting embeddings are used to create recommendations
Prod2VecModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Prod2VecModel: """Model to train embedding network on product sequences. Neural network is trained and resulting embeddings are used to create recommendations""" def __init__(self, vector_size=100): """initializes Prod2Vec recommendation model Parameters ---------- vector_size : int,...
stack_v2_sparse_classes_36k_train_017970
5,418
no_license
[ { "docstring": "initializes Prod2Vec recommendation model Parameters ---------- vector_size : int, embedding layer size Attributes ---------- vector_size item_vectors : dict of (song_id => p2v vectors) embeddings_model : Keras model to train embeddings id_index_dict : dict (item_id => index in embeddings layer)...
3
stack_v2_sparse_classes_30k_train_011209
Implement the Python class `Prod2VecModel` described below. Class description: Model to train embedding network on product sequences. Neural network is trained and resulting embeddings are used to create recommendations Method signatures and docstrings: - def __init__(self, vector_size=100): initializes Prod2Vec reco...
Implement the Python class `Prod2VecModel` described below. Class description: Model to train embedding network on product sequences. Neural network is trained and resulting embeddings are used to create recommendations Method signatures and docstrings: - def __init__(self, vector_size=100): initializes Prod2Vec reco...
f9ccc8b3289b5b2de36321cd5d2f1058d411e578
<|skeleton|> class Prod2VecModel: """Model to train embedding network on product sequences. Neural network is trained and resulting embeddings are used to create recommendations""" def __init__(self, vector_size=100): """initializes Prod2Vec recommendation model Parameters ---------- vector_size : int,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Prod2VecModel: """Model to train embedding network on product sequences. Neural network is trained and resulting embeddings are used to create recommendations""" def __init__(self, vector_size=100): """initializes Prod2Vec recommendation model Parameters ---------- vector_size : int, embedding la...
the_stack_v2_python_sparse
KGRec/Prod2Vec.py
joerenner/TextBasedRecommendation
train
3
fbc5b75791e9f60c6e12bd01e5f593eeb4acbecc
[ "alpha = 0.001\nk2, p = normaltest(data)\nif p < alpha:\n return True\nelse:\n return False", "beta = 0.001\nif skew(data) < beta:\n return True\nelse:\n return False", "if question == 'normal?':\n try:\n return cls.check_normal_population(experimental_data)\n except:\n return Fa...
<|body_start_0|> alpha = 0.001 k2, p = normaltest(data) if p < alpha: return True else: return False <|end_body_0|> <|body_start_1|> beta = 0.001 if skew(data) < beta: return True else: return False <|end_body_1|> ...
**Checks for situations for which Hypothesis Testing About Means is valid, i.e, is t-Test (or standard z-score) valid?** **Situation-1** For large sample sizes and randomly collected individuals one may assume that the population of the measurements (of interest) is normal. Thus condition for hypothesis testing about m...
NecessaryForHTMeans
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NecessaryForHTMeans: """**Checks for situations for which Hypothesis Testing About Means is valid, i.e, is t-Test (or standard z-score) valid?** **Situation-1** For large sample sizes and randomly collected individuals one may assume that the population of the measurements (of interest) is normal...
stack_v2_sparse_classes_36k_train_017971
6,047
permissive
[ { "docstring": "Tests if sample is from a normal distribution. Algorithm to check if population is normal -------- | **Given:** data | **Parameter:** :math:`\\\\alpha = 0.001` | **Compute:** p :math:`\\\\leftarrow` normaltest(data) | **if** p < :math:`\\\\alpha` | \"data is normal\" | **else** | \"data is not n...
3
stack_v2_sparse_classes_30k_train_004777
Implement the Python class `NecessaryForHTMeans` described below. Class description: **Checks for situations for which Hypothesis Testing About Means is valid, i.e, is t-Test (or standard z-score) valid?** **Situation-1** For large sample sizes and randomly collected individuals one may assume that the population of t...
Implement the Python class `NecessaryForHTMeans` described below. Class description: **Checks for situations for which Hypothesis Testing About Means is valid, i.e, is t-Test (or standard z-score) valid?** **Situation-1** For large sample sizes and randomly collected individuals one may assume that the population of t...
1f12ec3c5559467b6cc48c12384e93d0ca0d2a45
<|skeleton|> class NecessaryForHTMeans: """**Checks for situations for which Hypothesis Testing About Means is valid, i.e, is t-Test (or standard z-score) valid?** **Situation-1** For large sample sizes and randomly collected individuals one may assume that the population of the measurements (of interest) is normal...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NecessaryForHTMeans: """**Checks for situations for which Hypothesis Testing About Means is valid, i.e, is t-Test (or standard z-score) valid?** **Situation-1** For large sample sizes and randomly collected individuals one may assume that the population of the measurements (of interest) is normal. Thus condit...
the_stack_v2_python_sparse
cerebstats/data_conditions/forHTmeans.py
HarshKhilawala/cerebstats
train
0
659df4336699a99c4801fe23ed733bf7a7dd971c
[ "self.arr = vec2d\nself.row = 0\nself.col = 0", "nextVar = self.arr[self.row][self.col]\nself.col += 1\nreturn nextVar", "while self.row <= len(self.arr) - 1:\n if self.col <= len(self.arr[self.row]) - 1:\n return True\n self.col = 0\n self.row += 1\nreturn False" ]
<|body_start_0|> self.arr = vec2d self.row = 0 self.col = 0 <|end_body_0|> <|body_start_1|> nextVar = self.arr[self.row][self.col] self.col += 1 return nextVar <|end_body_1|> <|body_start_2|> while self.row <= len(self.arr) - 1: if self.col <= len(se...
Vector2D
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Vector2D: def __init__(self, vec2d): """Initialize your data structure here. :type vec2d: List[List[int]]""" <|body_0|> def next(self): """:rtype: int""" <|body_1|> def hasNext(self): """:rtype: bool""" <|body_2|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_36k_train_017972
1,182
no_license
[ { "docstring": "Initialize your data structure here. :type vec2d: List[List[int]]", "name": "__init__", "signature": "def __init__(self, vec2d)" }, { "docstring": ":rtype: int", "name": "next", "signature": "def next(self)" }, { "docstring": ":rtype: bool", "name": "hasNext",...
3
null
Implement the Python class `Vector2D` described below. Class description: Implement the Vector2D class. Method signatures and docstrings: - def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]] - def next(self): :rtype: int - def hasNext(self): :rtype: bool
Implement the Python class `Vector2D` described below. Class description: Implement the Vector2D class. Method signatures and docstrings: - def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]] - def next(self): :rtype: int - def hasNext(self): :rtype: bool <|skeleton|> class V...
d1666d44226274f13af25cf878cd63a24e1c5528
<|skeleton|> class Vector2D: def __init__(self, vec2d): """Initialize your data structure here. :type vec2d: List[List[int]]""" <|body_0|> def next(self): """:rtype: int""" <|body_1|> def hasNext(self): """:rtype: bool""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Vector2D: def __init__(self, vec2d): """Initialize your data structure here. :type vec2d: List[List[int]]""" self.arr = vec2d self.row = 0 self.col = 0 def next(self): """:rtype: int""" nextVar = self.arr[self.row][self.col] self.col += 1 re...
the_stack_v2_python_sparse
Array+HashTable/LeetCode251_Flatten2DVector.py
rexhzhang/LeetCodeProbelms
train
0
cc5ab69f1468a10c31c063c1110edba44ba2bc7e
[ "youtube_form = YoutubeForm(request.GET, page_token=page_token)\nif youtube_form.is_valid():\n\n def move_to_library_form(youtube_result):\n form = MoveToYoutubeForm(initial={'name': youtube_result['snippet']['title'], 'video_id': youtube_result['id']['videoId']})\n return {'result': youtube_result...
<|body_start_0|> youtube_form = YoutubeForm(request.GET, page_token=page_token) if youtube_form.is_valid(): def move_to_library_form(youtube_result): form = MoveToYoutubeForm(initial={'name': youtube_result['snippet']['title'], 'video_id': youtube_result['id']['videoId']}) ...
Give additional options for user to have search over youtube enabled
YoutubeAdmin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class YoutubeAdmin: """Give additional options for user to have search over youtube enabled""" def changelist_view(self, request, extra_context=None, page_token=None): """Extend normal admin changelist view to add youtube video searchs. We search only if youtube form is valid. (Youtube for...
stack_v2_sparse_classes_36k_train_017973
3,435
no_license
[ { "docstring": "Extend normal admin changelist view to add youtube video searchs. We search only if youtube form is valid. (Youtube form requires query phrase to be available in get) We also might push page_token to youtube. We can not put page_token in GET b'coz django admin check params and will make redirect...
3
stack_v2_sparse_classes_30k_train_002078
Implement the Python class `YoutubeAdmin` described below. Class description: Give additional options for user to have search over youtube enabled Method signatures and docstrings: - def changelist_view(self, request, extra_context=None, page_token=None): Extend normal admin changelist view to add youtube video searc...
Implement the Python class `YoutubeAdmin` described below. Class description: Give additional options for user to have search over youtube enabled Method signatures and docstrings: - def changelist_view(self, request, extra_context=None, page_token=None): Extend normal admin changelist view to add youtube video searc...
3d2a3efc44dae59f0c36127ec090365f63bebcdd
<|skeleton|> class YoutubeAdmin: """Give additional options for user to have search over youtube enabled""" def changelist_view(self, request, extra_context=None, page_token=None): """Extend normal admin changelist view to add youtube video searchs. We search only if youtube form is valid. (Youtube for...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class YoutubeAdmin: """Give additional options for user to have search over youtube enabled""" def changelist_view(self, request, extra_context=None, page_token=None): """Extend normal admin changelist view to add youtube video searchs. We search only if youtube form is valid. (Youtube form requires qu...
the_stack_v2_python_sparse
filebrowser_extensions/youtube/admin.py
tomaszroszko/django_filebrowser_extension
train
0
f07806006c298a28ad82d28de5280161094c355f
[ "vals = super(PurchaseOrder, self)._prepare_picking()\nif self.inter_company_transfer_id:\n vals.update({'inter_company_transfer_id': self.inter_company_transfer_id.id})\nreturn vals", "action = super(PurchaseOrder, self).action_view_invoice()\nif self.env.context.get('create_bill', False) and self.inter_compa...
<|body_start_0|> vals = super(PurchaseOrder, self)._prepare_picking() if self.inter_company_transfer_id: vals.update({'inter_company_transfer_id': self.inter_company_transfer_id.id}) return vals <|end_body_0|> <|body_start_1|> action = super(PurchaseOrder, self).action_view_...
Inherited for adding relation with inter company transfer. @author: Maulik Barad on Date 24-Sep-2019.
PurchaseOrder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PurchaseOrder: """Inherited for adding relation with inter company transfer. @author: Maulik Barad on Date 24-Sep-2019.""" def _prepare_picking(self): """Inherited for adding relation with ICT if created by it. @author: Maulik Barad on Date 16-Oct-2019. @return: Dictionary for creati...
stack_v2_sparse_classes_36k_train_017974
1,503
no_license
[ { "docstring": "Inherited for adding relation with ICT if created by it. @author: Maulik Barad on Date 16-Oct-2019. @return: Dictionary for creating picking.", "name": "_prepare_picking", "signature": "def _prepare_picking(self)" }, { "docstring": "Inherited for adding relation with ICT if creat...
2
null
Implement the Python class `PurchaseOrder` described below. Class description: Inherited for adding relation with inter company transfer. @author: Maulik Barad on Date 24-Sep-2019. Method signatures and docstrings: - def _prepare_picking(self): Inherited for adding relation with ICT if created by it. @author: Maulik ...
Implement the Python class `PurchaseOrder` described below. Class description: Inherited for adding relation with inter company transfer. @author: Maulik Barad on Date 24-Sep-2019. Method signatures and docstrings: - def _prepare_picking(self): Inherited for adding relation with ICT if created by it. @author: Maulik ...
45749da5cc82d0a50cdf5627072b9bd43a4206dc
<|skeleton|> class PurchaseOrder: """Inherited for adding relation with inter company transfer. @author: Maulik Barad on Date 24-Sep-2019.""" def _prepare_picking(self): """Inherited for adding relation with ICT if created by it. @author: Maulik Barad on Date 16-Oct-2019. @return: Dictionary for creati...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PurchaseOrder: """Inherited for adding relation with inter company transfer. @author: Maulik Barad on Date 24-Sep-2019.""" def _prepare_picking(self): """Inherited for adding relation with ICT if created by it. @author: Maulik Barad on Date 16-Oct-2019. @return: Dictionary for creating picking.""...
the_stack_v2_python_sparse
intercompany_transaction_ept/models/purchase.py
ecgroupca/ECGroup
train
1
a9ceafab490122dac75b3d293f5f2c34a175258a
[ "kwargs_dict = {'loadpath_controller': LoadSteppingControl(), 'loadpath_controller_options': {'nonlinear_solver_options': {'log_iterations': True, 'rtol': 1e-08}, 'N_steps': 1}}\nkwargs_dict.update(kwargs)\nsuper().__init__(integrator_dict, B_dict, t0, t_end, q0_dict, dq0_dict, ddq0_dict, **kwargs_dict)\nself._nonl...
<|body_start_0|> kwargs_dict = {'loadpath_controller': LoadSteppingControl(), 'loadpath_controller_options': {'nonlinear_solver_options': {'log_iterations': True, 'rtol': 1e-08}, 'N_steps': 1}} kwargs_dict.update(kwargs) super().__init__(integrator_dict, B_dict, t0, t_end, q0_dict, dq0_dict, ddq...
FETI-solver for nonlinear dynamic problems Attributes ---------- _nonlinear_solver : ControlBase nonlinear global solver _solver_manager : SolverManagerBase solver manager for the global problem _local_problem : LocalProblemBase local problem _config_dict : dict solver-configuration _dual_solution_length : int number o...
NonlinearDynamicFetiSolver
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NonlinearDynamicFetiSolver: """FETI-solver for nonlinear dynamic problems Attributes ---------- _nonlinear_solver : ControlBase nonlinear global solver _solver_manager : SolverManagerBase solver manager for the global problem _local_problem : LocalProblemBase local problem _config_dict : dict sol...
stack_v2_sparse_classes_36k_train_017975
13,384
permissive
[ { "docstring": "Parameters ---------- integrator_dict : dict integrator-objects describing the dynamic behavior of the local problems. For detailed specifications on the Integrator-class see `Basics of time-integration` or `Requirements to an Integrator-Class` and for the required API the :class:`~amfeti.local_...
5
stack_v2_sparse_classes_30k_train_000597
Implement the Python class `NonlinearDynamicFetiSolver` described below. Class description: FETI-solver for nonlinear dynamic problems Attributes ---------- _nonlinear_solver : ControlBase nonlinear global solver _solver_manager : SolverManagerBase solver manager for the global problem _local_problem : LocalProblemBas...
Implement the Python class `NonlinearDynamicFetiSolver` described below. Class description: FETI-solver for nonlinear dynamic problems Attributes ---------- _nonlinear_solver : ControlBase nonlinear global solver _solver_manager : SolverManagerBase solver manager for the global problem _local_problem : LocalProblemBas...
be209dffe4d170aca735f1e912fd5cb448502119
<|skeleton|> class NonlinearDynamicFetiSolver: """FETI-solver for nonlinear dynamic problems Attributes ---------- _nonlinear_solver : ControlBase nonlinear global solver _solver_manager : SolverManagerBase solver manager for the global problem _local_problem : LocalProblemBase local problem _config_dict : dict sol...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NonlinearDynamicFetiSolver: """FETI-solver for nonlinear dynamic problems Attributes ---------- _nonlinear_solver : ControlBase nonlinear global solver _solver_manager : SolverManagerBase solver manager for the global problem _local_problem : LocalProblemBase local problem _config_dict : dict solver-configura...
the_stack_v2_python_sparse
amfeti/feti_solvers/dynamic_feti_solver.py
AppliedMechanics/AMfeti
train
3
2f5431ff48b1ec9144b37c5220fc2ad296c24d58
[ "super().__init__(with_jokers=with_jokers)\nif with_jokers:\n for _ in range(2):\n self._cards.append(Card(JOKER_RANK, JOKER_SUIT))\nfor suit in POSSIBLE_SUIT:\n for rank in POSSIBLE_RANK:\n self._cards.append(Card(rank, suit))", "total_possible_cards = 2 * (13 * 4 + (2 if self._with_jokers el...
<|body_start_0|> super().__init__(with_jokers=with_jokers) if with_jokers: for _ in range(2): self._cards.append(Card(JOKER_RANK, JOKER_SUIT)) for suit in POSSIBLE_SUIT: for rank in POSSIBLE_RANK: self._cards.append(Card(rank, suit)) <|end_...
A DoubleDeck object A new double deck starts out ordered. If jokers are included, contains 2 * (2 + 4 * 13) :class:`deck_of_cards.card.Card` objects If no jokers are included, contains 2 * (4 * 13) :class:`deck_of_cards.card.Card` objects
DoubleDeck
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DoubleDeck: """A DoubleDeck object A new double deck starts out ordered. If jokers are included, contains 2 * (2 + 4 * 13) :class:`deck_of_cards.card.Card` objects If no jokers are included, contains 2 * (4 * 13) :class:`deck_of_cards.card.Card` objects""" def __init__(self, with_jokers=True...
stack_v2_sparse_classes_36k_train_017976
2,704
no_license
[ { "docstring": ":param bool with_jokers: include jokers if True", "name": "__init__", "signature": "def __init__(self, with_jokers=True)" }, { "docstring": "Check to make sure all the cards are accounted :returns: True if all cards are accounted :rtype: bool", "name": "check_deck", "sign...
2
stack_v2_sparse_classes_30k_train_008201
Implement the Python class `DoubleDeck` described below. Class description: A DoubleDeck object A new double deck starts out ordered. If jokers are included, contains 2 * (2 + 4 * 13) :class:`deck_of_cards.card.Card` objects If no jokers are included, contains 2 * (4 * 13) :class:`deck_of_cards.card.Card` objects Met...
Implement the Python class `DoubleDeck` described below. Class description: A DoubleDeck object A new double deck starts out ordered. If jokers are included, contains 2 * (2 + 4 * 13) :class:`deck_of_cards.card.Card` objects If no jokers are included, contains 2 * (4 * 13) :class:`deck_of_cards.card.Card` objects Met...
3cf666cb7f88fb0e317401b0c017c30fa742aead
<|skeleton|> class DoubleDeck: """A DoubleDeck object A new double deck starts out ordered. If jokers are included, contains 2 * (2 + 4 * 13) :class:`deck_of_cards.card.Card` objects If no jokers are included, contains 2 * (4 * 13) :class:`deck_of_cards.card.Card` objects""" def __init__(self, with_jokers=True...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DoubleDeck: """A DoubleDeck object A new double deck starts out ordered. If jokers are included, contains 2 * (2 + 4 * 13) :class:`deck_of_cards.card.Card` objects If no jokers are included, contains 2 * (4 * 13) :class:`deck_of_cards.card.Card` objects""" def __init__(self, with_jokers=True): ""...
the_stack_v2_python_sparse
base/cards/double_deck.py
MichielRuelens/Canasta
train
0
9b70c7c1460040908010eb17edc77510fe4e1ff1
[ "node = _Node(value)\nif self._root is None:\n self._root = node\n return\ncurrent = self._root\nwhile True:\n if value < current.value:\n if not current.left:\n current.left = node\n return\n else:\n current = current.left\n elif not current.right:\n ...
<|body_start_0|> node = _Node(value) if self._root is None: self._root = node return current = self._root while True: if value < current.value: if not current.left: current.left = node return ...
BinarySearchTree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinarySearchTree: def add(self, value): """Adds node to a tree and places it dependent upon the rest of the tree""" <|body_0|> def contains(self, value): """returns boolean that expresses whether or not value exists in binary tree""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k_train_017977
5,591
no_license
[ { "docstring": "Adds node to a tree and places it dependent upon the rest of the tree", "name": "add", "signature": "def add(self, value)" }, { "docstring": "returns boolean that expresses whether or not value exists in binary tree", "name": "contains", "signature": "def contains(self, v...
2
stack_v2_sparse_classes_30k_train_017868
Implement the Python class `BinarySearchTree` described below. Class description: Implement the BinarySearchTree class. Method signatures and docstrings: - def add(self, value): Adds node to a tree and places it dependent upon the rest of the tree - def contains(self, value): returns boolean that expresses whether or...
Implement the Python class `BinarySearchTree` described below. Class description: Implement the BinarySearchTree class. Method signatures and docstrings: - def add(self, value): Adds node to a tree and places it dependent upon the rest of the tree - def contains(self, value): returns boolean that expresses whether or...
677f071a04a429b6ec8c307bd32cfb654bc8ec11
<|skeleton|> class BinarySearchTree: def add(self, value): """Adds node to a tree and places it dependent upon the rest of the tree""" <|body_0|> def contains(self, value): """returns boolean that expresses whether or not value exists in binary tree""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinarySearchTree: def add(self, value): """Adds node to a tree and places it dependent upon the rest of the tree""" node = _Node(value) if self._root is None: self._root = node return current = self._root while True: if value < curren...
the_stack_v2_python_sparse
data-structures/tree/tree.py
Rayxclockwork/python-data-structures-and-algorithms
train
0
6f361577959126e469cd2343037be532f7c49eec
[ "try:\n payload = {'exp': datetime.utcnow() + timedelta(days=app.config.get('TOKEN_EXPIRATION_DAYS', 0), seconds=app.config.get('TOKEN_EXPIRATION_SECONDS', 0)), 'iat': datetime.utcnow(), 'sub': user_id, 'role': role}\n return jwt.encode(payload=payload, key=app.config.get('SECRET_KEY', None), algorithm='HS256...
<|body_start_0|> try: payload = {'exp': datetime.utcnow() + timedelta(days=app.config.get('TOKEN_EXPIRATION_DAYS', 0), seconds=app.config.get('TOKEN_EXPIRATION_SECONDS', 0)), 'iat': datetime.utcnow(), 'sub': user_id, 'role': role} return jwt.encode(payload=payload, key=app.config.get('SE...
AuthService
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthService: def encode_auth_token(user_id: ObjectId, role: str='user') -> Union[bytes, None]: """Generates JWT auth token that is returned as bytes. Args: user_id: an ObjectId for the User. role: the role of user. Must be one of: `admin` or `user`. Returns: A valid JWT token as bytes.""...
stack_v2_sparse_classes_36k_train_017978
4,615
permissive
[ { "docstring": "Generates JWT auth token that is returned as bytes. Args: user_id: an ObjectId for the User. role: the role of user. Must be one of: `admin` or `user`. Returns: A valid JWT token as bytes.", "name": "encode_auth_token", "signature": "def encode_auth_token(user_id: ObjectId, role: str='us...
4
stack_v2_sparse_classes_30k_train_006202
Implement the Python class `AuthService` described below. Class description: Implement the AuthService class. Method signatures and docstrings: - def encode_auth_token(user_id: ObjectId, role: str='user') -> Union[bytes, None]: Generates JWT auth token that is returned as bytes. Args: user_id: an ObjectId for the Use...
Implement the Python class `AuthService` described below. Class description: Implement the AuthService class. Method signatures and docstrings: - def encode_auth_token(user_id: ObjectId, role: str='user') -> Union[bytes, None]: Generates JWT auth token that is returned as bytes. Args: user_id: an ObjectId for the Use...
e04eaa315c76b0295d3d7450cf59b8b0b4a7f22b
<|skeleton|> class AuthService: def encode_auth_token(user_id: ObjectId, role: str='user') -> Union[bytes, None]: """Generates JWT auth token that is returned as bytes. Args: user_id: an ObjectId for the User. role: the role of user. Must be one of: `admin` or `user`. Returns: A valid JWT token as bytes.""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AuthService: def encode_auth_token(user_id: ObjectId, role: str='user') -> Union[bytes, None]: """Generates JWT auth token that is returned as bytes. Args: user_id: an ObjectId for the User. role: the role of user. Must be one of: `admin` or `user`. Returns: A valid JWT token as bytes.""" try:...
the_stack_v2_python_sparse
services/simcct/sim_api/auth_service.py
NeuralDev-io/arclytics_simcct
train
2
347099a8a6826dc74c7b0b29878d5277d6a29cb7
[ "self._dictionary = dictionary\nself._source = source\nself._filepath = filepath\nif self._validate(source=self._source, filepath=self._filepath):\n if self._source.lower() == 'json':\n dict_ = self._read_json(filepath=self._filepath)\n else:\n dict_ = self._dictionary\n for k, v in dict_.ite...
<|body_start_0|> self._dictionary = dictionary self._source = source self._filepath = filepath if self._validate(source=self._source, filepath=self._filepath): if self._source.lower() == 'json': dict_ = self._read_json(filepath=self._filepath) else...
Create a Python object from a standard dictionary, or JSON file. Args: dictionary (dict): A standard Python dictionary where all key/value pairs will be converted into an object. source (str): Source for the conversion. * 'dict': a standard Python dictionary * 'json': uses content from a JSON file filepath (str): Full ...
Dict2Obj
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dict2Obj: """Create a Python object from a standard dictionary, or JSON file. Args: dictionary (dict): A standard Python dictionary where all key/value pairs will be converted into an object. source (str): Source for the conversion. * 'dict': a standard Python dictionary * 'json': uses content fr...
stack_v2_sparse_classes_36k_train_017979
5,971
permissive
[ { "docstring": "Class initialiser.", "name": "__init__", "signature": "def __init__(self, dictionary=None, source='dict', filepath=None)" }, { "docstring": "Run the following validation tests: * The 'source' value is valid * If 'json' source, a file path is provided * If 'json' source, the provi...
6
stack_v2_sparse_classes_30k_train_018603
Implement the Python class `Dict2Obj` described below. Class description: Create a Python object from a standard dictionary, or JSON file. Args: dictionary (dict): A standard Python dictionary where all key/value pairs will be converted into an object. source (str): Source for the conversion. * 'dict': a standard Pyth...
Implement the Python class `Dict2Obj` described below. Class description: Create a Python object from a standard dictionary, or JSON file. Args: dictionary (dict): A standard Python dictionary where all key/value pairs will be converted into an object. source (str): Source for the conversion. * 'dict': a standard Pyth...
824bee75ecd756b9097581e5cf5929b389a74240
<|skeleton|> class Dict2Obj: """Create a Python object from a standard dictionary, or JSON file. Args: dictionary (dict): A standard Python dictionary where all key/value pairs will be converted into an object. source (str): Source for the conversion. * 'dict': a standard Python dictionary * 'json': uses content fr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Dict2Obj: """Create a Python object from a standard dictionary, or JSON file. Args: dictionary (dict): A standard Python dictionary where all key/value pairs will be converted into an object. source (str): Source for the conversion. * 'dict': a standard Python dictionary * 'json': uses content from a JSON fil...
the_stack_v2_python_sparse
build/lib/utils3/dict2obj.py
S3DEV/utils3
train
0
0e085728259f974c4846f38b245b7871f79f56bd
[ "s = set()\n\ndef helper(n, s):\n if n == 1:\n return True\n if n in s:\n return False\n l = list(str(n))\n res = 0\n for i in range(len(l)):\n res += pow(int(l[i]), 2)\n s.add(n)\n return helper(res, s)\nreturn helper(n, s)", "n = str(n)\nslow = n\nfast = str(sum((int(i)...
<|body_start_0|> s = set() def helper(n, s): if n == 1: return True if n in s: return False l = list(str(n)) res = 0 for i in range(len(l)): res += pow(int(l[i]), 2) s.add(n) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isHappy(self, n: int) -> bool: """集合解法""" <|body_0|> def isHappy1(self, n: int) -> bool: """快慢指针""" <|body_1|> <|end_skeleton|> <|body_start_0|> s = set() def helper(n, s): if n == 1: return True ...
stack_v2_sparse_classes_36k_train_017980
1,817
no_license
[ { "docstring": "集合解法", "name": "isHappy", "signature": "def isHappy(self, n: int) -> bool" }, { "docstring": "快慢指针", "name": "isHappy1", "signature": "def isHappy1(self, n: int) -> bool" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isHappy(self, n: int) -> bool: 集合解法 - def isHappy1(self, n: int) -> bool: 快慢指针
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isHappy(self, n: int) -> bool: 集合解法 - def isHappy1(self, n: int) -> bool: 快慢指针 <|skeleton|> class Solution: def isHappy(self, n: int) -> bool: """集合解法""" ...
40726506802d2d60028fdce206696b1df2f63ece
<|skeleton|> class Solution: def isHappy(self, n: int) -> bool: """集合解法""" <|body_0|> def isHappy1(self, n: int) -> bool: """快慢指针""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isHappy(self, n: int) -> bool: """集合解法""" s = set() def helper(n, s): if n == 1: return True if n in s: return False l = list(str(n)) res = 0 for i in range(len(l)): ...
the_stack_v2_python_sparse
二刷+题解/每日一题/isHappy.py
1oser5/LeetCode
train
0
8a533219aa03c524c720b82351c1350bae4d5db5
[ "self._image = str(image)\nself._nodes = int(nodes)\nself._cores_per_node = int(cores_per_node)\nself._mem_per_core = str(mem_per_core)\nself._gpus_per_node = int(gpus_per_node)\nif shape is not None:\n self._shape = str(shape)\nelse:\n self._shape = None\nself._tmp_disk_per_node = str(tmp_disk_per_node)\nsel...
<|body_start_0|> self._image = str(image) self._nodes = int(nodes) self._cores_per_node = int(cores_per_node) self._mem_per_core = str(mem_per_core) self._gpus_per_node = int(gpus_per_node) if shape is not None: self._shape = str(shape) else: ...
This class holds the full set of requestable resources needed for a Job submitted to the system. This includes the container URL for any container images used by the job, the number of nodes and processors, the amount of memory per node, the amount of disk space needed etc.
Resources
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Resources: """This class holds the full set of requestable resources needed for a Job submitted to the system. This includes the container URL for any container images used by the job, the number of nodes and processors, the amount of memory per node, the amount of disk space needed etc.""" ...
stack_v2_sparse_classes_36k_train_017981
2,450
permissive
[ { "docstring": "Construct a set of resources specifying everything that may be needed to obtain sufficient resource to run a job", "name": "__init__", "signature": "def __init__(self, image=None, nodes=1, cores_per_node=1, mem_per_core='100MB', gpus_per_node=0, shape=None, tmp_disk_per_node='4GB', scrat...
3
null
Implement the Python class `Resources` described below. Class description: This class holds the full set of requestable resources needed for a Job submitted to the system. This includes the container URL for any container images used by the job, the number of nodes and processors, the amount of memory per node, the am...
Implement the Python class `Resources` described below. Class description: This class holds the full set of requestable resources needed for a Job submitted to the system. This includes the container URL for any container images used by the job, the number of nodes and processors, the amount of memory per node, the am...
fe4c9cb2b90374b386d5ea38e514faa96661701a
<|skeleton|> class Resources: """This class holds the full set of requestable resources needed for a Job submitted to the system. This includes the container URL for any container images used by the job, the number of nodes and processors, the amount of memory per node, the amount of disk space needed etc.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Resources: """This class holds the full set of requestable resources needed for a Job submitted to the system. This includes the container URL for any container images used by the job, the number of nodes and processors, the amount of memory per node, the amount of disk space needed etc.""" def __init__(...
the_stack_v2_python_sparse
Acquire/Client/_resources.py
chryswoods/acquire
train
21
4a074abdf5792d7f80754ec250e0060d95518f0f
[ "self.arg_parser.add_argument('--operation', choices=('wifi_on', 'wifi_off'), default='', required=True, help='Operation to perform.')\nself.arg_parser.add_argument('--serial', default='', required=True, help='The device serial.')\nself.arg_parser.add_argument('--ap', default='', help=\"Access point (AP) name for '...
<|body_start_0|> self.arg_parser.add_argument('--operation', choices=('wifi_on', 'wifi_off'), default='', required=True, help='Operation to perform.') self.arg_parser.add_argument('--serial', default='', required=True, help='The device serial.') self.arg_parser.add_argument('--ap', default='', h...
Command processor for DUT command. Attributes: arg_parser: ConsoleArgumentParser object, argument parser. console: cmd.Cmd console object. command: string, command name which this processor will handle. command_detail: string, detailed explanation for the command.
CommandDUT
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommandDUT: """Command processor for DUT command. Attributes: arg_parser: ConsoleArgumentParser object, argument parser. console: cmd.Cmd console object. command: string, command name which this processor will handle. command_detail: string, detailed explanation for the command.""" def SetUp...
stack_v2_sparse_classes_36k_train_017982
2,952
no_license
[ { "docstring": "Initializes the parser for dut command.", "name": "SetUp", "signature": "def SetUp(self)" }, { "docstring": "Performs the requested operation on the selected DUT.", "name": "Run", "signature": "def Run(self, arg_line)" } ]
2
stack_v2_sparse_classes_30k_train_003015
Implement the Python class `CommandDUT` described below. Class description: Command processor for DUT command. Attributes: arg_parser: ConsoleArgumentParser object, argument parser. console: cmd.Cmd console object. command: string, command name which this processor will handle. command_detail: string, detailed explana...
Implement the Python class `CommandDUT` described below. Class description: Command processor for DUT command. Attributes: arg_parser: ConsoleArgumentParser object, argument parser. console: cmd.Cmd console object. command: string, command name which this processor will handle. command_detail: string, detailed explana...
5ed3caff05cae4777c0a49a9704b2bf73376489f
<|skeleton|> class CommandDUT: """Command processor for DUT command. Attributes: arg_parser: ConsoleArgumentParser object, argument parser. console: cmd.Cmd console object. command: string, command name which this processor will handle. command_detail: string, detailed explanation for the command.""" def SetUp...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommandDUT: """Command processor for DUT command. Attributes: arg_parser: ConsoleArgumentParser object, argument parser. console: cmd.Cmd console object. command: string, command name which this processor will handle. command_detail: string, detailed explanation for the command.""" def SetUp(self): ...
the_stack_v2_python_sparse
harnesses/host_controller/command_processor/command_dut.py
MIPS/test-framework
train
0
1104099e67c7aab03e383f51abd0bb50b28196a4
[ "if password == '':\n raise serializers.ValidationError(_('fill the password field'))\nreturn password", "username = data.get('username')\npassword = self.validate_password(data.get('password'))\ntry:\n user = User.objects.get(username=username)\nexcept User.DoesNotExist:\n raise serializers.ValidationEr...
<|body_start_0|> if password == '': raise serializers.ValidationError(_('fill the password field')) return password <|end_body_0|> <|body_start_1|> username = data.get('username') password = self.validate_password(data.get('password')) try: user = User.ob...
Serializer for user login.
LoginSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoginSerializer: """Serializer for user login.""" def validate_password(self, password): """Check password validation.""" <|body_0|> def validate(self, data): """Validation on both of the fields.""" <|body_1|> <|end_skeleton|> <|body_start_0|> i...
stack_v2_sparse_classes_36k_train_017983
1,296
no_license
[ { "docstring": "Check password validation.", "name": "validate_password", "signature": "def validate_password(self, password)" }, { "docstring": "Validation on both of the fields.", "name": "validate", "signature": "def validate(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_011673
Implement the Python class `LoginSerializer` described below. Class description: Serializer for user login. Method signatures and docstrings: - def validate_password(self, password): Check password validation. - def validate(self, data): Validation on both of the fields.
Implement the Python class `LoginSerializer` described below. Class description: Serializer for user login. Method signatures and docstrings: - def validate_password(self, password): Check password validation. - def validate(self, data): Validation on both of the fields. <|skeleton|> class LoginSerializer: """Se...
74c9eba52b4f47d60fad17b6cba874e3547b37d4
<|skeleton|> class LoginSerializer: """Serializer for user login.""" def validate_password(self, password): """Check password validation.""" <|body_0|> def validate(self, data): """Validation on both of the fields.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LoginSerializer: """Serializer for user login.""" def validate_password(self, password): """Check password validation.""" if password == '': raise serializers.ValidationError(_('fill the password field')) return password def validate(self, data): """Valida...
the_stack_v2_python_sparse
apps/registration/serializers.py
cisin-python/django-rest-sample
train
0
81b8e26b34bb9608030d522a626fc988576dee4b
[ "hook_name, key = value.split('::')\nwarnings.warn(cls.DEPRECATION_MSG, DeprecationWarning)\nLOGGER.warning(cls.DEPRECATION_MSG)\nreturn ('{}.{}'.format(hook_name, key), {})", "try:\n query, args = cls.parse(value)\nexcept ValueError:\n query, args = cls.legacy_parse(value)\nresult = context.hook_data.find(...
<|body_start_0|> hook_name, key = value.split('::') warnings.warn(cls.DEPRECATION_MSG, DeprecationWarning) LOGGER.warning(cls.DEPRECATION_MSG) return ('{}.{}'.format(hook_name, key), {}) <|end_body_0|> <|body_start_1|> try: query, args = cls.parse(value) exce...
Hook data lookup.
HookDataLookup
[ "BSD-2-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HookDataLookup: """Hook data lookup.""" def legacy_parse(cls, value): """Retain support for legacy lookup syntax. Args: value (str): Parameter(s) given to this lookup. Format of value: <hook_name>::<key>""" <|body_0|> def handle(cls, value, context=None, provider=None, *...
stack_v2_sparse_classes_36k_train_017984
2,074
permissive
[ { "docstring": "Retain support for legacy lookup syntax. Args: value (str): Parameter(s) given to this lookup. Format of value: <hook_name>::<key>", "name": "legacy_parse", "signature": "def legacy_parse(cls, value)" }, { "docstring": "Return the data from ``hook_data``. Args: value (str): Param...
2
null
Implement the Python class `HookDataLookup` described below. Class description: Hook data lookup. Method signatures and docstrings: - def legacy_parse(cls, value): Retain support for legacy lookup syntax. Args: value (str): Parameter(s) given to this lookup. Format of value: <hook_name>::<key> - def handle(cls, value...
Implement the Python class `HookDataLookup` described below. Class description: Hook data lookup. Method signatures and docstrings: - def legacy_parse(cls, value): Retain support for legacy lookup syntax. Args: value (str): Parameter(s) given to this lookup. Format of value: <hook_name>::<key> - def handle(cls, value...
94aebff4f83b294653192a1b74111f6a9f114de2
<|skeleton|> class HookDataLookup: """Hook data lookup.""" def legacy_parse(cls, value): """Retain support for legacy lookup syntax. Args: value (str): Parameter(s) given to this lookup. Format of value: <hook_name>::<key>""" <|body_0|> def handle(cls, value, context=None, provider=None, *...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HookDataLookup: """Hook data lookup.""" def legacy_parse(cls, value): """Retain support for legacy lookup syntax. Args: value (str): Parameter(s) given to this lookup. Format of value: <hook_name>::<key>""" hook_name, key = value.split('::') warnings.warn(cls.DEPRECATION_MSG, Depr...
the_stack_v2_python_sparse
runway/cfngin/lookups/handlers/hook_data.py
edgarpoce/runway
train
1
2740d84036bfd6135852408dd98769908d737f9d
[ "print(self.token)\nheaders = {'Authorization': 'Bearer ' + self.token}\nr = self.send('GET', 'https://open.feishu.cn/open-apis/okr/v1/periods', headers=headers)\nreturn r.json()", "url = 'https://open.feishu.cn/open-apis/okr/v1/users/:%s/okrs' % user_id\nprint(url)\nparams = {'user_id_type': user_id, 'offset': '...
<|body_start_0|> print(self.token) headers = {'Authorization': 'Bearer ' + self.token} r = self.send('GET', 'https://open.feishu.cn/open-apis/okr/v1/periods', headers=headers) return r.json() <|end_body_0|> <|body_start_1|> url = 'https://open.feishu.cn/open-apis/okr/v1/users/:%...
FeishuOkr
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeishuOkr: def get_information(self): """获取OKR周期列表信息 :param :return:""" <|body_0|> def get_user_information(self, user_id: str): """获取某个用户的OKR周期列表信息 :param :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> print(self.token) headers = ...
stack_v2_sparse_classes_36k_train_017985
1,053
no_license
[ { "docstring": "获取OKR周期列表信息 :param :return:", "name": "get_information", "signature": "def get_information(self)" }, { "docstring": "获取某个用户的OKR周期列表信息 :param :return:", "name": "get_user_information", "signature": "def get_user_information(self, user_id: str)" } ]
2
null
Implement the Python class `FeishuOkr` described below. Class description: Implement the FeishuOkr class. Method signatures and docstrings: - def get_information(self): 获取OKR周期列表信息 :param :return: - def get_user_information(self, user_id: str): 获取某个用户的OKR周期列表信息 :param :return:
Implement the Python class `FeishuOkr` described below. Class description: Implement the FeishuOkr class. Method signatures and docstrings: - def get_information(self): 获取OKR周期列表信息 :param :return: - def get_user_information(self, user_id: str): 获取某个用户的OKR周期列表信息 :param :return: <|skeleton|> class FeishuOkr: def ...
6648dbfb640b065ff2c76cb6889a8f9e4f124b91
<|skeleton|> class FeishuOkr: def get_information(self): """获取OKR周期列表信息 :param :return:""" <|body_0|> def get_user_information(self, user_id: str): """获取某个用户的OKR周期列表信息 :param :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeishuOkr: def get_information(self): """获取OKR周期列表信息 :param :return:""" print(self.token) headers = {'Authorization': 'Bearer ' + self.token} r = self.send('GET', 'https://open.feishu.cn/open-apis/okr/v1/periods', headers=headers) return r.json() def get_user_infor...
the_stack_v2_python_sparse
test_feishu/feishu/feishu_okr.py
Veraun/HogwartsSDET17-1
train
0
2c8107e7a8d8da7babf3458be79656bf6ddf9cf4
[ "super(SelfAttention, self).__init__()\nself.units = units\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)", "prev = tf.expand_dims(s_prev, axis=1)\nscore = self.V(tf.nn.tanh(self.W(prev) + self.U(hidden_states)))\nweights = tf.nn.softmax(score, axi...
<|body_start_0|> super(SelfAttention, self).__init__() self.units = units self.W = tf.keras.layers.Dense(units) self.U = tf.keras.layers.Dense(units) self.V = tf.keras.layers.Dense(1) <|end_body_0|> <|body_start_1|> prev = tf.expand_dims(s_prev, axis=1) score = s...
class SelfAttention
SelfAttention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SelfAttention: """class SelfAttention""" def __init__(self, units): """Class constructor""" <|body_0|> def call(self, s_prev, hidden_states): """call function""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(SelfAttention, self).__init__() ...
stack_v2_sparse_classes_36k_train_017986
754
no_license
[ { "docstring": "Class constructor", "name": "__init__", "signature": "def __init__(self, units)" }, { "docstring": "call function", "name": "call", "signature": "def call(self, s_prev, hidden_states)" } ]
2
stack_v2_sparse_classes_30k_train_015769
Implement the Python class `SelfAttention` described below. Class description: class SelfAttention Method signatures and docstrings: - def __init__(self, units): Class constructor - def call(self, s_prev, hidden_states): call function
Implement the Python class `SelfAttention` described below. Class description: class SelfAttention Method signatures and docstrings: - def __init__(self, units): Class constructor - def call(self, s_prev, hidden_states): call function <|skeleton|> class SelfAttention: """class SelfAttention""" def __init__(...
a49eb348ff994f35b0efbbd5ac3ac8ae8ccb57d2
<|skeleton|> class SelfAttention: """class SelfAttention""" def __init__(self, units): """Class constructor""" <|body_0|> def call(self, s_prev, hidden_states): """call function""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SelfAttention: """class SelfAttention""" def __init__(self, units): """Class constructor""" super(SelfAttention, self).__init__() self.units = units self.W = tf.keras.layers.Dense(units) self.U = tf.keras.layers.Dense(units) self.V = tf.keras.layers.Dense(1...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/1-self_attention.py
salmenz/holbertonschool-machine_learning
train
4
22e5e62e5ce6f2a0ce16c5fb276d3c0675432bb0
[ "self.conn = MySQLdb.connect(host=config_reader.get('host'), db=config_reader.get('dbname'), read_default_file=config_reader.get('defaultcnf'), use_unicode=1, charset='utf8')\nself.cursor = self.conn.cursor()\nself.queries = hb_queries.Query(config_reader.get('wikidb'), config_reader.get('invitee_table'))", "quer...
<|body_start_0|> self.conn = MySQLdb.connect(host=config_reader.get('host'), db=config_reader.get('dbname'), read_default_file=config_reader.get('defaultcnf'), use_unicode=1, charset='utf8') self.cursor = self.conn.cursor() self.queries = hb_queries.Query(config_reader.get('wikidb'), config_read...
Create, parse, and post formatted messages to wiki.
Samples
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Samples: """Create, parse, and post formatted messages to wiki.""" def __init__(self): """Set up the db connection.""" <|body_0|> def insertInvitees(self, query_key): """Insert today's potential invitees into the database""" <|body_1|> def updateTalk...
stack_v2_sparse_classes_36k_train_017987
5,945
no_license
[ { "docstring": "Set up the db connection.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Insert today's potential invitees into the database", "name": "insertInvitees", "signature": "def insertInvitees(self, query_key)" }, { "docstring": "Updates the d...
5
stack_v2_sparse_classes_30k_train_004000
Implement the Python class `Samples` described below. Class description: Create, parse, and post formatted messages to wiki. Method signatures and docstrings: - def __init__(self): Set up the db connection. - def insertInvitees(self, query_key): Insert today's potential invitees into the database - def updateTalkPage...
Implement the Python class `Samples` described below. Class description: Create, parse, and post formatted messages to wiki. Method signatures and docstrings: - def __init__(self): Set up the db connection. - def insertInvitees(self, query_key): Insert today's potential invitees into the database - def updateTalkPage...
5359b875e9c22f2b517368b22e42e1304dd75bb3
<|skeleton|> class Samples: """Create, parse, and post formatted messages to wiki.""" def __init__(self): """Set up the db connection.""" <|body_0|> def insertInvitees(self, query_key): """Insert today's potential invitees into the database""" <|body_1|> def updateTalk...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Samples: """Create, parse, and post formatted messages to wiki.""" def __init__(self): """Set up the db connection.""" self.conn = MySQLdb.connect(host=config_reader.get('host'), db=config_reader.get('dbname'), read_default_file=config_reader.get('defaultcnf'), use_unicode=1, charset='utf...
the_stack_v2_python_sparse
hb_profiles.py
Wikimedia-Sverige/hostbot
train
2
d7cb0186b42ee8e9d8f7ce06bc2b376b7c3cb4c1
[ "self.set_counts = set_counts\nself.max_set = max(set_counts)\nnum_sets = len(set_counts)\nself.ranks = [1] * num_sets\nself.parents = list(range(num_sets))", "src_parent = self.get_parent(src)\ndst_parent = self.get_parent(dst)\nif src_parent == dst_parent:\n return False\nif self.ranks[dst_parent] >= self.ra...
<|body_start_0|> self.set_counts = set_counts self.max_set = max(set_counts) num_sets = len(set_counts) self.ranks = [1] * num_sets self.parents = list(range(num_sets)) <|end_body_0|> <|body_start_1|> src_parent = self.get_parent(src) dst_parent = self.get_parent...
DisjointSet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DisjointSet: def __init__(self, set_counts: list) -> None: """Initialize with a list of the number of items in each set and with rank = 1 for each set""" <|body_0|> def merge(self, src: int, dst: int) -> bool: """Merge two sets together using Union by rank heuristic ...
stack_v2_sparse_classes_36k_train_017988
2,192
permissive
[ { "docstring": "Initialize with a list of the number of items in each set and with rank = 1 for each set", "name": "__init__", "signature": "def __init__(self, set_counts: list) -> None" }, { "docstring": "Merge two sets together using Union by rank heuristic Return True if successful Merge two ...
3
null
Implement the Python class `DisjointSet` described below. Class description: Implement the DisjointSet class. Method signatures and docstrings: - def __init__(self, set_counts: list) -> None: Initialize with a list of the number of items in each set and with rank = 1 for each set - def merge(self, src: int, dst: int)...
Implement the Python class `DisjointSet` described below. Class description: Implement the DisjointSet class. Method signatures and docstrings: - def __init__(self, set_counts: list) -> None: Initialize with a list of the number of items in each set and with rank = 1 for each set - def merge(self, src: int, dst: int)...
421ace81edb0d9af3a173f4ca7e66cc900078c1d
<|skeleton|> class DisjointSet: def __init__(self, set_counts: list) -> None: """Initialize with a list of the number of items in each set and with rank = 1 for each set""" <|body_0|> def merge(self, src: int, dst: int) -> bool: """Merge two sets together using Union by rank heuristic ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DisjointSet: def __init__(self, set_counts: list) -> None: """Initialize with a list of the number of items in each set and with rank = 1 for each set""" self.set_counts = set_counts self.max_set = max(set_counts) num_sets = len(set_counts) self.ranks = [1] * num_sets ...
the_stack_v2_python_sparse
data_structures/disjoint_set/alternate_disjoint_set.py
TheAlgorithms/Python
train
184,217
b9bbee9ca458b3f4c3b13eb532817ee302b8bda5
[ "if root is None:\n return '[]'\nfrom collections import deque\nqueue = deque([root])\nresult = [root.val]\nwhile queue:\n node = queue.popleft()\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n result.append(node.left.val if node.left else 'null')...
<|body_start_0|> if root is None: return '[]' from collections import deque queue = deque([root]) result = [root.val] while queue: node = queue.popleft() if node.left: queue.append(node.left) if node.right: ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_017989
3,660
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_train_020315
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:...
c34b55bb42dc44a9026a902f6afcc018b4154662
<|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 root is None: return '[]' from collections import deque queue = deque([root]) result = [root.val] while queue: node = queue.pop...
the_stack_v2_python_sparse
Algorithm/Serialize and Deserialize Binary Tree.py
superpigBB/Happy-Coding
train
0
a211044d92f003de27782e8b3e066f1423236d0c
[ "memo = defaultdict(list)\n\ndef tree2list(r, d=0):\n if d == 0:\n memo.clear()\n if not r:\n return\n memo[d].append(r.val)\n tree2list(r.left, d + 1)\n tree2list(r.right, d + 1)\ntree2list(root)\nreturn [v for k, v in sorted(memo.items(), key=lambda x: x[0])]", "if not root:\n re...
<|body_start_0|> memo = defaultdict(list) def tree2list(r, d=0): if d == 0: memo.clear() if not r: return memo[d].append(r.val) tree2list(r.left, d + 1) tree2list(r.right, d + 1) tree2list(root) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def levelOrder(self, root): """05/06/2018 22:20""" <|body_0|> def levelOrder(self, root: TreeNode) -> List[List[int]]: """06/01/2021 14:48""" <|body_1|> def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: """07/30/2022 18...
stack_v2_sparse_classes_36k_train_017990
2,850
no_license
[ { "docstring": "05/06/2018 22:20", "name": "levelOrder", "signature": "def levelOrder(self, root)" }, { "docstring": "06/01/2021 14:48", "name": "levelOrder", "signature": "def levelOrder(self, root: TreeNode) -> List[List[int]]" }, { "docstring": "07/30/2022 18:30", "name": ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrder(self, root): 05/06/2018 22:20 - def levelOrder(self, root: TreeNode) -> List[List[int]]: 06/01/2021 14:48 - def levelOrder(self, root: Optional[TreeNode]) -> List[...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrder(self, root): 05/06/2018 22:20 - def levelOrder(self, root: TreeNode) -> List[List[int]]: 06/01/2021 14:48 - def levelOrder(self, root: Optional[TreeNode]) -> List[...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def levelOrder(self, root): """05/06/2018 22:20""" <|body_0|> def levelOrder(self, root: TreeNode) -> List[List[int]]: """06/01/2021 14:48""" <|body_1|> def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: """07/30/2022 18...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def levelOrder(self, root): """05/06/2018 22:20""" memo = defaultdict(list) def tree2list(r, d=0): if d == 0: memo.clear() if not r: return memo[d].append(r.val) tree2list(r.left, d + 1) ...
the_stack_v2_python_sparse
leetcode/solved/102_Binary_Tree_Level_Order_Traversal/solution.py
sungminoh/algorithms
train
0
426b8b52dbe77606a7859c50635fd81da02f943a
[ "config.LoadConfig()\npsq_publisher = pubsub.PublisherClient()\npsq_subscriber = pubsub.SubscriberClient()\ndatastore_client = datastore.Client(project=config.TURBINIA_PROJECT)\ntry:\n self.psq = psq.Queue(psq_publisher, psq_subscriber, config.TURBINIA_PROJECT, name=config.PSQ_TOPIC, storage=psq.DatastoreStorage...
<|body_start_0|> config.LoadConfig() psq_publisher = pubsub.PublisherClient() psq_subscriber = pubsub.SubscriberClient() datastore_client = datastore.Client(project=config.TURBINIA_PROJECT) try: self.psq = psq.Queue(psq_publisher, psq_subscriber, config.TURBINIA_PROJE...
Turbinia PSQ Worker class. Attributes: worker (psq.Worker): PSQ Worker object psq (psq.Queue): A Task queue object Raises: TurbiniaException: When errors occur
TurbiniaPsqWorker
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TurbiniaPsqWorker: """Turbinia PSQ Worker class. Attributes: worker (psq.Worker): PSQ Worker object psq (psq.Queue): A Task queue object Raises: TurbiniaException: When errors occur""" def __init__(self, jobs_denylist=None, jobs_allowlist=None): """Initialization for PSQ Worker. Args...
stack_v2_sparse_classes_36k_train_017991
46,828
permissive
[ { "docstring": "Initialization for PSQ Worker. Args: jobs_denylist (Optional[list[str]]): Jobs we will exclude from running jobs_allowlist (Optional[list[str]]): The only Jobs we will include to run", "name": "__init__", "signature": "def __init__(self, jobs_denylist=None, jobs_allowlist=None)" }, {...
2
stack_v2_sparse_classes_30k_train_016399
Implement the Python class `TurbiniaPsqWorker` described below. Class description: Turbinia PSQ Worker class. Attributes: worker (psq.Worker): PSQ Worker object psq (psq.Queue): A Task queue object Raises: TurbiniaException: When errors occur Method signatures and docstrings: - def __init__(self, jobs_denylist=None, ...
Implement the Python class `TurbiniaPsqWorker` described below. Class description: Turbinia PSQ Worker class. Attributes: worker (psq.Worker): PSQ Worker object psq (psq.Queue): A Task queue object Raises: TurbiniaException: When errors occur Method signatures and docstrings: - def __init__(self, jobs_denylist=None, ...
e73717549c6919e869ce4963449c36f227e3ccd6
<|skeleton|> class TurbiniaPsqWorker: """Turbinia PSQ Worker class. Attributes: worker (psq.Worker): PSQ Worker object psq (psq.Queue): A Task queue object Raises: TurbiniaException: When errors occur""" def __init__(self, jobs_denylist=None, jobs_allowlist=None): """Initialization for PSQ Worker. Args...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TurbiniaPsqWorker: """Turbinia PSQ Worker class. Attributes: worker (psq.Worker): PSQ Worker object psq (psq.Queue): A Task queue object Raises: TurbiniaException: When errors occur""" def __init__(self, jobs_denylist=None, jobs_allowlist=None): """Initialization for PSQ Worker. Args: jobs_denyli...
the_stack_v2_python_sparse
turbinia/client.py
Ash515/turbinia
train
6
4291729ce43ce1d71195d016ba3a46f016bc7ca6
[ "self.d = dict()\nfor i in range(len(dictionary)):\n if len(dictionary[i]) > 2:\n abbr = dictionary[i][0] + str(len(dictionary[i]) - 2) + dictionary[i][-1]\n else:\n abbr = dictionary[i]\n self.d[abbr] = self.d.get(abbr, set())\n self.d[abbr].add(dictionary[i])", "if len(word) > 2:\n ...
<|body_start_0|> self.d = dict() for i in range(len(dictionary)): if len(dictionary[i]) > 2: abbr = dictionary[i][0] + str(len(dictionary[i]) - 2) + dictionary[i][-1] else: abbr = dictionary[i] self.d[abbr] = self.d.get(abbr, set()) ...
ValidWordAbbr
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidWordAbbr: def __init__(self, dictionary): """:type dictionary: List[str]""" <|body_0|> def isUnique(self, word): """:type word: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.d = dict() for i in range(len(dictiona...
stack_v2_sparse_classes_36k_train_017992
1,910
no_license
[ { "docstring": ":type dictionary: List[str]", "name": "__init__", "signature": "def __init__(self, dictionary)" }, { "docstring": ":type word: str :rtype: bool", "name": "isUnique", "signature": "def isUnique(self, word)" } ]
2
null
Implement the Python class `ValidWordAbbr` described below. Class description: Implement the ValidWordAbbr class. Method signatures and docstrings: - def __init__(self, dictionary): :type dictionary: List[str] - def isUnique(self, word): :type word: str :rtype: bool
Implement the Python class `ValidWordAbbr` described below. Class description: Implement the ValidWordAbbr class. Method signatures and docstrings: - def __init__(self, dictionary): :type dictionary: List[str] - def isUnique(self, word): :type word: str :rtype: bool <|skeleton|> class ValidWordAbbr: def __init_...
9eb44afa4233fdedc2e5c72be0fdf54b25d1c45c
<|skeleton|> class ValidWordAbbr: def __init__(self, dictionary): """:type dictionary: List[str]""" <|body_0|> def isUnique(self, word): """:type word: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ValidWordAbbr: def __init__(self, dictionary): """:type dictionary: List[str]""" self.d = dict() for i in range(len(dictionary)): if len(dictionary[i]) > 2: abbr = dictionary[i][0] + str(len(dictionary[i]) - 2) + dictionary[i][-1] else: ...
the_stack_v2_python_sparse
Google/Pro288. Unique Word Abbreviation.py
YoyinZyc/Leetcode_Python
train
0
4224c8405a9967bed6d36b1ffd83b909f7cb0f8f
[ "modules = script.split('.')\nself.scriptname = modules[0]\nself.script = import_module('scripts.' + self.scriptname)\nfor m in modules:\n self.script = getattr(self.script, m)\nself.messages = {}\nfor msg in args:\n if hasattr(self.script, msg):\n self.messages[msg] = msg\n else:\n print(f'm...
<|body_start_0|> modules = script.split('.') self.scriptname = modules[0] self.script = import_module('scripts.' + self.scriptname) for m in modules: self.script = getattr(self.script, m) self.messages = {} for msg in args: if hasattr(self.script, ...
I18n bot.
i18nBot
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class i18nBot: """I18n bot.""" def __init__(self, script, *args, **kwargs): """Initializer.""" <|body_0|> def print_all(self): """Pretty print the dict as a file content to screen.""" <|body_1|> def read(self, oldmsg, newmsg=None): """Read a single...
stack_v2_sparse_classes_36k_train_017993
5,029
permissive
[ { "docstring": "Initializer.", "name": "__init__", "signature": "def __init__(self, script, *args, **kwargs)" }, { "docstring": "Pretty print the dict as a file content to screen.", "name": "print_all", "signature": "def print_all(self)" }, { "docstring": "Read a single message f...
5
stack_v2_sparse_classes_30k_test_000037
Implement the Python class `i18nBot` described below. Class description: I18n bot. Method signatures and docstrings: - def __init__(self, script, *args, **kwargs): Initializer. - def print_all(self): Pretty print the dict as a file content to screen. - def read(self, oldmsg, newmsg=None): Read a single message from s...
Implement the Python class `i18nBot` described below. Class description: I18n bot. Method signatures and docstrings: - def __init__(self, script, *args, **kwargs): Initializer. - def print_all(self): Pretty print the dict as a file content to screen. - def read(self, oldmsg, newmsg=None): Read a single message from s...
5c01e6bfcd328bc6eae643e661f1a0ae57612808
<|skeleton|> class i18nBot: """I18n bot.""" def __init__(self, script, *args, **kwargs): """Initializer.""" <|body_0|> def print_all(self): """Pretty print the dict as a file content to screen.""" <|body_1|> def read(self, oldmsg, newmsg=None): """Read a single...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class i18nBot: """I18n bot.""" def __init__(self, script, *args, **kwargs): """Initializer.""" modules = script.split('.') self.scriptname = modules[0] self.script = import_module('scripts.' + self.scriptname) for m in modules: self.script = getattr(self.scri...
the_stack_v2_python_sparse
scripts/maintenance/make_i18n_dict.py
wikimedia/pywikibot
train
432
6a5e0a13c38a5a06b9751fbbe26122eb6c10b4bc
[ "if not nums:\n return False\nn = len(nums)\npreSum = [0] * (n + 1)\nfor i in range(n):\n preSum[i + 1] = preSum[i] + nums[i]\nfor i in range(n):\n for j in range(i + 1, n):\n sums = preSum[j + 1] - preSum[i]\n if sums == 0 and k == 0:\n return True\n elif k != 0 and sums % ...
<|body_start_0|> if not nums: return False n = len(nums) preSum = [0] * (n + 1) for i in range(n): preSum[i + 1] = preSum[i] + nums[i] for i in range(n): for j in range(i + 1, n): sums = preSum[j + 1] - preSum[i] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def checkSubarraySum(self, nums: list, k: int) -> bool: """前缀和法 开辟一个数组来记录前缀和 注意: 前缀和记录的只是从0开始,一直到长度n的和 如: [1,2,3] 其前缀和数组为[0, 1, 3, 6], 即0, 0+1, 0+1+2(index) 所以,要双循环计算某个范围的和 特别注意当k=0的情况""" <|body_0|> def checkSubarraySum_2(self, nums, k): """优化版 1. 前缀和不用全部保存...
stack_v2_sparse_classes_36k_train_017994
1,960
no_license
[ { "docstring": "前缀和法 开辟一个数组来记录前缀和 注意: 前缀和记录的只是从0开始,一直到长度n的和 如: [1,2,3] 其前缀和数组为[0, 1, 3, 6], 即0, 0+1, 0+1+2(index) 所以,要双循环计算某个范围的和 特别注意当k=0的情况", "name": "checkSubarraySum", "signature": "def checkSubarraySum(self, nums: list, k: int) -> bool" }, { "docstring": "优化版 1. 前缀和不用全部保存,只需要记录好前面的和+当前值即可 2...
2
stack_v2_sparse_classes_30k_train_020943
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def checkSubarraySum(self, nums: list, k: int) -> bool: 前缀和法 开辟一个数组来记录前缀和 注意: 前缀和记录的只是从0开始,一直到长度n的和 如: [1,2,3] 其前缀和数组为[0, 1, 3, 6], 即0, 0+1, 0+1+2(index) 所以,要双循环计算某个范围的和 特别注意当k=0...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def checkSubarraySum(self, nums: list, k: int) -> bool: 前缀和法 开辟一个数组来记录前缀和 注意: 前缀和记录的只是从0开始,一直到长度n的和 如: [1,2,3] 其前缀和数组为[0, 1, 3, 6], 即0, 0+1, 0+1+2(index) 所以,要双循环计算某个范围的和 特别注意当k=0...
3508e1ce089131b19603c3206aab4cf43023bb19
<|skeleton|> class Solution: def checkSubarraySum(self, nums: list, k: int) -> bool: """前缀和法 开辟一个数组来记录前缀和 注意: 前缀和记录的只是从0开始,一直到长度n的和 如: [1,2,3] 其前缀和数组为[0, 1, 3, 6], 即0, 0+1, 0+1+2(index) 所以,要双循环计算某个范围的和 特别注意当k=0的情况""" <|body_0|> def checkSubarraySum_2(self, nums, k): """优化版 1. 前缀和不用全部保存...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def checkSubarraySum(self, nums: list, k: int) -> bool: """前缀和法 开辟一个数组来记录前缀和 注意: 前缀和记录的只是从0开始,一直到长度n的和 如: [1,2,3] 其前缀和数组为[0, 1, 3, 6], 即0, 0+1, 0+1+2(index) 所以,要双循环计算某个范围的和 特别注意当k=0的情况""" if not nums: return False n = len(nums) preSum = [0] * (n + 1) ...
the_stack_v2_python_sparse
algorithm/leetcode/list/18-连续的子数组和.py
lxconfig/UbuntuCode_bak
train
0
81f8768c46ebce0b9835ff90b40f6ab4fc860c1f
[ "mock_warn = mock.Mock()\ntest_class = deprecated.MovedHelper(urls.Url, 'grow.common.urls.Url', warn=mock_warn)\n_ = test_class('/')\nmock_warn.assert_called_with('The grow.common.urls.Url class has moved to grow.common.urls.Url and will be removed in a future version.')", "mock_warn = mock.Mock()\ntest_class = d...
<|body_start_0|> mock_warn = mock.Mock() test_class = deprecated.MovedHelper(urls.Url, 'grow.common.urls.Url', warn=mock_warn) _ = test_class('/') mock_warn.assert_called_with('The grow.common.urls.Url class has moved to grow.common.urls.Url and will be removed in a future version.') <|e...
Test the terminal colors.
MovedHelperTestCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovedHelperTestCase: """Test the terminal colors.""" def test_moved(self): """Warning message when the class has moved.""" <|body_0|> def test_static_method(self): """Moved warning also works with static methods.""" <|body_1|> <|end_skeleton|> <|body_st...
stack_v2_sparse_classes_36k_train_017995
1,175
permissive
[ { "docstring": "Warning message when the class has moved.", "name": "test_moved", "signature": "def test_moved(self)" }, { "docstring": "Moved warning also works with static methods.", "name": "test_static_method", "signature": "def test_static_method(self)" } ]
2
null
Implement the Python class `MovedHelperTestCase` described below. Class description: Test the terminal colors. Method signatures and docstrings: - def test_moved(self): Warning message when the class has moved. - def test_static_method(self): Moved warning also works with static methods.
Implement the Python class `MovedHelperTestCase` described below. Class description: Test the terminal colors. Method signatures and docstrings: - def test_moved(self): Warning message when the class has moved. - def test_static_method(self): Moved warning also works with static methods. <|skeleton|> class MovedHelp...
17471c436621ebfd978b51225fa4de05367a53e1
<|skeleton|> class MovedHelperTestCase: """Test the terminal colors.""" def test_moved(self): """Warning message when the class has moved.""" <|body_0|> def test_static_method(self): """Moved warning also works with static methods.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovedHelperTestCase: """Test the terminal colors.""" def test_moved(self): """Warning message when the class has moved.""" mock_warn = mock.Mock() test_class = deprecated.MovedHelper(urls.Url, 'grow.common.urls.Url', warn=mock_warn) _ = test_class('/') mock_warn.as...
the_stack_v2_python_sparse
grow/common/deprecated_test.py
grow/grow
train
352
925178fb4714793ca037188df98996cf78aeec71
[ "st = ''\nlength = 0\nfor i in s:\n index = st.find(i)\n if index >= 0:\n if len(st) > length:\n length = len(st)\n st = st[index + 1:]\n st += i\nreturn len(st) if len(st) > length else length", "index = 0\nmax_count = 0\ndata = {}\nwhile index < len(s):\n if s[index] not in ...
<|body_start_0|> st = '' length = 0 for i in s: index = st.find(i) if index >= 0: if len(st) > length: length = len(st) st = st[index + 1:] st += i return len(st) if len(st) > length else length <|end...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _lengthOfLongestSubstring(self, s): """:type s: str :rtype: int""" <|body_0|> def __lengthOfLongestSubstring(self, s): """:type s: str :rtype: int""" <|body_1|> def ___lengthOfLongestSubstring(self, s): """:type s: str :rtype: int""...
stack_v2_sparse_classes_36k_train_017996
3,690
permissive
[ { "docstring": ":type s: str :rtype: int", "name": "_lengthOfLongestSubstring", "signature": "def _lengthOfLongestSubstring(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "__lengthOfLongestSubstring", "signature": "def __lengthOfLongestSubstring(self, s)" }, { "d...
5
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _lengthOfLongestSubstring(self, s): :type s: str :rtype: int - def __lengthOfLongestSubstring(self, s): :type s: str :rtype: int - def ___lengthOfLongestSubstring(self, s): :...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _lengthOfLongestSubstring(self, s): :type s: str :rtype: int - def __lengthOfLongestSubstring(self, s): :type s: str :rtype: int - def ___lengthOfLongestSubstring(self, s): :...
0dd67edca4e0b0323cb5a7239f02ea46383cd15a
<|skeleton|> class Solution: def _lengthOfLongestSubstring(self, s): """:type s: str :rtype: int""" <|body_0|> def __lengthOfLongestSubstring(self, s): """:type s: str :rtype: int""" <|body_1|> def ___lengthOfLongestSubstring(self, s): """:type s: str :rtype: int""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def _lengthOfLongestSubstring(self, s): """:type s: str :rtype: int""" st = '' length = 0 for i in s: index = st.find(i) if index >= 0: if len(st) > length: length = len(st) st = st[index + 1:...
the_stack_v2_python_sparse
3.longest-substring-without-repeating-characters.py
windard/leeeeee
train
0
f8a67518f1dcfe885fee0215fa76191d0a4bc8d8
[ "self.parse_arguments(arguments)\nself.load_config(self.args.config)\nself.yesterday = datetime.date.today() - datetime.timedelta(days=1)", "parser = argparse.ArgumentParser(description='HEG data collector')\nparser.add_argument('-v', '--verbose', action='store_true', help='Make output more verbose.')\nparser.add...
<|body_start_0|> self.parse_arguments(arguments) self.load_config(self.args.config) self.yesterday = datetime.date.today() - datetime.timedelta(days=1) <|end_body_0|> <|body_start_1|> parser = argparse.ArgumentParser(description='HEG data collector') parser.add_argument('-v', '-...
App
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class App: def __init__(self, arguments=[]): """Keyword Arguments: arguments {list} -- The cli options as a list (default: {[]})""" <|body_0|> def parse_arguments(self, arguments): """Parses cli options/arguments given as a list. Arguments: arguments {list} -- The cli opti...
stack_v2_sparse_classes_36k_train_017997
2,146
permissive
[ { "docstring": "Keyword Arguments: arguments {list} -- The cli options as a list (default: {[]})", "name": "__init__", "signature": "def __init__(self, arguments=[])" }, { "docstring": "Parses cli options/arguments given as a list. Arguments: arguments {list} -- The cli options/list", "name"...
3
stack_v2_sparse_classes_30k_train_019164
Implement the Python class `App` described below. Class description: Implement the App class. Method signatures and docstrings: - def __init__(self, arguments=[]): Keyword Arguments: arguments {list} -- The cli options as a list (default: {[]}) - def parse_arguments(self, arguments): Parses cli options/arguments give...
Implement the Python class `App` described below. Class description: Implement the App class. Method signatures and docstrings: - def __init__(self, arguments=[]): Keyword Arguments: arguments {list} -- The cli options as a list (default: {[]}) - def parse_arguments(self, arguments): Parses cli options/arguments give...
c4f47444369151c606a4597aed5562503842e2f3
<|skeleton|> class App: def __init__(self, arguments=[]): """Keyword Arguments: arguments {list} -- The cli options as a list (default: {[]})""" <|body_0|> def parse_arguments(self, arguments): """Parses cli options/arguments given as a list. Arguments: arguments {list} -- The cli opti...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class App: def __init__(self, arguments=[]): """Keyword Arguments: arguments {list} -- The cli options as a list (default: {[]})""" self.parse_arguments(arguments) self.load_config(self.args.config) self.yesterday = datetime.date.today() - datetime.timedelta(days=1) def parse_ar...
the_stack_v2_python_sparse
heg/app.py
morris-frank/heg-plant-monitor
train
0
19e116b07caeafdd93845f253511a52907a00973
[ "super().__init__(independent_variables, equations)\nself.single_variable_sample = single_variable_sample\nself.single_equation_sample = single_equation_sample", "variable_samples = [self.single_variable_sample() for _ in range(size)]\nequation_samples = [self.single_equation_sample() for _ in range(size)]\nvaria...
<|body_start_0|> super().__init__(independent_variables, equations) self.single_variable_sample = single_variable_sample self.single_equation_sample = single_equation_sample <|end_body_0|> <|body_start_1|> variable_samples = [self.single_variable_sample() for _ in range(size)] e...
AnonymousSampler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnonymousSampler: def __init__(self, independent_variables, equations, single_variable_sample, single_equation_sample): """Class for samplers that can be constructed on the fly.""" <|body_0|> def get_sample(self, size): """Retrieve a batch of samples from the sampler...
stack_v2_sparse_classes_36k_train_017998
1,886
no_license
[ { "docstring": "Class for samplers that can be constructed on the fly.", "name": "__init__", "signature": "def __init__(self, independent_variables, equations, single_variable_sample, single_equation_sample)" }, { "docstring": "Retrieve a batch of samples from the sampler. Each sample should be ...
2
stack_v2_sparse_classes_30k_train_002162
Implement the Python class `AnonymousSampler` described below. Class description: Implement the AnonymousSampler class. Method signatures and docstrings: - def __init__(self, independent_variables, equations, single_variable_sample, single_equation_sample): Class for samplers that can be constructed on the fly. - def...
Implement the Python class `AnonymousSampler` described below. Class description: Implement the AnonymousSampler class. Method signatures and docstrings: - def __init__(self, independent_variables, equations, single_variable_sample, single_equation_sample): Class for samplers that can be constructed on the fly. - def...
5f353012a9ed14dc957211b9f3d3e9620ce82a42
<|skeleton|> class AnonymousSampler: def __init__(self, independent_variables, equations, single_variable_sample, single_equation_sample): """Class for samplers that can be constructed on the fly.""" <|body_0|> def get_sample(self, size): """Retrieve a batch of samples from the sampler...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AnonymousSampler: def __init__(self, independent_variables, equations, single_variable_sample, single_equation_sample): """Class for samplers that can be constructed on the fly.""" super().__init__(independent_variables, equations) self.single_variable_sample = single_variable_sample ...
the_stack_v2_python_sparse
puddle/api/samplers/anonymous.py
aatack/puddle
train
0
387ae31a89d3274ae806680007108354037fc40b
[ "if _id is None:\n _id = (id(self) >> 16 ^ id(self) & 65535) & 65535\nself.id: int = _id\nsessionid = session.short_session_id()\nlocalname = f'gt.{self.id}.{sessionid}'\nname = f'{localname}p'\nsuper().__init__(0, name, localname, session.use_ovs(), mtu, node, server)\nself.transport_type: TransportType = Trans...
<|body_start_0|> if _id is None: _id = (id(self) >> 16 ^ id(self) & 65535) & 65535 self.id: int = _id sessionid = session.short_session_id() localname = f'gt.{self.id}.{sessionid}' name = f'{localname}p' super().__init__(0, name, localname, session.use_ovs(), ...
GRE TAP device for tunneling between emulation servers. Uses the "gretap" tunnel device type from Linux which is a GRE device having a MAC address. The MAC address is required for bridging.
GreTap
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GreTap: """GRE TAP device for tunneling between emulation servers. Uses the "gretap" tunnel device type from Linux which is a GRE device having a MAC address. The MAC address is required for bridging.""" def __init__(self, session: 'Session', remoteip: str, key: int=None, node: 'CoreNode'=No...
stack_v2_sparse_classes_36k_train_017999
13,109
permissive
[ { "docstring": "Creates a GreTap instance. :param session: session for this gre tap :param remoteip: remote address :param key: gre tap key :param node: related core node :param mtu: interface mtu :param _id: object id :param localip: local address :param ttl: ttl value :param server: remote server node will ru...
3
null
Implement the Python class `GreTap` described below. Class description: GRE TAP device for tunneling between emulation servers. Uses the "gretap" tunnel device type from Linux which is a GRE device having a MAC address. The MAC address is required for bridging. Method signatures and docstrings: - def __init__(self, s...
Implement the Python class `GreTap` described below. Class description: GRE TAP device for tunneling between emulation servers. Uses the "gretap" tunnel device type from Linux which is a GRE device having a MAC address. The MAC address is required for bridging. Method signatures and docstrings: - def __init__(self, s...
20071eed2e73a2287aa385698dd604f4933ae7ff
<|skeleton|> class GreTap: """GRE TAP device for tunneling between emulation servers. Uses the "gretap" tunnel device type from Linux which is a GRE device having a MAC address. The MAC address is required for bridging.""" def __init__(self, session: 'Session', remoteip: str, key: int=None, node: 'CoreNode'=No...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GreTap: """GRE TAP device for tunneling between emulation servers. Uses the "gretap" tunnel device type from Linux which is a GRE device having a MAC address. The MAC address is required for bridging.""" def __init__(self, session: 'Session', remoteip: str, key: int=None, node: 'CoreNode'=None, mtu: int=...
the_stack_v2_python_sparse
daemon/core/nodes/interface.py
coreemu/core
train
606