blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aadb23d90c0116aea1942077501b7d5fa726839f | [
"if not nums:\n return 0\ncurrSum = nums[0]\nmaxSum = nums[0]\nfor i in range(1, len(nums)):\n currSum = max(nums[i], nums[i] + currSum)\n maxSum = max(maxSum, currSum)\nreturn maxSum",
"if not nums:\n return []\ncurrSum = nums[0]\ncurrIdx = [0, 0]\nmaxSum = nums[0]\nres = [0, 0]\nstart = 0\nfor i in ... | <|body_start_0|>
if not nums:
return 0
currSum = nums[0]
maxSum = nums[0]
for i in range(1, len(nums)):
currSum = max(nums[i], nums[i] + currSum)
maxSum = max(maxSum, currSum)
return maxSum
<|end_body_0|>
<|body_start_1|>
if not nums:
... | Solution2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution2:
def maxSubArray(self, nums):
"""i, max local currSum ending at i update golbal maxSum"""
<|body_0|>
def maxSubArray_index(self, nums):
"""start: the start index of currSum ending at i currSum: [start, i]"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_10k_train_002100 | 2,233 | no_license | [
{
"docstring": "i, max local currSum ending at i update golbal maxSum",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
},
{
"docstring": "start: the start index of currSum ending at i currSum: [start, i]",
"name": "maxSubArray_index",
"signature": "def maxSubArray_inde... | 2 | null | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def maxSubArray(self, nums): i, max local currSum ending at i update golbal maxSum
- def maxSubArray_index(self, nums): start: the start index of currSum ending at i currSum: [... | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def maxSubArray(self, nums): i, max local currSum ending at i update golbal maxSum
- def maxSubArray_index(self, nums): start: the start index of currSum ending at i currSum: [... | 63120dbaabd7c3c19633ebe952bcee4cf826b0e0 | <|skeleton|>
class Solution2:
def maxSubArray(self, nums):
"""i, max local currSum ending at i update golbal maxSum"""
<|body_0|>
def maxSubArray_index(self, nums):
"""start: the start index of currSum ending at i currSum: [start, i]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution2:
def maxSubArray(self, nums):
"""i, max local currSum ending at i update golbal maxSum"""
if not nums:
return 0
currSum = nums[0]
maxSum = nums[0]
for i in range(1, len(nums)):
currSum = max(nums[i], nums[i] + currSum)
maxSu... | the_stack_v2_python_sparse | 53. Maximum Subarray _ divide and conquer.py | CaizhiXu/LeetCode-Python-Solutions | train | 0 | |
57efe61e025fff8b6a5e5d4cba5b634ad9c5dc1b | [
"action_key = request.POST.get('action')\n_, method = self.actions[action_key]\ngetattr(self, method)()\nreturn HttpResponseRedirect(reverse('event_admin', kwargs={'pk': pk}))",
"username = self.request.POST.get('text')\nif self.request.POST.get('Regelboks') == 'True':\n regelbryting = True\nelse:\n regelbr... | <|body_start_0|>
action_key = request.POST.get('action')
_, method = self.actions[action_key]
getattr(self, method)()
return HttpResponseRedirect(reverse('event_admin', kwargs={'pk': pk}))
<|end_body_0|>
<|body_start_1|>
username = self.request.POST.get('text')
if self.r... | Viser påmeldingslisten til et Event med mulighet for å melde folk på og av. | AdministerRegistrationsView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdministerRegistrationsView:
"""Viser påmeldingslisten til et Event med mulighet for å melde folk på og av."""
def post(self, request, pk):
"""Handle http post request"""
<|body_0|>
def register_user(self):
"""Melder på brukeren nevnt i POST['text'] på arrangemen... | stack_v2_sparse_classes_10k_train_002101 | 24,750 | permissive | [
{
"docstring": "Handle http post request",
"name": "post",
"signature": "def post(self, request, pk)"
},
{
"docstring": "Melder på brukeren nevnt i POST['text'] på arrangementet.",
"name": "register_user",
"signature": "def register_user(self)"
},
{
"docstring": "Melder av bruker... | 3 | stack_v2_sparse_classes_30k_train_002686 | Implement the Python class `AdministerRegistrationsView` described below.
Class description:
Viser påmeldingslisten til et Event med mulighet for å melde folk på og av.
Method signatures and docstrings:
- def post(self, request, pk): Handle http post request
- def register_user(self): Melder på brukeren nevnt i POST[... | Implement the Python class `AdministerRegistrationsView` described below.
Class description:
Viser påmeldingslisten til et Event med mulighet for å melde folk på og av.
Method signatures and docstrings:
- def post(self, request, pk): Handle http post request
- def register_user(self): Melder på brukeren nevnt i POST[... | 5661cbea1011f8851a244ae3d72351fce647123f | <|skeleton|>
class AdministerRegistrationsView:
"""Viser påmeldingslisten til et Event med mulighet for å melde folk på og av."""
def post(self, request, pk):
"""Handle http post request"""
<|body_0|>
def register_user(self):
"""Melder på brukeren nevnt i POST['text'] på arrangemen... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdministerRegistrationsView:
"""Viser påmeldingslisten til et Event med mulighet for å melde folk på og av."""
def post(self, request, pk):
"""Handle http post request"""
action_key = request.POST.get('action')
_, method = self.actions[action_key]
getattr(self, method)()
... | the_stack_v2_python_sparse | nablapps/events/views.py | Nabla-NTNU/nablaweb | train | 21 |
b8a828f8a4367ca2a8a5e2d6598123bbc8fa1606 | [
"if 'nan_option' in kwargs:\n assert kwargs['nan_option'] in [self.DEFAULT_NAN_OPTION], 'nan_option={} is not supported'.format(kwargs['nan_option'])\nelse:\n kwargs['nan_option'] = self.DEFAULT_NAN_OPTION\nsuper().__init__(**kwargs)\nassert factor_model in [self.FACTOR_MODEL_PCA, self.FACTOR_MODEL_FA], 'fact... | <|body_start_0|>
if 'nan_option' in kwargs:
assert kwargs['nan_option'] in [self.DEFAULT_NAN_OPTION], 'nan_option={} is not supported'.format(kwargs['nan_option'])
else:
kwargs['nan_option'] = self.DEFAULT_NAN_OPTION
super().__init__(**kwargs)
assert factor_model ... | Structured Covariance Estimator This estimator assumes observations can be predicted by multiple factors X = B @ F.T + U where `X` contains observations (row) of multiple variables (column), `F` contains factor exposures (column) for all variables (row), `B` is the regression coefficients matrix for all observations (r... | StructuredCovEstimator | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StructuredCovEstimator:
"""Structured Covariance Estimator This estimator assumes observations can be predicted by multiple factors X = B @ F.T + U where `X` contains observations (row) of multiple variables (column), `F` contains factor exposures (column) for all variables (row), `B` is the regr... | stack_v2_sparse_classes_10k_train_002102 | 3,801 | permissive | [
{
"docstring": "Args: factor_model (str): the latent factor models used to estimate the structured covariance (`pca`/`fa`). num_factors (int): number of components to keep. kwargs: see `RiskModel` for more information",
"name": "__init__",
"signature": "def __init__(self, factor_model: str='pca', num_fa... | 2 | stack_v2_sparse_classes_30k_train_000486 | Implement the Python class `StructuredCovEstimator` described below.
Class description:
Structured Covariance Estimator This estimator assumes observations can be predicted by multiple factors X = B @ F.T + U where `X` contains observations (row) of multiple variables (column), `F` contains factor exposures (column) f... | Implement the Python class `StructuredCovEstimator` described below.
Class description:
Structured Covariance Estimator This estimator assumes observations can be predicted by multiple factors X = B @ F.T + U where `X` contains observations (row) of multiple variables (column), `F` contains factor exposures (column) f... | 4c30e5827b74bcc45f14cf3ae0c1715459ed09ae | <|skeleton|>
class StructuredCovEstimator:
"""Structured Covariance Estimator This estimator assumes observations can be predicted by multiple factors X = B @ F.T + U where `X` contains observations (row) of multiple variables (column), `F` contains factor exposures (column) for all variables (row), `B` is the regr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StructuredCovEstimator:
"""Structured Covariance Estimator This estimator assumes observations can be predicted by multiple factors X = B @ F.T + U where `X` contains observations (row) of multiple variables (column), `F` contains factor exposures (column) for all variables (row), `B` is the regression coeffi... | the_stack_v2_python_sparse | qlib/model/riskmodel/structured.py | microsoft/qlib | train | 12,822 |
36e48b0590000fa827a2e56b9dce38f137090867 | [
"if N == 0:\n return []\nif N == 1:\n return [TreeNode(0)]\nif N % 2 == 0:\n return []\nleft_num = 1\nright_num = N - 2\nres = []\nwhile right_num > 0:\n lefts = self.allPossibleFBT(left_num)\n rights = self.allPossibleFBT(right_num)\n for i in range(len(lefts)):\n for j in range(len(rights... | <|body_start_0|>
if N == 0:
return []
if N == 1:
return [TreeNode(0)]
if N % 2 == 0:
return []
left_num = 1
right_num = N - 2
res = []
while right_num > 0:
lefts = self.allPossibleFBT(left_num)
rights = s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def allPossibleFBT(self, N):
""":type N: int :rtype: List[TreeNode] 现在这个树一共是N个节点的话,根节点算一个,左子树一共i个,那右子树一共就N-1-i个。 然后迭代的时候每次左边+2个,右边-2个。把所有的结果加起来就好啦。"""
<|body_0|>
def allPossibleFBT2(self, N):
""":type N: int :rtype: List[TreeNode]"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k_train_002103 | 2,349 | no_license | [
{
"docstring": ":type N: int :rtype: List[TreeNode] 现在这个树一共是N个节点的话,根节点算一个,左子树一共i个,那右子树一共就N-1-i个。 然后迭代的时候每次左边+2个,右边-2个。把所有的结果加起来就好啦。",
"name": "allPossibleFBT",
"signature": "def allPossibleFBT(self, N)"
},
{
"docstring": ":type N: int :rtype: List[TreeNode]",
"name": "allPossibleFBT2",
"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def allPossibleFBT(self, N): :type N: int :rtype: List[TreeNode] 现在这个树一共是N个节点的话,根节点算一个,左子树一共i个,那右子树一共就N-1-i个。 然后迭代的时候每次左边+2个,右边-2个。把所有的结果加起来就好啦。
- def allPossibleFBT2(self, N): :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def allPossibleFBT(self, N): :type N: int :rtype: List[TreeNode] 现在这个树一共是N个节点的话,根节点算一个,左子树一共i个,那右子树一共就N-1-i个。 然后迭代的时候每次左边+2个,右边-2个。把所有的结果加起来就好啦。
- def allPossibleFBT2(self, N): :... | 4105e18050b15fc0409c75353ad31be17187dd34 | <|skeleton|>
class Solution:
def allPossibleFBT(self, N):
""":type N: int :rtype: List[TreeNode] 现在这个树一共是N个节点的话,根节点算一个,左子树一共i个,那右子树一共就N-1-i个。 然后迭代的时候每次左边+2个,右边-2个。把所有的结果加起来就好啦。"""
<|body_0|>
def allPossibleFBT2(self, N):
""":type N: int :rtype: List[TreeNode]"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def allPossibleFBT(self, N):
""":type N: int :rtype: List[TreeNode] 现在这个树一共是N个节点的话,根节点算一个,左子树一共i个,那右子树一共就N-1-i个。 然后迭代的时候每次左边+2个,右边-2个。把所有的结果加起来就好啦。"""
if N == 0:
return []
if N == 1:
return [TreeNode(0)]
if N % 2 == 0:
return []
... | the_stack_v2_python_sparse | allPossibleFBT.py | NeilWangziyu/Leetcode_py | train | 2 | |
ac0a7bcb212ab02d93461d9be4fc5b92dbc16198 | [
"invalid_filters = check_filters(self, special_filters=['ids', 'organism__name', 'dataset_id', 'experiment_accession_code', 'accession_codes', 'filter_by'])\nif invalid_filters:\n raise InvalidFilters(invalid_filters=invalid_filters)\nqueryset = Sample.public_objects.select_related('organism').prefetch_related('... | <|body_start_0|>
invalid_filters = check_filters(self, special_filters=['ids', 'organism__name', 'dataset_id', 'experiment_accession_code', 'accession_codes', 'filter_by'])
if invalid_filters:
raise InvalidFilters(invalid_filters=invalid_filters)
queryset = Sample.public_objects.sele... | Returns detailed information about Samples | SampleListView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleListView:
"""Returns detailed information about Samples"""
def get_queryset(self):
"""ref https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters"""
<|body_0|>
def get_query_params_filters(self):
"""We do advanced filte... | stack_v2_sparse_classes_10k_train_002104 | 9,331 | permissive | [
{
"docstring": "ref https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "We do advanced filtering on the queryset depending on the query parameters. This returns the parame... | 2 | null | Implement the Python class `SampleListView` described below.
Class description:
Returns detailed information about Samples
Method signatures and docstrings:
- def get_queryset(self): ref https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters
- def get_query_params_filters(self):... | Implement the Python class `SampleListView` described below.
Class description:
Returns detailed information about Samples
Method signatures and docstrings:
- def get_queryset(self): ref https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters
- def get_query_params_filters(self):... | 99d853dd2583e42c76a28d1a59baa2d65d953119 | <|skeleton|>
class SampleListView:
"""Returns detailed information about Samples"""
def get_queryset(self):
"""ref https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters"""
<|body_0|>
def get_query_params_filters(self):
"""We do advanced filte... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SampleListView:
"""Returns detailed information about Samples"""
def get_queryset(self):
"""ref https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters"""
invalid_filters = check_filters(self, special_filters=['ids', 'organism__name', 'dataset_id', 'e... | the_stack_v2_python_sparse | api/data_refinery_api/views/sample.py | AlexsLemonade/refinebio | train | 117 |
5ee18fa9af9efb894d2f8996ef864f1a2ec12e80 | [
"self.power_spectrum = power_spectrum\nself.delta_f = delta_f\nself.zero_padding = zero_padding\nif any(self.power_spectrum < self.eps):\n if not suppress_small_elements_warning:\n logging.warning('Some elements of power spectrum are too small, setting to zero')\n self.power_spectrum[self.power_spectru... | <|body_start_0|>
self.power_spectrum = power_spectrum
self.delta_f = delta_f
self.zero_padding = zero_padding
if any(self.power_spectrum < self.eps):
if not suppress_small_elements_warning:
logging.warning('Some elements of power spectrum are too small, settin... | SpectralFactorization | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectralFactorization:
def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False):
"""Calculate the minimum-phase causal wavelet of a given power spectrum. In other words: Given the power transmission spectrum S(f) = |h(f)|² of a system with ... | stack_v2_sparse_classes_10k_train_002105 | 3,853 | permissive | [
{
"docstring": "Calculate the minimum-phase causal wavelet of a given power spectrum. In other words: Given the power transmission spectrum S(f) = |h(f)|² of a system with transfer function h(f), reconstruct the phase of h(f) so that h(t) = 0 for t < 0. The answer is only unique up to an all-pass component; the... | 2 | stack_v2_sparse_classes_30k_train_003895 | Implement the Python class `SpectralFactorization` described below.
Class description:
Implement the SpectralFactorization class.
Method signatures and docstrings:
- def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False): Calculate the minimum-phase causal wavelet of ... | Implement the Python class `SpectralFactorization` described below.
Class description:
Implement the SpectralFactorization class.
Method signatures and docstrings:
- def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False): Calculate the minimum-phase causal wavelet of ... | 4fc56396ad603bbe61e6d548f66b818d51a3301b | <|skeleton|>
class SpectralFactorization:
def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False):
"""Calculate the minimum-phase causal wavelet of a given power spectrum. In other words: Given the power transmission spectrum S(f) = |h(f)|² of a system with ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SpectralFactorization:
def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False):
"""Calculate the minimum-phase causal wavelet of a given power spectrum. In other words: Given the power transmission spectrum S(f) = |h(f)|² of a system with transfer funct... | the_stack_v2_python_sparse | pycqed/analysis/tools/spectralfac.py | DiCarloLab-Delft/PycQED_py3 | train | 72 | |
2c82bde0852d6d4d2fdd122fae56b1aad47abeda | [
"user_kwargs = optimizer_kwargs\noptimizer_kwargs = {}\nprint(f'in {optimizer}: max_iterations = {max_iterations}')\nif optimizer == 'BFGS':\n from scipy.optimize import minimize as optimizer\n optimizer_kwargs = {'method': 'BFGS', 'options': {'gtol': 1e-15, 'maxiter': max_iterations}}\nelif optimizer == 'L-B... | <|body_start_0|>
user_kwargs = optimizer_kwargs
optimizer_kwargs = {}
print(f'in {optimizer}: max_iterations = {max_iterations}')
if optimizer == 'BFGS':
from scipy.optimize import minimize as optimizer
optimizer_kwargs = {'method': 'BFGS', 'options': {'gtol': 1e-... | Class to manage the regression of a generic model. That is, for a given parameter set, calculates the cost function (the difference in predicted energies and actual energies across training images), then decides how to adjust the parameters to reduce this cost function. Global optimization conditioners (e.g., simulated... | Regressor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Regressor:
"""Class to manage the regression of a generic model. That is, for a given parameter set, calculates the cost function (the difference in predicted energies and actual energies across training images), then decides how to adjust the parameters to reduce this cost function. Global optim... | stack_v2_sparse_classes_10k_train_002106 | 5,499 | no_license | [
{
"docstring": "optimizer can be specified; it should behave like a scipy.optimize optimizer. That is, it should take as its first two arguments the function to be optimized and the initial guess of the optimal parameters. Additional keyword arguments can be fed through the optimizer_kwargs dictionary.",
"n... | 2 | stack_v2_sparse_classes_30k_train_003096 | Implement the Python class `Regressor` described below.
Class description:
Class to manage the regression of a generic model. That is, for a given parameter set, calculates the cost function (the difference in predicted energies and actual energies across training images), then decides how to adjust the parameters to ... | Implement the Python class `Regressor` described below.
Class description:
Class to manage the regression of a generic model. That is, for a given parameter set, calculates the cost function (the difference in predicted energies and actual energies across training images), then decides how to adjust the parameters to ... | 4d26767f287be6abc88dc74374003b04d509bebf | <|skeleton|>
class Regressor:
"""Class to manage the regression of a generic model. That is, for a given parameter set, calculates the cost function (the difference in predicted energies and actual energies across training images), then decides how to adjust the parameters to reduce this cost function. Global optim... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Regressor:
"""Class to manage the regression of a generic model. That is, for a given parameter set, calculates the cost function (the difference in predicted energies and actual energies across training images), then decides how to adjust the parameters to reduce this cost function. Global optimization condi... | the_stack_v2_python_sparse | MLdyn/amp_patches/amp.regression.__init__.py | hopefulp/sandbox | train | 1 |
4a0521e733d7580ef3eba6519f3e26a369b68637 | [
"super().__init__()\nself.pooling = pooling\nself.spherical_cheb = SphericalChebConv(in_channels, out_channels, lap, kernel_size)",
"x = self.pooling(x)\nx = self.spherical_cheb(x)\nreturn x"
] | <|body_start_0|>
super().__init__()
self.pooling = pooling
self.spherical_cheb = SphericalChebConv(in_channels, out_channels, lap, kernel_size)
<|end_body_0|>
<|body_start_1|>
x = self.pooling(x)
x = self.spherical_cheb(x)
return x
<|end_body_1|>
| Building Block with a pooling/unpooling and a Chebyshev Convolution. | SphericalChebPool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalChebPool:
"""Building Block with a pooling/unpooling and a Chebyshev Convolution."""
def __init__(self, in_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of channel... | stack_v2_sparse_classes_10k_train_002107 | 41,403 | no_license | [
{
"docstring": "Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of channels. lap (:obj:`torch.sparse.FloatTensor`): laplacian. pooling (:obj:`torch.nn.Module`): pooling/unpooling module. kernel_size (int, optional): polynomial degree.",
"name": "__init_... | 2 | null | Implement the Python class `SphericalChebPool` described below.
Class description:
Building Block with a pooling/unpooling and a Chebyshev Convolution.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, lap, pooling, kernel_size): Initialization. Args: in_channels (int): initial number ... | Implement the Python class `SphericalChebPool` described below.
Class description:
Building Block with a pooling/unpooling and a Chebyshev Convolution.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, lap, pooling, kernel_size): Initialization. Args: in_channels (int): initial number ... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SphericalChebPool:
"""Building Block with a pooling/unpooling and a Chebyshev Convolution."""
def __init__(self, in_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of channel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SphericalChebPool:
"""Building Block with a pooling/unpooling and a Chebyshev Convolution."""
def __init__(self, in_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of channels. lap (:obj:... | the_stack_v2_python_sparse | generated/test_deepsphere_deepsphere_pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
12966f92699ae5857ab02cbab03d7b4e078803e3 | [
"self.dmax = dmax\ndist, order = torch.sort(dist, dim=1)\nself.order = order\ndmax_vec = dmax * torch.ones(dist.shape[0], 1)\noff_one = torch.cat((dist[:, 1:], dmax_vec), dim=1)\nself.m = dist - off_one\nself.temp = temp\nself.hardmax = hardmax",
"x_sort = x[self.order]\nprobs = 1 - torch.cumprod(1 - x_sort, dim=... | <|body_start_0|>
self.dmax = dmax
dist, order = torch.sort(dist, dim=1)
self.order = order
dmax_vec = dmax * torch.ones(dist.shape[0], 1)
off_one = torch.cat((dist[:, 1:], dmax_vec), dim=1)
self.m = dist - off_one
self.temp = temp
self.hardmax = hardmax
<|... | CenterObjective | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CenterObjective:
def __init__(self, dist, dmax, temp, hardmax=False):
"""dist: (num customers) * (num locations) matrix dmax: maximum distance that can be suffered by any customer (e.g., if no facilities are chosen) temp: how hard to make the softmax over customers"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_002108 | 4,317 | permissive | [
{
"docstring": "dist: (num customers) * (num locations) matrix dmax: maximum distance that can be suffered by any customer (e.g., if no facilities are chosen) temp: how hard to make the softmax over customers",
"name": "__init__",
"signature": "def __init__(self, dist, dmax, temp, hardmax=False)"
},
... | 2 | stack_v2_sparse_classes_30k_train_004275 | Implement the Python class `CenterObjective` described below.
Class description:
Implement the CenterObjective class.
Method signatures and docstrings:
- def __init__(self, dist, dmax, temp, hardmax=False): dist: (num customers) * (num locations) matrix dmax: maximum distance that can be suffered by any customer (e.g... | Implement the Python class `CenterObjective` described below.
Class description:
Implement the CenterObjective class.
Method signatures and docstrings:
- def __init__(self, dist, dmax, temp, hardmax=False): dist: (num customers) * (num locations) matrix dmax: maximum distance that can be suffered by any customer (e.g... | 911c90da4b2761678582108e6b7875a8aedce8ac | <|skeleton|>
class CenterObjective:
def __init__(self, dist, dmax, temp, hardmax=False):
"""dist: (num customers) * (num locations) matrix dmax: maximum distance that can be suffered by any customer (e.g., if no facilities are chosen) temp: how hard to make the softmax over customers"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CenterObjective:
def __init__(self, dist, dmax, temp, hardmax=False):
"""dist: (num customers) * (num locations) matrix dmax: maximum distance that can be suffered by any customer (e.g., if no facilities are chosen) temp: how hard to make the softmax over customers"""
self.dmax = dmax
... | the_stack_v2_python_sparse | kcenter.py | yuvalsimon/clusternet | train | 0 | |
1fade49394ddb6490be49c5a9a6c02e2f2af05e7 | [
"len_s = len(strs)\ndp = [[[0] * (n + 1) for i in range(m + 1)] for j in range(len_s + 1)]\nfor k in range(1, len_s + 1):\n count_0 = strs[k - 1].count('0')\n count_1 = strs[k - 1].count('1')\n for i in range(m + 1):\n for j in range(n + 1):\n dp[k][i][j] = dp[k - 1][i][j]\n if... | <|body_start_0|>
len_s = len(strs)
dp = [[[0] * (n + 1) for i in range(m + 1)] for j in range(len_s + 1)]
for k in range(1, len_s + 1):
count_0 = strs[k - 1].count('0')
count_1 = strs[k - 1].count('1')
for i in range(m + 1):
for j in range(n + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
"""执行用时: 5960 ms , 在所有 Python3 提交中击败了 12.47% 的用户 内存消耗: 70.1 MB , 在所有 Python3 提交中击败了 10.96% 的用户"""
<|body_0|>
def findMaxForm1(self, strs: List[str], m: int, n: int) -> int:
"""执行用时: 3024 ms , 在所... | stack_v2_sparse_classes_10k_train_002109 | 2,621 | no_license | [
{
"docstring": "执行用时: 5960 ms , 在所有 Python3 提交中击败了 12.47% 的用户 内存消耗: 70.1 MB , 在所有 Python3 提交中击败了 10.96% 的用户",
"name": "findMaxForm",
"signature": "def findMaxForm(self, strs: List[str], m: int, n: int) -> int"
},
{
"docstring": "执行用时: 3024 ms , 在所有 Python3 提交中击败了 75.50% 的用户 内存消耗: 15 MB , 在所有 Pyt... | 2 | stack_v2_sparse_classes_30k_train_004663 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxForm(self, strs: List[str], m: int, n: int) -> int: 执行用时: 5960 ms , 在所有 Python3 提交中击败了 12.47% 的用户 内存消耗: 70.1 MB , 在所有 Python3 提交中击败了 10.96% 的用户
- def findMaxForm1(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxForm(self, strs: List[str], m: int, n: int) -> int: 执行用时: 5960 ms , 在所有 Python3 提交中击败了 12.47% 的用户 内存消耗: 70.1 MB , 在所有 Python3 提交中击败了 10.96% 的用户
- def findMaxForm1(self... | d613ed8a5a2c15ace7d513965b372d128845d66a | <|skeleton|>
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
"""执行用时: 5960 ms , 在所有 Python3 提交中击败了 12.47% 的用户 内存消耗: 70.1 MB , 在所有 Python3 提交中击败了 10.96% 的用户"""
<|body_0|>
def findMaxForm1(self, strs: List[str], m: int, n: int) -> int:
"""执行用时: 3024 ms , 在所... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
"""执行用时: 5960 ms , 在所有 Python3 提交中击败了 12.47% 的用户 内存消耗: 70.1 MB , 在所有 Python3 提交中击败了 10.96% 的用户"""
len_s = len(strs)
dp = [[[0] * (n + 1) for i in range(m + 1)] for j in range(len_s + 1)]
for k in range(1, ... | the_stack_v2_python_sparse | 一和零.py | nomboy/leetcode | train | 0 | |
4c5950ddf6f2c8b2bd1b805712ea1fb4d0c9fb83 | [
"if not 'L_NU_X_BAR' in simtab.colnames:\n for val in ['L', 'E', 'ALPHA']:\n simtab[f'{val}_NU_X_BAR'] = simtab[f'{val}_NU_X']\ntime = simtab['TIME'] << u.s\nself.luminosity = {}\nself.meanE = {}\nself.pinch = {}\nfor f in Flavor:\n self.luminosity[f] = simtab[f'L_{f.name}'] << u.erg / u.s\n self.me... | <|body_start_0|>
if not 'L_NU_X_BAR' in simtab.colnames:
for val in ['L', 'E', 'ALPHA']:
simtab[f'{val}_NU_X_BAR'] = simtab[f'{val}_NU_X']
time = simtab['TIME'] << u.s
self.luminosity = {}
self.meanE = {}
self.pinch = {}
for f in Flavor:
... | Subclass that contains spectra/luminosity pinches | PinchedModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PinchedModel:
"""Subclass that contains spectra/luminosity pinches"""
def __init__(self, simtab, metadata):
"""Initialize the PinchedModel using the data from the given table. Parameters ---------- simtab: astropy.Table Should contain columns TIME, {L,E,ALPHA}_NU_{E,E_BAR,X,X_BAR} Th... | stack_v2_sparse_classes_10k_train_002110 | 18,095 | permissive | [
{
"docstring": "Initialize the PinchedModel using the data from the given table. Parameters ---------- simtab: astropy.Table Should contain columns TIME, {L,E,ALPHA}_NU_{E,E_BAR,X,X_BAR} The values for X_BAR may be missing, then NU_X data will be used metadata: dict Model parameters dict",
"name": "__init__... | 2 | stack_v2_sparse_classes_30k_train_002355 | Implement the Python class `PinchedModel` described below.
Class description:
Subclass that contains spectra/luminosity pinches
Method signatures and docstrings:
- def __init__(self, simtab, metadata): Initialize the PinchedModel using the data from the given table. Parameters ---------- simtab: astropy.Table Should ... | Implement the Python class `PinchedModel` described below.
Class description:
Subclass that contains spectra/luminosity pinches
Method signatures and docstrings:
- def __init__(self, simtab, metadata): Initialize the PinchedModel using the data from the given table. Parameters ---------- simtab: astropy.Table Should ... | feb3a6c46d7dc4e999446994025001de77768e1d | <|skeleton|>
class PinchedModel:
"""Subclass that contains spectra/luminosity pinches"""
def __init__(self, simtab, metadata):
"""Initialize the PinchedModel using the data from the given table. Parameters ---------- simtab: astropy.Table Should contain columns TIME, {L,E,ALPHA}_NU_{E,E_BAR,X,X_BAR} Th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PinchedModel:
"""Subclass that contains spectra/luminosity pinches"""
def __init__(self, simtab, metadata):
"""Initialize the PinchedModel using the data from the given table. Parameters ---------- simtab: astropy.Table Should contain columns TIME, {L,E,ALPHA}_NU_{E,E_BAR,X,X_BAR} The values for ... | the_stack_v2_python_sparse | python/snewpy/models/base.py | SNEWS2/snewpy | train | 22 |
433f98ff29f5b2bf1f99d8aad5899984a658d99c | [
"if isinstance(identifier, str):\n domain = expression.OR([[(field, '=', identifier)] for field in self.MSM_STR_DOMAIN])\nelif isinstance(identifier, int):\n domain = [('id', '=', identifier)]\nelse:\n raise TypeError(_('Identifier must be either int or str, not %s') % type(identifier))\nreturn domain",
... | <|body_start_0|>
if isinstance(identifier, str):
domain = expression.OR([[(field, '=', identifier)] for field in self.MSM_STR_DOMAIN])
elif isinstance(identifier, int):
domain = [('id', '=', identifier)]
else:
raise TypeError(_('Identifier must be either int o... | MixinStockModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixinStockModel:
def _get_msm_domain(self, identifier):
"""Return a domain based on MSM_STR_DOMAIN attribute (which can be changed on the model which this model is mixed in to) :args: - identifier: str or int The identifier to search by :returns: List of tuples (Odoo style domain)"""
... | stack_v2_sparse_classes_10k_train_002111 | 3,927 | no_license | [
{
"docstring": "Return a domain based on MSM_STR_DOMAIN attribute (which can be changed on the model which this model is mixed in to) :args: - identifier: str or int The identifier to search by :returns: List of tuples (Odoo style domain)",
"name": "_get_msm_domain",
"signature": "def _get_msm_domain(se... | 2 | stack_v2_sparse_classes_30k_train_006795 | Implement the Python class `MixinStockModel` described below.
Class description:
Implement the MixinStockModel class.
Method signatures and docstrings:
- def _get_msm_domain(self, identifier): Return a domain based on MSM_STR_DOMAIN attribute (which can be changed on the model which this model is mixed in to) :args: ... | Implement the Python class `MixinStockModel` described below.
Class description:
Implement the MixinStockModel class.
Method signatures and docstrings:
- def _get_msm_domain(self, identifier): Return a domain based on MSM_STR_DOMAIN attribute (which can be changed on the model which this model is mixed in to) :args: ... | 0f69491b1538892c1921ae8063d9ea269e15d9ce | <|skeleton|>
class MixinStockModel:
def _get_msm_domain(self, identifier):
"""Return a domain based on MSM_STR_DOMAIN attribute (which can be changed on the model which this model is mixed in to) :args: - identifier: str or int The identifier to search by :returns: List of tuples (Odoo style domain)"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MixinStockModel:
def _get_msm_domain(self, identifier):
"""Return a domain based on MSM_STR_DOMAIN attribute (which can be changed on the model which this model is mixed in to) :args: - identifier: str or int The identifier to search by :returns: List of tuples (Odoo style domain)"""
if isinst... | the_stack_v2_python_sparse | addons/udes_stock/models/mixin_stock_model.py | unipartdigital/udes-open | train | 7 | |
a551fb1ccc5e8e449033e9df480158dfe3c56ae3 | [
"self._data = sys_array.array('i', [0] * M * N)\nself._rows = M\nself._cols = N",
"row, col = self._validate_key(key)\nprint('Row: ', row)\nprint('_cols ', self._cols)\nprint('col ', col)\nprint('getItem Return: ', self._data[row * self._cols + col])\nreturn self._data[row * self._cols + col]",
"row, col = self... | <|body_start_0|>
self._data = sys_array.array('i', [0] * M * N)
self._rows = M
self._cols = N
<|end_body_0|>
<|body_start_1|>
row, col = self._validate_key(key)
print('Row: ', row)
print('_cols ', self._cols)
print('col ', col)
print('getItem Return: ', s... | array | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class array:
def __init__(self, M, N):
"""Create an M-element list of N-element row lists."""
<|body_0|>
def __getitem__(self, key):
"""Returns the appropriate element for a two-element subscript tuple."""
<|body_1|>
def __setitem__(self, key, value):
... | stack_v2_sparse_classes_10k_train_002112 | 2,459 | no_license | [
{
"docstring": "Create an M-element list of N-element row lists.",
"name": "__init__",
"signature": "def __init__(self, M, N)"
},
{
"docstring": "Returns the appropriate element for a two-element subscript tuple.",
"name": "__getitem__",
"signature": "def __getitem__(self, key)"
},
{... | 4 | null | Implement the Python class `array` described below.
Class description:
Implement the array class.
Method signatures and docstrings:
- def __init__(self, M, N): Create an M-element list of N-element row lists.
- def __getitem__(self, key): Returns the appropriate element for a two-element subscript tuple.
- def __seti... | Implement the Python class `array` described below.
Class description:
Implement the array class.
Method signatures and docstrings:
- def __init__(self, M, N): Create an M-element list of N-element row lists.
- def __getitem__(self, key): Returns the appropriate element for a two-element subscript tuple.
- def __seti... | 7306581d542d6d045a9b2e6377ade0fc5ab8bc0e | <|skeleton|>
class array:
def __init__(self, M, N):
"""Create an M-element list of N-element row lists."""
<|body_0|>
def __getitem__(self, key):
"""Returns the appropriate element for a two-element subscript tuple."""
<|body_1|>
def __setitem__(self, key, value):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class array:
def __init__(self, M, N):
"""Create an M-element list of N-element row lists."""
self._data = sys_array.array('i', [0] * M * N)
self._rows = M
self._cols = N
def __getitem__(self, key):
"""Returns the appropriate element for a two-element subscript tuple."""... | the_stack_v2_python_sparse | PythonHomeWork/Py4/Py4_Lesson02/src/arr_array.py | rduvalwa5/OReillyPy | train | 0 | |
75316ed6b1e36d938bea1e10466f3ba774ddac00 | [
"check_arg(dirpath, u._('Directory path'), str)\ndirpath = safe_decode(dirpath)\nif not os.path.exists(dirpath):\n raise InvalidArgument(u._('Directory path: {path} does not exist').format(path=dirpath))\ndumpfile_path = dump(dirpath)\nreturn dumpfile_path",
"check_arg(dirpath, u._('Directory path'), str)\ndir... | <|body_start_0|>
check_arg(dirpath, u._('Directory path'), str)
dirpath = safe_decode(dirpath)
if not os.path.exists(dirpath):
raise InvalidArgument(u._('Directory path: {path} does not exist').format(path=dirpath))
dumpfile_path = dump(dirpath)
return dumpfile_path
<... | SupportApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupportApi:
def support_dump(self, dirpath):
"""Dumps configuration data for debugging. Dumps most files in /etc/kolla and /usr/share/kolla into a tar file so be given to support / development to help with debugging problems. :param dirpath: path to directory where dump will be placed :t... | stack_v2_sparse_classes_10k_train_002113 | 3,067 | permissive | [
{
"docstring": "Dumps configuration data for debugging. Dumps most files in /etc/kolla and /usr/share/kolla into a tar file so be given to support / development to help with debugging problems. :param dirpath: path to directory where dump will be placed :type dirpath: string :return: path to dump file :rtype: s... | 2 | stack_v2_sparse_classes_30k_train_006417 | Implement the Python class `SupportApi` described below.
Class description:
Implement the SupportApi class.
Method signatures and docstrings:
- def support_dump(self, dirpath): Dumps configuration data for debugging. Dumps most files in /etc/kolla and /usr/share/kolla into a tar file so be given to support / developm... | Implement the Python class `SupportApi` described below.
Class description:
Implement the SupportApi class.
Method signatures and docstrings:
- def support_dump(self, dirpath): Dumps configuration data for debugging. Dumps most files in /etc/kolla and /usr/share/kolla into a tar file so be given to support / developm... | dc38107ff2462f62124b5feab275fa369e223169 | <|skeleton|>
class SupportApi:
def support_dump(self, dirpath):
"""Dumps configuration data for debugging. Dumps most files in /etc/kolla and /usr/share/kolla into a tar file so be given to support / development to help with debugging problems. :param dirpath: path to directory where dump will be placed :t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SupportApi:
def support_dump(self, dirpath):
"""Dumps configuration data for debugging. Dumps most files in /etc/kolla and /usr/share/kolla into a tar file so be given to support / development to help with debugging problems. :param dirpath: path to directory where dump will be placed :type dirpath: s... | the_stack_v2_python_sparse | kolla_cli/api/support.py | iputra/kolla-cli | train | 0 | |
5f67b68dd51fe5b9c669862657c7b6a2dd754abe | [
"n, m = (len(text1), len(text2))\nif n * m == 0:\n return 0\ndp = [[0] * (m + 1) for _ in range(n + 1)]\nfor i in range(1, n + 1):\n for j in range(1, m + 1):\n if text1[i - 1] == text2[j - 1]:\n dp[i][j] = 1 + dp[i - 1][j - 1]\n else:\n dp[i][j] = max(dp[i - 1][j], dp[i][j... | <|body_start_0|>
n, m = (len(text1), len(text2))
if n * m == 0:
return 0
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
if text1[i - 1] == text2[j - 1]:
dp[i][j] = 1 + dp[i - 1][j ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longest_common_subsequence(self, text1: str, text2: str) -> int:
"""动态规划。"""
<|body_0|>
def longest_common_subsequence_2(self, text1: str, text2: str) -> int:
"""动态规划。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n, m = (len(text1),... | stack_v2_sparse_classes_10k_train_002114 | 3,316 | no_license | [
{
"docstring": "动态规划。",
"name": "longest_common_subsequence",
"signature": "def longest_common_subsequence(self, text1: str, text2: str) -> int"
},
{
"docstring": "动态规划。",
"name": "longest_common_subsequence_2",
"signature": "def longest_common_subsequence_2(self, text1: str, text2: str)... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longest_common_subsequence(self, text1: str, text2: str) -> int: 动态规划。
- def longest_common_subsequence_2(self, text1: str, text2: str) -> int: 动态规划。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longest_common_subsequence(self, text1: str, text2: str) -> int: 动态规划。
- def longest_common_subsequence_2(self, text1: str, text2: str) -> int: 动态规划。
<|skeleton|>
class Solu... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class Solution:
def longest_common_subsequence(self, text1: str, text2: str) -> int:
"""动态规划。"""
<|body_0|>
def longest_common_subsequence_2(self, text1: str, text2: str) -> int:
"""动态规划。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longest_common_subsequence(self, text1: str, text2: str) -> int:
"""动态规划。"""
n, m = (len(text1), len(text2))
if n * m == 0:
return 0
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
... | the_stack_v2_python_sparse | 1143_longest-common-subsequence.py | Nigirimeshi/leetcode | train | 0 | |
05a10c77d306e8e0370df84770ad35c62403ec94 | [
"self.conf = conf\nif not isinstance(section, str):\n raise TypeError('In DataCatalog.__init__, section must be a string.')\nself.section = section\nself.anltime = to_datetime(anltime)",
"if isinstance(self.anltime, datetime.datetime):\n stime = self.anltime.strftime('%Y%m%d%H')\nelse:\n stime = str(self... | <|body_start_0|>
self.conf = conf
if not isinstance(section, str):
raise TypeError('In DataCatalog.__init__, section must be a string.')
self.section = section
self.anltime = to_datetime(anltime)
<|end_body_0|>
<|body_start_1|>
if isinstance(self.anltime, datetime.da... | !Provides the location of a file in an archive, on disk or on a remote server via sftp or ftp. This class is a collection of functions that know how to provide the location of a file in either an archive or a filesystem. It does not know how to actually obtain the file. This serves as the underlying "where is that file... | DataCatalog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataCatalog:
"""!Provides the location of a file in an archive, on disk or on a remote server via sftp or ftp. This class is a collection of functions that know how to provide the location of a file in either an archive or a filesystem. It does not know how to actually obtain the file. This serve... | stack_v2_sparse_classes_10k_train_002115 | 48,880 | no_license | [
{
"docstring": "!DataCatalog constructor @param conf the configuration object, an hafs.config.HAFSConfig @param section the section that provides location information @param anltime the default analysis time",
"name": "__init__",
"signature": "def __init__(self, conf, section, anltime)"
},
{
"do... | 5 | stack_v2_sparse_classes_30k_train_002071 | Implement the Python class `DataCatalog` described below.
Class description:
!Provides the location of a file in an archive, on disk or on a remote server via sftp or ftp. This class is a collection of functions that know how to provide the location of a file in either an archive or a filesystem. It does not know how ... | Implement the Python class `DataCatalog` described below.
Class description:
!Provides the location of a file in an archive, on disk or on a remote server via sftp or ftp. This class is a collection of functions that know how to provide the location of a file in either an archive or a filesystem. It does not know how ... | cba6b3649eb7a25bb8be392db1901f47d3287c93 | <|skeleton|>
class DataCatalog:
"""!Provides the location of a file in an archive, on disk or on a remote server via sftp or ftp. This class is a collection of functions that know how to provide the location of a file in either an archive or a filesystem. It does not know how to actually obtain the file. This serve... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DataCatalog:
"""!Provides the location of a file in an archive, on disk or on a remote server via sftp or ftp. This class is a collection of functions that know how to provide the location of a file in either an archive or a filesystem. It does not know how to actually obtain the file. This serves as the unde... | the_stack_v2_python_sparse | ush/hafs/input.py | hafs-community/HAFS | train | 22 |
6d00027bc2ce07503efbf6d0a034558688368a13 | [
"key = tokey(source.key, geometry_string, serialize(options))\nfilename, _ext = os.path.splitext(os.path.basename(source.name))\npath = '%s/%s' % (key, filename)\nreturn '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])",
"source_image = source_image.convert('RGB')\nlogger.debug('Creati... | <|body_start_0|>
key = tokey(source.key, geometry_string, serialize(options))
filename, _ext = os.path.splitext(os.path.basename(source.name))
path = '%s/%s' % (key, filename)
return '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])
<|end_body_0|>
<|body_start... | SEOThumbnailBackend | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEOThumbnailBackend:
def _get_thumbnail_filename(self, source, geometry_string, options):
"""Computes the destination filename."""
<|body_0|>
def _create_thumbnail(self, source_image, geometry_string, options, thumbnail):
"""Creates the thumbnail by using default.eng... | stack_v2_sparse_classes_10k_train_002116 | 1,602 | permissive | [
{
"docstring": "Computes the destination filename.",
"name": "_get_thumbnail_filename",
"signature": "def _get_thumbnail_filename(self, source, geometry_string, options)"
},
{
"docstring": "Creates the thumbnail by using default.engine",
"name": "_create_thumbnail",
"signature": "def _cr... | 2 | stack_v2_sparse_classes_30k_train_000591 | Implement the Python class `SEOThumbnailBackend` described below.
Class description:
Implement the SEOThumbnailBackend class.
Method signatures and docstrings:
- def _get_thumbnail_filename(self, source, geometry_string, options): Computes the destination filename.
- def _create_thumbnail(self, source_image, geometry... | Implement the Python class `SEOThumbnailBackend` described below.
Class description:
Implement the SEOThumbnailBackend class.
Method signatures and docstrings:
- def _get_thumbnail_filename(self, source, geometry_string, options): Computes the destination filename.
- def _create_thumbnail(self, source_image, geometry... | e21aa8fa62df96f41ddbea913f386ee7c6780ed0 | <|skeleton|>
class SEOThumbnailBackend:
def _get_thumbnail_filename(self, source, geometry_string, options):
"""Computes the destination filename."""
<|body_0|>
def _create_thumbnail(self, source_image, geometry_string, options, thumbnail):
"""Creates the thumbnail by using default.eng... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SEOThumbnailBackend:
def _get_thumbnail_filename(self, source, geometry_string, options):
"""Computes the destination filename."""
key = tokey(source.key, geometry_string, serialize(options))
filename, _ext = os.path.splitext(os.path.basename(source.name))
path = '%s/%s' % (key... | the_stack_v2_python_sparse | jobsp/thumbnailname.py | MicroPyramid/opensource-job-portal | train | 360 | |
4a0521e733d7580ef3eba6519f3e26a369b68637 | [
"super().__init__()\nself.unpooling = unpooling\nself.kernel_size = kernel_size\nself.dec_l1 = SphericalChebBNPoolConcat(512, 512, laps[1], self.unpooling, self.kernel_size)\nself.dec_l2 = SphericalChebBNPoolConcat(512, 256, laps[2], self.unpooling, self.kernel_size)\nself.dec_l3 = SphericalChebBNPoolConcat(256, 12... | <|body_start_0|>
super().__init__()
self.unpooling = unpooling
self.kernel_size = kernel_size
self.dec_l1 = SphericalChebBNPoolConcat(512, 512, laps[1], self.unpooling, self.kernel_size)
self.dec_l2 = SphericalChebBNPoolConcat(512, 256, laps[2], self.unpooling, self.kernel_size)
... | The decoder of the Spherical UNet. | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""The decoder of the Spherical UNet."""
def __init__(self, unpooling, laps, kernel_size):
"""Initialization. Args: unpooling (:obj:`torch.nn.Module`): The unpooling object. laps (list): List of laplacians."""
<|body_0|>
def forward(self, x_enc0, x_enc1, x_enc2,... | stack_v2_sparse_classes_10k_train_002117 | 41,403 | no_license | [
{
"docstring": "Initialization. Args: unpooling (:obj:`torch.nn.Module`): The unpooling object. laps (list): List of laplacians.",
"name": "__init__",
"signature": "def __init__(self, unpooling, laps, kernel_size)"
},
{
"docstring": "Forward Pass. Args: x_enc* (:obj:`torch.Tensor`): input tensor... | 2 | null | Implement the Python class `Decoder` described below.
Class description:
The decoder of the Spherical UNet.
Method signatures and docstrings:
- def __init__(self, unpooling, laps, kernel_size): Initialization. Args: unpooling (:obj:`torch.nn.Module`): The unpooling object. laps (list): List of laplacians.
- def forwa... | Implement the Python class `Decoder` described below.
Class description:
The decoder of the Spherical UNet.
Method signatures and docstrings:
- def __init__(self, unpooling, laps, kernel_size): Initialization. Args: unpooling (:obj:`torch.nn.Module`): The unpooling object. laps (list): List of laplacians.
- def forwa... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Decoder:
"""The decoder of the Spherical UNet."""
def __init__(self, unpooling, laps, kernel_size):
"""Initialization. Args: unpooling (:obj:`torch.nn.Module`): The unpooling object. laps (list): List of laplacians."""
<|body_0|>
def forward(self, x_enc0, x_enc1, x_enc2,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Decoder:
"""The decoder of the Spherical UNet."""
def __init__(self, unpooling, laps, kernel_size):
"""Initialization. Args: unpooling (:obj:`torch.nn.Module`): The unpooling object. laps (list): List of laplacians."""
super().__init__()
self.unpooling = unpooling
self.ker... | the_stack_v2_python_sparse | generated/test_deepsphere_deepsphere_pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
2d847b13623df0618d4b18aa8a341ec617691bc7 | [
"data = self.cleaned_data\ncategory = self.cleaned_data['phone_category']\nif PhoneCategory.objects.count() >= 4 and self.instance.pk is None:\n raise ValidationError(phone_category_error)\nif PhoneCategory.objects.filter(phone_category=category) and (not self.instance.pk):\n error_message = phone_category_er... | <|body_start_0|>
data = self.cleaned_data
category = self.cleaned_data['phone_category']
if PhoneCategory.objects.count() >= 4 and self.instance.pk is None:
raise ValidationError(phone_category_error)
if PhoneCategory.objects.filter(phone_category=category) and (not self.inst... | A form for validating Phone category data. | PhoneCategoryForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhoneCategoryForm:
"""A form for validating Phone category data."""
def clean(self):
"""Validate that categories do not exceed four and a category has not been repeated."""
<|body_0|>
def clean_category_image(self):
"""Validate that the height and width of the im... | stack_v2_sparse_classes_10k_train_002118 | 2,354 | no_license | [
{
"docstring": "Validate that categories do not exceed four and a category has not been repeated.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Validate that the height and width of the image are equal.",
"name": "clean_category_image",
"signature": "def clean_cate... | 2 | stack_v2_sparse_classes_30k_train_006194 | Implement the Python class `PhoneCategoryForm` described below.
Class description:
A form for validating Phone category data.
Method signatures and docstrings:
- def clean(self): Validate that categories do not exceed four and a category has not been repeated.
- def clean_category_image(self): Validate that the heigh... | Implement the Python class `PhoneCategoryForm` described below.
Class description:
A form for validating Phone category data.
Method signatures and docstrings:
- def clean(self): Validate that categories do not exceed four and a category has not been repeated.
- def clean_category_image(self): Validate that the heigh... | 16ab89be35bebe4c9090415288205e5ea543df29 | <|skeleton|>
class PhoneCategoryForm:
"""A form for validating Phone category data."""
def clean(self):
"""Validate that categories do not exceed four and a category has not been repeated."""
<|body_0|>
def clean_category_image(self):
"""Validate that the height and width of the im... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PhoneCategoryForm:
"""A form for validating Phone category data."""
def clean(self):
"""Validate that categories do not exceed four and a category has not been repeated."""
data = self.cleaned_data
category = self.cleaned_data['phone_category']
if PhoneCategory.objects.cou... | the_stack_v2_python_sparse | hirola/front/forms/model_forms.py | JamesKirkAndSpock/Hirola | train | 0 |
50a42b8ebedb69c94f5cfc3eea66f289d068c7ff | [
"Ioput.function_name(self.__class__.__name__)\ntry:\n self.execute_test(url=url)\n self.get_text_value(kone='subject')\nexcept AssertionError as a:\n self.assertTrue('', '返回结果text非字典 %s' % a)\nelse:\n self.assertTrue(self.datalist1, '键 subject 无内容')",
"Ioput.function_name(self.__class__.__name__)\ntr... | <|body_start_0|>
Ioput.function_name(self.__class__.__name__)
try:
self.execute_test(url=url)
self.get_text_value(kone='subject')
except AssertionError as a:
self.assertTrue('', '返回结果text非字典 %s' % a)
else:
self.assertTrue(self.datalist1, '... | Test_语音搜索服务接口 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_语音搜索服务接口:
def test_1直播搜索节目列表接口(self, url='http://{{idpURL}}/idpvoice/searchchannel?name={{name}}&start={{start}}&count={{count}}'):
"""6.1 直播搜索节目列表接口"""
<|body_0|>
def test_2回看搜索节目列表接口(self, url='http://{{snm_idpVoice}}/idpvoice/searchschedule?name={{name}}&channelname=... | stack_v2_sparse_classes_10k_train_002119 | 1,871 | no_license | [
{
"docstring": "6.1 直播搜索节目列表接口",
"name": "test_1直播搜索节目列表接口",
"signature": "def test_1直播搜索节目列表接口(self, url='http://{{idpURL}}/idpvoice/searchchannel?name={{name}}&start={{start}}&count={{count}}')"
},
{
"docstring": "6.2回看搜索节目列表接口",
"name": "test_2回看搜索节目列表接口",
"signature": "def test_2回看搜索... | 3 | stack_v2_sparse_classes_30k_train_005144 | Implement the Python class `Test_语音搜索服务接口` described below.
Class description:
Implement the Test_语音搜索服务接口 class.
Method signatures and docstrings:
- def test_1直播搜索节目列表接口(self, url='http://{{idpURL}}/idpvoice/searchchannel?name={{name}}&start={{start}}&count={{count}}'): 6.1 直播搜索节目列表接口
- def test_2回看搜索节目列表接口(self, ur... | Implement the Python class `Test_语音搜索服务接口` described below.
Class description:
Implement the Test_语音搜索服务接口 class.
Method signatures and docstrings:
- def test_1直播搜索节目列表接口(self, url='http://{{idpURL}}/idpvoice/searchchannel?name={{name}}&start={{start}}&count={{count}}'): 6.1 直播搜索节目列表接口
- def test_2回看搜索节目列表接口(self, ur... | 8c3a2447e53f1fcf7d418e171a01c8e94fc4c8ae | <|skeleton|>
class Test_语音搜索服务接口:
def test_1直播搜索节目列表接口(self, url='http://{{idpURL}}/idpvoice/searchchannel?name={{name}}&start={{start}}&count={{count}}'):
"""6.1 直播搜索节目列表接口"""
<|body_0|>
def test_2回看搜索节目列表接口(self, url='http://{{snm_idpVoice}}/idpvoice/searchschedule?name={{name}}&channelname=... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test_语音搜索服务接口:
def test_1直播搜索节目列表接口(self, url='http://{{idpURL}}/idpvoice/searchchannel?name={{name}}&start={{start}}&count={{count}}'):
"""6.1 直播搜索节目列表接口"""
Ioput.function_name(self.__class__.__name__)
try:
self.execute_test(url=url)
self.get_text_value(kone='s... | the_stack_v2_python_sparse | BI_6.0.7_WebUI_AUTOTOOLS_003/BI_6.0.7_WebUI_AUTOTOOLS_03/BI_6.0.7_WebUI_AUTOTOOLS_03/test_case/idmp/搜索推荐/语音搜索服务接口_6/case.py | demi52/mandy | train | 0 | |
a9648759bc8fc2afc4617ed609c16c285ee417f2 | [
"self.__stks = []\nself.__c = capacity\nself.__min_heap = []",
"if self.__min_heap:\n l = heapq.heappop(self.__min_heap)\n if l < len(self.__stks):\n self.__stks[l].append(val)\n return\n self.__min_heap = []\nif not self.__stks or len(self.__stks[-1]) == self.__c:\n self.__stks.append([... | <|body_start_0|>
self.__stks = []
self.__c = capacity
self.__min_heap = []
<|end_body_0|>
<|body_start_1|>
if self.__min_heap:
l = heapq.heappop(self.__min_heap)
if l < len(self.__stks):
self.__stks[l].append(val)
return
... | DinnerPlates | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DinnerPlates:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def push(self, val):
""":type val: int :rtype: None"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def popAtStack(self, index):
""":t... | stack_v2_sparse_classes_10k_train_002120 | 1,294 | permissive | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type val: int :rtype: None",
"name": "push",
"signature": "def push(self, val)"
},
{
"docstring": ":rtype: int",
"name": "pop",
"signature": "def pop(... | 4 | null | Implement the Python class `DinnerPlates` described below.
Class description:
Implement the DinnerPlates class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def push(self, val): :type val: int :rtype: None
- def pop(self): :rtype: int
- def popAtStack(self, index): :type ind... | Implement the Python class `DinnerPlates` described below.
Class description:
Implement the DinnerPlates class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def push(self, val): :type val: int :rtype: None
- def pop(self): :rtype: int
- def popAtStack(self, index): :type ind... | 4dc4e6642dc92f1983c13564cc0fd99917cab358 | <|skeleton|>
class DinnerPlates:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def push(self, val):
""":type val: int :rtype: None"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def popAtStack(self, index):
""":t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DinnerPlates:
def __init__(self, capacity):
""":type capacity: int"""
self.__stks = []
self.__c = capacity
self.__min_heap = []
def push(self, val):
""":type val: int :rtype: None"""
if self.__min_heap:
l = heapq.heappop(self.__min_heap)
... | the_stack_v2_python_sparse | Python/dinner-plate-stacks.py | kamyu104/LeetCode-Solutions | train | 4,549 | |
5ca359631eab5a5205457dba67ca43f49785e9c1 | [
"if not string:\n return ''\nm, M = (min(string), max(string))\nfor i, letter in enumerate(m):\n if letter != M[i]:\n return m[:i]\nreturn m",
"if not string:\n return ''\nm = min(string, key=len)\nleft, right = (0, len(m))\nwhile left <= right:\n pivot = (left + right) // 2\n prefix = strin... | <|body_start_0|>
if not string:
return ''
m, M = (min(string), max(string))
for i, letter in enumerate(m):
if letter != M[i]:
return m[:i]
return m
<|end_body_0|>
<|body_start_1|>
if not string:
return ''
m = min(string... | LongestCommonPrefix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LongestCommonPrefix:
def longest_common_prefix_1(self, string: str) -> str:
"""Approach: Using min and max function. :param string: :return:"""
<|body_0|>
def longest_common_prefix_2(self, string: str) -> str:
"""Approach: Binary Search :param string: :return:"""
... | stack_v2_sparse_classes_10k_train_002121 | 1,164 | no_license | [
{
"docstring": "Approach: Using min and max function. :param string: :return:",
"name": "longest_common_prefix_1",
"signature": "def longest_common_prefix_1(self, string: str) -> str"
},
{
"docstring": "Approach: Binary Search :param string: :return:",
"name": "longest_common_prefix_2",
... | 2 | null | Implement the Python class `LongestCommonPrefix` described below.
Class description:
Implement the LongestCommonPrefix class.
Method signatures and docstrings:
- def longest_common_prefix_1(self, string: str) -> str: Approach: Using min and max function. :param string: :return:
- def longest_common_prefix_2(self, str... | Implement the Python class `LongestCommonPrefix` described below.
Class description:
Implement the LongestCommonPrefix class.
Method signatures and docstrings:
- def longest_common_prefix_1(self, string: str) -> str: Approach: Using min and max function. :param string: :return:
- def longest_common_prefix_2(self, str... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class LongestCommonPrefix:
def longest_common_prefix_1(self, string: str) -> str:
"""Approach: Using min and max function. :param string: :return:"""
<|body_0|>
def longest_common_prefix_2(self, string: str) -> str:
"""Approach: Binary Search :param string: :return:"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LongestCommonPrefix:
def longest_common_prefix_1(self, string: str) -> str:
"""Approach: Using min and max function. :param string: :return:"""
if not string:
return ''
m, M = (min(string), max(string))
for i, letter in enumerate(m):
if letter != M[i]:
... | the_stack_v2_python_sparse | math_and_srings/longestcommonprefix.py | Shiv2157k/leet_code | train | 1 | |
f8991605b63979febe95371fada99ea635315fd0 | [
"super().__init__(mass_profile=None, grid=grid, mat_plot_1d=mat_plot_1d, visuals_1d=visuals_1d, include_1d=include_1d, mat_plot_2d=mat_plot_2d, visuals_2d=visuals_2d, include_2d=include_2d)\nself.mass_profile_pdf_list = mass_profile_pdf_list\nself.sigma = sigma\nself.low_limit = (1 - math.erf(sigma / math.sqrt(2)))... | <|body_start_0|>
super().__init__(mass_profile=None, grid=grid, mat_plot_1d=mat_plot_1d, visuals_1d=visuals_1d, include_1d=include_1d, mat_plot_2d=mat_plot_2d, visuals_2d=visuals_2d, include_2d=include_2d)
self.mass_profile_pdf_list = mass_profile_pdf_list
self.sigma = sigma
self.low_lim... | MassProfilePDFPlotter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MassProfilePDFPlotter:
def __init__(self, mass_profile_pdf_list: List[MassProfile], grid: aa.Grid2D, mat_plot_1d: MatPlot1D=MatPlot1D(), visuals_1d: Visuals1D=Visuals1D(), include_1d: Include1D=Include1D(), mat_plot_2d: MatPlot2D=MatPlot2D(), visuals_2d: Visuals2D=Visuals2D(), include_2d: Includ... | stack_v2_sparse_classes_10k_train_002122 | 14,759 | permissive | [
{
"docstring": "Plots the attributes of a list of `MassProfile` objects using the matplotlib methods `plot()` and `imshow()` and many other matplotlib functions which customize the plot's appearance. Figures plotted by this object average over a list mass profiles to computed the average value of each attribute... | 2 | stack_v2_sparse_classes_30k_val_000168 | Implement the Python class `MassProfilePDFPlotter` described below.
Class description:
Implement the MassProfilePDFPlotter class.
Method signatures and docstrings:
- def __init__(self, mass_profile_pdf_list: List[MassProfile], grid: aa.Grid2D, mat_plot_1d: MatPlot1D=MatPlot1D(), visuals_1d: Visuals1D=Visuals1D(), inc... | Implement the Python class `MassProfilePDFPlotter` described below.
Class description:
Implement the MassProfilePDFPlotter class.
Method signatures and docstrings:
- def __init__(self, mass_profile_pdf_list: List[MassProfile], grid: aa.Grid2D, mat_plot_1d: MatPlot1D=MatPlot1D(), visuals_1d: Visuals1D=Visuals1D(), inc... | d1a2e400b7ac984a21d972f54e419d8783342454 | <|skeleton|>
class MassProfilePDFPlotter:
def __init__(self, mass_profile_pdf_list: List[MassProfile], grid: aa.Grid2D, mat_plot_1d: MatPlot1D=MatPlot1D(), visuals_1d: Visuals1D=Visuals1D(), include_1d: Include1D=Include1D(), mat_plot_2d: MatPlot2D=MatPlot2D(), visuals_2d: Visuals2D=Visuals2D(), include_2d: Includ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MassProfilePDFPlotter:
def __init__(self, mass_profile_pdf_list: List[MassProfile], grid: aa.Grid2D, mat_plot_1d: MatPlot1D=MatPlot1D(), visuals_1d: Visuals1D=Visuals1D(), include_1d: Include1D=Include1D(), mat_plot_2d: MatPlot2D=MatPlot2D(), visuals_2d: Visuals2D=Visuals2D(), include_2d: Include2D=Include2D(... | the_stack_v2_python_sparse | autogalaxy/profiles/plot/mass_profile_plotters.py | Jammy2211/PyAutoGalaxy | train | 27 | |
f6e0b997e0ab73243c7e9380538a593e2e0e5dbc | [
"if self._disable:\n return False\nif self.spectrograph is None or self.telescope is None:\n return False\nif self.unknown != 'snr':\n raise NotImplementedError('Only SNR calculations currently supported')\nself._update_snr()",
"if self.verbose:\n msg1 = 'Creating exposure for {} ({})'.format(self.tel... | <|body_start_0|>
if self._disable:
return False
if self.spectrograph is None or self.telescope is None:
return False
if self.unknown != 'snr':
raise NotImplementedError('Only SNR calculations currently supported')
self._update_snr()
<|end_body_0|>
<|b... | A subclass of the base Exposure model, for spectroscopic ETC calculations. | SpectrographicExposure | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectrographicExposure:
"""A subclass of the base Exposure model, for spectroscopic ETC calculations."""
def calculate(self):
"""Wrapper to calculate the exposure time, SNR, or limiting magnitude, based on the other two. The "unknown" attribute controls which of these parameters is c... | stack_v2_sparse_classes_10k_train_002123 | 18,852 | no_license | [
{
"docstring": "Wrapper to calculate the exposure time, SNR, or limiting magnitude, based on the other two. The \"unknown\" attribute controls which of these parameters is calculated.",
"name": "calculate",
"signature": "def calculate(self)"
},
{
"docstring": "Calculate the SNR based on the curr... | 2 | stack_v2_sparse_classes_30k_train_004008 | Implement the Python class `SpectrographicExposure` described below.
Class description:
A subclass of the base Exposure model, for spectroscopic ETC calculations.
Method signatures and docstrings:
- def calculate(self): Wrapper to calculate the exposure time, SNR, or limiting magnitude, based on the other two. The "u... | Implement the Python class `SpectrographicExposure` described below.
Class description:
A subclass of the base Exposure model, for spectroscopic ETC calculations.
Method signatures and docstrings:
- def calculate(self): Wrapper to calculate the exposure time, SNR, or limiting magnitude, based on the other two. The "u... | ccd63cc79671fb333b892c3125861be2128e5ee8 | <|skeleton|>
class SpectrographicExposure:
"""A subclass of the base Exposure model, for spectroscopic ETC calculations."""
def calculate(self):
"""Wrapper to calculate the exposure time, SNR, or limiting magnitude, based on the other two. The "unknown" attribute controls which of these parameters is c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SpectrographicExposure:
"""A subclass of the base Exposure model, for spectroscopic ETC calculations."""
def calculate(self):
"""Wrapper to calculate the exposure time, SNR, or limiting magnitude, based on the other two. The "unknown" attribute controls which of these parameters is calculated."""... | the_stack_v2_python_sparse | syotools/models/exposure.py | tumlinson/luvoir_simtools | train | 1 |
a63e105ca0c8f7079019ce3abf22cadb6b2fa4cc | [
"target = '%s://%s' % (self.proto or 'http', self.host or self.ip)\nok, cms = cms_explorer.get_cms_type(target)\nif not ok:\n self._write_result('CMS-Explorer call error!')\nself._write_result(cms)",
"self.proto = 'http'\nself.host = 'gtta.demo.stellarbit.com'\nself.main()"
] | <|body_start_0|>
target = '%s://%s' % (self.proto or 'http', self.host or self.ip)
ok, cms = cms_explorer.get_cms_type(target)
if not ok:
self._write_result('CMS-Explorer call error!')
self._write_result(cms)
<|end_body_0|>
<|body_start_1|>
self.proto = 'http'
... | CMS Detection checker | CMSDetectionTask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CMSDetectionTask:
"""CMS Detection checker"""
def main(self, *args):
"""Main function"""
<|body_0|>
def test(self):
"""Test function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
target = '%s://%s' % (self.proto or 'http', self.host or self.ip... | stack_v2_sparse_classes_10k_train_002124 | 680 | no_license | [
{
"docstring": "Main function",
"name": "main",
"signature": "def main(self, *args)"
},
{
"docstring": "Test function",
"name": "test",
"signature": "def test(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006477 | Implement the Python class `CMSDetectionTask` described below.
Class description:
CMS Detection checker
Method signatures and docstrings:
- def main(self, *args): Main function
- def test(self): Test function | Implement the Python class `CMSDetectionTask` described below.
Class description:
CMS Detection checker
Method signatures and docstrings:
- def main(self, *args): Main function
- def test(self): Test function
<|skeleton|>
class CMSDetectionTask:
"""CMS Detection checker"""
def main(self, *args):
"""... | aab6927de8424f0a8e9eb9b9a462a775555a80d5 | <|skeleton|>
class CMSDetectionTask:
"""CMS Detection checker"""
def main(self, *args):
"""Main function"""
<|body_0|>
def test(self):
"""Test function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CMSDetectionTask:
"""CMS Detection checker"""
def main(self, *args):
"""Main function"""
target = '%s://%s' % (self.proto or 'http', self.host or self.ip)
ok, cms = cms_explorer.get_cms_type(target)
if not ok:
self._write_result('CMS-Explorer call error!')
... | the_stack_v2_python_sparse | cms_detection/run.py | Silentsoul04/gtta-scripts | train | 0 |
e4cd54d4f19977fef53f7424053a3a8f9a862a5a | [
"if not isinstance(query, FetchQueryBuilder):\n raise ImapInvalidArgument('query', query)\nself.__fetch_query = query",
"func = 'fetch'\nargs = self.__fetch_query.build()\nif self.__fetch_query.uids:\n func = 'uid'\n args = ('fetch',) + args\ntyp, data = getattr(imap_obj, func)(*args)\nself.check_respons... | <|body_start_0|>
if not isinstance(query, FetchQueryBuilder):
raise ImapInvalidArgument('query', query)
self.__fetch_query = query
<|end_body_0|>
<|body_start_1|>
func = 'fetch'
args = self.__fetch_query.build()
if self.__fetch_query.uids:
func = 'uid'
... | Executes IMAP Fetch cammand | ImapFetchCommand | [
"WTFPL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImapFetchCommand:
"""Executes IMAP Fetch cammand"""
def __init__(self, query: FetchQueryBuilder):
"""Creates instance of Fetch IMAP command Raises: ImapRuntimeError - if :param query is not instance of FetchQueryBuilder :param query: FetchQueryBuilder :return:"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_002125 | 1,604 | permissive | [
{
"docstring": "Creates instance of Fetch IMAP command Raises: ImapRuntimeError - if :param query is not instance of FetchQueryBuilder :param query: FetchQueryBuilder :return:",
"name": "__init__",
"signature": "def __init__(self, query: FetchQueryBuilder)"
},
{
"docstring": "Executes IMAP fetch... | 2 | stack_v2_sparse_classes_30k_train_001649 | Implement the Python class `ImapFetchCommand` described below.
Class description:
Executes IMAP Fetch cammand
Method signatures and docstrings:
- def __init__(self, query: FetchQueryBuilder): Creates instance of Fetch IMAP command Raises: ImapRuntimeError - if :param query is not instance of FetchQueryBuilder :param ... | Implement the Python class `ImapFetchCommand` described below.
Class description:
Executes IMAP Fetch cammand
Method signatures and docstrings:
- def __init__(self, query: FetchQueryBuilder): Creates instance of Fetch IMAP command Raises: ImapRuntimeError - if :param query is not instance of FetchQueryBuilder :param ... | 002a916494591e31ec9a0c2dbef66427a72bc036 | <|skeleton|>
class ImapFetchCommand:
"""Executes IMAP Fetch cammand"""
def __init__(self, query: FetchQueryBuilder):
"""Creates instance of Fetch IMAP command Raises: ImapRuntimeError - if :param query is not instance of FetchQueryBuilder :param query: FetchQueryBuilder :return:"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImapFetchCommand:
"""Executes IMAP Fetch cammand"""
def __init__(self, query: FetchQueryBuilder):
"""Creates instance of Fetch IMAP command Raises: ImapRuntimeError - if :param query is not instance of FetchQueryBuilder :param query: FetchQueryBuilder :return:"""
if not isinstance(query, ... | the_stack_v2_python_sparse | pymaillib/imap/commands/fetch.py | pussbb/pymaillib | train | 0 |
5ba168808aada276dad4aad1a07b340dfb890745 | [
"self.deque = collections.deque([])\nself.dic = {}\nself.capacity = capacity",
"if key not in self.dic:\n return -1\nself.deque.remove(key)\nself.deque.append(key)\nreturn self.dic[key]",
"if key in self.dic:\n self.deque.remove(key)\nelif len(self.dic) == self.capacity:\n v = self.deque.popleft()\n ... | <|body_start_0|>
self.deque = collections.deque([])
self.dic = {}
self.capacity = capacity
<|end_body_0|>
<|body_start_1|>
if key not in self.dic:
return -1
self.deque.remove(key)
self.deque.append(key)
return self.dic[key]
<|end_body_1|>
<|body_star... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_002126 | 2,684 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | 9b82e3bd1b404e3cff31469986577ceec3924f73 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.deque = collections.deque([])
self.dic = {}
self.capacity = capacity
def get(self, key):
""":rtype: int"""
if key not in self.dic:
return -1
self.deque.remove(key)
... | the_stack_v2_python_sparse | Python/146. LRU Cache.py | Qiumy/leetcode | train | 0 | |
96724c43d250e93473a694c17134e1c7a1248d04 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MicrosoftAuthenticatorAuthenticationMethodConfiguration()",
"from .authentication_method_configuration import AuthenticationMethodConfiguration\nfrom .microsoft_authenticator_authentication_method_target import MicrosoftAuthenticatorAu... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return MicrosoftAuthenticatorAuthenticationMethodConfiguration()
<|end_body_0|>
<|body_start_1|>
from .authentication_method_configuration import AuthenticationMethodConfiguration
from .microso... | MicrosoftAuthenticatorAuthenticationMethodConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MicrosoftAuthenticatorAuthenticationMethodConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MicrosoftAuthenticatorAuthenticationMethodConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node:... | stack_v2_sparse_classes_10k_train_002127 | 4,083 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: MicrosoftAuthenticatorAuthenticationMethodConfiguration",
"name": "create_from_discriminator_value",
"signat... | 3 | null | Implement the Python class `MicrosoftAuthenticatorAuthenticationMethodConfiguration` described below.
Class description:
Implement the MicrosoftAuthenticatorAuthenticationMethodConfiguration class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Microso... | Implement the Python class `MicrosoftAuthenticatorAuthenticationMethodConfiguration` described below.
Class description:
Implement the MicrosoftAuthenticatorAuthenticationMethodConfiguration class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Microso... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class MicrosoftAuthenticatorAuthenticationMethodConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MicrosoftAuthenticatorAuthenticationMethodConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MicrosoftAuthenticatorAuthenticationMethodConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MicrosoftAuthenticatorAuthenticationMethodConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse nod... | the_stack_v2_python_sparse | msgraph/generated/models/microsoft_authenticator_authentication_method_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
49b30b7fe93956329bc1fc8ffe663f976f1ba00b | [
"ans = 0\nfor item in S:\n if item in J:\n ans += 1\nreturn ans",
"mydict = {}\nfor item in J:\n if item in mydict.keys():\n mydict[item] += 1\n else:\n mydict[item] = 1\nans = 0\nfor item in S:\n if item in mydict.keys():\n ans += 1\nreturn ans"
] | <|body_start_0|>
ans = 0
for item in S:
if item in J:
ans += 1
return ans
<|end_body_0|>
<|body_start_1|>
mydict = {}
for item in J:
if item in mydict.keys():
mydict[item] += 1
else:
mydict[item]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numJewelsInStones(self, J, S):
""":type J: str :type S: str :rtype: int"""
<|body_0|>
def numJewelsInStones2(self, J, S):
""":type J: str :type S: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = 0
for item... | stack_v2_sparse_classes_10k_train_002128 | 1,186 | no_license | [
{
"docstring": ":type J: str :type S: str :rtype: int",
"name": "numJewelsInStones",
"signature": "def numJewelsInStones(self, J, S)"
},
{
"docstring": ":type J: str :type S: str :rtype: int",
"name": "numJewelsInStones2",
"signature": "def numJewelsInStones2(self, J, S)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numJewelsInStones(self, J, S): :type J: str :type S: str :rtype: int
- def numJewelsInStones2(self, J, S): :type J: str :type S: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numJewelsInStones(self, J, S): :type J: str :type S: str :rtype: int
- def numJewelsInStones2(self, J, S): :type J: str :type S: str :rtype: int
<|skeleton|>
class Solution:... | 690b685048c8e89d26047b6bc48b5f9af7d59cbb | <|skeleton|>
class Solution:
def numJewelsInStones(self, J, S):
""":type J: str :type S: str :rtype: int"""
<|body_0|>
def numJewelsInStones2(self, J, S):
""":type J: str :type S: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def numJewelsInStones(self, J, S):
""":type J: str :type S: str :rtype: int"""
ans = 0
for item in S:
if item in J:
ans += 1
return ans
def numJewelsInStones2(self, J, S):
""":type J: str :type S: str :rtype: int"""
myd... | the_stack_v2_python_sparse | 哈希表/771. 宝石与石头.py | SimmonsChen/LeetCode | train | 0 | |
22c21443c1937c665d36225b929d2e63180b370a | [
"if not os.path.exists('/home/mziaeefard/nas/human-ai-dialog/vilbert/data2/conceptnet/processed/numberbatch_en.gensim'):\n print(colored('Processing the `Numberbatch` dataset for the first time...', 'yellow'))\n if not os.path.exists('/home/mziaeefard/nas/human-ai-dialog/vilbert/data2/conceptnet/raw/numberbat... | <|body_start_0|>
if not os.path.exists('/home/mziaeefard/nas/human-ai-dialog/vilbert/data2/conceptnet/processed/numberbatch_en.gensim'):
print(colored('Processing the `Numberbatch` dataset for the first time...', 'yellow'))
if not os.path.exists('/home/mziaeefard/nas/human-ai-dialog/vilb... | Class to get the Numberbatch embeddings of words | NumberbatchConverter | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumberbatchConverter:
"""Class to get the Numberbatch embeddings of words"""
def __init__(self):
"""Loads the Numberbatch model"""
<|body_0|>
def convert_word_to_embedding(self, word):
"""Given a word, returns its Numberbatch embedding"""
<|body_1|>
<|en... | stack_v2_sparse_classes_10k_train_002129 | 4,555 | permissive | [
{
"docstring": "Loads the Numberbatch model",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Given a word, returns its Numberbatch embedding",
"name": "convert_word_to_embedding",
"signature": "def convert_word_to_embedding(self, word)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005468 | Implement the Python class `NumberbatchConverter` described below.
Class description:
Class to get the Numberbatch embeddings of words
Method signatures and docstrings:
- def __init__(self): Loads the Numberbatch model
- def convert_word_to_embedding(self, word): Given a word, returns its Numberbatch embedding | Implement the Python class `NumberbatchConverter` described below.
Class description:
Class to get the Numberbatch embeddings of words
Method signatures and docstrings:
- def __init__(self): Loads the Numberbatch model
- def convert_word_to_embedding(self, word): Given a word, returns its Numberbatch embedding
<|ske... | 0fb558af7df8c61be47bcf278e30cdf10315b572 | <|skeleton|>
class NumberbatchConverter:
"""Class to get the Numberbatch embeddings of words"""
def __init__(self):
"""Loads the Numberbatch model"""
<|body_0|>
def convert_word_to_embedding(self, word):
"""Given a word, returns its Numberbatch embedding"""
<|body_1|>
<|en... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumberbatchConverter:
"""Class to get the Numberbatch embeddings of words"""
def __init__(self):
"""Loads the Numberbatch model"""
if not os.path.exists('/home/mziaeefard/nas/human-ai-dialog/vilbert/data2/conceptnet/processed/numberbatch_en.gensim'):
print(colored('Processing ... | the_stack_v2_python_sparse | conceptBert/vilbert/knowledge_graph/create_embedding_files.py | liubo12/ConceptBERT | train | 0 |
8d2d7c499358b08cea4fd4c350bead222a568644 | [
"if type(data) is not np.ndarray:\n raise TypeError('data must be a 2D numpy.ndarray')\nif len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nd, n = data.shape\nself.mean = np.mean(data, axis=1).res... | <|body_start_0|>
if type(data) is not np.ndarray:
raise TypeError('data must be a 2D numpy.ndarray')
if len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data points')
... | Multinormal class that represents a Multivariate Normal distribution | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""Multinormal class that represents a Multivariate Normal distribution"""
def __init__(self, data):
"""Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is... | stack_v2_sparse_classes_10k_train_002130 | 2,602 | no_license | [
{
"docstring": "Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is not a 2D numpy.ndarray, raise a TypeError with the message data must be a 2D numpy.ndarray If n is less than 2, raise a ValueErr... | 2 | stack_v2_sparse_classes_30k_train_001950 | Implement the Python class `MultiNormal` described below.
Class description:
Multinormal class that represents a Multivariate Normal distribution
Method signatures and docstrings:
- def __init__(self, data): Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d ... | Implement the Python class `MultiNormal` described below.
Class description:
Multinormal class that represents a Multivariate Normal distribution
Method signatures and docstrings:
- def __init__(self, data): Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d ... | e8a98d85b3bfd5665cb04bec9ee8c3eb23d6bd58 | <|skeleton|>
class MultiNormal:
"""Multinormal class that represents a Multivariate Normal distribution"""
def __init__(self, data):
"""Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiNormal:
"""Multinormal class that represents a Multivariate Normal distribution"""
def __init__(self, data):
"""Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is not a 2D num... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | AndrewMiranda/holbertonschool-machine_learning-1 | train | 0 |
58de4c2654c6ab3c86707f74eb019eed82c0dfae | [
"g = [[] for _ in range(n)]\nfor a, b in edges:\n g[a].append(b)\n g[b].append(a)\nret = [0] * n\n\ndef dfs(a, p):\n counter = defaultdict(int)\n counter[labels[a]] += 1\n for b in g[a]:\n if b == p:\n continue\n for l, c in dfs(b, a).items():\n counter[l] += c\n ... | <|body_start_0|>
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
ret = [0] * n
def dfs(a, p):
counter = defaultdict(int)
counter[labels[a]] += 1
for b in g[a]:
if b == p:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
"""Mar 05, 2023 14:37"""
<|body_0|>
def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
"""Mar 05, 2023 14:39 Use one counter"""
<|body... | stack_v2_sparse_classes_10k_train_002131 | 3,712 | no_license | [
{
"docstring": "Mar 05, 2023 14:37",
"name": "countSubTrees",
"signature": "def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]"
},
{
"docstring": "Mar 05, 2023 14:39 Use one counter",
"name": "countSubTrees",
"signature": "def countSubTrees(self, n: int, ed... | 2 | stack_v2_sparse_classes_30k_train_006040 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]: Mar 05, 2023 14:37
- def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]: Mar 05, 2023 14:37
- def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> Li... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
"""Mar 05, 2023 14:37"""
<|body_0|>
def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
"""Mar 05, 2023 14:39 Use one counter"""
<|body... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
"""Mar 05, 2023 14:37"""
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
ret = [0] * n
def dfs(a, p):
counter = ... | the_stack_v2_python_sparse | leetcode/solved/1643_Number_of_Nodes_in_the_Sub-Tree_With_the_Same_Label/solution.py | sungminoh/algorithms | train | 0 | |
17ee0daaafa97c0964a24881ac8b96baf8a1f688 | [
"n = len(nums)\nM = [0] * n\nj = n - 1\nfor i in range(n - 2, -1, -1):\n if nums[i] != 0:\n M[i] = 1 + min(M[j:j + nums[i]])\n else:\n M[i] = 1 + M[j]\n j = i\nreturn M[0]",
"length = len(nums)\njumps, curEnd, curFarthest = (0, 0, 0)\nfor i in range(length - 1):\n curFarthest = max(curFa... | <|body_start_0|>
n = len(nums)
M = [0] * n
j = n - 1
for i in range(n - 2, -1, -1):
if nums[i] != 0:
M[i] = 1 + min(M[j:j + nums[i]])
else:
M[i] = 1 + M[j]
j = i
return M[0]
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_2|>
<|end_sk... | stack_v2_sparse_classes_10k_train_002132 | 1,304 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "jump",
"signature": "def jump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "jump",
"signature": "def jump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "j... | 3 | stack_v2_sparse_classes_30k_train_003494 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): :type nums: List[int] :rtype: int
- def jump(self, nums): :type nums: List[int] :rtype: int
- def jump(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 jump(self, nums): :type nums: List[int] :rtype: int
- def jump(self, nums): :type nums: List[int] :rtype: int
- def jump(self, nums): :type nums: List[int] :rtype: int
<|ske... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_2|>
<|end_sk... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
n = len(nums)
M = [0] * n
j = n - 1
for i in range(n - 2, -1, -1):
if nums[i] != 0:
M[i] = 1 + min(M[j:j + nums[i]])
else:
M[i] = 1 + M[j]
... | the_stack_v2_python_sparse | 0045_Jump_Game_II.py | bingli8802/leetcode | train | 0 | |
2615f7084d90dc4b463a651644c519be9b214dd8 | [
"if p.val < root.val and q.val < root.val:\n return self.lowestCommonAncestor(root.left, p, q)\nelif p.val > root.val and q.val > root.val:\n return self.lowestCommonAncestor(root.right, p, q)\nelse:\n return root",
"node = root\nwhile True:\n if p.val < node.val and q.val < node.val:\n node = ... | <|body_start_0|>
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
else:
return root
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""... | stack_v2_sparse_classes_10k_train_002133 | 1,256 | no_license | [
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root, p, q)"
},
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode",
"name": "lowest... | 2 | stack_v2_sparse_classes_30k_train_000254 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
- def lowestCommonAncestor(self, root, p, q): :type root: Tr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
- def lowestCommonAncestor(self, root, p, q): :type root: Tr... | 6582b0f138a19f9d4a005eda298ecb1488eb0d2e | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
... | the_stack_v2_python_sparse | Tree/235.py | ShangruZhong/leetcode | train | 0 | |
0f29dfbeb8b6a0df5cb497b266db133252027762 | [
"def backtrack(nums, size, start, path):\n res.append(path[:])\n for i in range(start, size):\n path.append(nums[i])\n backtrack(nums, size, i + 1, path)\n path.pop()\nres = []\nsize = len(nums)\nbacktrack(nums, size, 0, [])\nreturn res",
"if len(nums) == 0:\n return [[]]\nlast = num... | <|body_start_0|>
def backtrack(nums, size, start, path):
res.append(path[:])
for i in range(start, size):
path.append(nums[i])
backtrack(nums, size, i + 1, path)
path.pop()
res = []
size = len(nums)
backtrack(nums, s... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
"""题解:https://leetcode-cn.com/problems/subsets/solution/c-zong-jie-liao-hui-su-wen-ti-lei-xing-dai-ni-gao-/"""
<|body_0|>
def subsets1(self, nums: List[int]) -> List[List[int]]:
"""数学归纳递归:subset([1,2,3]... | stack_v2_sparse_classes_10k_train_002134 | 3,816 | permissive | [
{
"docstring": "题解:https://leetcode-cn.com/problems/subsets/solution/c-zong-jie-liao-hui-su-wen-ti-lei-xing-dai-ni-gao-/",
"name": "subsets",
"signature": "def subsets(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "数学归纳递归:subset([1,2,3]) = A + [A[i].add(3) for i = 1..len(A)] https... | 5 | stack_v2_sparse_classes_30k_train_005263 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets(self, nums: List[int]) -> List[List[int]]: 题解:https://leetcode-cn.com/problems/subsets/solution/c-zong-jie-liao-hui-su-wen-ti-lei-xing-dai-ni-gao-/
- def subsets1(sel... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets(self, nums: List[int]) -> List[List[int]]: 题解:https://leetcode-cn.com/problems/subsets/solution/c-zong-jie-liao-hui-su-wen-ti-lei-xing-dai-ni-gao-/
- def subsets1(sel... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
"""题解:https://leetcode-cn.com/problems/subsets/solution/c-zong-jie-liao-hui-su-wen-ti-lei-xing-dai-ni-gao-/"""
<|body_0|>
def subsets1(self, nums: List[int]) -> List[List[int]]:
"""数学归纳递归:subset([1,2,3]... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
"""题解:https://leetcode-cn.com/problems/subsets/solution/c-zong-jie-liao-hui-su-wen-ti-lei-xing-dai-ni-gao-/"""
def backtrack(nums, size, start, path):
res.append(path[:])
for i in range(start, size):
... | the_stack_v2_python_sparse | 78-subsets.py | yuenliou/leetcode | train | 0 | |
4bf8a3ca5213dc8e7bf9ec6fde34577bd28bfb41 | [
"super().__init__()\nself.args = args\nself.get_controller(args)",
"image = data['image']\nimage = cv2.imdecode(np.asarray(bytearray(image), dtype=np.uint8), 1)\nglobal global_steer\nglobal_steer = self.controller.get_steering_angle(image, args.horizon)"
] | <|body_start_0|>
super().__init__()
self.args = args
self.get_controller(args)
<|end_body_0|>
<|body_start_1|>
image = data['image']
image = cv2.imdecode(np.asarray(bytearray(image), dtype=np.uint8), 1)
global global_steer
global_steer = self.controller.get_steer... | Class that extends the client socket and BaseEnvironment Attributes: args (Object): command line arguments | WheelchairClientProtocol | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WheelchairClientProtocol:
"""Class that extends the client socket and BaseEnvironment Attributes: args (Object): command line arguments"""
def __init__(self, args):
"""Instantiate an instance of the WheelchairClientProtocol Calls the __init__ of the extended classes Get the controlle... | stack_v2_sparse_classes_10k_train_002135 | 4,116 | no_license | [
{
"docstring": "Instantiate an instance of the WheelchairClientProtocol Calls the __init__ of the extended classes Get the controller based on the command line arguments",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Function that receives the centre image from ... | 2 | stack_v2_sparse_classes_30k_train_000335 | Implement the Python class `WheelchairClientProtocol` described below.
Class description:
Class that extends the client socket and BaseEnvironment Attributes: args (Object): command line arguments
Method signatures and docstrings:
- def __init__(self, args): Instantiate an instance of the WheelchairClientProtocol Cal... | Implement the Python class `WheelchairClientProtocol` described below.
Class description:
Class that extends the client socket and BaseEnvironment Attributes: args (Object): command line arguments
Method signatures and docstrings:
- def __init__(self, args): Instantiate an instance of the WheelchairClientProtocol Cal... | b5c67e0e7737e524d7780286552face882b63531 | <|skeleton|>
class WheelchairClientProtocol:
"""Class that extends the client socket and BaseEnvironment Attributes: args (Object): command line arguments"""
def __init__(self, args):
"""Instantiate an instance of the WheelchairClientProtocol Calls the __init__ of the extended classes Get the controlle... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WheelchairClientProtocol:
"""Class that extends the client socket and BaseEnvironment Attributes: args (Object): command line arguments"""
def __init__(self, args):
"""Instantiate an instance of the WheelchairClientProtocol Calls the __init__ of the extended classes Get the controller based on th... | the_stack_v2_python_sparse | src/environment/wheelchair.py | DomhnallBoyle/Research-Project | train | 0 |
0cb010fec95294db88560c917b9bb2ec7568225b | [
"form.instance.review = Review.objects.get(pk=self.kwargs['id'])\nform.instance.type = 'RV'\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['name'] = Review.objects.get(pk=self.kwargs['id']).title\nreturn context"
] | <|body_start_0|>
form.instance.review = Review.objects.get(pk=self.kwargs['id'])
form.instance.type = 'RV'
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context['name'] = Review.objects.get(pk=self.kwargs['id']).titl... | Class based view for reporting reviews | ReviewReportForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewReportForm:
"""Class based view for reporting reviews"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Passes item name to template"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_10k_train_002136 | 10,733 | permissive | [
{
"docstring": "Ensures hidden form values are filled",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Passes item name to template",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006558 | Implement the Python class `ReviewReportForm` described below.
Class description:
Class based view for reporting reviews
Method signatures and docstrings:
- def form_valid(self, form): Ensures hidden form values are filled
- def get_context_data(self, **kwargs): Passes item name to template | Implement the Python class `ReviewReportForm` described below.
Class description:
Class based view for reporting reviews
Method signatures and docstrings:
- def form_valid(self, form): Ensures hidden form values are filled
- def get_context_data(self, **kwargs): Passes item name to template
<|skeleton|>
class Review... | 6bf8e75a1f279ac584daa4ee19927ffccaa67551 | <|skeleton|>
class ReviewReportForm:
"""Class based view for reporting reviews"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Passes item name to template"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReviewReportForm:
"""Class based view for reporting reviews"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
form.instance.review = Review.objects.get(pk=self.kwargs['id'])
form.instance.type = 'RV'
return super().form_valid(form)
def get_con... | the_stack_v2_python_sparse | rameniaapp/views/report.py | awlane/ramenia | train | 0 |
e85e146b6da17ff5b9efeb4c044d6b3c5e360557 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsBaseline()",
"from .entity import Entity\nfrom .user_experience_analytics_category import UserExperienceAnalyticsCategory\nfrom .entity import Entity\nfrom .user_experience_analytics_category import UserExperienc... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsBaseline()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .user_experience_analytics_category import UserExperienceAnalyticsCategory
from ... | The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores. | UserExperienceAnalyticsBaseline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsBaseline:
"""The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsBaseline:
"... | stack_v2_sparse_classes_10k_train_002137 | 6,064 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UserExperienceAnalyticsBaseline",
"name": "create_from_discriminator_value",
"signature": "def create_from_d... | 3 | null | Implement the Python class `UserExperienceAnalyticsBaseline` described below.
Class description:
The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Opt... | Implement the Python class `UserExperienceAnalyticsBaseline` described below.
Class description:
The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Opt... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsBaseline:
"""The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsBaseline:
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserExperienceAnalyticsBaseline:
"""The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsBaseline:
"""Creates a n... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_baseline.py | microsoftgraph/msgraph-sdk-python | train | 135 |
8facccb193cc9b3d0636edc3be2890470aebd3ac | [
"super().__init__()\nprototype_shape = (num_prototypes, num_features, w_1, h_1)\nself.prototype_vectors = nn.Parameter(torch.randn(prototype_shape), requires_grad=True)",
"ones = torch.ones_like(self.prototype_vectors, device=xs.device)\nxs_squared_l2 = F.conv2d(xs ** 2, weight=ones)\nps_squared_l2 = torch.sum(se... | <|body_start_0|>
super().__init__()
prototype_shape = (num_prototypes, num_features, w_1, h_1)
self.prototype_vectors = nn.Parameter(torch.randn(prototype_shape), requires_grad=True)
<|end_body_0|>
<|body_start_1|>
ones = torch.ones_like(self.prototype_vectors, device=xs.device)
... | Convolutional layer that computes the squared L2 distance instead of the conventional inner product. | L2Conv2D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class L2Conv2D:
"""Convolutional layer that computes the squared L2 distance instead of the conventional inner product."""
def __init__(self, num_prototypes, num_features, w_1, h_1):
"""Create a new L2Conv2D layer :param num_prototypes: The number of prototypes in the layer :param num_feat... | stack_v2_sparse_classes_10k_train_002138 | 3,404 | permissive | [
{
"docstring": "Create a new L2Conv2D layer :param num_prototypes: The number of prototypes in the layer :param num_features: The number of channels in the input features :param w_1: Width of the prototypes :param h_1: Height of the prototypes",
"name": "__init__",
"signature": "def __init__(self, num_p... | 2 | stack_v2_sparse_classes_30k_train_006535 | Implement the Python class `L2Conv2D` described below.
Class description:
Convolutional layer that computes the squared L2 distance instead of the conventional inner product.
Method signatures and docstrings:
- def __init__(self, num_prototypes, num_features, w_1, h_1): Create a new L2Conv2D layer :param num_prototyp... | Implement the Python class `L2Conv2D` described below.
Class description:
Convolutional layer that computes the squared L2 distance instead of the conventional inner product.
Method signatures and docstrings:
- def __init__(self, num_prototypes, num_features, w_1, h_1): Create a new L2Conv2D layer :param num_prototyp... | d9e77a90b47cb1efe19f1736c6701872a3c4a62e | <|skeleton|>
class L2Conv2D:
"""Convolutional layer that computes the squared L2 distance instead of the conventional inner product."""
def __init__(self, num_prototypes, num_features, w_1, h_1):
"""Create a new L2Conv2D layer :param num_prototypes: The number of prototypes in the layer :param num_feat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class L2Conv2D:
"""Convolutional layer that computes the squared L2 distance instead of the conventional inner product."""
def __init__(self, num_prototypes, num_features, w_1, h_1):
"""Create a new L2Conv2D layer :param num_prototypes: The number of prototypes in the layer :param num_features: The num... | the_stack_v2_python_sparse | util/l2conv.py | TristanGomez44/ProtoTree | train | 0 |
86c7a1aeeb13f4a3527cb6a2b3ac757a1b9f78dd | [
"n_samples, n_features = X.shape\nself.classes = np.unique(y)\nn_classes = len(self.classes)\nself.phi = np.zeros((n_classes, 1))\nself.means = np.zeros((n_classes, n_features))\nself.sigma = 0\nfor i in range(n_classes):\n indexes = np.flatnonzero(y == self.classes[i])\n self.phi[i] = len(indexes) / n_sample... | <|body_start_0|>
n_samples, n_features = X.shape
self.classes = np.unique(y)
n_classes = len(self.classes)
self.phi = np.zeros((n_classes, 1))
self.means = np.zeros((n_classes, n_features))
self.sigma = 0
for i in range(n_classes):
indexes = np.flatnon... | GDA | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GDA:
def fit(self, X, y):
"""Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels"""
<|body_0|>
def predict(self, X):
"""Parameters ---------- X : shape (n_samples, n_features) Predicting data Returns ------- y : ... | stack_v2_sparse_classes_10k_train_002139 | 1,310 | permissive | [
{
"docstring": "Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels",
"name": "fit",
"signature": "def fit(self, X, y)"
},
{
"docstring": "Parameters ---------- X : shape (n_samples, n_features) Predicting data Returns ------- y : shape (n_s... | 2 | stack_v2_sparse_classes_30k_train_005875 | Implement the Python class `GDA` described below.
Class description:
Implement the GDA class.
Method signatures and docstrings:
- def fit(self, X, y): Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels
- def predict(self, X): Parameters ---------- X : shape (n_s... | Implement the Python class `GDA` described below.
Class description:
Implement the GDA class.
Method signatures and docstrings:
- def fit(self, X, y): Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels
- def predict(self, X): Parameters ---------- X : shape (n_s... | 7034798a5f0b92c6b8fdfa5948d2ad78a77a1a05 | <|skeleton|>
class GDA:
def fit(self, X, y):
"""Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels"""
<|body_0|>
def predict(self, X):
"""Parameters ---------- X : shape (n_samples, n_features) Predicting data Returns ------- y : ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GDA:
def fit(self, X, y):
"""Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels"""
n_samples, n_features = X.shape
self.classes = np.unique(y)
n_classes = len(self.classes)
self.phi = np.zeros((n_classes, 1))
... | the_stack_v2_python_sparse | 7. Machine Learning/gaussian_discriminant_analysis.py | Nhiemth1985/Pynaissance | train | 0 | |
9337c48b67d1d779f77eb40ccd3be8df5b9f06b8 | [
"super(FileSystemWinRegistryFileReader, self).__init__()\nself._file_system = file_system\nself._path_resolver = windows_path_resolver.WindowsPathResolver(file_system, mount_point)\nif path_attributes:\n for attribute_name, attribute_value in iter(path_attributes.items()):\n if attribute_name == u'systemr... | <|body_start_0|>
super(FileSystemWinRegistryFileReader, self).__init__()
self._file_system = file_system
self._path_resolver = windows_path_resolver.WindowsPathResolver(file_system, mount_point)
if path_attributes:
for attribute_name, attribute_value in iter(path_attributes.i... | A file system-based Windows Registry file reader. | FileSystemWinRegistryFileReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileSystemWinRegistryFileReader:
"""A file system-based Windows Registry file reader."""
def __init__(self, file_system, mount_point, path_attributes=None):
"""Initializes a Windows Registry file reader object. Args: file_system (dfvfs.FileSytem): file system. mount_point (dfvfs.Path... | stack_v2_sparse_classes_10k_train_002140 | 9,000 | permissive | [
{
"docstring": "Initializes a Windows Registry file reader object. Args: file_system (dfvfs.FileSytem): file system. mount_point (dfvfs.PathSpec): mount point path specification. path_attributes (Optional[dict[str, str]]): path attributes e.g. {'SystemRoot': '\\\\Windows'}",
"name": "__init__",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_005639 | Implement the Python class `FileSystemWinRegistryFileReader` described below.
Class description:
A file system-based Windows Registry file reader.
Method signatures and docstrings:
- def __init__(self, file_system, mount_point, path_attributes=None): Initializes a Windows Registry file reader object. Args: file_syste... | Implement the Python class `FileSystemWinRegistryFileReader` described below.
Class description:
A file system-based Windows Registry file reader.
Method signatures and docstrings:
- def __init__(self, file_system, mount_point, path_attributes=None): Initializes a Windows Registry file reader object. Args: file_syste... | 0ee446ebf03d17c515f76a666bd3795e91a2dd17 | <|skeleton|>
class FileSystemWinRegistryFileReader:
"""A file system-based Windows Registry file reader."""
def __init__(self, file_system, mount_point, path_attributes=None):
"""Initializes a Windows Registry file reader object. Args: file_system (dfvfs.FileSytem): file system. mount_point (dfvfs.Path... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FileSystemWinRegistryFileReader:
"""A file system-based Windows Registry file reader."""
def __init__(self, file_system, mount_point, path_attributes=None):
"""Initializes a Windows Registry file reader object. Args: file_system (dfvfs.FileSytem): file system. mount_point (dfvfs.PathSpec): mount ... | the_stack_v2_python_sparse | plaso/preprocessors/manager.py | aarontp/plaso | train | 1 |
86fb1e3951d579b6b2023346d0cc8b054f5586b5 | [
"if not root or root == p or root == q:\n return root\nleft = self.lowestCommonAncestor(root.left, p, q)\nright = self.lowestCommonAncestor(root.right, p, q)\nif not left:\n return right\nif not right:\n return left\nreturn root",
"if not root or root == p or root == q:\n return root\nleft = self.lowe... | <|body_start_0|>
if not root or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if not left:
return right
if not right:
return left
return root
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点root.left 和右子节点 root.right都不是p和q的公共祖先,则称root是“最近的公共祖先” 根据以上定义,若root是p,q的最近公共祖先,则只可能为以下情况之一: 1,p和q ... | stack_v2_sparse_classes_10k_train_002141 | 4,599 | no_license | [
{
"docstring": "祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点root.left 和右子节点 root.right都不是p和q的公共祖先,则称root是“最近的公共祖先” 根据以上定义,若root是p,q的最近公共祖先,则只可能为以下情况之一: 1,p和q 在root的子树中,且分列root的异侧,(即分别在左,右子树中) 2,p=root,且q在root的左子树或右子树中 3,q=root,且p在root的左子树或右子树中 考虑通过递归对二叉树进行后续遍历,当遇到节点p和q时返回,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点r... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点root.left 和右子节点 root.right都不是p和q的公共祖先,则称root是“最近的公共祖先” 根据以上定义,若root是p,q的最近公共祖先,则只可能为以下情况之一: 1,p和q ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点root.left 和右子节点 root.right都不是p和q的公共祖先,则称root是“最近的公共祖先” 根据以上定义,若root是p,q的最近公共祖先,则只可能为以下情况之一: 1,p和q 在root的子树中,且分列r... | the_stack_v2_python_sparse | 剑指offer/PythonVersion/68_2_二叉树的最近公共祖先.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
c3de7388bd76854e8b231a7906d56ce8741421d2 | [
"self.sensor = Sensor('127.0.0.1', 1111)\nself.pump = Pump('127.0.0.1', 2222)\nself.decider = Decider(100, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)\nself.actions = {'PUMP_IN': self.pump.PUMP_IN, 'PUMP_OUT': self.pump.PUMP_OUT, 'PUMP_OFF': self.pump.PUMP_OFF}",
"height = 50\ncur_ac... | <|body_start_0|>
self.sensor = Sensor('127.0.0.1', 1111)
self.pump = Pump('127.0.0.1', 2222)
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
self.actions = {'PUMP_IN': self.pump.PUMP_IN, 'PUMP_OUT': self.pump.PUMP_OUT, 'PUMP_OF... | Unit tests for the Controller class | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Create dummy instance"""
<|body_0|>
def test_tick(self):
"""Test behavior of tick method"""
<|body_1|>
def test_fail(self):
"""Test for exception in controller.tic... | stack_v2_sparse_classes_10k_train_002142 | 4,886 | no_license | [
{
"docstring": "Create dummy instance",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test behavior of tick method",
"name": "test_tick",
"signature": "def test_tick(self)"
},
{
"docstring": "Test for exception in controller.tick method",
"name": "test_fa... | 3 | null | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Create dummy instance
- def test_tick(self): Test behavior of tick method
- def test_fail(self): Test for exception in controller.tick method | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Create dummy instance
- def test_tick(self): Test behavior of tick method
- def test_fail(self): Test for exception in controller.tick method
<|ske... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Create dummy instance"""
<|body_0|>
def test_tick(self):
"""Test behavior of tick method"""
<|body_1|>
def test_fail(self):
"""Test for exception in controller.tic... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Create dummy instance"""
self.sensor = Sensor('127.0.0.1', 1111)
self.pump = Pump('127.0.0.1', 2222)
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump... | the_stack_v2_python_sparse | students/tbrackney/Lesson6/water-regulation/waterregulation/test.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
ff8c72a0e71ce1a99e8abd26334438830b94938e | [
"my_survey = AnonymousSurvey('what language did you first learn to code?')\nmy_survey.store_response('python')\nself.assertIn('python', my_survey.responses)",
"my_survey = AnonymousSurvey('what language did you first learn to code?')\nuresponses = ['python', 'java', 'C#']\nfor response in uresponses:\n my_surv... | <|body_start_0|>
my_survey = AnonymousSurvey('what language did you first learn to code?')
my_survey.store_response('python')
self.assertIn('python', my_survey.responses)
<|end_body_0|>
<|body_start_1|>
my_survey = AnonymousSurvey('what language did you first learn to code?')
ur... | 针对class的test | TestAnonymousSurvey | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnonymousSurvey:
"""针对class的test"""
def test_store_single_response(self):
"""测试单个答案的储存状况"""
<|body_0|>
def test_store_three_responses(self):
"""Test that three individual responses are stored properly."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_002143 | 936 | no_license | [
{
"docstring": "测试单个答案的储存状况",
"name": "test_store_single_response",
"signature": "def test_store_single_response(self)"
},
{
"docstring": "Test that three individual responses are stored properly.",
"name": "test_store_three_responses",
"signature": "def test_store_three_responses(self)"... | 2 | null | Implement the Python class `TestAnonymousSurvey` described below.
Class description:
针对class的test
Method signatures and docstrings:
- def test_store_single_response(self): 测试单个答案的储存状况
- def test_store_three_responses(self): Test that three individual responses are stored properly. | Implement the Python class `TestAnonymousSurvey` described below.
Class description:
针对class的test
Method signatures and docstrings:
- def test_store_single_response(self): 测试单个答案的储存状况
- def test_store_three_responses(self): Test that three individual responses are stored properly.
<|skeleton|>
class TestAnonymousSur... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class TestAnonymousSurvey:
"""针对class的test"""
def test_store_single_response(self):
"""测试单个答案的储存状况"""
<|body_0|>
def test_store_three_responses(self):
"""Test that three individual responses are stored properly."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestAnonymousSurvey:
"""针对class的test"""
def test_store_single_response(self):
"""测试单个答案的储存状况"""
my_survey = AnonymousSurvey('what language did you first learn to code?')
my_survey.store_response('python')
self.assertIn('python', my_survey.responses)
def test_store_thr... | the_stack_v2_python_sparse | ProgrammingCourses/PythonCrashCourse/C11_testing5_Class.py | jxie0755/Learning_Python | train | 0 |
c9465e488bac63ddb11ed7ce749a2a6ce1765a04 | [
"self.K = K\nself.D = D\nif type(exp_list) is not list:\n self.exp_list = [exp_list for i in range(K)]\nelse:\n self.exp_list = exp_list\nreturn",
"self.GMM_model = GMM(X, self.K)\nself.GMM_model.fit(tol=0.001)\nself.MoE_list = []\nfor i in range(self.K):\n indices = self.GMM_model.get_cluster_indices(y,... | <|body_start_0|>
self.K = K
self.D = D
if type(exp_list) is not list:
self.exp_list = [exp_list for i in range(K)]
else:
self.exp_list = exp_list
return
<|end_body_0|>
<|body_start_1|>
self.GMM_model = GMM(X, self.K)
self.GMM_model.fit(tol... | This class is to fit a cluster model over data given. After that, for each cluster, a MoE model is fitted for each cluster. It has methods for make predictions and test validation error. | cluster_fit | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cluster_fit:
"""This class is to fit a cluster model over data given. After that, for each cluster, a MoE model is fitted for each cluster. It has methods for make predictions and test validation error."""
def __init__(self, K, L, exp_list):
"""Initialize the class with L clusters in... | stack_v2_sparse_classes_10k_train_002144 | 1,937 | permissive | [
{
"docstring": "Initialize the class with L clusters in a space with K features. The MoE model has a number of experts given in exp_list. Input: D dimensionality of space K number of clusters exp_list ()/[] list of L number of experts for each cluster model (if a number it's the same for every cluster) Output:"... | 2 | stack_v2_sparse_classes_30k_train_001342 | Implement the Python class `cluster_fit` described below.
Class description:
This class is to fit a cluster model over data given. After that, for each cluster, a MoE model is fitted for each cluster. It has methods for make predictions and test validation error.
Method signatures and docstrings:
- def __init__(self,... | Implement the Python class `cluster_fit` described below.
Class description:
This class is to fit a cluster model over data given. After that, for each cluster, a MoE model is fitted for each cluster. It has methods for make predictions and test validation error.
Method signatures and docstrings:
- def __init__(self,... | a786e9ce5845ba1f82980c5265307914c3c26e68 | <|skeleton|>
class cluster_fit:
"""This class is to fit a cluster model over data given. After that, for each cluster, a MoE model is fitted for each cluster. It has methods for make predictions and test validation error."""
def __init__(self, K, L, exp_list):
"""Initialize the class with L clusters in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class cluster_fit:
"""This class is to fit a cluster model over data given. After that, for each cluster, a MoE model is fitted for each cluster. It has methods for make predictions and test validation error."""
def __init__(self, K, L, exp_list):
"""Initialize the class with L clusters in a space with... | the_stack_v2_python_sparse | dev/tries_checks/tries/cluster_fit.py | stefanoschmidt1995/MLGW | train | 12 |
48222a242e4f09aaf36396c975d8b1685538ddc1 | [
"params = ParamsParser(request.GET)\nlimit = params.int('limit', desc='每页最大渲染数', require=False, default=10)\npage = params.int('page', desc='当前页数', require=False, default=1)\nattendances = PracticeAttendance.objects.filter(arrangement_id=aid).values('id', 'update_time')\nif params.has('leaver'):\n attendances = ... | <|body_start_0|>
params = ParamsParser(request.GET)
limit = params.int('limit', desc='每页最大渲染数', require=False, default=10)
page = params.int('page', desc='当前页数', require=False, default=1)
attendances = PracticeAttendance.objects.filter(arrangement_id=aid).values('id', 'update_time')
... | PracticeAttendanceListMgetView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PracticeAttendanceListMgetView:
def get(self, request, sid, cid, aid):
"""获取排课考勤 :param request: :param sid: :param cid: :param aid: :return:"""
<|body_0|>
def post(self, request, sid, cid, aid):
"""批量获取考勤信息 :param request: :param sid: :param cid: :param aid: :return... | stack_v2_sparse_classes_10k_train_002145 | 2,392 | no_license | [
{
"docstring": "获取排课考勤 :param request: :param sid: :param cid: :param aid: :return:",
"name": "get",
"signature": "def get(self, request, sid, cid, aid)"
},
{
"docstring": "批量获取考勤信息 :param request: :param sid: :param cid: :param aid: :return:",
"name": "post",
"signature": "def post(self... | 2 | stack_v2_sparse_classes_30k_train_005601 | Implement the Python class `PracticeAttendanceListMgetView` described below.
Class description:
Implement the PracticeAttendanceListMgetView class.
Method signatures and docstrings:
- def get(self, request, sid, cid, aid): 获取排课考勤 :param request: :param sid: :param cid: :param aid: :return:
- def post(self, request, s... | Implement the Python class `PracticeAttendanceListMgetView` described below.
Class description:
Implement the PracticeAttendanceListMgetView class.
Method signatures and docstrings:
- def get(self, request, sid, cid, aid): 获取排课考勤 :param request: :param sid: :param cid: :param aid: :return:
- def post(self, request, s... | 7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b | <|skeleton|>
class PracticeAttendanceListMgetView:
def get(self, request, sid, cid, aid):
"""获取排课考勤 :param request: :param sid: :param cid: :param aid: :return:"""
<|body_0|>
def post(self, request, sid, cid, aid):
"""批量获取考勤信息 :param request: :param sid: :param cid: :param aid: :return... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PracticeAttendanceListMgetView:
def get(self, request, sid, cid, aid):
"""获取排课考勤 :param request: :param sid: :param cid: :param aid: :return:"""
params = ParamsParser(request.GET)
limit = params.int('limit', desc='每页最大渲染数', require=False, default=10)
page = params.int('page', d... | the_stack_v2_python_sparse | FireHydrant/server/practice/views/attendance/list_mget.py | shoogoome/FireHydrant | train | 4 | |
18b9f3bb3784e1cb5953e0da9a69174ed1449819 | [
"_inv_index: InvIndex\n_tokenizer: Tokenizer\n_inv_index, _tokenizer = self.__load_inv_index(index_path, dicdir)\nlogging.info('Loaded inverted index')\nself._inv_index = _inv_index\nself._tokenizer = _tokenizer",
"name: str\nversion: str\ninv_index: InvIndex\ntokenizer: Tokenizer\nif not path.exists(index_path):... | <|body_start_0|>
_inv_index: InvIndex
_tokenizer: Tokenizer
_inv_index, _tokenizer = self.__load_inv_index(index_path, dicdir)
logging.info('Loaded inverted index')
self._inv_index = _inv_index
self._tokenizer = _tokenizer
<|end_body_0|>
<|body_start_1|>
name: st... | Engine class. | Engine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Engine:
"""Engine class."""
def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None:
"""Initialize the search engine."""
<|body_0|>
def __load_inv_index(self, index_path: str, dicdir: Optional[str]) -> Tuple[InvIndex, Tokenizer]:
"""Load inverted ... | stack_v2_sparse_classes_10k_train_002146 | 2,559 | permissive | [
{
"docstring": "Initialize the search engine.",
"name": "__init__",
"signature": "def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None"
},
{
"docstring": "Load inverted index.",
"name": "__load_inv_index",
"signature": "def __load_inv_index(self, index_path: str, dicdi... | 3 | stack_v2_sparse_classes_30k_train_003057 | Implement the Python class `Engine` described below.
Class description:
Engine class.
Method signatures and docstrings:
- def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None: Initialize the search engine.
- def __load_inv_index(self, index_path: str, dicdir: Optional[str]) -> Tuple[InvIndex, Token... | Implement the Python class `Engine` described below.
Class description:
Engine class.
Method signatures and docstrings:
- def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None: Initialize the search engine.
- def __load_inv_index(self, index_path: str, dicdir: Optional[str]) -> Tuple[InvIndex, Token... | c0a221a8038879107a5fe07d2b9452abf51815b1 | <|skeleton|>
class Engine:
"""Engine class."""
def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None:
"""Initialize the search engine."""
<|body_0|>
def __load_inv_index(self, index_path: str, dicdir: Optional[str]) -> Tuple[InvIndex, Tokenizer]:
"""Load inverted ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Engine:
"""Engine class."""
def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None:
"""Initialize the search engine."""
_inv_index: InvIndex
_tokenizer: Tokenizer
_inv_index, _tokenizer = self.__load_inv_index(index_path, dicdir)
logging.info('Load... | the_stack_v2_python_sparse | dzo/engine.py | moriaki3193/dzo | train | 8 |
8ab848d19dfc0072a1b664b4134e9ea43b47886b | [
"self.radius = radius\nself.x_center = x_center\nself.y_center = y_center",
"degree = random.random() * 360\nr = math.sqrt(random.random()) * self.radius\nx = self.x_center + r * math.cos(degree)\ny = self.y_center + r * math.sin(degree)\nreturn [x, y]"
] | <|body_start_0|>
self.radius = radius
self.x_center = x_center
self.y_center = y_center
<|end_body_0|>
<|body_start_1|>
degree = random.random() * 360
r = math.sqrt(random.random()) * self.radius
x = self.x_center + r * math.cos(degree)
y = self.y_center + r * ma... | Solution_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_1:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float 228ms"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.radiu... | stack_v2_sparse_classes_10k_train_002147 | 2,530 | no_license | [
{
"docstring": ":type radius: float :type x_center: float :type y_center: float 228ms",
"name": "__init__",
"signature": "def __init__(self, radius, x_center, y_center)"
},
{
"docstring": ":rtype: List[float]",
"name": "randPoint",
"signature": "def randPoint(self)"
}
] | 2 | null | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float 228ms
- def randPoint(self): :rtype: List[float] | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float 228ms
- def randPoint(self): :rtype: List[float]
<|skeleton|>... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution_1:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float 228ms"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution_1:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float 228ms"""
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def randPoint(self):
""":rtype: List[float]"""
deg... | the_stack_v2_python_sparse | GenerateRandomPointInACircle_MID_883.py | 953250587/leetcode-python | train | 2 | |
780fb64f052cbe629bd0201d50ec4b1b5965feb6 | [
"if not value:\n msg = 'Traffic filter expression required.'\n raise AppResponseException(msg)\nif type_ and type_.upper() not in self.valid_types:\n msg = 'Traffic filter type needs to be one of {}'.format(self.valid_types)\n raise AppResponseException(msg)\nif type_ and type_.upper() == 'WIRESHARK' an... | <|body_start_0|>
if not value:
msg = 'Traffic filter expression required.'
raise AppResponseException(msg)
if type_ and type_.upper() not in self.valid_types:
msg = 'Traffic filter type needs to be one of {}'.format(self.valid_types)
raise AppResponseExcep... | TrafficFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrafficFilter:
def __init__(self, value, type_=None, id_=None):
"""Initialize a TrafficFilter object. :param value: string, the actual filter expression :param type_: string, 'STEELFILTER' or 'WIRESHARK' or 'BPF', defaults to 'STEELFILTER' example STEELFILTER expression: <column_id>==<va... | stack_v2_sparse_classes_10k_train_002148 | 7,858 | permissive | [
{
"docstring": "Initialize a TrafficFilter object. :param value: string, the actual filter expression :param type_: string, 'STEELFILTER' or 'WIRESHARK' or 'BPF', defaults to 'STEELFILTER' example STEELFILTER expression: <column_id>==<value1> OR <column_id>==<value2> where \"column_id\" refers to the ID of the ... | 2 | stack_v2_sparse_classes_30k_train_001546 | Implement the Python class `TrafficFilter` described below.
Class description:
Implement the TrafficFilter class.
Method signatures and docstrings:
- def __init__(self, value, type_=None, id_=None): Initialize a TrafficFilter object. :param value: string, the actual filter expression :param type_: string, 'STEELFILTE... | Implement the Python class `TrafficFilter` described below.
Class description:
Implement the TrafficFilter class.
Method signatures and docstrings:
- def __init__(self, value, type_=None, id_=None): Initialize a TrafficFilter object. :param value: string, the actual filter expression :param type_: string, 'STEELFILTE... | 69fafaa19f36efc33fdd9a407f41520bdbea78d4 | <|skeleton|>
class TrafficFilter:
def __init__(self, value, type_=None, id_=None):
"""Initialize a TrafficFilter object. :param value: string, the actual filter expression :param type_: string, 'STEELFILTER' or 'WIRESHARK' or 'BPF', defaults to 'STEELFILTER' example STEELFILTER expression: <column_id>==<va... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TrafficFilter:
def __init__(self, value, type_=None, id_=None):
"""Initialize a TrafficFilter object. :param value: string, the actual filter expression :param type_: string, 'STEELFILTER' or 'WIRESHARK' or 'BPF', defaults to 'STEELFILTER' example STEELFILTER expression: <column_id>==<value1> OR <colu... | the_stack_v2_python_sparse | steelscript/appresponse/core/types.py | riverbed/steelscript-appresponse | train | 8 | |
43bf693141882344e27d5de1f5f969d02f326407 | [
"Thread.__init__(self)\nself.router = router\nself.daemon = True",
"logging.info('%sCheck if Router is online ...', LoggerSetup.get_log_deep(1))\ntry:\n Dhclient.update_ip(self.router.vlan_iface_name)\n self._test_connection()\nexcept FileExistsError:\n self._test_connection()\nexcept Exception:\n log... | <|body_start_0|>
Thread.__init__(self)
self.router = router
self.daemon = True
<|end_body_0|>
<|body_start_1|>
logging.info('%sCheck if Router is online ...', LoggerSetup.get_log_deep(1))
try:
Dhclient.update_ip(self.router.vlan_iface_name)
self._test_con... | Checks if the given Router is online and sets the Mode (normal, configuration). | RouterOnline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouterOnline:
"""Checks if the given Router is online and sets the Mode (normal, configuration)."""
def __init__(self, router: Router):
""":param router: Router-Obj"""
<|body_0|>
def run(self):
"""Uses the Dhlcient to get an IP from a given Router and tries to co... | stack_v2_sparse_classes_10k_train_002149 | 2,967 | no_license | [
{
"docstring": ":param router: Router-Obj",
"name": "__init__",
"signature": "def __init__(self, router: Router)"
},
{
"docstring": "Uses the Dhlcient to get an IP from a given Router and tries to connect to.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Sends ... | 3 | stack_v2_sparse_classes_30k_train_000573 | Implement the Python class `RouterOnline` described below.
Class description:
Checks if the given Router is online and sets the Mode (normal, configuration).
Method signatures and docstrings:
- def __init__(self, router: Router): :param router: Router-Obj
- def run(self): Uses the Dhlcient to get an IP from a given R... | Implement the Python class `RouterOnline` described below.
Class description:
Checks if the given Router is online and sets the Mode (normal, configuration).
Method signatures and docstrings:
- def __init__(self, router: Router): :param router: Router-Obj
- def run(self): Uses the Dhlcient to get an IP from a given R... | 551fb53a6d4f865f076d9485e7290699d988731c | <|skeleton|>
class RouterOnline:
"""Checks if the given Router is online and sets the Mode (normal, configuration)."""
def __init__(self, router: Router):
""":param router: Router-Obj"""
<|body_0|>
def run(self):
"""Uses the Dhlcient to get an IP from a given Router and tries to co... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RouterOnline:
"""Checks if the given Router is online and sets the Mode (normal, configuration)."""
def __init__(self, router: Router):
""":param router: Router-Obj"""
Thread.__init__(self)
self.router = router
self.daemon = True
def run(self):
"""Uses the Dhl... | the_stack_v2_python_sparse | util/router_online.py | PumucklOnTheAir/TestFramework | train | 9 |
dcdf5d5c13b0cdd7502e1121c04f40c1feb8e6d6 | [
"instance = models.Instance(key=instances.get_instance_key('base-name', 'revision', 'zone', 'instance-name'))\ninstance_template_revision = models.InstanceTemplateRevision()\nexpected_dimensions = {'backend': 'GCE', 'hostname': 'instance-name'}\nself.assertEqual(catalog.extract_dimensions(instance, instance_templat... | <|body_start_0|>
instance = models.Instance(key=instances.get_instance_key('base-name', 'revision', 'zone', 'instance-name'))
instance_template_revision = models.InstanceTemplateRevision()
expected_dimensions = {'backend': 'GCE', 'hostname': 'instance-name'}
self.assertEqual(catalog.extr... | Tests for catalog.extract_dimensions. | ExtractDimensionsTest | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtractDimensionsTest:
"""Tests for catalog.extract_dimensions."""
def test_no_dimensions(self):
"""Ensures basic dimensions are returned when there are no others."""
<|body_0|>
def test_dimensions(self):
"""Ensures dimensions are returned."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_002150 | 2,078 | permissive | [
{
"docstring": "Ensures basic dimensions are returned when there are no others.",
"name": "test_no_dimensions",
"signature": "def test_no_dimensions(self)"
},
{
"docstring": "Ensures dimensions are returned.",
"name": "test_dimensions",
"signature": "def test_dimensions(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003842 | Implement the Python class `ExtractDimensionsTest` described below.
Class description:
Tests for catalog.extract_dimensions.
Method signatures and docstrings:
- def test_no_dimensions(self): Ensures basic dimensions are returned when there are no others.
- def test_dimensions(self): Ensures dimensions are returned. | Implement the Python class `ExtractDimensionsTest` described below.
Class description:
Tests for catalog.extract_dimensions.
Method signatures and docstrings:
- def test_no_dimensions(self): Ensures basic dimensions are returned when there are no others.
- def test_dimensions(self): Ensures dimensions are returned.
... | a2349b78d2dce6aa4e131e6f7afaa202ccd72ea8 | <|skeleton|>
class ExtractDimensionsTest:
"""Tests for catalog.extract_dimensions."""
def test_no_dimensions(self):
"""Ensures basic dimensions are returned when there are no others."""
<|body_0|>
def test_dimensions(self):
"""Ensures dimensions are returned."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExtractDimensionsTest:
"""Tests for catalog.extract_dimensions."""
def test_no_dimensions(self):
"""Ensures basic dimensions are returned when there are no others."""
instance = models.Instance(key=instances.get_instance_key('base-name', 'revision', 'zone', 'instance-name'))
insta... | the_stack_v2_python_sparse | appengine/gce-backend/catalog_test.py | mellowdistrict/luci-py | train | 1 |
0c240ab1089768b8091acd1d4e20e74faaf7dd8c | [
"self.args = args\nif args is not None:\n self.save_path, self.load_path = common.read_save_load_args(args)\n load_path = self.load_path\nif load_path is None:\n assert len(ranges) == EFFECTIVE_DIM\n assert len(n_bins) == EFFECTIVE_DIM\n self.n_bins = n_bins\n self.ranges = ranges\n self.d = co... | <|body_start_0|>
self.args = args
if args is not None:
self.save_path, self.load_path = common.read_save_load_args(args)
load_path = self.load_path
if load_path is None:
assert len(ranges) == EFFECTIVE_DIM
assert len(n_bins) == EFFECTIVE_DIM
... | Learn using value iteration on a discretized version of the simulator. Note: it is based on the false assumptions that the discretized model is still deterministic and markovic. | ValueIteration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueIteration:
"""Learn using value iteration on a discretized version of the simulator. Note: it is based on the false assumptions that the discretized model is still deterministic and markovic."""
def __init__(self, args=None, ranges=None, n_bins=None, load_path=None):
"""Create a... | stack_v2_sparse_classes_10k_train_002151 | 5,255 | permissive | [
{
"docstring": "Create a ValueIteration instance using args. ranges is a list of pairs (min value, max value) for each dimentions. n_bins is a list of ints telling how many bins to have in each dimention.",
"name": "__init__",
"signature": "def __init__(self, args=None, ranges=None, n_bins=None, load_pa... | 5 | stack_v2_sparse_classes_30k_train_005227 | Implement the Python class `ValueIteration` described below.
Class description:
Learn using value iteration on a discretized version of the simulator. Note: it is based on the false assumptions that the discretized model is still deterministic and markovic.
Method signatures and docstrings:
- def __init__(self, args=... | Implement the Python class `ValueIteration` described below.
Class description:
Learn using value iteration on a discretized version of the simulator. Note: it is based on the false assumptions that the discretized model is still deterministic and markovic.
Method signatures and docstrings:
- def __init__(self, args=... | bf0474cd141d51f40af12ee5aba9b7c911ccc4d2 | <|skeleton|>
class ValueIteration:
"""Learn using value iteration on a discretized version of the simulator. Note: it is based on the false assumptions that the discretized model is still deterministic and markovic."""
def __init__(self, args=None, ranges=None, n_bins=None, load_path=None):
"""Create a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ValueIteration:
"""Learn using value iteration on a discretized version of the simulator. Note: it is based on the false assumptions that the discretized model is still deterministic and markovic."""
def __init__(self, args=None, ranges=None, n_bins=None, load_path=None):
"""Create a ValueIterati... | the_stack_v2_python_sparse | ApproxiPong-master/pong/learning/value_iteration.py | bareluz93/exam | train | 0 |
421560b36a98fd94be0190d8421d18f4e66d66ab | [
"if not root:\n return\nleft = self.flatten(root.left)\nright = self.flatten(root.right)\nroot.right = left\nnode, next_ = (root, root.right)\nwhile next_:\n node.left, node, next_ = (None, next_, next_.right)\nnode.right = right\nreturn root",
"nodes = list()\n\ndef dfs(root):\n if not root:\n re... | <|body_start_0|>
if not root:
return
left = self.flatten(root.left)
right = self.flatten(root.right)
root.right = left
node, next_ = (root, root.right)
while next_:
node.left, node, next_ = (None, next_, next_.right)
node.right = right
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_10k_train_002152 | 1,279 | no_license | [
{
"docstring": "Do not return anything, modify root in-place instead.",
"name": "flatten",
"signature": "def flatten(self, root: TreeNode) -> None"
},
{
"docstring": "Do not return anything, modify root in-place instead.",
"name": "flatten",
"signature": "def flatten(self, root: TreeNode... | 2 | stack_v2_sparse_classes_30k_train_001434 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead.
- def flatten(self, root: TreeNode) -> None: Do not return anything, modify root ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead.
- def flatten(self, root: TreeNode) -> None: Do not return anything, modify root ... | 5d29bcf7ea1a9e489a92bc36d2158456de25829e | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
if not root:
return
left = self.flatten(root.left)
right = self.flatten(root.right)
root.right = left
node, next_ = (root, root.right)
... | the_stack_v2_python_sparse | 114.二叉树展开为链表.py | oceanbei333/leetcode | train | 0 | |
284b845b668cfc0d72c8a860873b77fe70f512b4 | [
"self.output_dir = output_dir\nself.postfix = postfix\nself.ext = extension\nself.parent = parent\nself.makedirs = makedirs\nself.data_root_dir = data_root_dir",
"full_name = create_file_basename(postfix=self.postfix, input_file_name=subject, folder_path=self.output_dir, data_root_dir=self.data_root_dir, separate... | <|body_start_0|>
self.output_dir = output_dir
self.postfix = postfix
self.ext = extension
self.parent = parent
self.makedirs = makedirs
self.data_root_dir = data_root_dir
<|end_body_0|>
<|body_start_1|>
full_name = create_file_basename(postfix=self.postfix, input... | A utility class to create organized filenames within ``output_dir``. The ``filename`` method could be used to create a filename following the folder structure. Example: .. code-block:: python from monai.data import FolderLayout layout = FolderLayout( output_dir="/test_run_1/", postfix="seg", extension="nii", makedirs=F... | FolderLayout | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FolderLayout:
"""A utility class to create organized filenames within ``output_dir``. The ``filename`` method could be used to create a filename following the folder structure. Example: .. code-block:: python from monai.data import FolderLayout layout = FolderLayout( output_dir="/test_run_1/", po... | stack_v2_sparse_classes_10k_train_002153 | 6,344 | permissive | [
{
"docstring": "Args: output_dir: output directory. postfix: a postfix string for output file name appended to ``subject``. extension: output file extension to be appended to the end of an output filename. parent: whether to add a level of parent folder to contain each image to the output filename. makedirs: wh... | 2 | null | Implement the Python class `FolderLayout` described below.
Class description:
A utility class to create organized filenames within ``output_dir``. The ``filename`` method could be used to create a filename following the folder structure. Example: .. code-block:: python from monai.data import FolderLayout layout = Fold... | Implement the Python class `FolderLayout` described below.
Class description:
A utility class to create organized filenames within ``output_dir``. The ``filename`` method could be used to create a filename following the folder structure. Example: .. code-block:: python from monai.data import FolderLayout layout = Fold... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class FolderLayout:
"""A utility class to create organized filenames within ``output_dir``. The ``filename`` method could be used to create a filename following the folder structure. Example: .. code-block:: python from monai.data import FolderLayout layout = FolderLayout( output_dir="/test_run_1/", po... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FolderLayout:
"""A utility class to create organized filenames within ``output_dir``. The ``filename`` method could be used to create a filename following the folder structure. Example: .. code-block:: python from monai.data import FolderLayout layout = FolderLayout( output_dir="/test_run_1/", postfix="seg", ... | the_stack_v2_python_sparse | monai/data/folder_layout.py | Project-MONAI/MONAI | train | 4,805 |
a5fc04de933383c7358c86eedacf8724925494b3 | [
"r = re.compile('\\\\s+')\nsearch_target = r.sub('%20', search_target)\nenc_search_target = urllib.parse.quote_plus(search_target)\nurl = 'http://www.google.com/complete/search?hl=ja&q={}&output=toolbar'.format(enc_search_target)\nresponse = urllib.request.urlopen(url)\ntext = response.readlines()\ntext = text[0].d... | <|body_start_0|>
r = re.compile('\\s+')
search_target = r.sub('%20', search_target)
enc_search_target = urllib.parse.quote_plus(search_target)
url = 'http://www.google.com/complete/search?hl=ja&q={}&output=toolbar'.format(enc_search_target)
response = urllib.request.urlopen(url)
... | GetGoogleSuggest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetGoogleSuggest:
def __init__(self, search_target, get_max_count=6):
"""XMLを読み込んでitemタグのリストを作る"""
<|body_0|>
def get_data(self):
"""欲しいデータがディクショナリ形式で入ったリストを返す"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
r = re.compile('\\s+')
search_tar... | stack_v2_sparse_classes_10k_train_002154 | 1,828 | no_license | [
{
"docstring": "XMLを読み込んでitemタグのリストを作る",
"name": "__init__",
"signature": "def __init__(self, search_target, get_max_count=6)"
},
{
"docstring": "欲しいデータがディクショナリ形式で入ったリストを返す",
"name": "get_data",
"signature": "def get_data(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002919 | Implement the Python class `GetGoogleSuggest` described below.
Class description:
Implement the GetGoogleSuggest class.
Method signatures and docstrings:
- def __init__(self, search_target, get_max_count=6): XMLを読み込んでitemタグのリストを作る
- def get_data(self): 欲しいデータがディクショナリ形式で入ったリストを返す | Implement the Python class `GetGoogleSuggest` described below.
Class description:
Implement the GetGoogleSuggest class.
Method signatures and docstrings:
- def __init__(self, search_target, get_max_count=6): XMLを読み込んでitemタグのリストを作る
- def get_data(self): 欲しいデータがディクショナリ形式で入ったリストを返す
<|skeleton|>
class GetGoogleSuggest:
... | d70a0c21858e5d37a3cf3fca81b69ea7f73af661 | <|skeleton|>
class GetGoogleSuggest:
def __init__(self, search_target, get_max_count=6):
"""XMLを読み込んでitemタグのリストを作る"""
<|body_0|>
def get_data(self):
"""欲しいデータがディクショナリ形式で入ったリストを返す"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetGoogleSuggest:
def __init__(self, search_target, get_max_count=6):
"""XMLを読み込んでitemタグのリストを作る"""
r = re.compile('\\s+')
search_target = r.sub('%20', search_target)
enc_search_target = urllib.parse.quote_plus(search_target)
url = 'http://www.google.com/complete/search?... | the_stack_v2_python_sparse | application/module/misc/get_googlesuggest.py | fujimisakari/otherbu | train | 0 | |
116a13dbedb359684640e24e5013196c0d370e05 | [
"super().__init__(env)\nself.beta = 0.9\nself.loss = 'mse'",
"gamma = 0.95\nr = last_value\nfor item in self.memory[::-1]:\n [step, state, next_state, reward, done] = item\n r = reward + gamma * r\n item = [step, state, next_state, r, done]\n self.train(item)",
"[step, state, next_state, reward, don... | <|body_start_0|>
super().__init__(env)
self.beta = 0.9
self.loss = 'mse'
<|end_body_0|>
<|body_start_1|>
gamma = 0.95
r = last_value
for item in self.memory[::-1]:
[step, state, next_state, reward, done] = item
r = reward + gamma * r
i... | A2CAgent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class A2CAgent:
def __init__(self, env):
"""Implements the models and training of A2C policy gradient method Arguments: env (Object): OpenAI gym environment"""
<|body_0|>
def train_by_episode(self, last_value=0):
"""Train by episode Prepare the dataset before the step by s... | stack_v2_sparse_classes_10k_train_002155 | 29,328 | permissive | [
{
"docstring": "Implements the models and training of A2C policy gradient method Arguments: env (Object): OpenAI gym environment",
"name": "__init__",
"signature": "def __init__(self, env)"
},
{
"docstring": "Train by episode Prepare the dataset before the step by step training Arguments: last_v... | 3 | stack_v2_sparse_classes_30k_train_005998 | Implement the Python class `A2CAgent` described below.
Class description:
Implement the A2CAgent class.
Method signatures and docstrings:
- def __init__(self, env): Implements the models and training of A2C policy gradient method Arguments: env (Object): OpenAI gym environment
- def train_by_episode(self, last_value=... | Implement the Python class `A2CAgent` described below.
Class description:
Implement the A2CAgent class.
Method signatures and docstrings:
- def __init__(self, env): Implements the models and training of A2C policy gradient method Arguments: env (Object): OpenAI gym environment
- def train_by_episode(self, last_value=... | 7f447a07eb2f3dc41c83d468ae102ab8fa9dff05 | <|skeleton|>
class A2CAgent:
def __init__(self, env):
"""Implements the models and training of A2C policy gradient method Arguments: env (Object): OpenAI gym environment"""
<|body_0|>
def train_by_episode(self, last_value=0):
"""Train by episode Prepare the dataset before the step by s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class A2CAgent:
def __init__(self, env):
"""Implements the models and training of A2C policy gradient method Arguments: env (Object): OpenAI gym environment"""
super().__init__(env)
self.beta = 0.9
self.loss = 'mse'
def train_by_episode(self, last_value=0):
"""Train by e... | the_stack_v2_python_sparse | chapter10-policy/policygradient-car-10.1.1.py | PacktPublishing/Advanced-Deep-Learning-with-Keras | train | 1,672 | |
9e6fff1b87214c7a11b8d00be7c6166de86e5f64 | [
"self.timeToSpawn = timeToSpawn\nself.spawnTimer = 0\nself.map = map\nself.currTankId = 1",
"if self.spawnTimer == 0:\n if len(self.map.tanks) < self.map.maxNoOfEnemies + 1 and len(self.map.tanks) < self.map.enemiesToKill + 1:\n tank = Tank(self.currTankId, self.map.getFreeCoords(), self.map)\n s... | <|body_start_0|>
self.timeToSpawn = timeToSpawn
self.spawnTimer = 0
self.map = map
self.currTankId = 1
<|end_body_0|>
<|body_start_1|>
if self.spawnTimer == 0:
if len(self.map.tanks) < self.map.maxNoOfEnemies + 1 and len(self.map.tanks) < self.map.enemiesToKill + 1:
... | A class that spawns enemies. | EnemySpawner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnemySpawner:
"""A class that spawns enemies."""
def __init__(self, map, timeToSpawn):
"""The constructor"""
<|body_0|>
def process(self):
"""Method checks wether the timer to spawn is equal to 0. If not then it decrements the timer. Otherwise it checks if the nu... | stack_v2_sparse_classes_10k_train_002156 | 1,138 | no_license | [
{
"docstring": "The constructor",
"name": "__init__",
"signature": "def __init__(self, map, timeToSpawn)"
},
{
"docstring": "Method checks wether the timer to spawn is equal to 0. If not then it decrements the timer. Otherwise it checks if the number of enemies has not exceeded the maximum numbe... | 2 | stack_v2_sparse_classes_30k_train_002776 | Implement the Python class `EnemySpawner` described below.
Class description:
A class that spawns enemies.
Method signatures and docstrings:
- def __init__(self, map, timeToSpawn): The constructor
- def process(self): Method checks wether the timer to spawn is equal to 0. If not then it decrements the timer. Otherwis... | Implement the Python class `EnemySpawner` described below.
Class description:
A class that spawns enemies.
Method signatures and docstrings:
- def __init__(self, map, timeToSpawn): The constructor
- def process(self): Method checks wether the timer to spawn is equal to 0. If not then it decrements the timer. Otherwis... | eec95e28603b3a55c1df4f39e98ef9978881df73 | <|skeleton|>
class EnemySpawner:
"""A class that spawns enemies."""
def __init__(self, map, timeToSpawn):
"""The constructor"""
<|body_0|>
def process(self):
"""Method checks wether the timer to spawn is equal to 0. If not then it decrements the timer. Otherwise it checks if the nu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EnemySpawner:
"""A class that spawns enemies."""
def __init__(self, map, timeToSpawn):
"""The constructor"""
self.timeToSpawn = timeToSpawn
self.spawnTimer = 0
self.map = map
self.currTankId = 1
def process(self):
"""Method checks wether the timer to s... | the_stack_v2_python_sparse | game/EnemySpawner.py | eatrunner/tank-game | train | 0 |
c416bb36fc141debebd4f63bd7372035523d5e34 | [
"if request.user.is_authenticated:\n lists = ListsStream().get_list_stream(request.user)\nelse:\n lists = models.List.objects.filter(privacy='public')\npaginated = Paginator(lists, 12)\ndata = {'lists': paginated.get_page(request.GET.get('page')), 'list_form': forms.ListForm(), 'path': '/list'}\nreturn Templa... | <|body_start_0|>
if request.user.is_authenticated:
lists = ListsStream().get_list_stream(request.user)
else:
lists = models.List.objects.filter(privacy='public')
paginated = Paginator(lists, 12)
data = {'lists': paginated.get_page(request.GET.get('page')), 'list_f... | book list page | Lists | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lists:
"""book list page"""
def get(self, request):
"""display a book list"""
<|body_0|>
def post(self, request):
"""create a book_list"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if request.user.is_authenticated:
lists = ListsSt... | stack_v2_sparse_classes_10k_train_002157 | 2,823 | no_license | [
{
"docstring": "display a book list",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "create a book_list",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003704 | Implement the Python class `Lists` described below.
Class description:
book list page
Method signatures and docstrings:
- def get(self, request): display a book list
- def post(self, request): create a book_list | Implement the Python class `Lists` described below.
Class description:
book list page
Method signatures and docstrings:
- def get(self, request): display a book list
- def post(self, request): create a book_list
<|skeleton|>
class Lists:
"""book list page"""
def get(self, request):
"""display a book... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class Lists:
"""book list page"""
def get(self, request):
"""display a book list"""
<|body_0|>
def post(self, request):
"""create a book_list"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Lists:
"""book list page"""
def get(self, request):
"""display a book list"""
if request.user.is_authenticated:
lists = ListsStream().get_list_stream(request.user)
else:
lists = models.List.objects.filter(privacy='public')
paginated = Paginator(list... | the_stack_v2_python_sparse | bookwyrm/views/list/lists.py | bookwyrm-social/bookwyrm | train | 1,398 |
74d8c37775bcba9cac2315c1d7f9a27e52f89daf | [
"needed_size = 2 * length - 1\nif hasattr(self, 'pe') and self.pe.size(1) >= needed_size:\n return\npositions = torch.arange(length - 1, -length, -1, dtype=torch.float32, device=device).unsqueeze(1)\nself.create_pe(positions=positions)",
"if self.xscale:\n x = x * self.xscale\ninput_len = x.size(1) + cache_... | <|body_start_0|>
needed_size = 2 * length - 1
if hasattr(self, 'pe') and self.pe.size(1) >= needed_size:
return
positions = torch.arange(length - 1, -length, -1, dtype=torch.float32, device=device).unsqueeze(1)
self.create_pe(positions=positions)
<|end_body_0|>
<|body_start_... | Relative positional encoding for TransformerXL's layers See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): embedding dim dropout_rate (float): dropout rate max_len (int): maximum input length xscale (bool): whether to scale the input by sqrt(d_model) dropout_rate_emb (float): dropout rate for the... | RelPositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding for TransformerXL's layers See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): embedding dim dropout_rate (float): dropout rate max_len (int): maximum input length xscale (bool): whether to scale the input by sqrt(d_mode... | stack_v2_sparse_classes_10k_train_002158 | 45,820 | permissive | [
{
"docstring": "Reset and extend the positional encodings if needed.",
"name": "extend_pe",
"signature": "def extend_pe(self, length, device)"
},
{
"docstring": "Compute positional encoding. Args: x (torch.Tensor): Input. Its shape is (batch, time, feature_size) cache_len (int): the size of the ... | 2 | null | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding for TransformerXL's layers See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): embedding dim dropout_rate (float): dropout rate max_len (int): maximum input length xscale (bool): wh... | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding for TransformerXL's layers See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): embedding dim dropout_rate (float): dropout rate max_len (int): maximum input length xscale (bool): wh... | c20a16ea8aa2a9d8e31a98eb22178ddb9d5935e7 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding for TransformerXL's layers See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): embedding dim dropout_rate (float): dropout rate max_len (int): maximum input length xscale (bool): whether to scale the input by sqrt(d_mode... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RelPositionalEncoding:
"""Relative positional encoding for TransformerXL's layers See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): embedding dim dropout_rate (float): dropout rate max_len (int): maximum input length xscale (bool): whether to scale the input by sqrt(d_model) dropout_ra... | the_stack_v2_python_sparse | nemo/collections/asr/parts/submodules/multi_head_attention.py | NVIDIA/NeMo | train | 7,957 |
4a11ad8a0bf8b8772aa39bfa39c7ba5a9acccff5 | [
"mats = cmds.ls(materials=1)\nmats.remove('lambert1')\nmats.remove('particleCloud1')\nreturn mats",
"rv = []\nSS = cmds.shadingNode('surfaceShader', asShader=1, n=name)\nSLCode = cmds.shadingNode('SLCodeNode', asUtility=1, n=name)\nmel.eval('source \"//file-cluster/GDC/Resource/Support/AnimalLogic/mayaman2.0.7/me... | <|body_start_0|>
mats = cmds.ls(materials=1)
mats.remove('lambert1')
mats.remove('particleCloud1')
return mats
<|end_body_0|>
<|body_start_1|>
rv = []
SS = cmds.shadingNode('surfaceShader', asShader=1, n=name)
SLCode = cmds.shadingNode('SLCodeNode', asUtility=1, ... | Materials | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Materials:
def ListMats(self):
"""list all materials except lamber1 and particleCloud1"""
<|body_0|>
def CreateZdpShader(self, name):
"""return value===>[surfaceShader,SLCode,]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
mats = cmds.ls(materials... | stack_v2_sparse_classes_10k_train_002159 | 14,297 | no_license | [
{
"docstring": "list all materials except lamber1 and particleCloud1",
"name": "ListMats",
"signature": "def ListMats(self)"
},
{
"docstring": "return value===>[surfaceShader,SLCode,]",
"name": "CreateZdpShader",
"signature": "def CreateZdpShader(self, name)"
}
] | 2 | null | Implement the Python class `Materials` described below.
Class description:
Implement the Materials class.
Method signatures and docstrings:
- def ListMats(self): list all materials except lamber1 and particleCloud1
- def CreateZdpShader(self, name): return value===>[surfaceShader,SLCode,] | Implement the Python class `Materials` described below.
Class description:
Implement the Materials class.
Method signatures and docstrings:
- def ListMats(self): list all materials except lamber1 and particleCloud1
- def CreateZdpShader(self, name): return value===>[surfaceShader,SLCode,]
<|skeleton|>
class Material... | c11f715996a435396c28ffb4c20f11f8e3c1a681 | <|skeleton|>
class Materials:
def ListMats(self):
"""list all materials except lamber1 and particleCloud1"""
<|body_0|>
def CreateZdpShader(self, name):
"""return value===>[surfaceShader,SLCode,]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Materials:
def ListMats(self):
"""list all materials except lamber1 and particleCloud1"""
mats = cmds.ls(materials=1)
mats.remove('lambert1')
mats.remove('particleCloud1')
return mats
def CreateZdpShader(self, name):
"""return value===>[surfaceShader,SLCode... | the_stack_v2_python_sparse | OLD/idmt/maya/ROMA/wxII_RenderTools.py | Bn-com/myProj_octv | train | 1 | |
ac0161de90c9246f28e6c132b8e1475d3af8c24f | [
"table = getattr(self, model + '_table', None)\nself.default_r_v = None\nif table is None:\n raise AttributeError('%s model not available' % model)\nself.table = table()\nself.range = (min(self.table[0]), max(self.table[0]))\nself.arange = (self.range[0] * 10000.0, self.range[1] * 10000.0)\nself.sigma = sigma\ns... | <|body_start_0|>
table = getattr(self, model + '_table', None)
self.default_r_v = None
if table is None:
raise AttributeError('%s model not available' % model)
self.table = table()
self.range = (min(self.table[0]), max(self.table[0]))
self.arange = (self.range... | Extinction model for de-reddening spectra. | ExtinctionModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtinctionModel:
"""Extinction model for de-reddening spectra."""
def __init__(self, model='rieke1989', cval=np.nan, sigma=10.0, extrapolate=False):
"""Set extinction model. Parameters ---------- model : {'rieke1989', 'nishiyama2009'} Model to use. Options are `rieke1989_table` and `... | stack_v2_sparse_classes_10k_train_002160 | 3,929 | permissive | [
{
"docstring": "Set extinction model. Parameters ---------- model : {'rieke1989', 'nishiyama2009'} Model to use. Options are `rieke1989_table` and `nishiyama2009_table`. cval : float, optional Value to fill for missing data. sigma : float, optional Spline fit tension. extrapolate : bool, optional If set, missin... | 4 | null | Implement the Python class `ExtinctionModel` described below.
Class description:
Extinction model for de-reddening spectra.
Method signatures and docstrings:
- def __init__(self, model='rieke1989', cval=np.nan, sigma=10.0, extrapolate=False): Set extinction model. Parameters ---------- model : {'rieke1989', 'nishiyam... | Implement the Python class `ExtinctionModel` described below.
Class description:
Extinction model for de-reddening spectra.
Method signatures and docstrings:
- def __init__(self, model='rieke1989', cval=np.nan, sigma=10.0, extrapolate=False): Set extinction model. Parameters ---------- model : {'rieke1989', 'nishiyam... | 493700340cd34d5f319af6f3a562a82135bb30dd | <|skeleton|>
class ExtinctionModel:
"""Extinction model for de-reddening spectra."""
def __init__(self, model='rieke1989', cval=np.nan, sigma=10.0, extrapolate=False):
"""Set extinction model. Parameters ---------- model : {'rieke1989', 'nishiyama2009'} Model to use. Options are `rieke1989_table` and `... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExtinctionModel:
"""Extinction model for de-reddening spectra."""
def __init__(self, model='rieke1989', cval=np.nan, sigma=10.0, extrapolate=False):
"""Set extinction model. Parameters ---------- model : {'rieke1989', 'nishiyama2009'} Model to use. Options are `rieke1989_table` and `nishiyama2009... | the_stack_v2_python_sparse | sofia_redux/spectroscopy/extinction_model.py | SOFIA-USRA/sofia_redux | train | 12 |
dad74fa89cfd44bb2bcf7fa17afb49328662d2df | [
"file_presets = FilePreset.objects.filter(input_template=input_template)\nfile_preset_files = [x for x in project.files if FilePreset.match_any(x.filename, file_presets)]\nif len(file_preset_files) == 1 and input_template.unique:\n return [FileSetting.objects.get_or_create(file=x, input_template=input_template) ... | <|body_start_0|>
file_presets = FilePreset.objects.filter(input_template=input_template)
file_preset_files = [x for x in project.files if FilePreset.match_any(x.filename, file_presets)]
if len(file_preset_files) == 1 and input_template.unique:
return [FileSetting.objects.get_or_creat... | Class for adding Files to InputTemplates. | FileSetting | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileSetting:
"""Class for adding Files to InputTemplates."""
def create_for_file_presets(input_template: InputTemplate, project: Project):
"""Create file settings automatically for the input template using the file presets."""
<|body_0|>
def create_for_input_template(inp... | stack_v2_sparse_classes_10k_train_002161 | 25,346 | no_license | [
{
"docstring": "Create file settings automatically for the input template using the file presets.",
"name": "create_for_file_presets",
"signature": "def create_for_file_presets(input_template: InputTemplate, project: Project)"
},
{
"docstring": "Create file settings automatically for the input t... | 2 | stack_v2_sparse_classes_30k_train_005251 | Implement the Python class `FileSetting` described below.
Class description:
Class for adding Files to InputTemplates.
Method signatures and docstrings:
- def create_for_file_presets(input_template: InputTemplate, project: Project): Create file settings automatically for the input template using the file presets.
- d... | Implement the Python class `FileSetting` described below.
Class description:
Class for adding Files to InputTemplates.
Method signatures and docstrings:
- def create_for_file_presets(input_template: InputTemplate, project: Project): Create file settings automatically for the input template using the file presets.
- d... | dfa60c9a812e52fa44f0d3cf1c201943574976df | <|skeleton|>
class FileSetting:
"""Class for adding Files to InputTemplates."""
def create_for_file_presets(input_template: InputTemplate, project: Project):
"""Create file settings automatically for the input template using the file presets."""
<|body_0|>
def create_for_input_template(inp... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FileSetting:
"""Class for adding Files to InputTemplates."""
def create_for_file_presets(input_template: InputTemplate, project: Project):
"""Create file settings automatically for the input template using the file presets."""
file_presets = FilePreset.objects.filter(input_template=input_... | the_stack_v2_python_sparse | equestria/processes/models.py | KiOui/CLST-2020 | train | 0 |
7be15996c028f9465222161469983854f37d1277 | [
"def inorder(root, k):\n if root is None or Solution.RES is not None:\n return\n inorder(root.left, k)\n Solution.COUNTER += 1\n if Solution.COUNTER == k:\n Solution.RES = root\n return\n inorder(root.right, k)\ninorder(root, k)\nreturn Solution.RES.val",
"def inorder(root, con... | <|body_start_0|>
def inorder(root, k):
if root is None or Solution.RES is not None:
return
inorder(root.left, k)
Solution.COUNTER += 1
if Solution.COUNTER == k:
Solution.RES = root
return
inorder(root.rig... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, root, k):
"""This one requires two global(in class scope) varirables to track the ith node it's visiting and ref desired node to it. :type root: TreeNode :type k: int :rtype: int"""
<|body_0|>
def kthSmallestWithExtraSpace(self, root, k):
... | stack_v2_sparse_classes_10k_train_002162 | 2,279 | no_license | [
{
"docstring": "This one requires two global(in class scope) varirables to track the ith node it's visiting and ref desired node to it. :type root: TreeNode :type k: int :rtype: int",
"name": "kthSmallest",
"signature": "def kthSmallest(self, root, k)"
},
{
"docstring": "Extra O(n) space. :type ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root, k): This one requires two global(in class scope) varirables to track the ith node it's visiting and ref desired node to it. :type root: TreeNode :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root, k): This one requires two global(in class scope) varirables to track the ith node it's visiting and ref desired node to it. :type root: TreeNode :type... | 33c623f226981942780751554f0593f2c71cf458 | <|skeleton|>
class Solution:
def kthSmallest(self, root, k):
"""This one requires two global(in class scope) varirables to track the ith node it's visiting and ref desired node to it. :type root: TreeNode :type k: int :rtype: int"""
<|body_0|>
def kthSmallestWithExtraSpace(self, root, k):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def kthSmallest(self, root, k):
"""This one requires two global(in class scope) varirables to track the ith node it's visiting and ref desired node to it. :type root: TreeNode :type k: int :rtype: int"""
def inorder(root, k):
if root is None or Solution.RES is not None:
... | the_stack_v2_python_sparse | tree/leetcode_Kth_Smallest_Element_In_A_BST.py | monkeylyf/interviewjam | train | 59 | |
97322b1a1663f996942b3ad36f20fed78340d95a | [
"super(MCBertForPretrainingModel, self).__init__()\nself.vis_feat_dim = vis_feat_dim\nself.spatial_size = spatial_size\nself.hidden_dim = hidden_dim\nself.cmb_feat_dim = cmb_feat_dim\nself.kernel_size = kernel_size\nself.mcbert_model = MCBertModel(vis_feat_dim=vis_feat_dim, spatial_size=spatial_size, hidden_dim=hid... | <|body_start_0|>
super(MCBertForPretrainingModel, self).__init__()
self.vis_feat_dim = vis_feat_dim
self.spatial_size = spatial_size
self.hidden_dim = hidden_dim
self.cmb_feat_dim = cmb_feat_dim
self.kernel_size = kernel_size
self.mcbert_model = MCBertModel(vis_fe... | Class implementing MCBERT model for unsupervised pre-training. | MCBertForPretrainingModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MCBertForPretrainingModel:
"""Class implementing MCBERT model for unsupervised pre-training."""
def __init__(self, vis_feat_dim=2208, spatial_size=7, hidden_dim=768, cmb_feat_dim=16000, kernel_size=3):
"""Initialize SkipGramDistNet."""
<|body_0|>
def forward(self, vis_fe... | stack_v2_sparse_classes_10k_train_002163 | 2,272 | no_license | [
{
"docstring": "Initialize SkipGramDistNet.",
"name": "__init__",
"signature": "def __init__(self, vis_feat_dim=2208, spatial_size=7, hidden_dim=768, cmb_feat_dim=16000, kernel_size=3)"
},
{
"docstring": "Forward Pass.",
"name": "forward",
"signature": "def forward(self, vis_feats, input... | 2 | stack_v2_sparse_classes_30k_train_003055 | Implement the Python class `MCBertForPretrainingModel` described below.
Class description:
Class implementing MCBERT model for unsupervised pre-training.
Method signatures and docstrings:
- def __init__(self, vis_feat_dim=2208, spatial_size=7, hidden_dim=768, cmb_feat_dim=16000, kernel_size=3): Initialize SkipGramDis... | Implement the Python class `MCBertForPretrainingModel` described below.
Class description:
Class implementing MCBERT model for unsupervised pre-training.
Method signatures and docstrings:
- def __init__(self, vis_feat_dim=2208, spatial_size=7, hidden_dim=768, cmb_feat_dim=16000, kernel_size=3): Initialize SkipGramDis... | fbfa1766dbc52cbf39036abe1a44f9315fad4a5c | <|skeleton|>
class MCBertForPretrainingModel:
"""Class implementing MCBERT model for unsupervised pre-training."""
def __init__(self, vis_feat_dim=2208, spatial_size=7, hidden_dim=768, cmb_feat_dim=16000, kernel_size=3):
"""Initialize SkipGramDistNet."""
<|body_0|>
def forward(self, vis_fe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MCBertForPretrainingModel:
"""Class implementing MCBERT model for unsupervised pre-training."""
def __init__(self, vis_feat_dim=2208, spatial_size=7, hidden_dim=768, cmb_feat_dim=16000, kernel_size=3):
"""Initialize SkipGramDistNet."""
super(MCBertForPretrainingModel, self).__init__()
... | the_stack_v2_python_sparse | mcbert/models/mcbert_for_pretraining.py | estebandito22/MC-BERT | train | 0 |
d1ed43bab6171c876b2ad9ef9db834ab8f9026d5 | [
"query = User.Q\nif 'status' in where.keys():\n query = query.filter(User.status == where['status'])\nelse:\n query = query.filter(User.status != -1)\npagelist_obj = query.paginate(page=page, per_page=per_page)\nreturn pagelist_obj",
"if not id:\n raise JsonError('ID不能为空')\nobj = User.Q.filter(User.id ==... | <|body_start_0|>
query = User.Q
if 'status' in where.keys():
query = query.filter(User.status == where['status'])
else:
query = query.filter(User.status != -1)
pagelist_obj = query.paginate(page=page, per_page=per_page)
return pagelist_obj
<|end_body_0|>
... | UserService | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserService:
def page_list(where, page, per_page):
"""列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None"""
<|body_0|>
def get(id):
"""获取单条记录 [description] Arguments: id int -- 主键 return: User Model 实例 | None"""
... | stack_v2_sparse_classes_10k_train_002164 | 2,701 | permissive | [
{
"docstring": "列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None",
"name": "page_list",
"signature": "def page_list(where, page, per_page)"
},
{
"docstring": "获取单条记录 [description] Arguments: id int -- 主键 return: User Model 实例 | None",
"name"... | 4 | stack_v2_sparse_classes_30k_train_003664 | Implement the Python class `UserService` described below.
Class description:
Implement the UserService class.
Method signatures and docstrings:
- def page_list(where, page, per_page): 列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None
- def get(id): 获取单条记录 [description... | Implement the Python class `UserService` described below.
Class description:
Implement the UserService class.
Method signatures and docstrings:
- def page_list(where, page, per_page): 列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None
- def get(id): 获取单条记录 [description... | 3300561c5686b674197ffc097cf781a931fd4787 | <|skeleton|>
class UserService:
def page_list(where, page, per_page):
"""列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None"""
<|body_0|>
def get(id):
"""获取单条记录 [description] Arguments: id int -- 主键 return: User Model 实例 | None"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserService:
def page_list(where, page, per_page):
"""列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None"""
query = User.Q
if 'status' in where.keys():
query = query.filter(User.status == where['status'])
else:
... | the_stack_v2_python_sparse | applications/admin/services/user.py | leeyisoft/py_admin | train | 17 | |
e3f619f08b839e1e1d7b5bb10daf8eb34bdeb2c8 | [
"if directory is None:\n directory = os.getcwd()\nproject_name = os.path.basename(directory)\nif app_name == project_name:\n raise CommandError('You cannot create an app with the same name (%r) as your project.' % app_name)\ntry:\n __import__(app_name)\nexcept ImportError:\n pass\nelse:\n raise Comma... | <|body_start_0|>
if directory is None:
directory = os.getcwd()
project_name = os.path.basename(directory)
if app_name == project_name:
raise CommandError('You cannot create an app with the same name (%r) as your project.' % app_name)
try:
__import__(ap... | Creates new XML Collection Application. | Command | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Creates new XML Collection Application."""
def handle_label(self, app_name, directory=None, **options):
"""Deal with the given label."""
<|body_0|>
def create_xml_database(self, app_name, directory):
"""Create the XML Database and the stub pixelate.""... | stack_v2_sparse_classes_10k_train_002165 | 2,868 | no_license | [
{
"docstring": "Deal with the given label.",
"name": "handle_label",
"signature": "def handle_label(self, app_name, directory=None, **options)"
},
{
"docstring": "Create the XML Database and the stub pixelate.",
"name": "create_xml_database",
"signature": "def create_xml_database(self, a... | 2 | stack_v2_sparse_classes_30k_train_006479 | Implement the Python class `Command` described below.
Class description:
Creates new XML Collection Application.
Method signatures and docstrings:
- def handle_label(self, app_name, directory=None, **options): Deal with the given label.
- def create_xml_database(self, app_name, directory): Create the XML Database and... | Implement the Python class `Command` described below.
Class description:
Creates new XML Collection Application.
Method signatures and docstrings:
- def handle_label(self, app_name, directory=None, **options): Deal with the given label.
- def create_xml_database(self, app_name, directory): Create the XML Database and... | 5486128b5b3b7ddb9ec81d43e3bb601a23b4025a | <|skeleton|>
class Command:
"""Creates new XML Collection Application."""
def handle_label(self, app_name, directory=None, **options):
"""Deal with the given label."""
<|body_0|>
def create_xml_database(self, app_name, directory):
"""Create the XML Database and the stub pixelate.""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Command:
"""Creates new XML Collection Application."""
def handle_label(self, app_name, directory=None, **options):
"""Deal with the given label."""
if directory is None:
directory = os.getcwd()
project_name = os.path.basename(directory)
if app_name == project_... | the_stack_v2_python_sparse | sdpub/staging/SDPublisher_MIN/pixelise/management/commands/startxml.py | mikanyman/.virtualenvs-legacy | train | 0 |
a25fdc277578b2111e1eb7828565387d18c757b4 | [
"expr = expr.replace(' ', '').replace(',', '.')\nself.app = app\nif expr.count('=') > 1:\n raise InvalidEquacaoException(\"Há mais que um '=' na equação\")\nelif expr.count('=') == 0:\n expr += '=0'\nterm, term2 = expr.split('=')\nself.first = Expressao(term)\nself.last = Expressao(term2)",
"if self.first !... | <|body_start_0|>
expr = expr.replace(' ', '').replace(',', '.')
self.app = app
if expr.count('=') > 1:
raise InvalidEquacaoException("Há mais que um '=' na equação")
elif expr.count('=') == 0:
expr += '=0'
term, term2 = expr.split('=')
self.first =... | Classe que representa a equação do segundo grau. | Equacao | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Equacao:
"""Classe que representa a equação do segundo grau."""
def __init__(self, app, expr):
"""Construtor da classe. Faz as primeiras verificações da equação. cria as instancias das expressões dadas, caso seja dado apenas uma, inicializa a outra com o valor 0."""
<|body_0|... | stack_v2_sparse_classes_10k_train_002166 | 2,803 | no_license | [
{
"docstring": "Construtor da classe. Faz as primeiras verificações da equação. cria as instancias das expressões dadas, caso seja dado apenas uma, inicializa a outra com o valor 0.",
"name": "__init__",
"signature": "def __init__(self, app, expr)"
},
{
"docstring": "Faz a segunda verificação, c... | 5 | stack_v2_sparse_classes_30k_train_003755 | Implement the Python class `Equacao` described below.
Class description:
Classe que representa a equação do segundo grau.
Method signatures and docstrings:
- def __init__(self, app, expr): Construtor da classe. Faz as primeiras verificações da equação. cria as instancias das expressões dadas, caso seja dado apenas um... | Implement the Python class `Equacao` described below.
Class description:
Classe que representa a equação do segundo grau.
Method signatures and docstrings:
- def __init__(self, app, expr): Construtor da classe. Faz as primeiras verificações da equação. cria as instancias das expressões dadas, caso seja dado apenas um... | f17de5dcfe057df28e956213737a95321693e848 | <|skeleton|>
class Equacao:
"""Classe que representa a equação do segundo grau."""
def __init__(self, app, expr):
"""Construtor da classe. Faz as primeiras verificações da equação. cria as instancias das expressões dadas, caso seja dado apenas uma, inicializa a outra com o valor 0."""
<|body_0|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Equacao:
"""Classe que representa a equação do segundo grau."""
def __init__(self, app, expr):
"""Construtor da classe. Faz as primeiras verificações da equação. cria as instancias das expressões dadas, caso seja dado apenas uma, inicializa a outra com o valor 0."""
expr = expr.replace(' ... | the_stack_v2_python_sparse | equacao_resolver/equacao.py | rafael146/workufal | train | 0 |
05be5a91b693202788e265bd222a20cc3df25b59 | [
"assert isinstance(response, scrapy.http.response.html.HtmlResponse)\ncurboard = ['Sea Fishing']\nurls = [response.url]\nfor x in range(2, LAST_PAGE + 1):\n urls.append('%spage/%s' % (urls[0], x))\nfor url in urls:\n yield scrapy.Request(url, callback=self.crawl_board_threads, dont_filter=False, meta={'curboa... | <|body_start_0|>
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
curboard = ['Sea Fishing']
urls = [response.url]
for x in range(2, LAST_PAGE + 1):
urls.append('%spage/%s' % (urls[0], x))
for url in urls:
yield scrapy.Request(url, callb... | scrape reports from angling addicts forum | TotalFishingReportsSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TotalFishingReportsSpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board yields: https://www.total-fishing.com/forums/forum/fishing/sea-fishing/page/24/"""
<|body_0|>
def crawl_board_threads(self, respons... | stack_v2_sparse_classes_10k_train_002167 | 3,813 | no_license | [
{
"docstring": "generate links to pages in a board yields: https://www.total-fishing.com/forums/forum/fishing/sea-fishing/page/24/",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "crawl",
"name": "crawl_board_threads",
"signature": "def crawl_board_threads(s... | 3 | stack_v2_sparse_classes_30k_train_006002 | Implement the Python class `TotalFishingReportsSpider` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board yields: https://www.total-fishing.com/forums/forum/fishing/sea-fishing/page/24/
- def c... | Implement the Python class `TotalFishingReportsSpider` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board yields: https://www.total-fishing.com/forums/forum/fishing/sea-fishing/page/24/
- def c... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class TotalFishingReportsSpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board yields: https://www.total-fishing.com/forums/forum/fishing/sea-fishing/page/24/"""
<|body_0|>
def crawl_board_threads(self, respons... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TotalFishingReportsSpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board yields: https://www.total-fishing.com/forums/forum/fishing/sea-fishing/page/24/"""
assert isinstance(response, scrapy.http.response.html.HtmlResponse... | the_stack_v2_python_sparse | imgscrape/spiders/total_fishing.py | gmonkman/python | train | 0 |
abadff1a2a56eb06f28f63634569d01455d0dd32 | [
"def height(root):\n \"\"\"Return height of the tree if the tree is height-balanced,\n -1 if the tree is not height-balanced\"\"\"\n if not root:\n return 0\n left_height = height(root.left)\n if left_height == -1:\n return -1\n right_height = height(root.right)\n if right... | <|body_start_0|>
def height(root):
"""Return height of the tree if the tree is height-balanced,
-1 if the tree is not height-balanced"""
if not root:
return 0
left_height = height(root.left)
if left_height == -1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBalanced(self, root):
"""Bottom up approach, O(n) :type root: TreeNode :rtype: bool"""
<|body_0|>
def isBalanced1(self, root):
"""Top down approach, O(n^2)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def height(root):
... | stack_v2_sparse_classes_10k_train_002168 | 1,840 | no_license | [
{
"docstring": "Bottom up approach, O(n) :type root: TreeNode :rtype: bool",
"name": "isBalanced",
"signature": "def isBalanced(self, root)"
},
{
"docstring": "Top down approach, O(n^2)",
"name": "isBalanced1",
"signature": "def isBalanced1(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005293 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): Bottom up approach, O(n) :type root: TreeNode :rtype: bool
- def isBalanced1(self, root): Top down approach, O(n^2) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): Bottom up approach, O(n) :type root: TreeNode :rtype: bool
- def isBalanced1(self, root): Top down approach, O(n^2)
<|skeleton|>
class Solution:
... | b18786c06417a2781662805a7e0e984ee7fa5240 | <|skeleton|>
class Solution:
def isBalanced(self, root):
"""Bottom up approach, O(n) :type root: TreeNode :rtype: bool"""
<|body_0|>
def isBalanced1(self, root):
"""Top down approach, O(n^2)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isBalanced(self, root):
"""Bottom up approach, O(n) :type root: TreeNode :rtype: bool"""
def height(root):
"""Return height of the tree if the tree is height-balanced,
-1 if the tree is not height-balanced"""
if not root:
... | the_stack_v2_python_sparse | data_structures/110. Balanced Binary Tree.py | YuriiPaziuk/leetcode | train | 0 | |
eb5a3d1ef291a7fb31526610ba6d5a92dc0d3f84 | [
"self.np_shape = params['shape'][::-1]\nself.np_dtype = params['dtype']\nself.seed = params['seed']\nself.rng = np.random.default_rng(self.seed)",
"probabilities = [1.0 - settings.FLIP_PROBABILITY, settings.FLIP_PROBABILITY]\nrandom_flips = self.rng.choice([0, 1], p=probabilities, size=self.np_shape)\nrandom_flip... | <|body_start_0|>
self.np_shape = params['shape'][::-1]
self.np_dtype = params['dtype']
self.seed = params['seed']
self.rng = np.random.default_rng(self.seed)
<|end_body_0|>
<|body_start_1|>
probabilities = [1.0 - settings.FLIP_PROBABILITY, settings.FLIP_PROBABILITY]
rand... | Class to randomly generate input for RandomFlip media node. | RandomFlipFunction | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomFlipFunction:
"""Class to randomly generate input for RandomFlip media node."""
def __init__(self, params):
""":params params: random_flip_func specific params. shape: output shape dtype: output data type seed: seed to be used"""
<|body_0|>
def __call__(self):
... | stack_v2_sparse_classes_10k_train_002169 | 7,309 | permissive | [
{
"docstring": ":params params: random_flip_func specific params. shape: output shape dtype: output data type seed: seed to be used",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": ":returns : randomly generated binary output per image.",
"name": "__call__",
... | 2 | stack_v2_sparse_classes_30k_train_002069 | Implement the Python class `RandomFlipFunction` described below.
Class description:
Class to randomly generate input for RandomFlip media node.
Method signatures and docstrings:
- def __init__(self, params): :params params: random_flip_func specific params. shape: output shape dtype: output data type seed: seed to be... | Implement the Python class `RandomFlipFunction` described below.
Class description:
Class to randomly generate input for RandomFlip media node.
Method signatures and docstrings:
- def __init__(self, params): :params params: random_flip_func specific params. shape: output shape dtype: output data type seed: seed to be... | 3ca77c4a5fb62c60372e8a2839b1fccc3c4e4212 | <|skeleton|>
class RandomFlipFunction:
"""Class to randomly generate input for RandomFlip media node."""
def __init__(self, params):
""":params params: random_flip_func specific params. shape: output shape dtype: output data type seed: seed to be used"""
<|body_0|>
def __call__(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomFlipFunction:
"""Class to randomly generate input for RandomFlip media node."""
def __init__(self, params):
""":params params: random_flip_func specific params. shape: output shape dtype: output data type seed: seed to be used"""
self.np_shape = params['shape'][::-1]
self.np... | the_stack_v2_python_sparse | PyTorch/computer_vision/classification/torchvision/resnet_media_pipe.py | HabanaAI/Model-References | train | 108 |
e7adb7f8edc8346ad656326dcb8c75350924576b | [
"if hasattr(file, 'write'):\n file_ctx = nullcontext(file)\nelse:\n file_ctx = open(file, 'w')\nwith file_ctx as fp:\n for d in self:\n json.dump(d.dict(), fp)\n fp.write('\\n')",
"if hasattr(file, 'read'):\n file_ctx = nullcontext(file)\nelse:\n file_ctx = open(file)\nfrom ....docume... | <|body_start_0|>
if hasattr(file, 'write'):
file_ctx = nullcontext(file)
else:
file_ctx = open(file, 'w')
with file_ctx as fp:
for d in self:
json.dump(d.dict(), fp)
fp.write('\n')
<|end_body_0|>
<|body_start_1|>
if has... | Save/load a array into a JSON file. | JsonIOMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonIOMixin:
"""Save/load a array into a JSON file."""
def save_json(self, file: Union[str, TextIO]) -> None:
"""Save array elements into a JSON file. Comparing to :meth:`save_binary`, it is human-readable but slower to save/load and the file size larger. :param file: File or filenam... | stack_v2_sparse_classes_10k_train_002170 | 1,417 | permissive | [
{
"docstring": "Save array elements into a JSON file. Comparing to :meth:`save_binary`, it is human-readable but slower to save/load and the file size larger. :param file: File or filename to which the data is saved.",
"name": "save_json",
"signature": "def save_json(self, file: Union[str, TextIO]) -> N... | 2 | stack_v2_sparse_classes_30k_val_000202 | Implement the Python class `JsonIOMixin` described below.
Class description:
Save/load a array into a JSON file.
Method signatures and docstrings:
- def save_json(self, file: Union[str, TextIO]) -> None: Save array elements into a JSON file. Comparing to :meth:`save_binary`, it is human-readable but slower to save/lo... | Implement the Python class `JsonIOMixin` described below.
Class description:
Save/load a array into a JSON file.
Method signatures and docstrings:
- def save_json(self, file: Union[str, TextIO]) -> None: Save array elements into a JSON file. Comparing to :meth:`save_binary`, it is human-readable but slower to save/lo... | 34c34acfb0115ad2ec4cc8e2e9a86c521855612f | <|skeleton|>
class JsonIOMixin:
"""Save/load a array into a JSON file."""
def save_json(self, file: Union[str, TextIO]) -> None:
"""Save array elements into a JSON file. Comparing to :meth:`save_binary`, it is human-readable but slower to save/load and the file size larger. :param file: File or filenam... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JsonIOMixin:
"""Save/load a array into a JSON file."""
def save_json(self, file: Union[str, TextIO]) -> None:
"""Save array elements into a JSON file. Comparing to :meth:`save_binary`, it is human-readable but slower to save/load and the file size larger. :param file: File or filename to which th... | the_stack_v2_python_sparse | jina/types/arrays/mixins/io/json.py | amitesh1as/jina | train | 0 |
2389facaa4178096d6f98d80815317be2d66febc | [
"self.count = 0\nself.size = size\nself.array = []",
"if self.count == self.size:\n return False\nself.array.append(value)\nself.count += 1\nreturn True",
"if self.count == 0:\n return False\ndata = self.array[self.count - 1]\nself.count -= 1\nreturn data"
] | <|body_start_0|>
self.count = 0
self.size = size
self.array = []
<|end_body_0|>
<|body_start_1|>
if self.count == self.size:
return False
self.array.append(value)
self.count += 1
return True
<|end_body_1|>
<|body_start_2|>
if self.count == 0:... | stack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stack:
def __init__(self, size):
"""栈结构 :param size: 栈大小"""
<|body_0|>
def push(self, value):
"""入栈 入栈判满 :param value:"""
<|body_1|>
def pop(self):
"""出栈 出栈判空 :return:"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.count =... | stack_v2_sparse_classes_10k_train_002171 | 856 | no_license | [
{
"docstring": "栈结构 :param size: 栈大小",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": "入栈 入栈判满 :param value:",
"name": "push",
"signature": "def push(self, value)"
},
{
"docstring": "出栈 出栈判空 :return:",
"name": "pop",
"signature": "def pop(se... | 3 | null | Implement the Python class `stack` described below.
Class description:
Implement the stack class.
Method signatures and docstrings:
- def __init__(self, size): 栈结构 :param size: 栈大小
- def push(self, value): 入栈 入栈判满 :param value:
- def pop(self): 出栈 出栈判空 :return: | Implement the Python class `stack` described below.
Class description:
Implement the stack class.
Method signatures and docstrings:
- def __init__(self, size): 栈结构 :param size: 栈大小
- def push(self, value): 入栈 入栈判满 :param value:
- def pop(self): 出栈 出栈判空 :return:
<|skeleton|>
class stack:
def __init__(self, size)... | 7543af3cf09cc225626af78a44b185ecad52ac24 | <|skeleton|>
class stack:
def __init__(self, size):
"""栈结构 :param size: 栈大小"""
<|body_0|>
def push(self, value):
"""入栈 入栈判满 :param value:"""
<|body_1|>
def pop(self):
"""出栈 出栈判空 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class stack:
def __init__(self, size):
"""栈结构 :param size: 栈大小"""
self.count = 0
self.size = size
self.array = []
def push(self, value):
"""入栈 入栈判满 :param value:"""
if self.count == self.size:
return False
self.array.append(value)
self... | the_stack_v2_python_sparse | stack/array_stack.py | cpeixin/leetcode-bbbbrent | train | 0 | |
74fab9a531cb2a49dd4404f5fa3a50e8af9eb83f | [
"super().__init__(key, value)\nself.age = age\nself.freq = freq",
"self.value = value\nself.age = 0\nself.freq += 1"
] | <|body_start_0|>
super().__init__(key, value)
self.age = age
self.freq = freq
<|end_body_0|>
<|body_start_1|>
self.value = value
self.age = 0
self.freq += 1
<|end_body_1|>
| Least Frequently Used Inherits from CacheItem | LFUCacheItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCacheItem:
"""Least Frequently Used Inherits from CacheItem"""
def __init__(self, key, value, age, freq):
"""Constructor"""
<|body_0|>
def updateItem(self, value):
"""Update a cache item"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super()... | stack_v2_sparse_classes_10k_train_002172 | 3,562 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, key, value, age, freq)"
},
{
"docstring": "Update a cache item",
"name": "updateItem",
"signature": "def updateItem(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000988 | Implement the Python class `LFUCacheItem` described below.
Class description:
Least Frequently Used Inherits from CacheItem
Method signatures and docstrings:
- def __init__(self, key, value, age, freq): Constructor
- def updateItem(self, value): Update a cache item | Implement the Python class `LFUCacheItem` described below.
Class description:
Least Frequently Used Inherits from CacheItem
Method signatures and docstrings:
- def __init__(self, key, value, age, freq): Constructor
- def updateItem(self, value): Update a cache item
<|skeleton|>
class LFUCacheItem:
"""Least Frequ... | ece925eabc1d1e22055f1b4d3f052b571e1c4400 | <|skeleton|>
class LFUCacheItem:
"""Least Frequently Used Inherits from CacheItem"""
def __init__(self, key, value, age, freq):
"""Constructor"""
<|body_0|>
def updateItem(self, value):
"""Update a cache item"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LFUCacheItem:
"""Least Frequently Used Inherits from CacheItem"""
def __init__(self, key, value, age, freq):
"""Constructor"""
super().__init__(key, value)
self.age = age
self.freq = freq
def updateItem(self, value):
"""Update a cache item"""
self.valu... | the_stack_v2_python_sparse | 0x03-caching/100-lfu_cache.py | zacwoll/holbertonschool-web_back_end | train | 0 |
4891cd65025a677d4f9f1828be8222c27826e829 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jguerero_mgarcia7', 'jguerero_mgarcia7')\nnstats = repo['jguerero_mgarcia7.neighborhoodstatistics'].find()\nfoodscores = []\nincome = []\nobesity = []\nfor nb in nstats:\n foodscores.append(nb['FoodSc... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jguerero_mgarcia7', 'jguerero_mgarcia7')
nstats = repo['jguerero_mgarcia7.neighborhoodstatistics'].find()
foodscores = []
income = []
... | statisticsanalysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class statisticsanalysis:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing every... | stack_v2_sparse_classes_10k_train_002173 | 3,448 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_001059 | Implement the Python class `statisticsanalysis` described below.
Class description:
Implement the statisticsanalysis class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTi... | Implement the Python class `statisticsanalysis` described below.
Class description:
Implement the statisticsanalysis class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTi... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class statisticsanalysis:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing every... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class statisticsanalysis:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jguerero_mgarcia7', 'jguerero_mg... | the_stack_v2_python_sparse | jguerero_mgarcia7/statisticsanalysis.py | lingyigu/course-2017-spr-proj | train | 0 | |
24906ed6aa5b0f57be95b64f1c61cde5804d26b9 | [
"super().__init__(**kwargs)\nself.set(w_pad=mpl.rcParams['figure.constrained_layout.w_pad'], h_pad=mpl.rcParams['figure.constrained_layout.h_pad'], wspace=mpl.rcParams['figure.constrained_layout.wspace'], hspace=mpl.rcParams['figure.constrained_layout.hspace'], rect=(0, 0, 1, 1))\nself.set(w_pad=w_pad, h_pad=h_pad,... | <|body_start_0|>
super().__init__(**kwargs)
self.set(w_pad=mpl.rcParams['figure.constrained_layout.w_pad'], h_pad=mpl.rcParams['figure.constrained_layout.h_pad'], wspace=mpl.rcParams['figure.constrained_layout.wspace'], hspace=mpl.rcParams['figure.constrained_layout.hspace'], rect=(0, 0, 1, 1))
... | Implements the ``constrained_layout`` geometry management. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for details. | ConstrainedLayoutEngine | [
"CC0-1.0",
"BSD-3-Clause",
"MIT",
"Bitstream-Charter",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-bakoma-fonts-1995",
"LicenseRef-scancode-unknown-license-reference",
"OFL-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConstrainedLayoutEngine:
"""Implements the ``constrained_layout`` geometry management. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for details."""
def __init__(self, *, h_pad=None, w_pad=None, hspace=None, wspace=None, rect=(0, 0, 1, 1), compress=False, **kwargs):
"""I... | stack_v2_sparse_classes_10k_train_002174 | 11,335 | permissive | [
{
"docstring": "Initialize ``constrained_layout`` settings. Parameters ---------- h_pad, w_pad : float Padding around the axes elements in figure-normalized units. Default to :rc:`figure.constrained_layout.h_pad` and :rc:`figure.constrained_layout.w_pad`. hspace, wspace : float Fraction of the figure to dedicat... | 3 | stack_v2_sparse_classes_30k_train_000114 | Implement the Python class `ConstrainedLayoutEngine` described below.
Class description:
Implements the ``constrained_layout`` geometry management. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for details.
Method signatures and docstrings:
- def __init__(self, *, h_pad=None, w_pad=None, hspace=None, wsp... | Implement the Python class `ConstrainedLayoutEngine` described below.
Class description:
Implements the ``constrained_layout`` geometry management. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for details.
Method signatures and docstrings:
- def __init__(self, *, h_pad=None, w_pad=None, hspace=None, wsp... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class ConstrainedLayoutEngine:
"""Implements the ``constrained_layout`` geometry management. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for details."""
def __init__(self, *, h_pad=None, w_pad=None, hspace=None, wspace=None, rect=(0, 0, 1, 1), compress=False, **kwargs):
"""I... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConstrainedLayoutEngine:
"""Implements the ``constrained_layout`` geometry management. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for details."""
def __init__(self, *, h_pad=None, w_pad=None, hspace=None, wspace=None, rect=(0, 0, 1, 1), compress=False, **kwargs):
"""Initialize ``c... | the_stack_v2_python_sparse | contrib/python/matplotlib/py3/matplotlib/layout_engine.py | catboost/catboost | train | 8,012 |
3140a93642e1fd952585b8c9297c03ea08103cc7 | [
"self.check_parameters(params)\nct = np.cos(params[0] / 2)\nst = np.sin(params[0] / 2)\ncp = np.cos(params[1])\nsp = np.sin(params[1])\ncl = np.cos(params[2])\nsl = np.sin(params[2])\nel = cl + 1j * sl\nep = cp + 1j * sp\nreturn UnitaryMatrix([[ct, -el * st], [ep * st, ep * el * ct]])",
"self.check_parameters(par... | <|body_start_0|>
self.check_parameters(params)
ct = np.cos(params[0] / 2)
st = np.sin(params[0] / 2)
cp = np.cos(params[1])
sp = np.sin(params[1])
cl = np.cos(params[2])
sl = np.sin(params[2])
el = cl + 1j * sl
ep = cp + 1j * sp
return Unit... | The U3 single qubit gate. | U3Gate | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class U3Gate:
"""The U3 single qubit gate."""
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gate, see Unitary for more info."""
<|body_0|>
def get_grad(self, params: Sequence[float]=[]) -> np.ndarray:
"""Returns the... | stack_v2_sparse_classes_10k_train_002175 | 2,018 | permissive | [
{
"docstring": "Returns the unitary for this gate, see Unitary for more info.",
"name": "get_unitary",
"signature": "def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix"
},
{
"docstring": "Returns the gradient for this gate, see Gate for more info.",
"name": "get_grad",
"s... | 2 | stack_v2_sparse_classes_30k_train_006459 | Implement the Python class `U3Gate` described below.
Class description:
The U3 single qubit gate.
Method signatures and docstrings:
- def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix: Returns the unitary for this gate, see Unitary for more info.
- def get_grad(self, params: Sequence[float]=[]) -> np... | Implement the Python class `U3Gate` described below.
Class description:
The U3 single qubit gate.
Method signatures and docstrings:
- def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix: Returns the unitary for this gate, see Unitary for more info.
- def get_grad(self, params: Sequence[float]=[]) -> np... | 3083218c2f4e3c3ce4ba027d12caa30c384d7665 | <|skeleton|>
class U3Gate:
"""The U3 single qubit gate."""
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gate, see Unitary for more info."""
<|body_0|>
def get_grad(self, params: Sequence[float]=[]) -> np.ndarray:
"""Returns the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class U3Gate:
"""The U3 single qubit gate."""
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gate, see Unitary for more info."""
self.check_parameters(params)
ct = np.cos(params[0] / 2)
st = np.sin(params[0] / 2)
cp = ... | the_stack_v2_python_sparse | bqskit/ir/gates/parameterized/u3.py | mtreinish/bqskit | train | 0 |
c33da48d04c3066abe2a34f9221bfe650f78f30b | [
"if not heights:\n return 0\nleft_max = right_max = 0\nleft, right = (0, len(heights) - 1)\nwater_area = 0\nwhile left < right:\n if heights[left] < heights[right]:\n left_max = max(left_max, heights[left])\n water_area += left_max - heights[left]\n left += 1\n else:\n right_max... | <|body_start_0|>
if not heights:
return 0
left_max = right_max = 0
left, right = (0, len(heights) - 1)
water_area = 0
while left < right:
if heights[left] < heights[right]:
left_max = max(left_max, heights[left])
water_area ... | RainWater | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RainWater:
def total_area_trapped(self, heights: List[int]) -> int:
"""Approach: Two Pointers Optimized Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:"""
<|body_0|>
def total_area_trapped_(self, heights: List[int]) -> int:
"""Approach: Two Poin... | stack_v2_sparse_classes_10k_train_002176 | 1,847 | no_license | [
{
"docstring": "Approach: Two Pointers Optimized Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:",
"name": "total_area_trapped",
"signature": "def total_area_trapped(self, heights: List[int]) -> int"
},
{
"docstring": "Approach: Two Pointers Time Complexity: O(N) Space Comp... | 2 | null | Implement the Python class `RainWater` described below.
Class description:
Implement the RainWater class.
Method signatures and docstrings:
- def total_area_trapped(self, heights: List[int]) -> int: Approach: Two Pointers Optimized Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:
- def total_area... | Implement the Python class `RainWater` described below.
Class description:
Implement the RainWater class.
Method signatures and docstrings:
- def total_area_trapped(self, heights: List[int]) -> int: Approach: Two Pointers Optimized Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:
- def total_area... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class RainWater:
def total_area_trapped(self, heights: List[int]) -> int:
"""Approach: Two Pointers Optimized Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:"""
<|body_0|>
def total_area_trapped_(self, heights: List[int]) -> int:
"""Approach: Two Poin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RainWater:
def total_area_trapped(self, heights: List[int]) -> int:
"""Approach: Two Pointers Optimized Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:"""
if not heights:
return 0
left_max = right_max = 0
left, right = (0, len(heights) - 1)
... | the_stack_v2_python_sparse | expedia/trapping_rain_water.py | Shiv2157k/leet_code | train | 1 | |
753056788778b94cc1c2f831acb72d03330ee43a | [
"def memoize(i, j):\n if i == -1:\n return 0\n if j == -1:\n return 0\n if cache[i][j] != 0:\n return cache[i][j]\n if text1[i] == text2[j]:\n cache[i][j] = memoize(i - 1, j - 1) + 1\n return cache[i][j]\n else:\n cache[i][j] = max(memoize(i, j - 1), memoize(... | <|body_start_0|>
def memoize(i, j):
if i == -1:
return 0
if j == -1:
return 0
if cache[i][j] != 0:
return cache[i][j]
if text1[i] == text2[j]:
cache[i][j] = memoize(i - 1, j - 1) + 1
r... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""带备忘录的递归算法:自顶向下"""
<|body_0|>
def longestCommonSubsequence1(self, text1: str, text2: str) -> int:
"""状态转移方程: 1.Try dynamic programming. DP[i][j] represents the longest common subsequence o... | stack_v2_sparse_classes_10k_train_002177 | 4,039 | permissive | [
{
"docstring": "带备忘录的递归算法:自顶向下",
"name": "longestCommonSubsequence",
"signature": "def longestCommonSubsequence(self, text1: str, text2: str) -> int"
},
{
"docstring": "状态转移方程: 1.Try dynamic programming. DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. 2.DP[... | 3 | stack_v2_sparse_classes_30k_train_005341 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonSubsequence(self, text1: str, text2: str) -> int: 带备忘录的递归算法:自顶向下
- def longestCommonSubsequence1(self, text1: str, text2: str) -> int: 状态转移方程: 1.Try dynamic prog... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonSubsequence(self, text1: str, text2: str) -> int: 带备忘录的递归算法:自顶向下
- def longestCommonSubsequence1(self, text1: str, text2: str) -> int: 状态转移方程: 1.Try dynamic prog... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""带备忘录的递归算法:自顶向下"""
<|body_0|>
def longestCommonSubsequence1(self, text1: str, text2: str) -> int:
"""状态转移方程: 1.Try dynamic programming. DP[i][j] represents the longest common subsequence o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""带备忘录的递归算法:自顶向下"""
def memoize(i, j):
if i == -1:
return 0
if j == -1:
return 0
if cache[i][j] != 0:
return cache[i][j]
... | the_stack_v2_python_sparse | 1143-longest-common-subsequence.py | yuenliou/leetcode | train | 0 | |
fe53b5ab6aaacdafae2d2d97b37f545b51b62eac | [
"self.jsonService = JsonService()\nself.dataFrame = pandas.read_csv(csvFile)\nself.dataFrame.dropna(inplace=True)",
"properties = dict()\nfor index, row in self.dataFrame.iterrows():\n func(properties, row)\nprint(properties)\nself.jsonService.save(jsonFile, properties)"
] | <|body_start_0|>
self.jsonService = JsonService()
self.dataFrame = pandas.read_csv(csvFile)
self.dataFrame.dropna(inplace=True)
<|end_body_0|>
<|body_start_1|>
properties = dict()
for index, row in self.dataFrame.iterrows():
func(properties, row)
print(proper... | 处理 CSV 文件为 JSON 文件 | CsvHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CsvHandler:
"""处理 CSV 文件为 JSON 文件"""
def __init__(self, csvFile):
"""初始化 新建对象时默认执行 参数值: csvFile (str): 要读取的 CSV 文件"""
<|body_0|>
def operate(self, func, jsonFile):
"""处理 CSV 文件为 JSON 文件 参数值: func (func(dict, row)): 处理规则函数 函数参数要求: dict(dict): JSON 文件格式 row(pandas.... | stack_v2_sparse_classes_10k_train_002178 | 2,353 | no_license | [
{
"docstring": "初始化 新建对象时默认执行 参数值: csvFile (str): 要读取的 CSV 文件",
"name": "__init__",
"signature": "def __init__(self, csvFile)"
},
{
"docstring": "处理 CSV 文件为 JSON 文件 参数值: func (func(dict, row)): 处理规则函数 函数参数要求: dict(dict): JSON 文件格式 row(pandas.series): CSV 文件的每一列 jsonFile (str): 要存储为的 JSON 文件",
... | 2 | stack_v2_sparse_classes_30k_train_002135 | Implement the Python class `CsvHandler` described below.
Class description:
处理 CSV 文件为 JSON 文件
Method signatures and docstrings:
- def __init__(self, csvFile): 初始化 新建对象时默认执行 参数值: csvFile (str): 要读取的 CSV 文件
- def operate(self, func, jsonFile): 处理 CSV 文件为 JSON 文件 参数值: func (func(dict, row)): 处理规则函数 函数参数要求: dict(dict): ... | Implement the Python class `CsvHandler` described below.
Class description:
处理 CSV 文件为 JSON 文件
Method signatures and docstrings:
- def __init__(self, csvFile): 初始化 新建对象时默认执行 参数值: csvFile (str): 要读取的 CSV 文件
- def operate(self, func, jsonFile): 处理 CSV 文件为 JSON 文件 参数值: func (func(dict, row)): 处理规则函数 函数参数要求: dict(dict): ... | 105caf2288435c50ae693ff12a0e4e72822587d6 | <|skeleton|>
class CsvHandler:
"""处理 CSV 文件为 JSON 文件"""
def __init__(self, csvFile):
"""初始化 新建对象时默认执行 参数值: csvFile (str): 要读取的 CSV 文件"""
<|body_0|>
def operate(self, func, jsonFile):
"""处理 CSV 文件为 JSON 文件 参数值: func (func(dict, row)): 处理规则函数 函数参数要求: dict(dict): JSON 文件格式 row(pandas.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CsvHandler:
"""处理 CSV 文件为 JSON 文件"""
def __init__(self, csvFile):
"""初始化 新建对象时默认执行 参数值: csvFile (str): 要读取的 CSV 文件"""
self.jsonService = JsonService()
self.dataFrame = pandas.read_csv(csvFile)
self.dataFrame.dropna(inplace=True)
def operate(self, func, jsonFile):
... | the_stack_v2_python_sparse | CsvHandler.py | YuanLinStudio/Inspection-Record-Consolidating-System | train | 0 |
585a4d6d52098f9d0570a0a72042a5a95108d28d | [
"if len(height) < 2:\n return 0\nn = len(height)\nmax_area = 0\nfor i in range(n - 1):\n for j in range(i + 1, n):\n area = (j - i) * min(height[i], height[j])\n max_area = max(area, max_area)\nreturn max_area",
"n = len(height)\ni, j = (0, n - 1)\nmax_area = 0\nwhile i < j:\n max_area = ma... | <|body_start_0|>
if len(height) < 2:
return 0
n = len(height)
max_area = 0
for i in range(n - 1):
for j in range(i + 1, n):
area = (j - i) * min(height[i], height[j])
max_area = max(area, max_area)
return max_area
<|end_body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea1(self, height):
"""用左右两个指针,求最大面积, 即 max((i-j)*min(height[i],height[j])),"""
<|body_1|>
def maxArea2(self, height):
"""除了两端的指针,中间的, 长度都变短了,因此只有当中... | stack_v2_sparse_classes_10k_train_002179 | 1,656 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
},
{
"docstring": "用左右两个指针,求最大面积, 即 max((i-j)*min(height[i],height[j])),",
"name": "maxArea1",
"signature": "def maxArea1(self, height)"
},
{
"docstring": "除了两端的指针,中间... | 3 | stack_v2_sparse_classes_30k_train_003054 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height): :type height: List[int] :rtype: int
- def maxArea1(self, height): 用左右两个指针,求最大面积, 即 max((i-j)*min(height[i],height[j])),
- def maxArea2(self, height): 除... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height): :type height: List[int] :rtype: int
- def maxArea1(self, height): 用左右两个指针,求最大面积, 即 max((i-j)*min(height[i],height[j])),
- def maxArea2(self, height): 除... | 11ad9d3841de09c0b4dc3a667e7e63c3558656a5 | <|skeleton|>
class Solution:
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea1(self, height):
"""用左右两个指针,求最大面积, 即 max((i-j)*min(height[i],height[j])),"""
<|body_1|>
def maxArea2(self, height):
"""除了两端的指针,中间的, 长度都变短了,因此只有当中... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
if len(height) < 2:
return 0
n = len(height)
max_area = 0
for i in range(n - 1):
for j in range(i + 1, n):
area = (j - i) * min(height[i], height[j])
... | the_stack_v2_python_sparse | container-with-most-water.py | ganlanshu/leetcode | train | 0 | |
363a45c6bf1ab508861ef94dedc9776eb690ebd1 | [
"self._scenario = []\nself._approaches = []\nself._approaches.append(PatApproach())\nself._approaches.append(MatApproach())\nself._approaches.append(MaxApproach())\nself._approaches.append(PacApproach())",
"scenario_file = open(scenario_file_name)\nfor current_line in scenario_file:\n new_customer = Customer(c... | <|body_start_0|>
self._scenario = []
self._approaches = []
self._approaches.append(PatApproach())
self._approaches.append(MatApproach())
self._approaches.append(MaxApproach())
self._approaches.append(PacApproach())
<|end_body_0|>
<|body_start_1|>
scenario_file = ... | A Simulator. This class represents the simulator which initiates different approaches, load scenario from the file, and call restaurant function for new customer arrivals and at each turn. Of course, you may add whatever private attributes and methods you want. But because you should not change the interface, you may n... | Simulator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulator:
"""A Simulator. This class represents the simulator which initiates different approaches, load scenario from the file, and call restaurant function for new customer arrivals and at each turn. Of course, you may add whatever private attributes and methods you want. But because you shoul... | stack_v2_sparse_classes_10k_train_002180 | 4,220 | no_license | [
{
"docstring": "Initialize a Simulation.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Load a scenario from the scenario_file_name and store it in _scenario :param scenario_file_name: Name of the scenario file :type scenario_file_name: str :rtype: None",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_006250 | Implement the Python class `Simulator` described below.
Class description:
A Simulator. This class represents the simulator which initiates different approaches, load scenario from the file, and call restaurant function for new customer arrivals and at each turn. Of course, you may add whatever private attributes and ... | Implement the Python class `Simulator` described below.
Class description:
A Simulator. This class represents the simulator which initiates different approaches, load scenario from the file, and call restaurant function for new customer arrivals and at each turn. Of course, you may add whatever private attributes and ... | 2b9312b30171686f1bb08f4052edd8c748cf848f | <|skeleton|>
class Simulator:
"""A Simulator. This class represents the simulator which initiates different approaches, load scenario from the file, and call restaurant function for new customer arrivals and at each turn. Of course, you may add whatever private attributes and methods you want. But because you shoul... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Simulator:
"""A Simulator. This class represents the simulator which initiates different approaches, load scenario from the file, and call restaurant function for new customer arrivals and at each turn. Of course, you may add whatever private attributes and methods you want. But because you should not change ... | the_stack_v2_python_sparse | Assignments/a1/simulator.py | Lost-Accountant/csc148_2016_s | train | 0 |
a3c337ea4b88cf59c96679c27be64b5d67581014 | [
"if 'airportdProcessDLILEvent' in action:\n network_interface = text.split()[0]\n return 'Interface {0:s} turn up.'.format(network_interface)\nif 'doAutoJoin' in action:\n match = self._CONNECTED_RE.match(text)\n if match:\n ssid = match.group(1)[1:-1]\n else:\n ssid = 'Unknown'\n re... | <|body_start_0|>
if 'airportdProcessDLILEvent' in action:
network_interface = text.split()[0]
return 'Interface {0:s} turn up.'.format(network_interface)
if 'doAutoJoin' in action:
match = self._CONNECTED_RE.match(text)
if match:
ssid = mat... | Text parser plugin MacOS Wi-Fi log (wifi.log) files. | MacOSWiFiLogTextPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MacOSWiFiLogTextPlugin:
"""Text parser plugin MacOS Wi-Fi log (wifi.log) files."""
def _GetAction(self, action, text):
"""Parse the well known actions for easy reading. Args: action (str): the function or action called by the agent. text (str): text from a log line. Returns: str: a f... | stack_v2_sparse_classes_10k_train_002181 | 9,805 | permissive | [
{
"docstring": "Parse the well known actions for easy reading. Args: action (str): the function or action called by the agent. text (str): text from a log line. Returns: str: a formatted string representing the known (or common) action. If the action is not known the original log text is returned.",
"name":... | 4 | stack_v2_sparse_classes_30k_train_005406 | Implement the Python class `MacOSWiFiLogTextPlugin` described below.
Class description:
Text parser plugin MacOS Wi-Fi log (wifi.log) files.
Method signatures and docstrings:
- def _GetAction(self, action, text): Parse the well known actions for easy reading. Args: action (str): the function or action called by the a... | Implement the Python class `MacOSWiFiLogTextPlugin` described below.
Class description:
Text parser plugin MacOS Wi-Fi log (wifi.log) files.
Method signatures and docstrings:
- def _GetAction(self, action, text): Parse the well known actions for easy reading. Args: action (str): the function or action called by the a... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class MacOSWiFiLogTextPlugin:
"""Text parser plugin MacOS Wi-Fi log (wifi.log) files."""
def _GetAction(self, action, text):
"""Parse the well known actions for easy reading. Args: action (str): the function or action called by the agent. text (str): text from a log line. Returns: str: a f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MacOSWiFiLogTextPlugin:
"""Text parser plugin MacOS Wi-Fi log (wifi.log) files."""
def _GetAction(self, action, text):
"""Parse the well known actions for easy reading. Args: action (str): the function or action called by the agent. text (str): text from a log line. Returns: str: a formatted stri... | the_stack_v2_python_sparse | plaso/parsers/text_plugins/macos_wifi.py | log2timeline/plaso | train | 1,506 |
80389afa393eb20ebc3429fcae5962fffb1f7523 | [
"self.name = name\nself.kernel_regularizer = kernel_regularizer\nself.bias_regularizer = bias_regularizer",
"func_name = 'get_critic_logits'\nnetwork = X\nprint_obj('\\n' + func_name, 'network', network)\nwith tf.variable_scope('critic', reuse=tf.AUTO_REUSE):\n for i in range(len(params['critic_num_filters']))... | <|body_start_0|>
self.name = name
self.kernel_regularizer = kernel_regularizer
self.bias_regularizer = bias_regularizer
<|end_body_0|>
<|body_start_1|>
func_name = 'get_critic_logits'
network = X
print_obj('\n' + func_name, 'network', network)
with tf.variable_sc... | Critic that takes image input and outputs logits. Fields: name: str, name of `Critic`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables. | Critic | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Critic:
"""Critic that takes image input and outputs logits. Fields: name: str, name of `Critic`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables."""
def __init__(self, kernel_regul... | stack_v2_sparse_classes_10k_train_002182 | 6,232 | permissive | [
{
"docstring": "Instantiates and builds critic network. Args: kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables. name: str, name of critic.",
"name": "__init__",
"signature": "def __init__(self, ... | 3 | stack_v2_sparse_classes_30k_train_000875 | Implement the Python class `Critic` described below.
Class description:
Critic that takes image input and outputs logits. Fields: name: str, name of `Critic`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables.
... | Implement the Python class `Critic` described below.
Class description:
Critic that takes image input and outputs logits. Fields: name: str, name of `Critic`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables.
... | f7c21af221f366b075d351deeeb00a1b266ac3e3 | <|skeleton|>
class Critic:
"""Critic that takes image input and outputs logits. Fields: name: str, name of `Critic`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables."""
def __init__(self, kernel_regul... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Critic:
"""Critic that takes image input and outputs logits. Fields: name: str, name of `Critic`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables."""
def __init__(self, kernel_regularizer, bias_... | the_stack_v2_python_sparse | machine_learning/gan/wgan/tf_wgan/wgan_module/trainer/critic.py | ryangillard/artificial_intelligence | train | 4 |
87bd5b6aa00433aa56a83a0ca2e03b02c93e1ac9 | [
"self.astar_fore = AStarLookup(grid, start, goal)\nself.astar_back = AStarLookup(grid, goal, start)\nself.expanded_nodes = 0\nself.len_optimal = 0",
"while not self.astar_fore.is_found and (not self.astar_back.is_found):\n self.astar_fore.next_move(self.astar_back.best)\n if self.astar_fore.is_found:\n ... | <|body_start_0|>
self.astar_fore = AStarLookup(grid, start, goal)
self.astar_back = AStarLookup(grid, goal, start)
self.expanded_nodes = 0
self.len_optimal = 0
<|end_body_0|>
<|body_start_1|>
while not self.astar_fore.is_found and (not self.astar_back.is_found):
self... | ============================================================================ Description: Bi-Directional A* (one turn each direction). ============================================================================ | AStarBi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AStarBi:
"""============================================================================ Description: Bi-Directional A* (one turn each direction). ============================================================================"""
def __init__(self, grid, start, goal):
"""===============... | stack_v2_sparse_classes_10k_train_002183 | 2,415 | no_license | [
{
"docstring": "======================================================================== Description: Constructor (inits the attributes). ======================================================================== Arguments: ------------------------------------------------------------------------ 1. grid : Grid. 2... | 3 | stack_v2_sparse_classes_30k_train_001162 | Implement the Python class `AStarBi` described below.
Class description:
============================================================================ Description: Bi-Directional A* (one turn each direction). ============================================================================
Method signatures and docstrings:... | Implement the Python class `AStarBi` described below.
Class description:
============================================================================ Description: Bi-Directional A* (one turn each direction). ============================================================================
Method signatures and docstrings:... | ef4d6218bc48d3c988f287187e6e3feec05d88cd | <|skeleton|>
class AStarBi:
"""============================================================================ Description: Bi-Directional A* (one turn each direction). ============================================================================"""
def __init__(self, grid, start, goal):
"""===============... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AStarBi:
"""============================================================================ Description: Bi-Directional A* (one turn each direction). ============================================================================"""
def __init__(self, grid, start, goal):
"""============================... | the_stack_v2_python_sparse | f_astar/c_astar_bi.py | valdas1966/old | train | 0 |
7b65bc3832a6c0ace5648b876ebb266aa31ece16 | [
"data = self.get_json()\ngroup_id = int(group_id)\nstream_id = data.get('stream_id')\nwith self.Session() as session:\n group = session.scalars(Group.select(session.user_or_token, mode='update').where(Group.id == group_id)).first()\n if group is None:\n return self.error(f'Group with ID {group_id} not ... | <|body_start_0|>
data = self.get_json()
group_id = int(group_id)
stream_id = data.get('stream_id')
with self.Session() as session:
group = session.scalars(Group.select(session.user_or_token, mode='update').where(Group.id == group_id)).first()
if group is None:
... | GroupStreamHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupStreamHandler:
def post(self, group_id, *ignored_args):
"""--- description: Add alert stream access to group tags: - groups - streams parameters: - in: path name: group_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: s... | stack_v2_sparse_classes_10k_train_002184 | 31,492 | permissive | [
{
"docstring": "--- description: Add alert stream access to group tags: - groups - streams parameters: - in: path name: group_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: stream_id: type: integer required: - stream_id responses: 200: content: a... | 2 | null | Implement the Python class `GroupStreamHandler` described below.
Class description:
Implement the GroupStreamHandler class.
Method signatures and docstrings:
- def post(self, group_id, *ignored_args): --- description: Add alert stream access to group tags: - groups - streams parameters: - in: path name: group_id requ... | Implement the Python class `GroupStreamHandler` described below.
Class description:
Implement the GroupStreamHandler class.
Method signatures and docstrings:
- def post(self, group_id, *ignored_args): --- description: Add alert stream access to group tags: - groups - streams parameters: - in: path name: group_id requ... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class GroupStreamHandler:
def post(self, group_id, *ignored_args):
"""--- description: Add alert stream access to group tags: - groups - streams parameters: - in: path name: group_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GroupStreamHandler:
def post(self, group_id, *ignored_args):
"""--- description: Add alert stream access to group tags: - groups - streams parameters: - in: path name: group_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: stream_id: type... | the_stack_v2_python_sparse | skyportal/handlers/api/group.py | skyportal/skyportal | train | 80 | |
34b4a13545849ab09324a47ee16889cd2f7ca3e3 | [
"self._variables = parameters\nassert len(self._variables) > 0\nself._prev_variables = [nn.Parameter(v.clone(), requires_grad=False) for v in parameters]",
"def _adjust_step(ratio):\n r = 0.9 / ratio\n for var, prev_var in zip(self._variables, self._prev_variables):\n var.data.copy_(prev_var + r * (v... | <|body_start_0|>
self._variables = parameters
assert len(self._variables) > 0
self._prev_variables = [nn.Parameter(v.clone(), requires_grad=False) for v in parameters]
<|end_body_0|>
<|body_start_1|>
def _adjust_step(ratio):
r = 0.9 / ratio
for var, prev_var in z... | Adjust variables based on the change calculated by `change_f()` The motivation is that if some quatity changes too much after an SGD update, the SGD step might be too big. We want to shink that step so that the concerned quatity does not change too much. We can also monitor multiple quantities to make sure none of them... | TrustedUpdater | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrustedUpdater:
"""Adjust variables based on the change calculated by `change_f()` The motivation is that if some quatity changes too much after an SGD update, the SGD step might be too big. We want to shink that step so that the concerned quatity does not change too much. We can also monitor mul... | stack_v2_sparse_classes_10k_train_002185 | 3,836 | permissive | [
{
"docstring": "Create a TrustedUpdater instance. Args: parameters (list[Parameter]): parameters to be monitored.",
"name": "__init__",
"signature": "def __init__(self, parameters)"
},
{
"docstring": "Adjust `parameters` based change calculated by change_f This function will copy the new values ... | 2 | null | Implement the Python class `TrustedUpdater` described below.
Class description:
Adjust variables based on the change calculated by `change_f()` The motivation is that if some quatity changes too much after an SGD update, the SGD step might be too big. We want to shink that step so that the concerned quatity does not c... | Implement the Python class `TrustedUpdater` described below.
Class description:
Adjust variables based on the change calculated by `change_f()` The motivation is that if some quatity changes too much after an SGD update, the SGD step might be too big. We want to shink that step so that the concerned quatity does not c... | b00ff2fa5e660de31020338ba340263183fbeaa4 | <|skeleton|>
class TrustedUpdater:
"""Adjust variables based on the change calculated by `change_f()` The motivation is that if some quatity changes too much after an SGD update, the SGD step might be too big. We want to shink that step so that the concerned quatity does not change too much. We can also monitor mul... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TrustedUpdater:
"""Adjust variables based on the change calculated by `change_f()` The motivation is that if some quatity changes too much after an SGD update, the SGD step might be too big. We want to shink that step so that the concerned quatity does not change too much. We can also monitor multiple quantit... | the_stack_v2_python_sparse | alf/optimizers/trusted_updater.py | HorizonRobotics/alf | train | 288 |
c35f6c3aedd55265c652655f14298b9df65a1a4d | [
"if not root:\n return []\nret = []\nq = [root]\nwhile q:\n tmp = q.pop(0)\n if tmp:\n ret.append(tmp.val)\n q.append(tmp.left)\n q.append(tmp.right)\n else:\n ret.append(None)\nwhile ret[-1] == None:\n ret.pop()\nreturn ret",
"if not data:\n return None\nroot = data.... | <|body_start_0|>
if not root:
return []
ret = []
q = [root]
while q:
tmp = q.pop(0)
if tmp:
ret.append(tmp.val)
q.append(tmp.left)
q.append(tmp.right)
else:
ret.append(None)
... | 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_10k_train_002186 | 1,530 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | c343ad45403d5f7f947abc9a82447d593c4938bc | <|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_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
ret = []
q = [root]
while q:
tmp = q.pop(0)
if tmp:
ret.append(tmp.val)
... | the_stack_v2_python_sparse | 297 Serialize and Deserialize Binary Tree/untitled.py | fangpings/Leetcode | train | 0 | |
f4f5b161af6b1f333d58687b1265ba6b5c90fa49 | [
"for doc_index, document in enumerate(self.document_store):\n target_length = self.target_length()\n tokenized_sentences = (self.tokenizer.tokenize(sentence) for sentence in document)\n segment_pairs = language_model_functions.split_document(tokenized_sentences, target_length)\n random_segments = self.g... | <|body_start_0|>
for doc_index, document in enumerate(self.document_store):
target_length = self.target_length()
tokenized_sentences = (self.tokenizer.tokenize(sentence) for sentence in document)
segment_pairs = language_model_functions.split_document(tokenized_sentences, tar... | The Language Model Dataset generates training batches from the document store. Please note that the process of generating samples from documents is stochastic (in consequences, most of the logic is detached to the `language_model_functions` module). Shuffle data after each epoch is not available. Along with three well-... | LanguageModelDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageModelDataset:
"""The Language Model Dataset generates training batches from the document store. Please note that the process of generating samples from documents is stochastic (in consequences, most of the logic is detached to the `language_model_functions` module). Shuffle data after eac... | stack_v2_sparse_classes_10k_train_002187 | 9,406 | permissive | [
{
"docstring": "The generator produces language model examples. It is equivalent to the single function from Google BERT's or HuggingFace repo. It can be easily adjust to the parallel processing (e.g. using queues).",
"name": "examples_generator",
"signature": "def examples_generator(self) -> Iterable[L... | 4 | stack_v2_sparse_classes_30k_train_002895 | Implement the Python class `LanguageModelDataset` described below.
Class description:
The Language Model Dataset generates training batches from the document store. Please note that the process of generating samples from documents is stochastic (in consequences, most of the logic is detached to the `language_model_fun... | Implement the Python class `LanguageModelDataset` described below.
Class description:
The Language Model Dataset generates training batches from the document store. Please note that the process of generating samples from documents is stochastic (in consequences, most of the logic is detached to the `language_model_fun... | 1e2d57277b33778309131e69b69ead7afbd0dd59 | <|skeleton|>
class LanguageModelDataset:
"""The Language Model Dataset generates training batches from the document store. Please note that the process of generating samples from documents is stochastic (in consequences, most of the logic is detached to the `language_model_functions` module). Shuffle data after eac... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LanguageModelDataset:
"""The Language Model Dataset generates training batches from the document store. Please note that the process of generating samples from documents is stochastic (in consequences, most of the logic is detached to the `language_model_functions` module). Shuffle data after each epoch is no... | the_stack_v2_python_sparse | aspect_based_sentiment_analysis/training/datasets/language_model.py | lavanaythakral/Aspect-Based-Sentiment-Analysis | train | 1 |
9c9858688c11fd8449d1ba76dda49f5e2dd41678 | [
"cur_x = 1\nans_list = set()\nwhile cur_x <= bound:\n cur_y = 1\n temp = cur_x + cur_y\n while temp <= bound:\n ans_list.add(temp)\n cur_y *= y\n temp = cur_x + cur_y\n if cur_y == 1:\n break\n cur_x *= x\n if cur_x == 1:\n break\nreturn list(ans_list)",
... | <|body_start_0|>
cur_x = 1
ans_list = set()
while cur_x <= bound:
cur_y = 1
temp = cur_x + cur_y
while temp <= bound:
ans_list.add(temp)
cur_y *= y
temp = cur_x + cur_y
if cur_y == 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def powerfulIntegers(self, x, y, bound):
""":type x: int :type y: int :type bound: int :rtype: List[int] 32 ms 11.7 MB"""
<|body_0|>
def powerfulIntegers_1(self, x, y, bound):
"""24 ms 12 MB :param x: :param y: :param bound: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_002188 | 2,220 | no_license | [
{
"docstring": ":type x: int :type y: int :type bound: int :rtype: List[int] 32 ms 11.7 MB",
"name": "powerfulIntegers",
"signature": "def powerfulIntegers(self, x, y, bound)"
},
{
"docstring": "24 ms 12 MB :param x: :param y: :param bound: :return:",
"name": "powerfulIntegers_1",
"signa... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def powerfulIntegers(self, x, y, bound): :type x: int :type y: int :type bound: int :rtype: List[int] 32 ms 11.7 MB
- def powerfulIntegers_1(self, x, y, bound): 24 ms 12 MB :para... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def powerfulIntegers(self, x, y, bound): :type x: int :type y: int :type bound: int :rtype: List[int] 32 ms 11.7 MB
- def powerfulIntegers_1(self, x, y, bound): 24 ms 12 MB :para... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def powerfulIntegers(self, x, y, bound):
""":type x: int :type y: int :type bound: int :rtype: List[int] 32 ms 11.7 MB"""
<|body_0|>
def powerfulIntegers_1(self, x, y, bound):
"""24 ms 12 MB :param x: :param y: :param bound: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def powerfulIntegers(self, x, y, bound):
""":type x: int :type y: int :type bound: int :rtype: List[int] 32 ms 11.7 MB"""
cur_x = 1
ans_list = set()
while cur_x <= bound:
cur_y = 1
temp = cur_x + cur_y
while temp <= bound:
... | the_stack_v2_python_sparse | PowerfulIntegers_970.py | 953250587/leetcode-python | train | 2 | |
7f48e77790dac742ac97cb74d9eb4a7b17f2cfcb | [
"self.client_id = client_id\nself.is_worm_enabled = is_worm_enabled\nself.storage_access_key = storage_access_key\nself.storage_account_name = storage_account_name\nself.tier_type = tier_type\nself.tiers = tiers",
"if dictionary is None:\n return None\nclient_id = dictionary.get('clientId')\nis_worm_enabled = ... | <|body_start_0|>
self.client_id = client_id
self.is_worm_enabled = is_worm_enabled
self.storage_access_key = storage_access_key
self.storage_account_name = storage_account_name
self.tier_type = tier_type
self.tiers = tiers
<|end_body_0|>
<|body_start_1|>
if dicti... | Implementation of the 'AzureCloudCredentials' model. Specifies the cloud credentials to connect to a Microsoft Azure service account. Attributes: client_id (string): Specifies the client id of the managed identity assigned to the cluster. This is used only for clusters running as Azure VMs where authentication is done ... | AzureCloudCredentials | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AzureCloudCredentials:
"""Implementation of the 'AzureCloudCredentials' model. Specifies the cloud credentials to connect to a Microsoft Azure service account. Attributes: client_id (string): Specifies the client id of the managed identity assigned to the cluster. This is used only for clusters r... | stack_v2_sparse_classes_10k_train_002189 | 3,634 | permissive | [
{
"docstring": "Constructor for the AzureCloudCredentials class",
"name": "__init__",
"signature": "def __init__(self, client_id=None, is_worm_enabled=None, storage_access_key=None, storage_account_name=None, tier_type=None, tiers=None)"
},
{
"docstring": "Creates an instance of this model from ... | 2 | null | Implement the Python class `AzureCloudCredentials` described below.
Class description:
Implementation of the 'AzureCloudCredentials' model. Specifies the cloud credentials to connect to a Microsoft Azure service account. Attributes: client_id (string): Specifies the client id of the managed identity assigned to the cl... | Implement the Python class `AzureCloudCredentials` described below.
Class description:
Implementation of the 'AzureCloudCredentials' model. Specifies the cloud credentials to connect to a Microsoft Azure service account. Attributes: client_id (string): Specifies the client id of the managed identity assigned to the cl... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AzureCloudCredentials:
"""Implementation of the 'AzureCloudCredentials' model. Specifies the cloud credentials to connect to a Microsoft Azure service account. Attributes: client_id (string): Specifies the client id of the managed identity assigned to the cluster. This is used only for clusters r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AzureCloudCredentials:
"""Implementation of the 'AzureCloudCredentials' model. Specifies the cloud credentials to connect to a Microsoft Azure service account. Attributes: client_id (string): Specifies the client id of the managed identity assigned to the cluster. This is used only for clusters running as Azu... | the_stack_v2_python_sparse | cohesity_management_sdk/models/azure_cloud_credentials.py | cohesity/management-sdk-python | train | 24 |
54af25741b68793d7e1de649df2f4d3af29fe226 | [
"if not len(result.affected_code) > 0:\n return 'The result is not associated with any source code.'\nfilenames = set((src.renamed_file(file_diff_dict) for src in result.affected_code))\nif not all((exists(filename) for filename in filenames)):\n return \"The result is associated with source code that doesn't... | <|body_start_0|>
if not len(result.affected_code) > 0:
return 'The result is not associated with any source code.'
filenames = set((src.renamed_file(file_diff_dict) for src in result.affected_code))
if not all((exists(filename) for filename in filenames)):
return "The res... | OpenEditorAction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenEditorAction:
def is_applicable(result: Result, original_file_dict, file_diff_dict):
"""For being applicable, the result has to point to a number of files that have to exist i.e. have not been previously deleted."""
<|body_0|>
def build_editor_call_args(self, editor, edi... | stack_v2_sparse_classes_10k_train_002190 | 6,600 | no_license | [
{
"docstring": "For being applicable, the result has to point to a number of files that have to exist i.e. have not been previously deleted.",
"name": "is_applicable",
"signature": "def is_applicable(result: Result, original_file_dict, file_diff_dict)"
},
{
"docstring": "Create argument list whi... | 3 | stack_v2_sparse_classes_30k_train_003332 | Implement the Python class `OpenEditorAction` described below.
Class description:
Implement the OpenEditorAction class.
Method signatures and docstrings:
- def is_applicable(result: Result, original_file_dict, file_diff_dict): For being applicable, the result has to point to a number of files that have to exist i.e. ... | Implement the Python class `OpenEditorAction` described below.
Class description:
Implement the OpenEditorAction class.
Method signatures and docstrings:
- def is_applicable(result: Result, original_file_dict, file_diff_dict): For being applicable, the result has to point to a number of files that have to exist i.e. ... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class OpenEditorAction:
def is_applicable(result: Result, original_file_dict, file_diff_dict):
"""For being applicable, the result has to point to a number of files that have to exist i.e. have not been previously deleted."""
<|body_0|>
def build_editor_call_args(self, editor, edi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OpenEditorAction:
def is_applicable(result: Result, original_file_dict, file_diff_dict):
"""For being applicable, the result has to point to a number of files that have to exist i.e. have not been previously deleted."""
if not len(result.affected_code) > 0:
return 'The result is no... | the_stack_v2_python_sparse | python/coala_coala/coala-master/coalib/results/result_actions/OpenEditorAction.py | LiuFang816/SALSTM_py_data | train | 10 | |
5e0500a0baf8f21e6e2408375874c8d7c28b631a | [
"import ray\nself.args = (function_name, traceback_str, cause, proctitle, pid, ip)\nif proctitle:\n self.proctitle = proctitle\nelse:\n self.proctitle = setproctitle.getproctitle()\nself.pid = pid or os.getpid()\nself.ip = ip or ray.util.get_node_ip_address()\nself.function_name = function_name\nself.tracebac... | <|body_start_0|>
import ray
self.args = (function_name, traceback_str, cause, proctitle, pid, ip)
if proctitle:
self.proctitle = proctitle
else:
self.proctitle = setproctitle.getproctitle()
self.pid = pid or os.getpid()
self.ip = ip or ray.util.get... | Indicates that a task threw an exception during execution. If a task throws an exception during execution, a RayTaskError is stored in the object store for each of the task's outputs. When an object is retrieved from the object store, the Python method that retrieved it checks to see if the object is a RayTaskError and... | RayTaskError | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RayTaskError:
"""Indicates that a task threw an exception during execution. If a task throws an exception during execution, a RayTaskError is stored in the object store for each of the task's outputs. When an object is retrieved from the object store, the Python method that retrieved it checks to... | stack_v2_sparse_classes_10k_train_002191 | 23,872 | permissive | [
{
"docstring": "Initialize a RayTaskError.",
"name": "__init__",
"signature": "def __init__(self, function_name, traceback_str, cause, proctitle=None, pid=None, ip=None, actor_repr=None, actor_id=None)"
},
{
"docstring": "Returns an exception that is an instance of the cause's class. The returne... | 3 | null | Implement the Python class `RayTaskError` described below.
Class description:
Indicates that a task threw an exception during execution. If a task throws an exception during execution, a RayTaskError is stored in the object store for each of the task's outputs. When an object is retrieved from the object store, the Py... | Implement the Python class `RayTaskError` described below.
Class description:
Indicates that a task threw an exception during execution. If a task throws an exception during execution, a RayTaskError is stored in the object store for each of the task's outputs. When an object is retrieved from the object store, the Py... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class RayTaskError:
"""Indicates that a task threw an exception during execution. If a task throws an exception during execution, a RayTaskError is stored in the object store for each of the task's outputs. When an object is retrieved from the object store, the Python method that retrieved it checks to... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RayTaskError:
"""Indicates that a task threw an exception during execution. If a task throws an exception during execution, a RayTaskError is stored in the object store for each of the task's outputs. When an object is retrieved from the object store, the Python method that retrieved it checks to see if the o... | the_stack_v2_python_sparse | python/ray/exceptions.py | ray-project/ray | train | 29,482 |
37eb6532ab3d33eaa04cc80491e77a523f1140b9 | [
"if fit_data is None and (a is None or b is None):\n raise ValueError('Either all the fit parameters or fit_data must be specified.')\nif not (fit_data is None or a is None or b is None):\n raise ValueError('Cannot specify fit parameters when fit_data is specified.')\nself.a = a\nself.b = b\nself.lower = lowe... | <|body_start_0|>
if fit_data is None and (a is None or b is None):
raise ValueError('Either all the fit parameters or fit_data must be specified.')
if not (fit_data is None or a is None or b is None):
raise ValueError('Cannot specify fit parameters when fit_data is specified.')
... | Represents various scaling relations that the axis ratio can follow with quantities like velocity dispersion, when its PDF is assumed to be a Rayleigh distribution Only the relation with velocity dispersion is currently supported. | AxisRatioRayleigh | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxisRatioRayleigh:
"""Represents various scaling relations that the axis ratio can follow with quantities like velocity dispersion, when its PDF is assumed to be a Rayleigh distribution Only the relation with velocity dispersion is currently supported."""
def __init__(self, a=None, b=None, l... | stack_v2_sparse_classes_10k_train_002192 | 19,262 | permissive | [
{
"docstring": "Parameters ---------- a : float linear slope of the scale vs. velocity dispersion relation, in (km/s)^-1, i.e. how much the velocity dispersion contributes to average flattening b : float intercept of the scale vs. velocity dispersion relation, i.e. the mean flattening independent of velocity di... | 3 | stack_v2_sparse_classes_30k_train_003182 | Implement the Python class `AxisRatioRayleigh` described below.
Class description:
Represents various scaling relations that the axis ratio can follow with quantities like velocity dispersion, when its PDF is assumed to be a Rayleigh distribution Only the relation with velocity dispersion is currently supported.
Meth... | Implement the Python class `AxisRatioRayleigh` described below.
Class description:
Represents various scaling relations that the axis ratio can follow with quantities like velocity dispersion, when its PDF is assumed to be a Rayleigh distribution Only the relation with velocity dispersion is currently supported.
Meth... | 2a9a1b3eafbafef925bedab4b3137a3505a9b750 | <|skeleton|>
class AxisRatioRayleigh:
"""Represents various scaling relations that the axis ratio can follow with quantities like velocity dispersion, when its PDF is assumed to be a Rayleigh distribution Only the relation with velocity dispersion is currently supported."""
def __init__(self, a=None, b=None, l... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AxisRatioRayleigh:
"""Represents various scaling relations that the axis ratio can follow with quantities like velocity dispersion, when its PDF is assumed to be a Rayleigh distribution Only the relation with velocity dispersion is currently supported."""
def __init__(self, a=None, b=None, lower=0.2, fit... | the_stack_v2_python_sparse | baobab/bnn_priors/parameter_models.py | jiwoncpark/baobab | train | 9 |
59f4afc0e6e78957b2fd8a284446f1b2882aaedc | [
"if handler_config is None:\n raise FTPCopyFileHandlerError('None passed as handler config.')\nself.source = handler_config[CONFIG_SOURCE]\nself.destination = handler_config[CONFIG_DESTINATION]\nself.exitonfailure = handler_config[CONFIG_EXITONFAILURE]\nself.deletesource = handler_config[CONFIG_DELETESOURCE]\nse... | <|body_start_0|>
if handler_config is None:
raise FTPCopyFileHandlerError('None passed as handler config.')
self.source = handler_config[CONFIG_SOURCE]
self.destination = handler_config[CONFIG_DESTINATION]
self.exitonfailure = handler_config[CONFIG_EXITONFAILURE]
self... | FTP Copy file/directories. FTP Copy files created in watch folder to destination folder on remote FTP server. Attributes: name: Name of handler object source: Folder to watch for files destination: Destination for copy on remote FTP server deletesource: Boolean == true delete source file on success exitonfailure: Boole... | FTPCopyFileHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FTPCopyFileHandler:
"""FTP Copy file/directories. FTP Copy files created in watch folder to destination folder on remote FTP server. Attributes: name: Name of handler object source: Folder to watch for files destination: Destination for copy on remote FTP server deletesource: Boolean == true dele... | stack_v2_sparse_classes_10k_train_002193 | 4,262 | permissive | [
{
"docstring": "Initialise handler attributes. Args: handler_config (ConfigDict): Handler configuration. Raises: FTPCopyFileHandlerError: None passed as handler configuration.",
"name": "__init__",
"signature": "def __init__(self, handler_config: ConfigDict) -> None"
},
{
"docstring": "Change cu... | 3 | stack_v2_sparse_classes_30k_train_003822 | Implement the Python class `FTPCopyFileHandler` described below.
Class description:
FTP Copy file/directories. FTP Copy files created in watch folder to destination folder on remote FTP server. Attributes: name: Name of handler object source: Folder to watch for files destination: Destination for copy on remote FTP se... | Implement the Python class `FTPCopyFileHandler` described below.
Class description:
FTP Copy file/directories. FTP Copy files created in watch folder to destination folder on remote FTP server. Attributes: name: Name of handler object source: Folder to watch for files destination: Destination for copy on remote FTP se... | abbd95b0ddd9da577b6cad69708f2e31db694d94 | <|skeleton|>
class FTPCopyFileHandler:
"""FTP Copy file/directories. FTP Copy files created in watch folder to destination folder on remote FTP server. Attributes: name: Name of handler object source: Folder to watch for files destination: Destination for copy on remote FTP server deletesource: Boolean == true dele... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FTPCopyFileHandler:
"""FTP Copy file/directories. FTP Copy files created in watch folder to destination folder on remote FTP server. Attributes: name: Name of handler object source: Folder to watch for files destination: Destination for copy on remote FTP server deletesource: Boolean == true delete source fil... | the_stack_v2_python_sparse | FPE/builtin/ftp_copyfile_handler.py | clockworkengineer/Constrictor | train | 1 |
7bdc64a53691f704603177e663af144b6d360444 | [
"network_1 = Conv1DNetwork()\nself.assertEqual(len(network_1.layers), 4)\nself.assertTrue(isinstance(network_1.layer_by_name('conv_pool_1'), tx.core.MergeLayer))\nfor layer in network_1.layers[0].layers:\n self.assertTrue(isinstance(layer, tx.core.SequentialLayer))\ninputs_1 = tf.ones([64, 16, 300], tf.float32)\... | <|body_start_0|>
network_1 = Conv1DNetwork()
self.assertEqual(len(network_1.layers), 4)
self.assertTrue(isinstance(network_1.layer_by_name('conv_pool_1'), tx.core.MergeLayer))
for layer in network_1.layers[0].layers:
self.assertTrue(isinstance(layer, tx.core.SequentialLayer))... | Tests :class:`~texar.tf.modules.Conv1DNetwork` class. | Conv1DNetworkTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv1DNetworkTest:
"""Tests :class:`~texar.tf.modules.Conv1DNetwork` class."""
def test_feedforward(self):
"""Tests feed forward."""
<|body_0|>
def test_unknown_seq_length(self):
"""Tests use of pooling layer when the seq_length dimension of inputs is `None`."""
... | stack_v2_sparse_classes_10k_train_002194 | 4,238 | permissive | [
{
"docstring": "Tests feed forward.",
"name": "test_feedforward",
"signature": "def test_feedforward(self)"
},
{
"docstring": "Tests use of pooling layer when the seq_length dimension of inputs is `None`.",
"name": "test_unknown_seq_length",
"signature": "def test_unknown_seq_length(self... | 3 | stack_v2_sparse_classes_30k_train_001811 | Implement the Python class `Conv1DNetworkTest` described below.
Class description:
Tests :class:`~texar.tf.modules.Conv1DNetwork` class.
Method signatures and docstrings:
- def test_feedforward(self): Tests feed forward.
- def test_unknown_seq_length(self): Tests use of pooling layer when the seq_length dimension of ... | Implement the Python class `Conv1DNetworkTest` described below.
Class description:
Tests :class:`~texar.tf.modules.Conv1DNetwork` class.
Method signatures and docstrings:
- def test_feedforward(self): Tests feed forward.
- def test_unknown_seq_length(self): Tests use of pooling layer when the seq_length dimension of ... | 0704b3d4c93915b9a6f96b725e49ae20bf5d1e90 | <|skeleton|>
class Conv1DNetworkTest:
"""Tests :class:`~texar.tf.modules.Conv1DNetwork` class."""
def test_feedforward(self):
"""Tests feed forward."""
<|body_0|>
def test_unknown_seq_length(self):
"""Tests use of pooling layer when the seq_length dimension of inputs is `None`."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Conv1DNetworkTest:
"""Tests :class:`~texar.tf.modules.Conv1DNetwork` class."""
def test_feedforward(self):
"""Tests feed forward."""
network_1 = Conv1DNetwork()
self.assertEqual(len(network_1.layers), 4)
self.assertTrue(isinstance(network_1.layer_by_name('conv_pool_1'), tx... | the_stack_v2_python_sparse | texar/tf/modules/networks/conv_networks_test.py | arita37/texar | train | 2 |
153474f62f69a29abb2b342a98bdaee7054431c5 | [
"value = super(NumpyState, self)._lookup_dependency(name)\nif value is None:\n value = _NumpyWrapper(numpy.array([]))\n new_reference = base.TrackableReference(name=name, ref=value)\n self._unconditional_checkpoint_dependencies.append(new_reference)\n self._unconditional_dependency_names[name] = value\n... | <|body_start_0|>
value = super(NumpyState, self)._lookup_dependency(name)
if value is None:
value = _NumpyWrapper(numpy.array([]))
new_reference = base.TrackableReference(name=name, ref=value)
self._unconditional_checkpoint_dependencies.append(new_reference)
... | A trackable object whose NumPy array attributes are saved/restored. Example usage: ```python arrays = tf.contrib.checkpoint.NumpyState() checkpoint = tf.train.Checkpoint(numpy_arrays=arrays) arrays.x = numpy.zeros([3, 4]) save_path = checkpoint.save("/tmp/ckpt") arrays.x[1, 1] = 4. checkpoint.restore(save_path) assert ... | NumpyState | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumpyState:
"""A trackable object whose NumPy array attributes are saved/restored. Example usage: ```python arrays = tf.contrib.checkpoint.NumpyState() checkpoint = tf.train.Checkpoint(numpy_arrays=arrays) arrays.x = numpy.zeros([3, 4]) save_path = checkpoint.save("/tmp/ckpt") arrays.x[1, 1] = 4.... | stack_v2_sparse_classes_10k_train_002195 | 6,337 | permissive | [
{
"docstring": "Create placeholder NumPy arrays for to-be-restored attributes. Typically `_lookup_dependency` is used to check by name whether a dependency exists. We cheat slightly by creating a trackable object for `name` if we don't already have one, giving us attribute re-creation behavior when loading a ch... | 3 | null | Implement the Python class `NumpyState` described below.
Class description:
A trackable object whose NumPy array attributes are saved/restored. Example usage: ```python arrays = tf.contrib.checkpoint.NumpyState() checkpoint = tf.train.Checkpoint(numpy_arrays=arrays) arrays.x = numpy.zeros([3, 4]) save_path = checkpoin... | Implement the Python class `NumpyState` described below.
Class description:
A trackable object whose NumPy array attributes are saved/restored. Example usage: ```python arrays = tf.contrib.checkpoint.NumpyState() checkpoint = tf.train.Checkpoint(numpy_arrays=arrays) arrays.x = numpy.zeros([3, 4]) save_path = checkpoin... | 7cbba04a2ee16d21309eefad5be6585183a2d5a9 | <|skeleton|>
class NumpyState:
"""A trackable object whose NumPy array attributes are saved/restored. Example usage: ```python arrays = tf.contrib.checkpoint.NumpyState() checkpoint = tf.train.Checkpoint(numpy_arrays=arrays) arrays.x = numpy.zeros([3, 4]) save_path = checkpoint.save("/tmp/ckpt") arrays.x[1, 1] = 4.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumpyState:
"""A trackable object whose NumPy array attributes are saved/restored. Example usage: ```python arrays = tf.contrib.checkpoint.NumpyState() checkpoint = tf.train.Checkpoint(numpy_arrays=arrays) arrays.x = numpy.zeros([3, 4]) save_path = checkpoint.save("/tmp/ckpt") arrays.x[1, 1] = 4. checkpoint.r... | the_stack_v2_python_sparse | tensorflow/contrib/checkpoint/python/python_state.py | NVIDIA/tensorflow | train | 763 |
08edbbd780a3bb748e04bd7ad35b5e161c726fb0 | [
"super(StatModOnStatusAbility, self).__init__(name)\nself.stat = stat\nself.mod = mod",
"messages = []\nstatus.statMods[self.stat] = self.mod\nmessages = [pkmn.getHeader() + \" raised it's \" + self.stat + '.']\nreturn messages"
] | <|body_start_0|>
super(StatModOnStatusAbility, self).__init__(name)
self.stat = stat
self.mod = mod
<|end_body_0|>
<|body_start_1|>
messages = []
status.statMods[self.stat] = self.mod
messages = [pkmn.getHeader() + " raised it's " + self.stat + '.']
return messag... | An ability that modifies a stat when the parent receives a status | StatModOnStatusAbility | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatModOnStatusAbility:
"""An ability that modifies a stat when the parent receives a status"""
def __init__(self, name, stat, mod):
"""Builds the Ability"""
<|body_0|>
def onStatus(self, pkmn, status):
"""Alter the statMods of the Status to reflect the abilities... | stack_v2_sparse_classes_10k_train_002196 | 649 | no_license | [
{
"docstring": "Builds the Ability",
"name": "__init__",
"signature": "def __init__(self, name, stat, mod)"
},
{
"docstring": "Alter the statMods of the Status to reflect the abilities effect",
"name": "onStatus",
"signature": "def onStatus(self, pkmn, status)"
}
] | 2 | null | Implement the Python class `StatModOnStatusAbility` described below.
Class description:
An ability that modifies a stat when the parent receives a status
Method signatures and docstrings:
- def __init__(self, name, stat, mod): Builds the Ability
- def onStatus(self, pkmn, status): Alter the statMods of the Status to ... | Implement the Python class `StatModOnStatusAbility` described below.
Class description:
An ability that modifies a stat when the parent receives a status
Method signatures and docstrings:
- def __init__(self, name, stat, mod): Builds the Ability
- def onStatus(self, pkmn, status): Alter the statMods of the Status to ... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class StatModOnStatusAbility:
"""An ability that modifies a stat when the parent receives a status"""
def __init__(self, name, stat, mod):
"""Builds the Ability"""
<|body_0|>
def onStatus(self, pkmn, status):
"""Alter the statMods of the Status to reflect the abilities... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StatModOnStatusAbility:
"""An ability that modifies a stat when the parent receives a status"""
def __init__(self, name, stat, mod):
"""Builds the Ability"""
super(StatModOnStatusAbility, self).__init__(name)
self.stat = stat
self.mod = mod
def onStatus(self, pkmn, st... | the_stack_v2_python_sparse | src/Pokemon/Abilities/statmodonstatus_ability.py | sgtnourry/Pokemon-Project | train | 0 |
bdcf768f75c74f4900f61438a4ee56b1ff924fec | [
"cached_state = None\nif self.cli_state is self.SHELL:\n cached_state = self.SHELL\nif self.cli_state is not self.CONFIG:\n self._drive_cli_state(self.cli_state, self.CONFIG)\nerr_cmd, status = (None, True)\nerr_msg = None\ncmd_list = self._va_list_of_cmds(cmd)\nfor each_cmd in cmd_list:\n output, status =... | <|body_start_0|>
cached_state = None
if self.cli_state is self.SHELL:
cached_state = self.SHELL
if self.cli_state is not self.CONFIG:
self._drive_cli_state(self.cli_state, self.CONFIG)
err_cmd, status = (None, True)
err_msg = None
cmd_list = self._... | Access implements methods that translate to executing cli commands remotely on the director. | VaAccess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VaAccess:
"""Access implements methods that translate to executing cli commands remotely on the director."""
def va_config(self, cmd=None, timeout=60, commit=True, exit=True, **kwargs):
"""method calls the _va_exec_cli_cmd method of the access layer. kwargs: :cmd (str|list): a single... | stack_v2_sparse_classes_10k_train_002197 | 5,550 | no_license | [
{
"docstring": "method calls the _va_exec_cli_cmd method of the access layer. kwargs: :cmd (str|list): a single string command or a list of string commands :timeout (int): timeout for each command in the list :commit (bool-True): if the config requires a commit :exit (bool-True): exit config mode and go back to... | 5 | stack_v2_sparse_classes_30k_train_004918 | Implement the Python class `VaAccess` described below.
Class description:
Access implements methods that translate to executing cli commands remotely on the director.
Method signatures and docstrings:
- def va_config(self, cmd=None, timeout=60, commit=True, exit=True, **kwargs): method calls the _va_exec_cli_cmd meth... | Implement the Python class `VaAccess` described below.
Class description:
Access implements methods that translate to executing cli commands remotely on the director.
Method signatures and docstrings:
- def va_config(self, cmd=None, timeout=60, commit=True, exit=True, **kwargs): method calls the _va_exec_cli_cmd meth... | cb02979e233ce772bd5fe88ecdc31caf8764d306 | <|skeleton|>
class VaAccess:
"""Access implements methods that translate to executing cli commands remotely on the director."""
def va_config(self, cmd=None, timeout=60, commit=True, exit=True, **kwargs):
"""method calls the _va_exec_cli_cmd method of the access layer. kwargs: :cmd (str|list): a single... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VaAccess:
"""Access implements methods that translate to executing cli commands remotely on the director."""
def va_config(self, cmd=None, timeout=60, commit=True, exit=True, **kwargs):
"""method calls the _va_exec_cli_cmd method of the access layer. kwargs: :cmd (str|list): a single string comma... | the_stack_v2_python_sparse | feature/director/accesslib/director_3_1.py | 18782967131/test | train | 1 |
00036ff9a57b5d138ddfc72cf02545214758506e | [
"r, nr = (0, 0)\nfor i in range(len(nums)):\n tmp = nr\n nr = max(r, nr)\n r = tmp + nums[i]\nreturn max(r, nr)",
"def helper(start, stop):\n r, nr = (0, 0)\n for i in range(start, stop):\n tmp = nr\n nr = max(r, nr)\n r = tmp + nums[i]\n return max(r, nr)\nif len(nums) == 1... | <|body_start_0|>
r, nr = (0, 0)
for i in range(len(nums)):
tmp = nr
nr = max(r, nr)
r = tmp + nums[i]
return max(r, nr)
<|end_body_0|>
<|body_start_1|>
def helper(start, stop):
r, nr = (0, 0)
for i in range(start, stop):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob1(self, nums):
"""line :param nums: :return:"""
<|body_0|>
def rob2(self, nums):
"""circle :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
r, nr = (0, 0)
for i in range(len(nums)):
... | stack_v2_sparse_classes_10k_train_002198 | 790 | no_license | [
{
"docstring": "line :param nums: :return:",
"name": "rob1",
"signature": "def rob1(self, nums)"
},
{
"docstring": "circle :type nums: List[int] :rtype: int",
"name": "rob2",
"signature": "def rob2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob1(self, nums): line :param nums: :return:
- def rob2(self, nums): circle :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob1(self, nums): line :param nums: :return:
- def rob2(self, nums): circle :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob1(self, nums):
... | e16702d2b3ec4e5054baad56f4320bc3b31676ad | <|skeleton|>
class Solution:
def rob1(self, nums):
"""line :param nums: :return:"""
<|body_0|>
def rob2(self, nums):
"""circle :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def rob1(self, nums):
"""line :param nums: :return:"""
r, nr = (0, 0)
for i in range(len(nums)):
tmp = nr
nr = max(r, nr)
r = tmp + nums[i]
return max(r, nr)
def rob2(self, nums):
"""circle :type nums: List[int] :rtype:... | the_stack_v2_python_sparse | leetcode/medium/house_robber.py | SuperMartinYang/learning_algorithm | train | 0 | |
241bb6da6f869f43c7ba6e691e28c397a370ff40 | [
"def serializeHelper(node, vals):\n if node:\n vals.append(node.val)\n serializeHelper(node.left, vals)\n serializeHelper(node.right, vals)\nvals = []\nserializeHelper(root, vals)\nreturn ' '.join(map(str, vals))",
"def deserializeHelper(minVal, maxVal, vals):\n if not vals:\n re... | <|body_start_0|>
def serializeHelper(node, vals):
if node:
vals.append(node.val)
serializeHelper(node.left, vals)
serializeHelper(node.right, vals)
vals = []
serializeHelper(root, vals)
return ' '.join(map(str, vals))
<|end_body... | 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_10k_train_002199 | 1,344 | 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:... | 4dc4e6642dc92f1983c13564cc0fd99917cab358 | <|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_10k | 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 serializeHelper(node, vals):
if node:
vals.append(node.val)
serializeHelper(node.left, vals)
serializeHelper(node.right, v... | the_stack_v2_python_sparse | Python/serialize-and-deserialize-bst.py | kamyu104/LeetCode-Solutions | train | 4,549 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.