blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4bec23fd4a8873fd5a1d651d06e571cafce27678 | [
"self.keypair = None\nif entropy:\n self.makeKeypair(entropy, mode)",
"if type(entropy) == type(1):\n cvar.random_seed = entropy\n self.keypair = EC_KEYPAIR()\n self.mode = mode\n if mode == 'DH':\n makeSecretKey(base, self.keypair)\n DH_gen(base, self.keypair)\n elif mode == 'ECKG... | <|body_start_0|>
self.keypair = None
if entropy:
self.makeKeypair(entropy, mode)
<|end_body_0|>
<|body_start_1|>
if type(entropy) == type(1):
cvar.random_seed = entropy
self.keypair = EC_KEYPAIR()
self.mode = mode
if mode == 'DH':
... | This is the Elliptic Curve Cryptography base class. Used for generating and receiving Diffie-Hellman values, along with Nyberg-Rueppel signature and verification. **Sample usage**:: >>> from ecc.ecc import ecc >>> e,f=ecc(1),ecc(2) >>> e_pub_key, f_pub_key = e.publicKey(), f.publicKey() >>> # Key Exchange >>> secret1 =... | ecc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ecc:
"""This is the Elliptic Curve Cryptography base class. Used for generating and receiving Diffie-Hellman values, along with Nyberg-Rueppel signature and verification. **Sample usage**:: >>> from ecc.ecc import ecc >>> e,f=ecc(1),ecc(2) >>> e_pub_key, f_pub_key = e.publicKey(), f.publicKey() >... | stack_v2_sparse_classes_36k_train_012000 | 6,480 | no_license | [
{
"docstring": "Constructor. Provide an arbitrary integer of cryptographically secure *entropy* to be used in generating a random secret key. Examples of good sources include CSPRNGs and /dev/random. *mode* determines how the public key is generated. Possible values are 'DH' for Diffie-Hellman and 'ECKGP' for t... | 6 | stack_v2_sparse_classes_30k_train_016091 | Implement the Python class `ecc` described below.
Class description:
This is the Elliptic Curve Cryptography base class. Used for generating and receiving Diffie-Hellman values, along with Nyberg-Rueppel signature and verification. **Sample usage**:: >>> from ecc.ecc import ecc >>> e,f=ecc(1),ecc(2) >>> e_pub_key, f_p... | Implement the Python class `ecc` described below.
Class description:
This is the Elliptic Curve Cryptography base class. Used for generating and receiving Diffie-Hellman values, along with Nyberg-Rueppel signature and verification. **Sample usage**:: >>> from ecc.ecc import ecc >>> e,f=ecc(1),ecc(2) >>> e_pub_key, f_p... | 65ab44813ec17a132e59fdef0d1b3197be585f58 | <|skeleton|>
class ecc:
"""This is the Elliptic Curve Cryptography base class. Used for generating and receiving Diffie-Hellman values, along with Nyberg-Rueppel signature and verification. **Sample usage**:: >>> from ecc.ecc import ecc >>> e,f=ecc(1),ecc(2) >>> e_pub_key, f_pub_key = e.publicKey(), f.publicKey() >... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ecc:
"""This is the Elliptic Curve Cryptography base class. Used for generating and receiving Diffie-Hellman values, along with Nyberg-Rueppel signature and verification. **Sample usage**:: >>> from ecc.ecc import ecc >>> e,f=ecc(1),ecc(2) >>> e_pub_key, f_pub_key = e.publicKey(), f.publicKey() >>> # Key Exch... | the_stack_v2_python_sparse | trunk/cryptkit-ecc/src/ecc.py | BackupTheBerlios/sumi-svn | train | 0 |
5911f509f680b0b3bdc36ab7d33b99a410265f37 | [
"m, n = (len(nums), m)\ndp = [[float('inf')] * (n + 1) for _ in range(m + 1)]\ndp[0][0] = 0\nsubSum = [0]\nfor i in nums:\n subSum.append(subSum[-1] + i)\nfor i in range(1, m + 1):\n for j in range(1, min(i, n) + 1):\n for k in range(i):\n dp[i][j] = min(max(dp[k][j - 1], subSum[i] - subSum[... | <|body_start_0|>
m, n = (len(nums), m)
dp = [[float('inf')] * (n + 1) for _ in range(m + 1)]
dp[0][0] = 0
subSum = [0]
for i in nums:
subSum.append(subSum[-1] + i)
for i in range(1, m + 1):
for j in range(1, min(i, n) + 1):
for k in... | Soluition | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Soluition:
def splitArray(self, nums, m):
"""动态规划 dp[i][j] 前i个数 分j次 和最大值最小 [7,2,5,10,8] m=5 0 [0,inf,inf,inf,inf,inf] inf,7,inf,inf,inf,inf inf,9,7,inf,inf,inf inf,14,7,2,inf,inf inf,24,14,10,inf inf,32,18, dp[i][j] = min(max(dp[k][j-1_最短回文串.py], sub_sum(k+1_最短回文串.py,i)), dp[i][j]) k<i i... | stack_v2_sparse_classes_36k_train_012001 | 2,631 | no_license | [
{
"docstring": "动态规划 dp[i][j] 前i个数 分j次 和最大值最小 [7,2,5,10,8] m=5 0 [0,inf,inf,inf,inf,inf] inf,7,inf,inf,inf,inf inf,9,7,inf,inf,inf inf,14,7,2,inf,inf inf,24,14,10,inf inf,32,18, dp[i][j] = min(max(dp[k][j-1_最短回文串.py], sub_sum(k+1_最短回文串.py,i)), dp[i][j]) k<i if j<=min(i,m) dp[i][0] = inf dp[0][j] = inf dp[0][0] ... | 2 | null | Implement the Python class `Soluition` described below.
Class description:
Implement the Soluition class.
Method signatures and docstrings:
- def splitArray(self, nums, m): 动态规划 dp[i][j] 前i个数 分j次 和最大值最小 [7,2,5,10,8] m=5 0 [0,inf,inf,inf,inf,inf] inf,7,inf,inf,inf,inf inf,9,7,inf,inf,inf inf,14,7,2,inf,inf inf,24,14,1... | Implement the Python class `Soluition` described below.
Class description:
Implement the Soluition class.
Method signatures and docstrings:
- def splitArray(self, nums, m): 动态规划 dp[i][j] 前i个数 分j次 和最大值最小 [7,2,5,10,8] m=5 0 [0,inf,inf,inf,inf,inf] inf,7,inf,inf,inf,inf inf,9,7,inf,inf,inf inf,14,7,2,inf,inf inf,24,14,1... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Soluition:
def splitArray(self, nums, m):
"""动态规划 dp[i][j] 前i个数 分j次 和最大值最小 [7,2,5,10,8] m=5 0 [0,inf,inf,inf,inf,inf] inf,7,inf,inf,inf,inf inf,9,7,inf,inf,inf inf,14,7,2,inf,inf inf,24,14,10,inf inf,32,18, dp[i][j] = min(max(dp[k][j-1_最短回文串.py], sub_sum(k+1_最短回文串.py,i)), dp[i][j]) k<i i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Soluition:
def splitArray(self, nums, m):
"""动态规划 dp[i][j] 前i个数 分j次 和最大值最小 [7,2,5,10,8] m=5 0 [0,inf,inf,inf,inf,inf] inf,7,inf,inf,inf,inf inf,9,7,inf,inf,inf inf,14,7,2,inf,inf inf,24,14,10,inf inf,32,18, dp[i][j] = min(max(dp[k][j-1_最短回文串.py], sub_sum(k+1_最短回文串.py,i)), dp[i][j]) k<i if j<=min(i,m) ... | the_stack_v2_python_sparse | 4_LEETCODE/2_DP/数组问题/410_分割数组的最大和.py | fzingithub/SwordRefers2Offer | train | 1 | |
7af226c00c73ced6b0f7a033a2e4a5c8bf29c161 | [
"url_primary = 'http://www.cstrois-lacs.qc.ca/prescolaire-et-primaire/liste-ecoles-primaires'\nurl_secondary = 'http://www.cstrois-lacs.qc.ca/secondaire/les-ecoles-secondaires'\nyield scrapy.Request(url_primary, callback=self.parse_list_schools, meta={'type': 'école primaire', 'grades': 'primaire'})\nyield scrapy.R... | <|body_start_0|>
url_primary = 'http://www.cstrois-lacs.qc.ca/prescolaire-et-primaire/liste-ecoles-primaires'
url_secondary = 'http://www.cstrois-lacs.qc.ca/secondaire/les-ecoles-secondaires'
yield scrapy.Request(url_primary, callback=self.parse_list_schools, meta={'type': 'école primaire', 'gra... | a scrapy spider to crawl cstrois-lacs.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found | MontrealCstroisSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MontrealCstroisSpider:
"""a scrapy spider to crawl cstrois-lacs.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found"""
def start_requests(self):
"""s... | stack_v2_sparse_classes_36k_train_012002 | 4,517 | no_license | [
{
"docstring": "spider starts from here, crawl url_primary and url_secondary to get a list of schools urls",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "get schools pages urls and yield a Request to crawl those pages",
"name": "parse_list_schools",
... | 3 | stack_v2_sparse_classes_30k_val_000427 | Implement the Python class `MontrealCstroisSpider` described below.
Class description:
a scrapy spider to crawl cstrois-lacs.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found
Method... | Implement the Python class `MontrealCstroisSpider` described below.
Class description:
a scrapy spider to crawl cstrois-lacs.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found
Method... | 350264cf6da323692c2838d8cb235ef61085851b | <|skeleton|>
class MontrealCstroisSpider:
"""a scrapy spider to crawl cstrois-lacs.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found"""
def start_requests(self):
"""s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MontrealCstroisSpider:
"""a scrapy spider to crawl cstrois-lacs.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found"""
def start_requests(self):
"""spider starts ... | the_stack_v2_python_sparse | school_scraping/spiders/montreal_cstrois.py | ramadanmostafa/canada_school_scraping | train | 0 |
0b5c0bc93c815bcb606b9619ae06fa36284a7cca | [
"queryset = models.Subject.objects.all()\nupna_id = self.request.query_params.get('upna_id', None)\ndegree_id = self.request.query_params.get('degree_id', None)\nupna_degree_id = self.request.query_params.get('upna_degree_id', None)\nif upna_id is not None:\n queryset = queryset.filter(upna_id__exact=upna_id)\ni... | <|body_start_0|>
queryset = models.Subject.objects.all()
upna_id = self.request.query_params.get('upna_id', None)
degree_id = self.request.query_params.get('degree_id', None)
upna_degree_id = self.request.query_params.get('upna_degree_id', None)
if upna_id is not None:
... | Listado y vista en detalle de las asignaturas de las titulaciones de la Universidad. | SubjectViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubjectViewSet:
"""Listado y vista en detalle de las asignaturas de las titulaciones de la Universidad."""
def get_queryset(self):
"""Método para gestionar los filtros sobre las asignaturas. Puede pedirse: - Un subconjunto de las asignaturas dado el id que utiliza la UPNA. - Un subco... | stack_v2_sparse_classes_36k_train_012003 | 9,178 | no_license | [
{
"docstring": "Método para gestionar los filtros sobre las asignaturas. Puede pedirse: - Un subconjunto de las asignaturas dado el id que utiliza la UPNA. - Un subconjunto de las asignaturas dado el id del grado en la base de datos. - Un subconjunto de las asignatruas dado el id del grado que utiliza la UPNA. ... | 2 | stack_v2_sparse_classes_30k_train_004246 | Implement the Python class `SubjectViewSet` described below.
Class description:
Listado y vista en detalle de las asignaturas de las titulaciones de la Universidad.
Method signatures and docstrings:
- def get_queryset(self): Método para gestionar los filtros sobre las asignaturas. Puede pedirse: - Un subconjunto de l... | Implement the Python class `SubjectViewSet` described below.
Class description:
Listado y vista en detalle de las asignaturas de las titulaciones de la Universidad.
Method signatures and docstrings:
- def get_queryset(self): Método para gestionar los filtros sobre las asignaturas. Puede pedirse: - Un subconjunto de l... | 13e369bc4ca64cb406046af319f1bdfdaabc8ee1 | <|skeleton|>
class SubjectViewSet:
"""Listado y vista en detalle de las asignaturas de las titulaciones de la Universidad."""
def get_queryset(self):
"""Método para gestionar los filtros sobre las asignaturas. Puede pedirse: - Un subconjunto de las asignaturas dado el id que utiliza la UPNA. - Un subco... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubjectViewSet:
"""Listado y vista en detalle de las asignaturas de las titulaciones de la Universidad."""
def get_queryset(self):
"""Método para gestionar los filtros sobre las asignaturas. Puede pedirse: - Un subconjunto de las asignaturas dado el id que utiliza la UPNA. - Un subconjunto de las... | the_stack_v2_python_sparse | mobile_app/views.py | CEUPNA/backend-ceupna | train | 1 |
e9467da874a3d25fc155315bfa2722f9824ef0b9 | [
"super(LSTMDiscriminator, self).__init__()\nself.hidden_dim = hidden_dim\nself.layer_dim = 2\ninput_dim = 2 * obs_dim + act_dim\nself.lstm = nn.LSTM(input_dim, hidden_dim, self.layer_dim, batch_first=True)\nself.fc = nn.Linear(hidden_dim, 1)",
"x = x.unsqueeze(0)\nh0 = to.zeros(self.layer_dim, x.size(0), self.hid... | <|body_start_0|>
super(LSTMDiscriminator, self).__init__()
self.hidden_dim = hidden_dim
self.layer_dim = 2
input_dim = 2 * obs_dim + act_dim
self.lstm = nn.LSTM(input_dim, hidden_dim, self.layer_dim, batch_first=True)
self.fc = nn.Linear(hidden_dim, 1)
<|end_body_0|>
<|b... | LSTM-based discriminator | LSTMDiscriminator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMDiscriminator:
"""LSTM-based discriminator"""
def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128):
"""Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hidden_dim: hidden layer size"""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_012004 | 6,086 | permissive | [
{
"docstring": "Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hidden_dim: hidden layer size",
"name": "__init__",
"signature": "def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128)"
},
{
"docstring": ":param x: A Tensor which... | 2 | stack_v2_sparse_classes_30k_train_010866 | Implement the Python class `LSTMDiscriminator` described below.
Class description:
LSTM-based discriminator
Method signatures and docstrings:
- def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128): Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hid... | Implement the Python class `LSTMDiscriminator` described below.
Class description:
LSTM-based discriminator
Method signatures and docstrings:
- def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128): Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hid... | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | <|skeleton|>
class LSTMDiscriminator:
"""LSTM-based discriminator"""
def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128):
"""Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hidden_dim: hidden layer size"""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSTMDiscriminator:
"""LSTM-based discriminator"""
def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128):
"""Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hidden_dim: hidden layer size"""
super(LSTMDiscriminator, self)._... | the_stack_v2_python_sparse | Pyrado/pyrado/algorithms/adr_discriminator.py | jacarvalho/SimuRLacra | train | 0 |
875cf3f0d9d0afd1a881457fa5c50c79688fc071 | [
"super(SmoothMixedL21Norm, self).__init__(L=1)\nself.epsilon = epsilon\nif self.epsilon == 0:\n raise ValueError('We need epsilon>0. Otherwise, call \"MixedL21Norm\" ')",
"if not isinstance(x, BlockDataContainer):\n raise ValueError('__call__ expected BlockDataContainer, got {}'.format(type(x)))\nreturn (x.... | <|body_start_0|>
super(SmoothMixedL21Norm, self).__init__(L=1)
self.epsilon = epsilon
if self.epsilon == 0:
raise ValueError('We need epsilon>0. Otherwise, call "MixedL21Norm" ')
<|end_body_0|>
<|body_start_1|>
if not isinstance(x, BlockDataContainer):
raise Valu... | SmoothMixedL21Norm function: :math:`F(x) = ||x||_{2,1} = \\sum |x|_{2} = \\sum \\sqrt{ (x^{1})^{2} + (x^{2})^{2} + \\epsilon^2 + \\dots}` where x is a BlockDataContainer, i.e., :math:`x=(x^{1}, x^{2}, \\dots)` Conjugate, proximal and proximal conjugate methods no closed-form solution | SmoothMixedL21Norm | [
"Apache-2.0",
"BSD-3-Clause",
"GPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmoothMixedL21Norm:
"""SmoothMixedL21Norm function: :math:`F(x) = ||x||_{2,1} = \\sum |x|_{2} = \\sum \\sqrt{ (x^{1})^{2} + (x^{2})^{2} + \\epsilon^2 + \\dots}` where x is a BlockDataContainer, i.e., :math:`x=(x^{1}, x^{2}, \\dots)` Conjugate, proximal and proximal conjugate methods no closed-for... | stack_v2_sparse_classes_36k_train_012005 | 7,271 | permissive | [
{
"docstring": ":param epsilon: smoothing parameter making MixedL21Norm differentiable",
"name": "__init__",
"signature": "def __init__(self, epsilon)"
},
{
"docstring": "Returns the value of the SmoothMixedL21Norm function at x.",
"name": "__call__",
"signature": "def __call__(self, x)"... | 3 | stack_v2_sparse_classes_30k_train_005492 | Implement the Python class `SmoothMixedL21Norm` described below.
Class description:
SmoothMixedL21Norm function: :math:`F(x) = ||x||_{2,1} = \\sum |x|_{2} = \\sum \\sqrt{ (x^{1})^{2} + (x^{2})^{2} + \\epsilon^2 + \\dots}` where x is a BlockDataContainer, i.e., :math:`x=(x^{1}, x^{2}, \\dots)` Conjugate, proximal and p... | Implement the Python class `SmoothMixedL21Norm` described below.
Class description:
SmoothMixedL21Norm function: :math:`F(x) = ||x||_{2,1} = \\sum |x|_{2} = \\sum \\sqrt{ (x^{1})^{2} + (x^{2})^{2} + \\epsilon^2 + \\dots}` where x is a BlockDataContainer, i.e., :math:`x=(x^{1}, x^{2}, \\dots)` Conjugate, proximal and p... | b0503d1b24cc71d937bbb780602d8778b36b0e77 | <|skeleton|>
class SmoothMixedL21Norm:
"""SmoothMixedL21Norm function: :math:`F(x) = ||x||_{2,1} = \\sum |x|_{2} = \\sum \\sqrt{ (x^{1})^{2} + (x^{2})^{2} + \\epsilon^2 + \\dots}` where x is a BlockDataContainer, i.e., :math:`x=(x^{1}, x^{2}, \\dots)` Conjugate, proximal and proximal conjugate methods no closed-for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SmoothMixedL21Norm:
"""SmoothMixedL21Norm function: :math:`F(x) = ||x||_{2,1} = \\sum |x|_{2} = \\sum \\sqrt{ (x^{1})^{2} + (x^{2})^{2} + \\epsilon^2 + \\dots}` where x is a BlockDataContainer, i.e., :math:`x=(x^{1}, x^{2}, \\dots)` Conjugate, proximal and proximal conjugate methods no closed-form solution"""... | the_stack_v2_python_sparse | Wrappers/Python/cil/optimisation/functions/MixedL21Norm.py | TomographicImaging/CIL | train | 72 |
873de64e006566dcd79f8e167559a92b83b1b928 | [
"process = subprocess.Popen(scriptfiles_parametrize, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\nstdout, stderr = process.communicate()\nretcode = process.returncode\nassert retcode == 2\nassert stdout == ''\nassert stderr.startswith('usage')",
"process = subprocess.Popen... | <|body_start_0|>
process = subprocess.Popen(scriptfiles_parametrize, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stdout, stderr = process.communicate()
retcode = process.returncode
assert retcode == 2
assert stdout == ''
assert std... | TestHelp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHelp:
def test_ShortHelp(self, scriptfiles_parametrize):
"""Test the abbreviated help for each script"""
<|body_0|>
def test_LongHelp(self, scriptfiles_parametrize):
"""Test the full help for each script"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_012006 | 1,954 | permissive | [
{
"docstring": "Test the abbreviated help for each script",
"name": "test_ShortHelp",
"signature": "def test_ShortHelp(self, scriptfiles_parametrize)"
},
{
"docstring": "Test the full help for each script",
"name": "test_LongHelp",
"signature": "def test_LongHelp(self, scriptfiles_parame... | 2 | null | Implement the Python class `TestHelp` described below.
Class description:
Implement the TestHelp class.
Method signatures and docstrings:
- def test_ShortHelp(self, scriptfiles_parametrize): Test the abbreviated help for each script
- def test_LongHelp(self, scriptfiles_parametrize): Test the full help for each scrip... | Implement the Python class `TestHelp` described below.
Class description:
Implement the TestHelp class.
Method signatures and docstrings:
- def test_ShortHelp(self, scriptfiles_parametrize): Test the abbreviated help for each script
- def test_LongHelp(self, scriptfiles_parametrize): Test the full help for each scrip... | 2a0d8a541431f84e4d887821cd66a5ea525e3026 | <|skeleton|>
class TestHelp:
def test_ShortHelp(self, scriptfiles_parametrize):
"""Test the abbreviated help for each script"""
<|body_0|>
def test_LongHelp(self, scriptfiles_parametrize):
"""Test the full help for each script"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestHelp:
def test_ShortHelp(self, scriptfiles_parametrize):
"""Test the abbreviated help for each script"""
process = subprocess.Popen(scriptfiles_parametrize, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stdout, stderr = process.communicate()
... | the_stack_v2_python_sparse | test_sfauto/test_20_help.py | cseelye/sfauto | train | 0 | |
1b53594b1a6c835aef36f9e85c0d7f5f63896733 | [
"if index.column() == 1:\n dataType = str(index.sibling(index.row(), 2).data())\n if dataType == 'int':\n editor = QtGui.QLineEdit(parent)\n editor.setValidator(QtGui.QIntValidator(parent))\n elif dataType == 'bool':\n editor = QtGui.QComboBox(parent)\n editor.addItem('True')\n ... | <|body_start_0|>
if index.column() == 1:
dataType = str(index.sibling(index.row(), 2).data())
if dataType == 'int':
editor = QtGui.QLineEdit(parent)
editor.setValidator(QtGui.QIntValidator(parent))
elif dataType == 'bool':
edito... | QConfigurationTreeWidgetItemDelegate allows a custom editor for each column of the QConfigurationTreeWidget | QConfigurationTreeWidgetItemDelegate | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QConfigurationTreeWidgetItemDelegate:
"""QConfigurationTreeWidgetItemDelegate allows a custom editor for each column of the QConfigurationTreeWidget"""
def createEditor(self, parent, option, index):
"""createEditor(parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex) ->... | stack_v2_sparse_classes_36k_train_012007 | 26,942 | permissive | [
{
"docstring": "createEditor(parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex) -> QWidget Return the editing widget depending on columns",
"name": "createEditor",
"signature": "def createEditor(self, parent, option, index)"
},
{
"docstring": "setEditorData(editor: QWidget, index... | 3 | stack_v2_sparse_classes_30k_train_013854 | Implement the Python class `QConfigurationTreeWidgetItemDelegate` described below.
Class description:
QConfigurationTreeWidgetItemDelegate allows a custom editor for each column of the QConfigurationTreeWidget
Method signatures and docstrings:
- def createEditor(self, parent, option, index): createEditor(parent: QWid... | Implement the Python class `QConfigurationTreeWidgetItemDelegate` described below.
Class description:
QConfigurationTreeWidgetItemDelegate allows a custom editor for each column of the QConfigurationTreeWidget
Method signatures and docstrings:
- def createEditor(self, parent, option, index): createEditor(parent: QWid... | 93f1e5d375ee1e870f9bad699a22c9aafb954090 | <|skeleton|>
class QConfigurationTreeWidgetItemDelegate:
"""QConfigurationTreeWidgetItemDelegate allows a custom editor for each column of the QConfigurationTreeWidget"""
def createEditor(self, parent, option, index):
"""createEditor(parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex) ->... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QConfigurationTreeWidgetItemDelegate:
"""QConfigurationTreeWidgetItemDelegate allows a custom editor for each column of the QConfigurationTreeWidget"""
def createEditor(self, parent, option, index):
"""createEditor(parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex) -> QWidget Retu... | the_stack_v2_python_sparse | vistrails/gui/configuration.py | alexmavr/VisTrails | train | 1 |
e7ad6610a556b0cbb2715f8394a45880309113cf | [
"self.baud = baud\nself.timeout = timeout\nself.pid = pid\nself.port = '/dev/youbot/gripper'",
"try:\n self.board = serial.Serial(self.port, self.baud, timeout=self.timeout)\nexcept Exception as a:\n rospy.logerr(a)\n rospy.logerr('Please check the port {}'.format(self.port))",
"self.board.flushInput()... | <|body_start_0|>
self.baud = baud
self.timeout = timeout
self.pid = pid
self.port = '/dev/youbot/gripper'
<|end_body_0|>
<|body_start_1|>
try:
self.board = serial.Serial(self.port, self.baud, timeout=self.timeout)
except Exception as a:
rospy.loge... | SerialInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SerialInterface:
def __init__(self, baud, timeout, pid):
"""This module contains a component that communicates with the particular Teensy board and sends the message via serial port with specified baudrate, timeout and pid of the microcontroller board. Keyword arguments: @param baud -- b... | stack_v2_sparse_classes_36k_train_012008 | 2,489 | no_license | [
{
"docstring": "This module contains a component that communicates with the particular Teensy board and sends the message via serial port with specified baudrate, timeout and pid of the microcontroller board. Keyword arguments: @param baud -- baudrate of the microcontroller @param timeout -- timeout after which... | 4 | stack_v2_sparse_classes_30k_train_021270 | Implement the Python class `SerialInterface` described below.
Class description:
Implement the SerialInterface class.
Method signatures and docstrings:
- def __init__(self, baud, timeout, pid): This module contains a component that communicates with the particular Teensy board and sends the message via serial port wi... | Implement the Python class `SerialInterface` described below.
Class description:
Implement the SerialInterface class.
Method signatures and docstrings:
- def __init__(self, baud, timeout, pid): This module contains a component that communicates with the particular Teensy board and sends the message via serial port wi... | 8129cd48351159508cae3438a8b8b3d776c771ca | <|skeleton|>
class SerialInterface:
def __init__(self, baud, timeout, pid):
"""This module contains a component that communicates with the particular Teensy board and sends the message via serial port with specified baudrate, timeout and pid of the microcontroller board. Keyword arguments: @param baud -- b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SerialInterface:
def __init__(self, baud, timeout, pid):
"""This module contains a component that communicates with the particular Teensy board and sends the message via serial port with specified baudrate, timeout and pid of the microcontroller board. Keyword arguments: @param baud -- baudrate of the... | the_stack_v2_python_sparse | mir_manipulation/mir_gripper_controller/ros/scripts/serial_interface.py | b-it-bots/mas_industrial_robotics | train | 25 | |
1481238e5ad059d397f277e1505274cf4b28f1e4 | [
"self.station_number = station_number\nif np.isscalar(year):\n self.year_list = [year]\nelse:\n self.year_list = year\nif np.isscalar(month):\n self.month_list = [month]\nelse:\n self.month_list = month\nself.day_start = day_start\nself.day_end = day_end\nself.start_hour = start_hour\nself.end_hour = en... | <|body_start_0|>
self.station_number = station_number
if np.isscalar(year):
self.year_list = [year]
else:
self.year_list = year
if np.isscalar(month):
self.month_list = [month]
else:
self.month_list = month
self.day_start = ... | DataFetcher for retrieving Wyoming Sounding data | DataFetcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataFetcher:
"""DataFetcher for retrieving Wyoming Sounding data"""
def __init__(self, station_number, year, month, day_start, day_end, start_hour=0, end_hour=12):
"""Initialize Data Fetcher @param station_number: Station number @param year: Input year @param month: Input month (Inte... | stack_v2_sparse_classes_36k_train_012009 | 4,311 | permissive | [
{
"docstring": "Initialize Data Fetcher @param station_number: Station number @param year: Input year @param month: Input month (Integer for a single month, or a list of integers for multiple months) @param day_start: First day of the month to include @param day_end: Last day of the month to include @param star... | 2 | stack_v2_sparse_classes_30k_train_000700 | Implement the Python class `DataFetcher` described below.
Class description:
DataFetcher for retrieving Wyoming Sounding data
Method signatures and docstrings:
- def __init__(self, station_number, year, month, day_start, day_end, start_hour=0, end_hour=12): Initialize Data Fetcher @param station_number: Station numbe... | Implement the Python class `DataFetcher` described below.
Class description:
DataFetcher for retrieving Wyoming Sounding data
Method signatures and docstrings:
- def __init__(self, station_number, year, month, day_start, day_end, start_hour=0, end_hour=12): Initialize Data Fetcher @param station_number: Station numbe... | 935bfd54149abd9542fe38e77b7eabab48b1c3a1 | <|skeleton|>
class DataFetcher:
"""DataFetcher for retrieving Wyoming Sounding data"""
def __init__(self, station_number, year, month, day_start, day_end, start_hour=0, end_hour=12):
"""Initialize Data Fetcher @param station_number: Station number @param year: Input year @param month: Input month (Inte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataFetcher:
"""DataFetcher for retrieving Wyoming Sounding data"""
def __init__(self, station_number, year, month, day_start, day_end, start_hour=0, end_hour=12):
"""Initialize Data Fetcher @param station_number: Station number @param year: Input year @param month: Input month (Integer for a sin... | the_stack_v2_python_sparse | skdaccess/geo/wyoming_sounding/cache/data_fetcher.py | MITHaystack/scikit-dataaccess | train | 41 |
15affd7f845f256010f1b5713a2bec46068da839 | [
"if not root:\n return []\nreturn self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]",
"if not root:\n return []\nans: List[int] = []\nstack: List[TreeNode] = [root]\nwhile stack:\n node = stack.pop()\n if not node:\n continue\n ans.append(node.val)\n if... | <|body_start_0|>
if not root:
return []
return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]
<|end_body_0|>
<|body_start_1|>
if not root:
return []
ans: List[int] = []
stack: List[TreeNode] = [root]
while st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
"""递归。"""
<|body_0|>
def postorderTraversal2(self, root: TreeNode) -> List[int]:
"""迭代(栈)。 修改前序遍历的代码,修改左右子树入栈的顺序,并将结果集取反即可。"""
<|body_1|>
def postorderTraversal3(self, root: TreeNode) -... | stack_v2_sparse_classes_36k_train_012010 | 2,520 | no_license | [
{
"docstring": "递归。",
"name": "postorderTraversal",
"signature": "def postorderTraversal(self, root: TreeNode) -> List[int]"
},
{
"docstring": "迭代(栈)。 修改前序遍历的代码,修改左右子树入栈的顺序,并将结果集取反即可。",
"name": "postorderTraversal2",
"signature": "def postorderTraversal2(self, root: TreeNode) -> List[int... | 3 | stack_v2_sparse_classes_30k_train_012224 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorderTraversal(self, root: TreeNode) -> List[int]: 递归。
- def postorderTraversal2(self, root: TreeNode) -> List[int]: 迭代(栈)。 修改前序遍历的代码,修改左右子树入栈的顺序,并将结果集取反即可。
- def postord... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorderTraversal(self, root: TreeNode) -> List[int]: 递归。
- def postorderTraversal2(self, root: TreeNode) -> List[int]: 迭代(栈)。 修改前序遍历的代码,修改左右子树入栈的顺序,并将结果集取反即可。
- def postord... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
"""递归。"""
<|body_0|>
def postorderTraversal2(self, root: TreeNode) -> List[int]:
"""迭代(栈)。 修改前序遍历的代码,修改左右子树入栈的顺序,并将结果集取反即可。"""
<|body_1|>
def postorderTraversal3(self, root: TreeNode) -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
"""递归。"""
if not root:
return []
return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]
def postorderTraversal2(self, root: TreeNode) -> List[int]:
"""迭代(... | the_stack_v2_python_sparse | 0145_binnay-tree-postorder-traversal.py | Nigirimeshi/leetcode | train | 0 | |
fdaecbc85a8bbef77a727b383387b45ccf0b1c87 | [
"if robot_lib_ctx:\n return BuiltIn().get_variable_value(var)\nelif var in Vars().global_vars:\n return Vars().global_vars[var]\nelse:\n return None",
"if robot_lib_ctx:\n BuiltIn().set_global_variable(var, val)\nelse:\n Vars().global_vars[var] = val\n return True"
] | <|body_start_0|>
if robot_lib_ctx:
return BuiltIn().get_variable_value(var)
elif var in Vars().global_vars:
return Vars().global_vars[var]
else:
return None
<|end_body_0|>
<|body_start_1|>
if robot_lib_ctx:
BuiltIn().set_global_variable(va... | Vars class is an Variables interface class for Toby framework. It uses Robot framework BuiltIn lib when used with Robot framework. When toby is used as Framework library, it will use Class member variables instead of Robot library. It provides set_global_variable() and get_global_variable() to set/get global variables ... | Vars | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vars:
"""Vars class is an Variables interface class for Toby framework. It uses Robot framework BuiltIn lib when used with Robot framework. When toby is used as Framework library, it will use Class member variables instead of Robot library. It provides set_global_variable() and get_global_variabl... | stack_v2_sparse_classes_36k_train_012011 | 2,679 | no_license | [
{
"docstring": "Get global variable value for a given variable :param var: *MANDATORY* mandatory name of variable :return: Returns the value of global variable",
"name": "get_global_variable",
"signature": "def get_global_variable(var)"
},
{
"docstring": "Set global variable 'var' to value 'val'... | 2 | null | Implement the Python class `Vars` described below.
Class description:
Vars class is an Variables interface class for Toby framework. It uses Robot framework BuiltIn lib when used with Robot framework. When toby is used as Framework library, it will use Class member variables instead of Robot library. It provides set_g... | Implement the Python class `Vars` described below.
Class description:
Vars class is an Variables interface class for Toby framework. It uses Robot framework BuiltIn lib when used with Robot framework. When toby is used as Framework library, it will use Class member variables instead of Robot library. It provides set_g... | 3966c63d48557b0b94303896eed7a767593a4832 | <|skeleton|>
class Vars:
"""Vars class is an Variables interface class for Toby framework. It uses Robot framework BuiltIn lib when used with Robot framework. When toby is used as Framework library, it will use Class member variables instead of Robot library. It provides set_global_variable() and get_global_variabl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vars:
"""Vars class is an Variables interface class for Toby framework. It uses Robot framework BuiltIn lib when used with Robot framework. When toby is used as Framework library, it will use Class member variables instead of Robot library. It provides set_global_variable() and get_global_variable() to set/ge... | the_stack_v2_python_sparse | NITA/lib/jnpr/toby/utils/Vars.py | fengyun4623/file | train | 0 |
1b0ee9944aa7d5f8a2368fd0f4ca9d635a8c6f8c | [
"if self.action in ['create']:\n permission_classes = [permissions.IsPlaylistToken & (permissions.IsTokenInstructor | permissions.IsTokenAdmin)]\nelse:\n permission_classes = self.permission_classes\nreturn [permission() for permission in permission_classes]",
"try:\n form = DocumentForm(request.data)\n ... | <|body_start_0|>
if self.action in ['create']:
permission_classes = [permissions.IsPlaylistToken & (permissions.IsTokenInstructor | permissions.IsTokenAdmin)]
else:
permission_classes = self.permission_classes
return [permission() for permission in permission_classes]
<|e... | Viewset for the API of the Document object. | DocumentViewSet | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentViewSet:
"""Viewset for the API of the Document object."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods. Default to the ViewSet's default permissions."""
<|body_0|>
def create(self, request, *args, **kwargs):
"""Create one doc... | stack_v2_sparse_classes_36k_train_012012 | 3,170 | permissive | [
{
"docstring": "Manage permissions for built-in DRF methods. Default to the ViewSet's default permissions.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Create one document based on the request payload.",
"name": "create",
"signature": "def crea... | 3 | null | Implement the Python class `DocumentViewSet` described below.
Class description:
Viewset for the API of the Document object.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods. Default to the ViewSet's default permissions.
- def create(self, request, *args, **kw... | Implement the Python class `DocumentViewSet` described below.
Class description:
Viewset for the API of the Document object.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods. Default to the ViewSet's default permissions.
- def create(self, request, *args, **kw... | f767f1bdc12c9712f26ea17cb8b19f536389f0ed | <|skeleton|>
class DocumentViewSet:
"""Viewset for the API of the Document object."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods. Default to the ViewSet's default permissions."""
<|body_0|>
def create(self, request, *args, **kwargs):
"""Create one doc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DocumentViewSet:
"""Viewset for the API of the Document object."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods. Default to the ViewSet's default permissions."""
if self.action in ['create']:
permission_classes = [permissions.IsPlaylistToken & (per... | the_stack_v2_python_sparse | src/backend/marsha/core/api/file.py | openfun/marsha | train | 92 |
c7b42adbe63d86b2d67cfa208ada015b466f759d | [
"self.pattern_th = math.inf\nself.trend_th = (-math.inf, math.inf)\nself.ratio = 0.01\nself.dist_measure = EuclideanDistance()\nself.mode = 'default'\nself.anomaly_indexes_ = None\nself.anomaly_scores_ = None",
"self.ratio = ratio\nself.dist_measure = dist_measure\nself.mode = mode\nself.pattern_th = pattern_thre... | <|body_start_0|>
self.pattern_th = math.inf
self.trend_th = (-math.inf, math.inf)
self.ratio = 0.01
self.dist_measure = EuclideanDistance()
self.mode = 'default'
self.anomaly_indexes_ = None
self.anomaly_scores_ = None
<|end_body_0|>
<|body_start_1|>
self... | Example: >>> #The dataset is split into x_train, x_test, y_train, y_test >>> forecaster = Forecaster(...) >>> forecaster.fit(x=x_train, y=y_train, ...) >>> y_pred = forecaster.predict(x_test) >>> td = ThresholdDetector() >>> td.fit(y_test, y_pred) >>> anomaly_scores = td.score() >>> anomaly_indexes = td.anomaly_indexes... | ThresholdDetector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThresholdDetector:
"""Example: >>> #The dataset is split into x_train, x_test, y_train, y_test >>> forecaster = Forecaster(...) >>> forecaster.fit(x=x_train, y=y_train, ...) >>> y_pred = forecaster.predict(x_test) >>> td = ThresholdDetector() >>> td.fit(y_test, y_pred) >>> anomaly_scores = td.sco... | stack_v2_sparse_classes_36k_train_012013 | 13,597 | permissive | [
{
"docstring": "Initialize a ThresholdDetector.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Set parameters for ThresholdDetector :param mode: mode can be \"default\" or \"gaussian\". \"default\" : fit data according to a uniform distribution \"gaussian\": fit data ... | 5 | null | Implement the Python class `ThresholdDetector` described below.
Class description:
Example: >>> #The dataset is split into x_train, x_test, y_train, y_test >>> forecaster = Forecaster(...) >>> forecaster.fit(x=x_train, y=y_train, ...) >>> y_pred = forecaster.predict(x_test) >>> td = ThresholdDetector() >>> td.fit(y_te... | Implement the Python class `ThresholdDetector` described below.
Class description:
Example: >>> #The dataset is split into x_train, x_test, y_train, y_test >>> forecaster = Forecaster(...) >>> forecaster.fit(x=x_train, y=y_train, ...) >>> y_pred = forecaster.predict(x_test) >>> td = ThresholdDetector() >>> td.fit(y_te... | 4ffa012a426e0d16ed13b707b03d8787ddca6aa4 | <|skeleton|>
class ThresholdDetector:
"""Example: >>> #The dataset is split into x_train, x_test, y_train, y_test >>> forecaster = Forecaster(...) >>> forecaster.fit(x=x_train, y=y_train, ...) >>> y_pred = forecaster.predict(x_test) >>> td = ThresholdDetector() >>> td.fit(y_test, y_pred) >>> anomaly_scores = td.sco... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThresholdDetector:
"""Example: >>> #The dataset is split into x_train, x_test, y_train, y_test >>> forecaster = Forecaster(...) >>> forecaster.fit(x=x_train, y=y_train, ...) >>> y_pred = forecaster.predict(x_test) >>> td = ThresholdDetector() >>> td.fit(y_test, y_pred) >>> anomaly_scores = td.score() >>> anom... | the_stack_v2_python_sparse | python/chronos/src/bigdl/chronos/detector/anomaly/th_detector.py | intel-analytics/BigDL | train | 4,913 |
dde5e8f8d6d833a526e3cec6ff285590387226dd | [
"M = [1] * (n + 1)\nM[1] = 1\nfor i in range(2, n + 1):\n M[i] = M[i - 1] + M[i - 2]\nreturn M[-1]",
"if n == 1 or n == 2:\n return n\nfirst = 1\nsecond = 2\nfor i in range(3, n + 1):\n tmp = first + second\n first = second\n second = tmp\nreturn second"
] | <|body_start_0|>
M = [1] * (n + 1)
M[1] = 1
for i in range(2, n + 1):
M[i] = M[i - 1] + M[i - 2]
return M[-1]
<|end_body_0|>
<|body_start_1|>
if n == 1 or n == 2:
return n
first = 1
second = 2
for i in range(3, n + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
M = [1] * (n + 1)
M[1] = 1
for i in range(2, n + 1):
... | stack_v2_sparse_classes_36k_train_012014 | 686 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018418 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): :type n: int :rtype: int
- def climbStairs(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): :type n: int :rtype: int
- def climbStairs(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def climbStairs(self, n):
""":t... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
M = [1] * (n + 1)
M[1] = 1
for i in range(2, n + 1):
M[i] = M[i - 1] + M[i - 2]
return M[-1]
def climbStairs(self, n):
""":type n: int :rtype: int"""
if n == 1 or n == 2:... | the_stack_v2_python_sparse | 0070_Climbing_Stairs.py | bingli8802/leetcode | train | 0 | |
f0f80f3716b3efd0a35fd3914efbf09ed4d9e0d2 | [
"from h5py import File as h5\nself.preexisting_slice = preexisting_slice\nself.incoming_slice = incoming_slice\nself.received_slices = []\nself.grid = np.squeeze(np.array(eval(grid)))\nself.frames_per_block = frames_per_block\nself.outputs = outputs\npdist = np.zeros(self.grid.size, dtype=[('center', 'f4'), ('kde',... | <|body_start_0|>
from h5py import File as h5
self.preexisting_slice = preexisting_slice
self.incoming_slice = incoming_slice
self.received_slices = []
self.grid = np.squeeze(np.array(eval(grid)))
self.frames_per_block = frames_per_block
self.outputs = outputs
... | Coroutine class; accumulates Blocks of data and performs analysis once complete dataset is present; may then be sent to a Block_Acceptor | KDE_Block_Accumulator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KDE_Block_Accumulator:
"""Coroutine class; accumulates Blocks of data and performs analysis once complete dataset is present; may then be sent to a Block_Acceptor"""
def __init__(self, preexisting_slice, incoming_slice, grid, bandwidth, frames_per_block, outputs, attrs={}, **kwargs):
... | stack_v2_sparse_classes_36k_train_012015 | 28,607 | permissive | [
{
"docstring": "Initializes accumulator **Arguments:** :*preexisting_slice*: Slice containing frame indices whose results were included in *outputs* before this invocation of program :*incoming_slice*: Slice containting frame indices whose results are to be added to *outputs* during this invocation of program :... | 3 | stack_v2_sparse_classes_30k_train_002823 | Implement the Python class `KDE_Block_Accumulator` described below.
Class description:
Coroutine class; accumulates Blocks of data and performs analysis once complete dataset is present; may then be sent to a Block_Acceptor
Method signatures and docstrings:
- def __init__(self, preexisting_slice, incoming_slice, grid... | Implement the Python class `KDE_Block_Accumulator` described below.
Class description:
Coroutine class; accumulates Blocks of data and performs analysis once complete dataset is present; may then be sent to a Block_Acceptor
Method signatures and docstrings:
- def __init__(self, preexisting_slice, incoming_slice, grid... | 9e86e996ed7958a348012c053fa957d94729be8a | <|skeleton|>
class KDE_Block_Accumulator:
"""Coroutine class; accumulates Blocks of data and performs analysis once complete dataset is present; may then be sent to a Block_Acceptor"""
def __init__(self, preexisting_slice, incoming_slice, grid, bandwidth, frames_per_block, outputs, attrs={}, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KDE_Block_Accumulator:
"""Coroutine class; accumulates Blocks of data and performs analysis once complete dataset is present; may then be sent to a Block_Acceptor"""
def __init__(self, preexisting_slice, incoming_slice, grid, bandwidth, frames_per_block, outputs, attrs={}, **kwargs):
"""Initializ... | the_stack_v2_python_sparse | secondary/pdist.py | KarlTDebiec/MDclt | train | 0 |
0be742c17f93a94c1a14712f36e734c98d655442 | [
"self.login()\nif self.try_get_Term():\n try:\n logger.info('有效期设备系统时间不可手动更改测试')\n self.uncheck_automaticbtn()\n self.assertTrue(self.get_element_att(self.year))\n except Exception as msg:\n logger.error(u'异常原因:%s' % msg)\n self.driver.get_screenshot_as_file(os.path.join(rea... | <|body_start_0|>
self.login()
if self.try_get_Term():
try:
logger.info('有效期设备系统时间不可手动更改测试')
self.uncheck_automaticbtn()
self.assertTrue(self.get_element_att(self.year))
except Exception as msg:
logger.error(u'异常原因:%s... | 系统时间测试 | SystemTimerTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemTimerTest:
"""系统时间测试"""
def test1_no_change_time(self):
"""手动更改设备系统时间不可测试"""
<|body_0|>
def test2_automatic_change_time(self):
"""自动同步网络时间测试"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.login()
if self.try_get_Term():
... | stack_v2_sparse_classes_36k_train_012016 | 2,940 | no_license | [
{
"docstring": "手动更改设备系统时间不可测试",
"name": "test1_no_change_time",
"signature": "def test1_no_change_time(self)"
},
{
"docstring": "自动同步网络时间测试",
"name": "test2_automatic_change_time",
"signature": "def test2_automatic_change_time(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015921 | Implement the Python class `SystemTimerTest` described below.
Class description:
系统时间测试
Method signatures and docstrings:
- def test1_no_change_time(self): 手动更改设备系统时间不可测试
- def test2_automatic_change_time(self): 自动同步网络时间测试 | Implement the Python class `SystemTimerTest` described below.
Class description:
系统时间测试
Method signatures and docstrings:
- def test1_no_change_time(self): 手动更改设备系统时间不可测试
- def test2_automatic_change_time(self): 自动同步网络时间测试
<|skeleton|>
class SystemTimerTest:
"""系统时间测试"""
def test1_no_change_time(self):
... | fd552eeb47fd4838c2c5caef4deea7480ab75ce9 | <|skeleton|>
class SystemTimerTest:
"""系统时间测试"""
def test1_no_change_time(self):
"""手动更改设备系统时间不可测试"""
<|body_0|>
def test2_automatic_change_time(self):
"""自动同步网络时间测试"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SystemTimerTest:
"""系统时间测试"""
def test1_no_change_time(self):
"""手动更改设备系统时间不可测试"""
self.login()
if self.try_get_Term():
try:
logger.info('有效期设备系统时间不可手动更改测试')
self.uncheck_automaticbtn()
self.assertTrue(self.get_element_at... | the_stack_v2_python_sparse | test_case/C007_system_time_test.py | luhuifnag/AVA_UIauto_test | train | 0 |
fadde5d11e11e098fb24fcd2cd04abbd229e063f | [
"children = children or []\nsuper(AccordionWithThread, self).__init__(children=children, **kwargs)\nself._thread = None\nself._device_list = None",
"if hasattr(self, '_thread'):\n try:\n self._thread.do_run = False\n self._thread.join()\n except Exception:\n pass\nself.close()"
] | <|body_start_0|>
children = children or []
super(AccordionWithThread, self).__init__(children=children, **kwargs)
self._thread = None
self._device_list = None
<|end_body_0|>
<|body_start_1|>
if hasattr(self, '_thread'):
try:
self._thread.do_run = Fals... | An ``Accordion`` that will close an attached thread. | AccordionWithThread | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccordionWithThread:
"""An ``Accordion`` that will close an attached thread."""
def __init__(self, children: Optional[List]=None, **kwargs: Any):
"""AccordionWithThread constructor. Args: children: A list of widgets to be attached to the accordion. **kwargs: Additional keywords to be... | stack_v2_sparse_classes_36k_train_012017 | 13,104 | permissive | [
{
"docstring": "AccordionWithThread constructor. Args: children: A list of widgets to be attached to the accordion. **kwargs: Additional keywords to be passed to ``ipywidgets.Accordion``.",
"name": "__init__",
"signature": "def __init__(self, children: Optional[List]=None, **kwargs: Any)"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_020747 | Implement the Python class `AccordionWithThread` described below.
Class description:
An ``Accordion`` that will close an attached thread.
Method signatures and docstrings:
- def __init__(self, children: Optional[List]=None, **kwargs: Any): AccordionWithThread constructor. Args: children: A list of widgets to be attac... | Implement the Python class `AccordionWithThread` described below.
Class description:
An ``Accordion`` that will close an attached thread.
Method signatures and docstrings:
- def __init__(self, children: Optional[List]=None, **kwargs: Any): AccordionWithThread constructor. Args: children: A list of widgets to be attac... | 590f68d9ddb42a45c4ac8a8626ea60da85575b21 | <|skeleton|>
class AccordionWithThread:
"""An ``Accordion`` that will close an attached thread."""
def __init__(self, children: Optional[List]=None, **kwargs: Any):
"""AccordionWithThread constructor. Args: children: A list of widgets to be attached to the accordion. **kwargs: Additional keywords to be... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccordionWithThread:
"""An ``Accordion`` that will close an attached thread."""
def __init__(self, children: Optional[List]=None, **kwargs: Any):
"""AccordionWithThread constructor. Args: children: A list of widgets to be attached to the accordion. **kwargs: Additional keywords to be passed to ``... | the_stack_v2_python_sparse | qiskit/providers/ibmq/jupyter/dashboard/dashboard.py | Qiskit/qiskit-ibmq-provider | train | 240 |
c982941bc595011a7459503a0421ae66287b6c6f | [
"self.id: Union[str, None] = id\nself.parent: Union['Tag', None] = parent\nself.parameter: Union[str, None] = parameter\nif children is None:\n self.children: List[Union[str, 'Tag']] = []",
"if self.children:\n if isinstance(self.children[-1], Tag):\n self.children.append(text)\n else:\n se... | <|body_start_0|>
self.id: Union[str, None] = id
self.parent: Union['Tag', None] = parent
self.parameter: Union[str, None] = parameter
if children is None:
self.children: List[Union[str, 'Tag']] = []
<|end_body_0|>
<|body_start_1|>
if self.children:
if isi... | Represents a tag in PoE texts. For example: <size:45>{I have <item>{My item} for sale} tag.id = 'size' tag.parent = None tag.children = ['I have ', <Tag object>, ' for sale'] tag.parameter = '45' Parameters ---------- id identifier string of the tag parent parent Tag instance if any children list of child strings or ta... | Tag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tag:
"""Represents a tag in PoE texts. For example: <size:45>{I have <item>{My item} for sale} tag.id = 'size' tag.parent = None tag.children = ['I have ', <Tag object>, ' for sale'] tag.parameter = '45' Parameters ---------- id identifier string of the tag parent parent Tag instance if any child... | stack_v2_sparse_classes_36k_train_012018 | 7,546 | permissive | [
{
"docstring": "Parameters ---------- id identifier string of the tag parent parent Tag instance if any children list of child strings or tag instances parameter parameter specified in the text to this tag if any",
"name": "__init__",
"signature": "def __init__(self, id: Union[str, None]=None, parent: U... | 4 | stack_v2_sparse_classes_30k_test_000636 | Implement the Python class `Tag` described below.
Class description:
Represents a tag in PoE texts. For example: <size:45>{I have <item>{My item} for sale} tag.id = 'size' tag.parent = None tag.children = ['I have ', <Tag object>, ' for sale'] tag.parameter = '45' Parameters ---------- id identifier string of the tag ... | Implement the Python class `Tag` described below.
Class description:
Represents a tag in PoE texts. For example: <size:45>{I have <item>{My item} for sale} tag.id = 'size' tag.parent = None tag.children = ['I have ', <Tag object>, ' for sale'] tag.parameter = '45' Parameters ---------- id identifier string of the tag ... | 7b3ddc8dc310c580c3e75c4835389c1204936206 | <|skeleton|>
class Tag:
"""Represents a tag in PoE texts. For example: <size:45>{I have <item>{My item} for sale} tag.id = 'size' tag.parent = None tag.children = ['I have ', <Tag object>, ' for sale'] tag.parameter = '45' Parameters ---------- id identifier string of the tag parent parent Tag instance if any child... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tag:
"""Represents a tag in PoE texts. For example: <size:45>{I have <item>{My item} for sale} tag.id = 'size' tag.parent = None tag.children = ['I have ', <Tag object>, ' for sale'] tag.parameter = '45' Parameters ---------- id identifier string of the tag parent parent Tag instance if any children list of c... | the_stack_v2_python_sparse | third-party/PyPoE/PyPoE/poe/text.py | erosson/pypoe-json | train | 1 |
96f739553865180aff8d362b80f56ca967bbd23f | [
"m = SortedDict()\nj = 0\nfor i in range(len(nums)):\n if i - j > k:\n m.pop(nums[j])\n j += 1\n a = m.bisect_left(nums[i] - t)\n keys = m.keys()\n if a < len(m) and abs(keys[a] - nums[i]) <= t:\n return True\n m[nums[i]] = i\nreturn False",
"\"\"\"\n The idea is like th... | <|body_start_0|>
m = SortedDict()
j = 0
for i in range(len(nums)):
if i - j > k:
m.pop(nums[j])
j += 1
a = m.bisect_left(nums[i] - t)
keys = m.keys()
if a < len(m) and abs(keys[a] - nums[i]) <= t:
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyAlmostDuplicateOrderMap(self, nums, k, t):
""":type nums: List[int] :type k: int :type t: int :rtype: bool"""
<|body_0|>
def containsNearbyAlmostDuplicate(self, nums, k, t):
""":type nums: List[int] :type k: int :type t: int :rtype: bool""... | stack_v2_sparse_classes_36k_train_012019 | 2,822 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :type t: int :rtype: bool",
"name": "containsNearbyAlmostDuplicateOrderMap",
"signature": "def containsNearbyAlmostDuplicateOrderMap(self, nums, k, t)"
},
{
"docstring": ":type nums: List[int] :type k: int :type t: int :rtype: bool",
"name":... | 2 | stack_v2_sparse_classes_30k_train_014573 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyAlmostDuplicateOrderMap(self, nums, k, t): :type nums: List[int] :type k: int :type t: int :rtype: bool
- def containsNearbyAlmostDuplicate(self, nums, k, t): :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyAlmostDuplicateOrderMap(self, nums, k, t): :type nums: List[int] :type k: int :type t: int :rtype: bool
- def containsNearbyAlmostDuplicate(self, nums, k, t): :... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def containsNearbyAlmostDuplicateOrderMap(self, nums, k, t):
""":type nums: List[int] :type k: int :type t: int :rtype: bool"""
<|body_0|>
def containsNearbyAlmostDuplicate(self, nums, k, t):
""":type nums: List[int] :type k: int :type t: int :rtype: bool""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containsNearbyAlmostDuplicateOrderMap(self, nums, k, t):
""":type nums: List[int] :type k: int :type t: int :rtype: bool"""
m = SortedDict()
j = 0
for i in range(len(nums)):
if i - j > k:
m.pop(nums[j])
j += 1
... | the_stack_v2_python_sparse | C/ContainsDuplicateIII.py | bssrdf/pyleet | train | 2 | |
f2bee36372386b72cd7497612d447b32f893e3ba | [
"self.positivePath, self.negetivePath = self.getPath()\nself.get_picture_path()\nself.rotate()\nself.split_images()\nif save:\n self.save()",
"front_viwe = np.load(front_viwe_path, allow_pickle=True).item()\npositivePath = front_viwe['81']\nnegetivePath = []\nfor key, paths in front_viwe.items():\n if key !... | <|body_start_0|>
self.positivePath, self.negetivePath = self.getPath()
self.get_picture_path()
self.rotate()
self.split_images()
if save:
self.save()
<|end_body_0|>
<|body_start_1|>
front_viwe = np.load(front_viwe_path, allow_pickle=True).item()
posit... | imagePocess | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class imagePocess:
def __init__(self, save: bool=True):
"""Parameters ---------- save : bool, optional The value is control when this class func finish whether save the result. Tue default is True Returns ------- None."""
<|body_0|>
def getPath(self, front_viwe_path: str='./data/f... | stack_v2_sparse_classes_36k_train_012020 | 5,760 | permissive | [
{
"docstring": "Parameters ---------- save : bool, optional The value is control when this class func finish whether save the result. Tue default is True Returns ------- None.",
"name": "__init__",
"signature": "def __init__(self, save: bool=True)"
},
{
"docstring": "Parameters ---------- front_... | 6 | stack_v2_sparse_classes_30k_train_010950 | Implement the Python class `imagePocess` described below.
Class description:
Implement the imagePocess class.
Method signatures and docstrings:
- def __init__(self, save: bool=True): Parameters ---------- save : bool, optional The value is control when this class func finish whether save the result. Tue default is Tr... | Implement the Python class `imagePocess` described below.
Class description:
Implement the imagePocess class.
Method signatures and docstrings:
- def __init__(self, save: bool=True): Parameters ---------- save : bool, optional The value is control when this class func finish whether save the result. Tue default is Tr... | 084b8c2b0437e3a30e2d74132cc3a55a06f18968 | <|skeleton|>
class imagePocess:
def __init__(self, save: bool=True):
"""Parameters ---------- save : bool, optional The value is control when this class func finish whether save the result. Tue default is True Returns ------- None."""
<|body_0|>
def getPath(self, front_viwe_path: str='./data/f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class imagePocess:
def __init__(self, save: bool=True):
"""Parameters ---------- save : bool, optional The value is control when this class func finish whether save the result. Tue default is True Returns ------- None."""
self.positivePath, self.negetivePath = self.getPath()
self.get_picture... | the_stack_v2_python_sparse | packages/prepare.py | YYYYifan/Real_Time_Car_Recognication_Embedded_System_Based_on_Convolution_Neural_Network | train | 0 | |
e74e64c7c73e5d81d8a59b53586a8cf9d678921e | [
"for i in range(num_consumer_types):\n if self.DiscFac == DiscFac_list[i]:\n self.solution_terminal.cFunc = deepcopy(consumers_ss[i].solution[0].cFunc)\n self.solution_terminal.vFunc = deepcopy(consumers_ss[i].solution[0].vFunc)\n self.solution_terminal.vPfunc = deepcopy(consumers_ss[i].solu... | <|body_start_0|>
for i in range(num_consumer_types):
if self.DiscFac == DiscFac_list[i]:
self.solution_terminal.cFunc = deepcopy(consumers_ss[i].solution[0].cFunc)
self.solution_terminal.vFunc = deepcopy(consumers_ss[i].solution[0].vFunc)
self.solution... | FBSNK2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FBSNK2:
def update_solution_terminal(self):
"""Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- none Returns ------- none"""
<|body_0|>
def sim_birth(self, which_agents):
"""Mak... | stack_v2_sparse_classes_36k_train_012021 | 31,380 | no_license | [
{
"docstring": "Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- none Returns ------- none",
"name": "update_solution_terminal",
"signature": "def update_solution_terminal(self)"
},
{
"docstring": "Makes ne... | 2 | stack_v2_sparse_classes_30k_train_021158 | Implement the Python class `FBSNK2` described below.
Class description:
Implement the FBSNK2 class.
Method signatures and docstrings:
- def update_solution_terminal(self): Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- none Re... | Implement the Python class `FBSNK2` described below.
Class description:
Implement the FBSNK2 class.
Method signatures and docstrings:
- def update_solution_terminal(self): Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- none Re... | a7bc0bba0734ed6d16c0fe26f650118507e6c115 | <|skeleton|>
class FBSNK2:
def update_solution_terminal(self):
"""Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- none Returns ------- none"""
<|body_0|>
def sim_birth(self, which_agents):
"""Mak... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FBSNK2:
def update_solution_terminal(self):
"""Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- none Returns ------- none"""
for i in range(num_consumer_types):
if self.DiscFac == DiscFac_list... | the_stack_v2_python_sparse | Jacobians/ConsumptionJacobians/Jacobian-SS.py | wdu9/FBS-NK | train | 1 | |
d207e3c0f902a9114dbcb8d88ba2adf41293480b | [
"db = sqlite3.connect(dbfile)\ncur = db.cursor()\ncur.execute('SELECT Id, Question, Source, Tags FROM questions')\ncount = 0\nfor question in cur:\n tokens = Tokenizer.tokenize(question[1] + ' ' + question[2] + ' ' + question[3])\n document = (question[0], tokens, question[3])\n count += 1\n if count % ... | <|body_start_0|>
db = sqlite3.connect(dbfile)
cur = db.cursor()
cur.execute('SELECT Id, Question, Source, Tags FROM questions')
count = 0
for question in cur:
tokens = Tokenizer.tokenize(question[1] + ' ' + question[2] + ' ' + question[3])
document = (ques... | Methods to build a new sentence embeddings index. | Index | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Index:
"""Methods to build a new sentence embeddings index."""
def stream(dbfile):
"""Streams questions from a questions.db file. This method is a generator and will yield a row at time. Args: dbfile: input SQLite file"""
<|body_0|>
def embeddings(dbfile):
"""Bui... | stack_v2_sparse_classes_36k_train_012022 | 2,363 | permissive | [
{
"docstring": "Streams questions from a questions.db file. This method is a generator and will yield a row at time. Args: dbfile: input SQLite file",
"name": "stream",
"signature": "def stream(dbfile)"
},
{
"docstring": "Builds a sentence embeddings index. Args: dbfile: input SQLite file Return... | 3 | stack_v2_sparse_classes_30k_train_020104 | Implement the Python class `Index` described below.
Class description:
Methods to build a new sentence embeddings index.
Method signatures and docstrings:
- def stream(dbfile): Streams questions from a questions.db file. This method is a generator and will yield a row at time. Args: dbfile: input SQLite file
- def em... | Implement the Python class `Index` described below.
Class description:
Methods to build a new sentence embeddings index.
Method signatures and docstrings:
- def stream(dbfile): Streams questions from a questions.db file. This method is a generator and will yield a row at time. Args: dbfile: input SQLite file
- def em... | c1fde2fcb3cf830247131385ec5340e6a148e70a | <|skeleton|>
class Index:
"""Methods to build a new sentence embeddings index."""
def stream(dbfile):
"""Streams questions from a questions.db file. This method is a generator and will yield a row at time. Args: dbfile: input SQLite file"""
<|body_0|>
def embeddings(dbfile):
"""Bui... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Index:
"""Methods to build a new sentence embeddings index."""
def stream(dbfile):
"""Streams questions from a questions.db file. This method is a generator and will yield a row at time. Args: dbfile: input SQLite file"""
db = sqlite3.connect(dbfile)
cur = db.cursor()
cur.... | the_stack_v2_python_sparse | src/python/codequestion/index.py | spreck/codequestion | train | 0 |
0828fb0729244f70b2d9b4837b53781fa9ba93aa | [
"super(RegExEdge, self).__init__(label)\nself.from_regex = from_regex\nself.to_regex = to_regex\nself.weight = weight",
"res_id_strct = IDStruct()\nfor left, right in id_strct:\n res_id_strct.add(left, re.sub(self.from_regex, self.to_regex, right))\nreturn res_id_strct"
] | <|body_start_0|>
super(RegExEdge, self).__init__(label)
self.from_regex = from_regex
self.to_regex = to_regex
self.weight = weight
<|end_body_0|>
<|body_start_1|>
res_id_strct = IDStruct()
for left, right in id_strct:
res_id_strct.add(left, re.sub(self.from_r... | The RegExEdge allows an identifier to be transformed using a regular expression. POSIX regular expressions are supported. | RegExEdge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegExEdge:
"""The RegExEdge allows an identifier to be transformed using a regular expression. POSIX regular expressions are supported."""
def __init__(self, from_regex, to_regex, weight=1, label=None):
""":param from_regex: The first parameter of the regular expression substitution.... | stack_v2_sparse_classes_36k_train_012023 | 22,080 | permissive | [
{
"docstring": ":param from_regex: The first parameter of the regular expression substitution. :type from_regex: str :param to_regex: The second parameter of the regular expression substitution. :type to_regex: str :param weight: Weights are used to prefer one path over another. The path with the lowest weight ... | 2 | stack_v2_sparse_classes_30k_train_014560 | Implement the Python class `RegExEdge` described below.
Class description:
The RegExEdge allows an identifier to be transformed using a regular expression. POSIX regular expressions are supported.
Method signatures and docstrings:
- def __init__(self, from_regex, to_regex, weight=1, label=None): :param from_regex: Th... | Implement the Python class `RegExEdge` described below.
Class description:
The RegExEdge allows an identifier to be transformed using a regular expression. POSIX regular expressions are supported.
Method signatures and docstrings:
- def __init__(self, from_regex, to_regex, weight=1, label=None): :param from_regex: Th... | 2c23e0da57b7c64b0a19e534b9f75da70f140159 | <|skeleton|>
class RegExEdge:
"""The RegExEdge allows an identifier to be transformed using a regular expression. POSIX regular expressions are supported."""
def __init__(self, from_regex, to_regex, weight=1, label=None):
""":param from_regex: The first parameter of the regular expression substitution.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegExEdge:
"""The RegExEdge allows an identifier to be transformed using a regular expression. POSIX regular expressions are supported."""
def __init__(self, from_regex, to_regex, weight=1, label=None):
""":param from_regex: The first parameter of the regular expression substitution. :type from_r... | the_stack_v2_python_sparse | biothings/hub/datatransform/datatransform.py | biothings/biothings.api | train | 36 |
f4d23c8d62644e695d35a82fe0d1542de79f5859 | [
"super(GANLoss, self).__init__()\nself.register_buffer('real_label', torch.tensor(target_real_label))\nself.register_buffer('fake_label', torch.tensor(target_fake_label))\nself.gan_mode = gan_mode\nif gan_mode == 'lsgan':\n self.loss = nn.MSELoss()\nelif gan_mode == 'vanilla':\n self.loss = nn.BCEWithLogitsLo... | <|body_start_0|>
super(GANLoss, self).__init__()
self.register_buffer('real_label', torch.tensor(target_real_label))
self.register_buffer('fake_label', torch.tensor(target_fake_label))
self.gan_mode = gan_mode
if gan_mode == 'lsgan':
self.loss = nn.MSELoss()
e... | Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix | GANLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GANLoss:
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix"""
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):... | stack_v2_sparse_classes_36k_train_012024 | 8,362 | permissive | [
{
"docstring": "Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp. target_real_label (bool) - - label for a real image target_fake_label (bool) - - label of a fake image Note: Do not use sigmoid as the last layer of Discrimin... | 3 | stack_v2_sparse_classes_30k_train_017991 | Implement the Python class `GANLoss` described below.
Class description:
Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix
Method signatures and docstrings:
- def __i... | Implement the Python class `GANLoss` described below.
Class description:
Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix
Method signatures and docstrings:
- def __i... | cf93437e5d7ae87fa916141cf4b5cc2e929b8199 | <|skeleton|>
class GANLoss:
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix"""
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GANLoss:
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix"""
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
"""I... | the_stack_v2_python_sparse | lib/loss/functions/basic_loss.py | JokerWDL/PyAnomaly | train | 1 |
c4e5a30af0996bf32da03b074756e621a391c406 | [
"if landmarks is not None:\n self.landmarks = landmarks[0]\nelse:\n raise BaseException('No landmarks are created')",
"if isinstance(idx_pair, int):\n return landmark(self.landmarks[idx_pair - 1][0], self.landmarks[idx_pair - 1][1])\nelse:\n from_idx, to_idx = idx_pair\n return landmark_vector(self... | <|body_start_0|>
if landmarks is not None:
self.landmarks = landmarks[0]
else:
raise BaseException('No landmarks are created')
<|end_body_0|>
<|body_start_1|>
if isinstance(idx_pair, int):
return landmark(self.landmarks[idx_pair - 1][0], self.landmarks[idx_pa... | Landmarks | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Landmarks:
def __init__(self, landmarks):
"""landmarks from face_alignment" [pt index][2] -> [x, y] Warning: pt index in the landmark figure counts from 1; however, pt index in a list counts from 0"""
<|body_0|>
def __getitem__(self, idx_pair):
"""Returns: landmark v... | stack_v2_sparse_classes_36k_train_012025 | 2,663 | permissive | [
{
"docstring": "landmarks from face_alignment\" [pt index][2] -> [x, y] Warning: pt index in the landmark figure counts from 1; however, pt index in a list counts from 0",
"name": "__init__",
"signature": "def __init__(self, landmarks)"
},
{
"docstring": "Returns: landmark vector from 1st node t... | 2 | stack_v2_sparse_classes_30k_train_006590 | Implement the Python class `Landmarks` described below.
Class description:
Implement the Landmarks class.
Method signatures and docstrings:
- def __init__(self, landmarks): landmarks from face_alignment" [pt index][2] -> [x, y] Warning: pt index in the landmark figure counts from 1; however, pt index in a list counts... | Implement the Python class `Landmarks` described below.
Class description:
Implement the Landmarks class.
Method signatures and docstrings:
- def __init__(self, landmarks): landmarks from face_alignment" [pt index][2] -> [x, y] Warning: pt index in the landmark figure counts from 1; however, pt index in a list counts... | 95814c0dc465d53bebfc1b672ec95e981ca81a28 | <|skeleton|>
class Landmarks:
def __init__(self, landmarks):
"""landmarks from face_alignment" [pt index][2] -> [x, y] Warning: pt index in the landmark figure counts from 1; however, pt index in a list counts from 0"""
<|body_0|>
def __getitem__(self, idx_pair):
"""Returns: landmark v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Landmarks:
def __init__(self, landmarks):
"""landmarks from face_alignment" [pt index][2] -> [x, y] Warning: pt index in the landmark figure counts from 1; however, pt index in a list counts from 0"""
if landmarks is not None:
self.landmarks = landmarks[0]
else:
... | the_stack_v2_python_sparse | src/data_process/data_augmentation/landmarks.py | heathcliffYang/data_process | train | 0 | |
683859b8ebbb5d83222e3e406b7333fa266a277e | [
"res = fn.cast(t, onp.float64)\nassert fn.get_interface(res) == fn.get_interface(t)\nif hasattr(res, 'numpy'):\n res = res.numpy()\n t = t.numpy()\nassert onp.issubdtype(onp.asarray(t).dtype, onp.integer)\nassert res.dtype.type is onp.float64",
"res = fn.cast(t, onp.dtype('float64'))\nassert fn.get_interfac... | <|body_start_0|>
res = fn.cast(t, onp.float64)
assert fn.get_interface(res) == fn.get_interface(t)
if hasattr(res, 'numpy'):
res = res.numpy()
t = t.numpy()
assert onp.issubdtype(onp.asarray(t).dtype, onp.integer)
assert res.dtype.type is onp.float64
<|end... | Tests for the cast function | TestCast | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCast:
"""Tests for the cast function"""
def test_cast_numpy(self, t):
"""Test that specifying a NumPy dtype results in proper casting behaviour"""
<|body_0|>
def test_cast_numpy_dtype(self, t):
"""Test that specifying a NumPy dtype object results in proper ca... | stack_v2_sparse_classes_36k_train_012026 | 47,600 | permissive | [
{
"docstring": "Test that specifying a NumPy dtype results in proper casting behaviour",
"name": "test_cast_numpy",
"signature": "def test_cast_numpy(self, t)"
},
{
"docstring": "Test that specifying a NumPy dtype object results in proper casting behaviour",
"name": "test_cast_numpy_dtype",
... | 5 | null | Implement the Python class `TestCast` described below.
Class description:
Tests for the cast function
Method signatures and docstrings:
- def test_cast_numpy(self, t): Test that specifying a NumPy dtype results in proper casting behaviour
- def test_cast_numpy_dtype(self, t): Test that specifying a NumPy dtype object... | Implement the Python class `TestCast` described below.
Class description:
Tests for the cast function
Method signatures and docstrings:
- def test_cast_numpy(self, t): Test that specifying a NumPy dtype results in proper casting behaviour
- def test_cast_numpy_dtype(self, t): Test that specifying a NumPy dtype object... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class TestCast:
"""Tests for the cast function"""
def test_cast_numpy(self, t):
"""Test that specifying a NumPy dtype results in proper casting behaviour"""
<|body_0|>
def test_cast_numpy_dtype(self, t):
"""Test that specifying a NumPy dtype object results in proper ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCast:
"""Tests for the cast function"""
def test_cast_numpy(self, t):
"""Test that specifying a NumPy dtype results in proper casting behaviour"""
res = fn.cast(t, onp.float64)
assert fn.get_interface(res) == fn.get_interface(t)
if hasattr(res, 'numpy'):
re... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits_backup/pennylane/pennylane#1081/before/test_functions.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
1c4e2fd34033973c51d13e82d5ea3f5609ce3716 | [
"try:\n return EnvironmentNote.objects.get(pk=pk)\nexcept EnvironmentNote.DoesNotExist:\n raise Http404",
"env_notes = self.get_object(pk)\nserializer = EnvironmentNotesSerializer(env_notes)\nreturn Response(serializer.data)",
"env_info = self.get_object(pk)\nserializer = EnvironmentNotesSerializer(env_in... | <|body_start_0|>
try:
return EnvironmentNote.objects.get(pk=pk)
except EnvironmentNote.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
env_notes = self.get_object(pk)
serializer = EnvironmentNotesSerializer(env_notes)
return Response(serialize... | Retrieve, update or delete a EnvironmentNotes instance. | EnvironmentNotesDetails | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvironmentNotesDetails:
"""Retrieve, update or delete a EnvironmentNotes instance."""
def get_object(self, pk):
"""Get the particular row from the table."""
<|body_0|>
def get(self, request, pk, format=None):
"""We are going to add the contact info content along... | stack_v2_sparse_classes_36k_train_012027 | 15,222 | permissive | [
{
"docstring": "Get the particular row from the table.",
"name": "get_object",
"signature": "def get_object(self, pk)"
},
{
"docstring": "We are going to add the contact info content along with this pull request",
"name": "get",
"signature": "def get(self, request, pk, format=None)"
},... | 4 | stack_v2_sparse_classes_30k_train_011487 | Implement the Python class `EnvironmentNotesDetails` described below.
Class description:
Retrieve, update or delete a EnvironmentNotes instance.
Method signatures and docstrings:
- def get_object(self, pk): Get the particular row from the table.
- def get(self, request, pk, format=None): We are going to add the conta... | Implement the Python class `EnvironmentNotesDetails` described below.
Class description:
Retrieve, update or delete a EnvironmentNotes instance.
Method signatures and docstrings:
- def get_object(self, pk): Get the particular row from the table.
- def get(self, request, pk, format=None): We are going to add the conta... | b0635e72338e14dad24f1ee0329212cd60a3e83a | <|skeleton|>
class EnvironmentNotesDetails:
"""Retrieve, update or delete a EnvironmentNotes instance."""
def get_object(self, pk):
"""Get the particular row from the table."""
<|body_0|>
def get(self, request, pk, format=None):
"""We are going to add the contact info content along... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnvironmentNotesDetails:
"""Retrieve, update or delete a EnvironmentNotes instance."""
def get_object(self, pk):
"""Get the particular row from the table."""
try:
return EnvironmentNote.objects.get(pk=pk)
except EnvironmentNote.DoesNotExist:
raise Http404
... | the_stack_v2_python_sparse | environment/views.py | faisaltheparttimecoder/carelogBackend | train | 1 |
7c8a599d62fc0b5e9012f440a9613baf220951de | [
"queryset = self.queryset.exclude(reply_rule=SUBSCRIPTION_ACCOUNT_REPLY_RULE['NOT_MATCH'])\nreply_account = self.request.query_params.get('reply_account')\nif reply_account:\n queryset = queryset.filter(reply_account=reply_account)\npage = self.paginate_queryset(queryset)\nif page is not None:\n serializer = ... | <|body_start_0|>
queryset = self.queryset.exclude(reply_rule=SUBSCRIPTION_ACCOUNT_REPLY_RULE['NOT_MATCH'])
reply_account = self.request.query_params.get('reply_account')
if reply_account:
queryset = queryset.filter(reply_account=reply_account)
page = self.paginate_queryset(qu... | 关键字回复 | KeyWordReplyManageView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyWordReplyManageView:
"""关键字回复"""
def list(self, request, *args, **kwargs):
"""关键字回复规则"""
<|body_0|>
def partial_update(self, request, *args, **kwargs):
"""更新关键字回复"""
<|body_1|>
def create(self, request, *args, **kwargs):
"""新建关键字回复"""
... | stack_v2_sparse_classes_36k_train_012028 | 5,675 | no_license | [
{
"docstring": "关键字回复规则",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstring": "更新关键字回复",
"name": "partial_update",
"signature": "def partial_update(self, request, *args, **kwargs)"
},
{
"docstring": "新建关键字回复",
"name": "create",
"signa... | 4 | stack_v2_sparse_classes_30k_train_010892 | Implement the Python class `KeyWordReplyManageView` described below.
Class description:
关键字回复
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): 关键字回复规则
- def partial_update(self, request, *args, **kwargs): 更新关键字回复
- def create(self, request, *args, **kwargs): 新建关键字回复
- def update_status(se... | Implement the Python class `KeyWordReplyManageView` described below.
Class description:
关键字回复
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): 关键字回复规则
- def partial_update(self, request, *args, **kwargs): 更新关键字回复
- def create(self, request, *args, **kwargs): 新建关键字回复
- def update_status(se... | 0d32f98f42591b43e0b4da5e978b627da517f758 | <|skeleton|>
class KeyWordReplyManageView:
"""关键字回复"""
def list(self, request, *args, **kwargs):
"""关键字回复规则"""
<|body_0|>
def partial_update(self, request, *args, **kwargs):
"""更新关键字回复"""
<|body_1|>
def create(self, request, *args, **kwargs):
"""新建关键字回复"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeyWordReplyManageView:
"""关键字回复"""
def list(self, request, *args, **kwargs):
"""关键字回复规则"""
queryset = self.queryset.exclude(reply_rule=SUBSCRIPTION_ACCOUNT_REPLY_RULE['NOT_MATCH'])
reply_account = self.request.query_params.get('reply_account')
if reply_account:
... | the_stack_v2_python_sparse | payserver/padmin/views/subscription_account_manage.py | yiyuhao/FukuanUnion | train | 0 |
91cc27ef0dc8daa2ebb6905c373d30fef03058d0 | [
"char_dict = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\n\ndef back_track(combination, next_digits):\n if len(next_digits) == 0:\n return res.append(combination)\n for c in char_dict[next_digits[0]]:\n back_track(combination + c, next_digit... | <|body_start_0|>
char_dict = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
def back_track(combination, next_digits):
if len(next_digits) == 0:
return res.append(combination)
for c in char_dict[next_digits[0]]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations_v1(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
char_dict = {'2': 'a... | stack_v2_sparse_classes_36k_train_012029 | 1,651 | no_license | [
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations_v1",
"signature": "def letterCombinations_v1(self, digits)"
},
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations_v1(self, digits): :type digits: str :rtype: List[str]
- def letterCombinations(self, digits): :type digits: str :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations_v1(self, digits): :type digits: str :rtype: List[str]
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
<|skeleton|>
class Solut... | c9bb551a1681af595dfc81f285d4c15e4d1ffb38 | <|skeleton|>
class Solution:
def letterCombinations_v1(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def letterCombinations_v1(self, digits):
""":type digits: str :rtype: List[str]"""
char_dict = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
def back_track(combination, next_digits):
if len(next_digits) == 0:
... | the_stack_v2_python_sparse | leetcode/middle/backTrack/letterCombinations.py | javacode123/oj | train | 0 | |
cd3e8572e1e7bfc4607a40f4198109b33d10a843 | [
"try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\ntry:\n obs = observaciones_pre_asf.read(id)\nexcept psycopg2.Error as err:\n ns.abort(400, message=get_msg_pgerror(err))\nexcept EmptySetError:\n ns.abort(404, message=ObservacionPreAsf.obs_not_found)\nexcep... | <|body_start_0|>
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
try:
obs = observaciones_pre_asf.read(id)
except psycopg2.Error as err:
ns.abort(400, message=get_msg_pgerror(err))
except Empty... | ObservacionPreAsf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObservacionPreAsf:
def get(self, id):
"""To fetch an observation (preliminar de la ASF)"""
<|body_0|>
def put(self, id):
"""To update an observation (preliminar de la ASF)"""
<|body_1|>
def delete(self, id):
"""To delete an observation (prelimina... | stack_v2_sparse_classes_36k_train_012030 | 13,540 | no_license | [
{
"docstring": "To fetch an observation (preliminar de la ASF)",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "To update an observation (preliminar de la ASF)",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "To delete an observation (preli... | 3 | stack_v2_sparse_classes_30k_train_005205 | Implement the Python class `ObservacionPreAsf` described below.
Class description:
Implement the ObservacionPreAsf class.
Method signatures and docstrings:
- def get(self, id): To fetch an observation (preliminar de la ASF)
- def put(self, id): To update an observation (preliminar de la ASF)
- def delete(self, id): T... | Implement the Python class `ObservacionPreAsf` described below.
Class description:
Implement the ObservacionPreAsf class.
Method signatures and docstrings:
- def get(self, id): To fetch an observation (preliminar de la ASF)
- def put(self, id): To update an observation (preliminar de la ASF)
- def delete(self, id): T... | e00610fac26ef3ca078fd037c0649b70fa0e9a09 | <|skeleton|>
class ObservacionPreAsf:
def get(self, id):
"""To fetch an observation (preliminar de la ASF)"""
<|body_0|>
def put(self, id):
"""To update an observation (preliminar de la ASF)"""
<|body_1|>
def delete(self, id):
"""To delete an observation (prelimina... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObservacionPreAsf:
def get(self, id):
"""To fetch an observation (preliminar de la ASF)"""
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
try:
obs = observaciones_pre_asf.read(id)
except psycopg... | the_stack_v2_python_sparse | DOS/soa/service/genl/endpoints/observaciones_pre_asf.py | Telematica/knight-rider | train | 1 | |
386e3f7e35652a26ed8ce5122c7deca74ea951ac | [
"self.entity_description = sensor\nself._attr_unique_id = f\"{coordinator.data['deviceID']}-{sensor.key}\"\nsuper().__init__(coordinator)",
"if (value := self.coordinator.data.get(self.entity_description.key)) is None:\n return None\nif self.entity_description.state_fn is not None:\n return self.entity_desc... | <|body_start_0|>
self.entity_description = sensor
self._attr_unique_id = f"{coordinator.data['deviceID']}-{sensor.key}"
super().__init__(coordinator)
<|end_body_0|>
<|body_start_1|>
if (value := self.coordinator.data.get(self.entity_description.key)) is None:
return None
... | Representation of a Fully Kiosk Browser sensor. | FullySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullySensor:
"""Representation of a Fully Kiosk Browser sensor."""
def __init__(self, coordinator: FullyKioskDataUpdateCoordinator, sensor: FullySensorEntityDescription) -> None:
"""Initialize the sensor entity."""
<|body_0|>
def native_value(self) -> StateType:
... | stack_v2_sparse_classes_36k_train_012031 | 4,613 | permissive | [
{
"docstring": "Initialize the sensor entity.",
"name": "__init__",
"signature": "def __init__(self, coordinator: FullyKioskDataUpdateCoordinator, sensor: FullySensorEntityDescription) -> None"
},
{
"docstring": "Return the state of the sensor.",
"name": "native_value",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_016146 | Implement the Python class `FullySensor` described below.
Class description:
Representation of a Fully Kiosk Browser sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: FullyKioskDataUpdateCoordinator, sensor: FullySensorEntityDescription) -> None: Initialize the sensor entity.
- def native_va... | Implement the Python class `FullySensor` described below.
Class description:
Representation of a Fully Kiosk Browser sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: FullyKioskDataUpdateCoordinator, sensor: FullySensorEntityDescription) -> None: Initialize the sensor entity.
- def native_va... | 2e65b77b2b5c17919939481f327963abdfdc53f0 | <|skeleton|>
class FullySensor:
"""Representation of a Fully Kiosk Browser sensor."""
def __init__(self, coordinator: FullyKioskDataUpdateCoordinator, sensor: FullySensorEntityDescription) -> None:
"""Initialize the sensor entity."""
<|body_0|>
def native_value(self) -> StateType:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullySensor:
"""Representation of a Fully Kiosk Browser sensor."""
def __init__(self, coordinator: FullyKioskDataUpdateCoordinator, sensor: FullySensorEntityDescription) -> None:
"""Initialize the sensor entity."""
self.entity_description = sensor
self._attr_unique_id = f"{coordin... | the_stack_v2_python_sparse | homeassistant/components/fully_kiosk/sensor.py | konnected-io/home-assistant | train | 24 |
890f122af0bd206ab1e01d03add889fcfdc72d5b | [
"with Resource(self._topo_source) as res:\n elev = res.get_meta_arr('elevation')\nreturn elev",
"with Resource(self._topo_source) as res:\n source_lat_lon = res.lat_lon\nreturn source_lat_lon"
] | <|body_start_0|>
with Resource(self._topo_source) as res:
elev = res.get_meta_arr('elevation')
return elev
<|end_body_0|>
<|body_start_1|>
with Resource(self._topo_source) as res:
source_lat_lon = res.lat_lon
return source_lat_lon
<|end_body_1|>
| TopoExtract for H5 files | TopoExtractH5 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopoExtractH5:
"""TopoExtract for H5 files"""
def source_elevation(self):
"""Get the 1D array of elevation data from the topo_source_h5"""
<|body_0|>
def source_lat_lon(self):
"""Get the 2D array (n, 2) of lat, lon data from the topo_source_h5"""
<|body_1... | stack_v2_sparse_classes_36k_train_012032 | 12,716 | permissive | [
{
"docstring": "Get the 1D array of elevation data from the topo_source_h5",
"name": "source_elevation",
"signature": "def source_elevation(self)"
},
{
"docstring": "Get the 2D array (n, 2) of lat, lon data from the topo_source_h5",
"name": "source_lat_lon",
"signature": "def source_lat_... | 2 | stack_v2_sparse_classes_30k_train_002484 | Implement the Python class `TopoExtractH5` described below.
Class description:
TopoExtract for H5 files
Method signatures and docstrings:
- def source_elevation(self): Get the 1D array of elevation data from the topo_source_h5
- def source_lat_lon(self): Get the 2D array (n, 2) of lat, lon data from the topo_source_h... | Implement the Python class `TopoExtractH5` described below.
Class description:
TopoExtract for H5 files
Method signatures and docstrings:
- def source_elevation(self): Get the 1D array of elevation data from the topo_source_h5
- def source_lat_lon(self): Get the 2D array (n, 2) of lat, lon data from the topo_source_h... | f3803a823c7bb0afd7ab6064625908dca0be3476 | <|skeleton|>
class TopoExtractH5:
"""TopoExtract for H5 files"""
def source_elevation(self):
"""Get the 1D array of elevation data from the topo_source_h5"""
<|body_0|>
def source_lat_lon(self):
"""Get the 2D array (n, 2) of lat, lon data from the topo_source_h5"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopoExtractH5:
"""TopoExtract for H5 files"""
def source_elevation(self):
"""Get the 1D array of elevation data from the topo_source_h5"""
with Resource(self._topo_source) as res:
elev = res.get_meta_arr('elevation')
return elev
def source_lat_lon(self):
"... | the_stack_v2_python_sparse | sup3r/utilities/topo.py | NREL/sup3r | train | 20 |
3d9ec6bbd1a3daf68331456a1faa0930e7a4d176 | [
"n = len(s)\n\n@lru_cache(None)\ndef dfs(i):\n if i == n:\n return 1\n result = 0\n for j in range(i + 1, min(i + 3, n + 1)):\n if s[i] != '0' and 1 <= int(s[i:j]) <= 26:\n result += dfs(j)\n return result\nreturn dfs(0)",
"n = len(s)\ndp = [0] * (n + 1)\ndp[0] = 1\nfor i in r... | <|body_start_0|>
n = len(s)
@lru_cache(None)
def dfs(i):
if i == n:
return 1
result = 0
for j in range(i + 1, min(i + 3, n + 1)):
if s[i] != '0' and 1 <= int(s[i:j]) <= 26:
result += dfs(j)
retur... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numDecodings(self, s: str) -> int:
"""DFS+Memoization"""
<|body_0|>
def numDecodings(self, s: str) -> int:
"""DP, Time: O(n), Space: O(n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(s)
@lru_cache(None)
def ... | stack_v2_sparse_classes_36k_train_012033 | 1,213 | no_license | [
{
"docstring": "DFS+Memoization",
"name": "numDecodings",
"signature": "def numDecodings(self, s: str) -> int"
},
{
"docstring": "DP, Time: O(n), Space: O(n)",
"name": "numDecodings",
"signature": "def numDecodings(self, s: str) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_000688 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDecodings(self, s: str) -> int: DFS+Memoization
- def numDecodings(self, s: str) -> int: DP, Time: O(n), Space: O(n) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDecodings(self, s: str) -> int: DFS+Memoization
- def numDecodings(self, s: str) -> int: DP, Time: O(n), Space: O(n)
<|skeleton|>
class Solution:
def numDecodings(se... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def numDecodings(self, s: str) -> int:
"""DFS+Memoization"""
<|body_0|>
def numDecodings(self, s: str) -> int:
"""DP, Time: O(n), Space: O(n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numDecodings(self, s: str) -> int:
"""DFS+Memoization"""
n = len(s)
@lru_cache(None)
def dfs(i):
if i == n:
return 1
result = 0
for j in range(i + 1, min(i + 3, n + 1)):
if s[i] != '0' and 1 <= i... | the_stack_v2_python_sparse | python/91-Decode Ways.py | cwza/leetcode | train | 0 | |
3b4c35bacb485fef9906c2fd9d7fbf2410ab1cf7 | [
"nmt_parser = argparse.ArgumentParser()\nnmt.add_arguments(nmt_parser)\nFLAGS, unparsed = nmt_parser.parse_known_args()\n_update_flags(FLAGS, 'nmt_train_test')\ndefault_hparams = nmt.create_hparams(FLAGS)\ntrain_fn = train.train\nnmt.run_main(FLAGS, default_hparams, train_fn, None)",
"nmt_parser = argparse.Argume... | <|body_start_0|>
nmt_parser = argparse.ArgumentParser()
nmt.add_arguments(nmt_parser)
FLAGS, unparsed = nmt_parser.parse_known_args()
_update_flags(FLAGS, 'nmt_train_test')
default_hparams = nmt.create_hparams(FLAGS)
train_fn = train.train
nmt.run_main(FLAGS, defa... | NMTTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NMTTest:
def testTrain(self):
"""Test the training loop is functional with basic hparams."""
<|body_0|>
def testTrainWithAvgCkpts(self):
"""Test the training loop is functional with basic hparams."""
<|body_1|>
def testInference(self):
"""Test in... | stack_v2_sparse_classes_36k_train_012034 | 3,404 | permissive | [
{
"docstring": "Test the training loop is functional with basic hparams.",
"name": "testTrain",
"signature": "def testTrain(self)"
},
{
"docstring": "Test the training loop is functional with basic hparams.",
"name": "testTrainWithAvgCkpts",
"signature": "def testTrainWithAvgCkpts(self)"... | 3 | stack_v2_sparse_classes_30k_val_001163 | Implement the Python class `NMTTest` described below.
Class description:
Implement the NMTTest class.
Method signatures and docstrings:
- def testTrain(self): Test the training loop is functional with basic hparams.
- def testTrainWithAvgCkpts(self): Test the training loop is functional with basic hparams.
- def test... | Implement the Python class `NMTTest` described below.
Class description:
Implement the NMTTest class.
Method signatures and docstrings:
- def testTrain(self): Test the training loop is functional with basic hparams.
- def testTrainWithAvgCkpts(self): Test the training loop is functional with basic hparams.
- def test... | c540fcc99eeacfb5c51de8daa0f8cca339f50799 | <|skeleton|>
class NMTTest:
def testTrain(self):
"""Test the training loop is functional with basic hparams."""
<|body_0|>
def testTrainWithAvgCkpts(self):
"""Test the training loop is functional with basic hparams."""
<|body_1|>
def testInference(self):
"""Test in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NMTTest:
def testTrain(self):
"""Test the training loop is functional with basic hparams."""
nmt_parser = argparse.ArgumentParser()
nmt.add_arguments(nmt_parser)
FLAGS, unparsed = nmt_parser.parse_known_args()
_update_flags(FLAGS, 'nmt_train_test')
default_hpara... | the_stack_v2_python_sparse | translation/gnmt/tensorflow/nmt/nmt_test.py | mlcommons/inference | train | 575 | |
c828d60b479b35486940725ccedc89a722ba5607 | [
"categoryAll = Category.objects.all()\nresult = [model_to_dict(category) for category in categoryAll]\nreturn JsonResponse({'status': True, 'category': result})",
"try:\n if not authCheck(['12', '515400'], request.session.get('login')):\n return JsonResponse({'err': '你没有权限', 'status': False}, status=401... | <|body_start_0|>
categoryAll = Category.objects.all()
result = [model_to_dict(category) for category in categoryAll]
return JsonResponse({'status': True, 'category': result})
<|end_body_0|>
<|body_start_1|>
try:
if not authCheck(['12', '515400'], request.session.get('login')... | CategoryView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryView:
def get(self, request):
"""获取文章分类列表 :param request: :return:"""
<|body_0|>
def post(self, request):
"""新增文章分裂 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
categoryAll = Category.objects.all()
result ... | stack_v2_sparse_classes_36k_train_012035 | 1,620 | no_license | [
{
"docstring": "获取文章分类列表 :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "新增文章分裂 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006725 | Implement the Python class `CategoryView` described below.
Class description:
Implement the CategoryView class.
Method signatures and docstrings:
- def get(self, request): 获取文章分类列表 :param request: :return:
- def post(self, request): 新增文章分裂 :param request: :return: | Implement the Python class `CategoryView` described below.
Class description:
Implement the CategoryView class.
Method signatures and docstrings:
- def get(self, request): 获取文章分类列表 :param request: :return:
- def post(self, request): 新增文章分裂 :param request: :return:
<|skeleton|>
class CategoryView:
def get(self, ... | 526dea540048fc92260bce611c520c50af744e0b | <|skeleton|>
class CategoryView:
def get(self, request):
"""获取文章分类列表 :param request: :return:"""
<|body_0|>
def post(self, request):
"""新增文章分裂 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoryView:
def get(self, request):
"""获取文章分类列表 :param request: :return:"""
categoryAll = Category.objects.all()
result = [model_to_dict(category) for category in categoryAll]
return JsonResponse({'status': True, 'category': result})
def post(self, request):
"""新... | the_stack_v2_python_sparse | apps/helps/views/category/categoryInfo.py | DICKQI/ALGYunXS | train | 0 | |
462ecb3196a7c99896ebfdb0eb28f4dcad84f6ad | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | BasicServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicServiceServicer:
"""Missing associated documentation comment in .proto file."""
def InferenceItem(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def ChangeThreads(self, request, context):
"""Missing associa... | stack_v2_sparse_classes_36k_train_012036 | 3,873 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "InferenceItem",
"signature": "def InferenceItem(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "ChangeThreads",
"signature": "def ChangeThre... | 2 | stack_v2_sparse_classes_30k_train_005285 | Implement the Python class `BasicServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def InferenceItem(self, request, context): Missing associated documentation comment in .proto file.
- def ChangeThreads(self, request, cont... | Implement the Python class `BasicServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def InferenceItem(self, request, context): Missing associated documentation comment in .proto file.
- def ChangeThreads(self, request, cont... | ac090279109f4975f253e3c3f37772b6bb20aad3 | <|skeleton|>
class BasicServiceServicer:
"""Missing associated documentation comment in .proto file."""
def InferenceItem(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def ChangeThreads(self, request, context):
"""Missing associa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicServiceServicer:
"""Missing associated documentation comment in .proto file."""
def InferenceItem(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemente... | the_stack_v2_python_sparse | vision/classification_and_detection/python/basic_pb2_grpc.py | omarnaman/inference | train | 0 |
aca758426dfd47587e8ec0a4b4516a4f3da88080 | [
"BOCSPuzzle.__init__(self, init_bundle)\nregister_callback(self.user_input_event_received)\nself.eink.set_text(self.PROMPT)\nself.piano_state = PianoState()\nself.piano_state.set_visible(True)\nself.update_io_state(PIANO, self.piano_state)",
"if event.id == EventType.PIANO_KEYBOARD_CHANGE:\n if event.data == '... | <|body_start_0|>
BOCSPuzzle.__init__(self, init_bundle)
register_callback(self.user_input_event_received)
self.eink.set_text(self.PROMPT)
self.piano_state = PianoState()
self.piano_state.set_visible(True)
self.update_io_state(PIANO, self.piano_state)
<|end_body_0|>
<|bod... | FrequencyPuzzle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrequencyPuzzle:
def __init__(self, init_bundle, register_callback):
"""Runs once, when the puzzle is first started. :param init_bundle: a callback function to update the state of an I/O device :param register_callback: a callback function to register the function that should be called a... | stack_v2_sparse_classes_36k_train_012037 | 4,591 | permissive | [
{
"docstring": "Runs once, when the puzzle is first started. :param init_bundle: a callback function to update the state of an I/O device :param register_callback: a callback function to register the function that should be called anytime a BOCS user input event occurs",
"name": "__init__",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_001168 | Implement the Python class `FrequencyPuzzle` described below.
Class description:
Implement the FrequencyPuzzle class.
Method signatures and docstrings:
- def __init__(self, init_bundle, register_callback): Runs once, when the puzzle is first started. :param init_bundle: a callback function to update the state of an I... | Implement the Python class `FrequencyPuzzle` described below.
Class description:
Implement the FrequencyPuzzle class.
Method signatures and docstrings:
- def __init__(self, init_bundle, register_callback): Runs once, when the puzzle is first started. :param init_bundle: a callback function to update the state of an I... | f2d6d96ee4e3d2365af3a7931697d2ded3433574 | <|skeleton|>
class FrequencyPuzzle:
def __init__(self, init_bundle, register_callback):
"""Runs once, when the puzzle is first started. :param init_bundle: a callback function to update the state of an I/O device :param register_callback: a callback function to register the function that should be called a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrequencyPuzzle:
def __init__(self, init_bundle, register_callback):
"""Runs once, when the puzzle is first started. :param init_bundle: a callback function to update the state of an I/O device :param register_callback: a callback function to register the function that should be called anytime a BOCS ... | the_stack_v2_python_sparse | raspi/puzzles/frequency_puzzle.py | kylecombes/bocs | train | 1 | |
0b9b6a167f83897cf41297c371875086b7913480 | [
"Inventory.__init__(self, product_code, description, market_price, rental_price)\nself.brand = brand\nself.voltage = voltage",
"output_dict = Inventory.return_as_dictionary(self)\noutput_dict['brand'] = self.brand\noutput_dict['voltage'] = self.voltage\nreturn output_dict"
] | <|body_start_0|>
Inventory.__init__(self, product_code, description, market_price, rental_price)
self.brand = brand
self.voltage = voltage
<|end_body_0|>
<|body_start_1|>
output_dict = Inventory.return_as_dictionary(self)
output_dict['brand'] = self.brand
output_dict['vo... | Class ElectricAppliances inherites from Inventtory class | ElectricAppliances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliances:
"""Class ElectricAppliances inherites from Inventtory class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Creates common instance variables from the parent class"""
<|body_0|>
def return_as_dictionary... | stack_v2_sparse_classes_36k_train_012038 | 825 | no_license | [
{
"docstring": "Creates common instance variables from the parent class",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price, brand, voltage)"
},
{
"docstring": "return ElectricAppliances class attributes",
"name": "return_as_dictionary... | 2 | null | Implement the Python class `ElectricAppliances` described below.
Class description:
Class ElectricAppliances inherites from Inventtory class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): Creates common instance variables from the parent ... | Implement the Python class `ElectricAppliances` described below.
Class description:
Class ElectricAppliances inherites from Inventtory class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): Creates common instance variables from the parent ... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class ElectricAppliances:
"""Class ElectricAppliances inherites from Inventtory class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Creates common instance variables from the parent class"""
<|body_0|>
def return_as_dictionary... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElectricAppliances:
"""Class ElectricAppliances inherites from Inventtory class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Creates common instance variables from the parent class"""
Inventory.__init__(self, product_code, description, m... | the_stack_v2_python_sparse | students/ttlarson/lesson01/assignment/inventory_management/electric_appliances_class.py | JavaRod/SP_Python220B_2019 | 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_36k_train_012039 | 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_013833 | 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_36k | 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 | |
01345fa2af09cc99a1f8b447883bc3b56cf14326 | [
"try:\n return eval(expr)\nexcept (ZeroDivisionError, TypeError):\n if self.muffled:\n print('Division is not allow 0')\n return 0\n else:\n raise\nfinally:\n print('hahaha')",
"try:\n eval(expr)\nexcept (ZeroDivisionError, TypeError) as e:\n print(e)\n if self.muffled:\n... | <|body_start_0|>
try:
return eval(expr)
except (ZeroDivisionError, TypeError):
if self.muffled:
print('Division is not allow 0')
return 0
else:
raise
finally:
print('hahaha')
<|end_body_0|>
<|body_st... | 使用参数控制是否抛出异常 | MuffledCalculator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MuffledCalculator:
"""使用参数控制是否抛出异常"""
def calc(self, expr):
"""计算表达式值 :param expr: :return:"""
<|body_0|>
def calc01(self, expr):
"""计算表达式值 :param expr: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
return eval(expr)
... | stack_v2_sparse_classes_36k_train_012040 | 1,609 | no_license | [
{
"docstring": "计算表达式值 :param expr: :return:",
"name": "calc",
"signature": "def calc(self, expr)"
},
{
"docstring": "计算表达式值 :param expr: :return:",
"name": "calc01",
"signature": "def calc01(self, expr)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000966 | Implement the Python class `MuffledCalculator` described below.
Class description:
使用参数控制是否抛出异常
Method signatures and docstrings:
- def calc(self, expr): 计算表达式值 :param expr: :return:
- def calc01(self, expr): 计算表达式值 :param expr: :return: | Implement the Python class `MuffledCalculator` described below.
Class description:
使用参数控制是否抛出异常
Method signatures and docstrings:
- def calc(self, expr): 计算表达式值 :param expr: :return:
- def calc01(self, expr): 计算表达式值 :param expr: :return:
<|skeleton|>
class MuffledCalculator:
"""使用参数控制是否抛出异常"""
def calc(self... | e66eda07e6b1302d8ac86f93490ec5230e50fa4e | <|skeleton|>
class MuffledCalculator:
"""使用参数控制是否抛出异常"""
def calc(self, expr):
"""计算表达式值 :param expr: :return:"""
<|body_0|>
def calc01(self, expr):
"""计算表达式值 :param expr: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MuffledCalculator:
"""使用参数控制是否抛出异常"""
def calc(self, expr):
"""计算表达式值 :param expr: :return:"""
try:
return eval(expr)
except (ZeroDivisionError, TypeError):
if self.muffled:
print('Division is not allow 0')
return 0
... | the_stack_v2_python_sparse | day04/exceptionTst.py | zhangshichen0/python3-study | train | 0 |
ce496292d4623868deef99a449930454008c046d | [
"self.n_clusters = n_clusters\nself.max_iter = max_iter\nself.shuffle = shuffle\nself.verbose = verbose\nself.cluster_sizes_ = np.zeros(self.n_clusters)",
"n, d = X.shape\nself.cluster_centers_ = np.zeros((self.n_clusters, d), dtype=X.dtype)\nstep = 0\nidx = np.arange(n)\nwhile step < self.max_iter:\n step = s... | <|body_start_0|>
self.n_clusters = n_clusters
self.max_iter = max_iter
self.shuffle = shuffle
self.verbose = verbose
self.cluster_sizes_ = np.zeros(self.n_clusters)
<|end_body_0|>
<|body_start_1|>
n, d = X.shape
self.cluster_centers_ = np.zeros((self.n_clusters, ... | Online Hartigan clustering. | HartiganOnline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HartiganOnline:
"""Online Hartigan clustering."""
def __init__(self, n_clusters=2, max_iter=10, shuffle=True, verbose=False):
"""Initialize a Hartigan clusterer. :parameters: - n_clusters : int Number of clusters - max_iter : int Maximum number of passes through the data - shuffle : ... | stack_v2_sparse_classes_36k_train_012041 | 2,619 | no_license | [
{
"docstring": "Initialize a Hartigan clusterer. :parameters: - n_clusters : int Number of clusters - max_iter : int Maximum number of passes through the data - shuffle : bool Shuffle the data between each pass - verbose : bool Display debugging output? :variables: - cluster_centers_ : ndarray, shape=(n_cluster... | 3 | null | Implement the Python class `HartiganOnline` described below.
Class description:
Online Hartigan clustering.
Method signatures and docstrings:
- def __init__(self, n_clusters=2, max_iter=10, shuffle=True, verbose=False): Initialize a Hartigan clusterer. :parameters: - n_clusters : int Number of clusters - max_iter : i... | Implement the Python class `HartiganOnline` described below.
Class description:
Online Hartigan clustering.
Method signatures and docstrings:
- def __init__(self, n_clusters=2, max_iter=10, shuffle=True, verbose=False): Initialize a Hartigan clusterer. :parameters: - n_clusters : int Number of clusters - max_iter : i... | 229393fd47716a87ecc4b37e306c7f7592e36e51 | <|skeleton|>
class HartiganOnline:
"""Online Hartigan clustering."""
def __init__(self, n_clusters=2, max_iter=10, shuffle=True, verbose=False):
"""Initialize a Hartigan clusterer. :parameters: - n_clusters : int Number of clusters - max_iter : int Maximum number of passes through the data - shuffle : ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HartiganOnline:
"""Online Hartigan clustering."""
def __init__(self, n_clusters=2, max_iter=10, shuffle=True, verbose=False):
"""Initialize a Hartigan clusterer. :parameters: - n_clusters : int Number of clusters - max_iter : int Maximum number of passes through the data - shuffle : bool Shuffle ... | the_stack_v2_python_sparse | code/seymour_analyzers/HartiganOnline.py | bmcfee/seymour | train | 4 |
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_36k_train_012042 | 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_012535 | 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_36k | 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 |
238a658225fe526ef7dae9b1f6f69d93149144dd | [
"super().__init__()\nself.name_param = name_param\nself.exp_value = exp_value\nself.actual_value = actual_value",
"error_msg = \"Configuration mismatch in {}: expected '{}', actual is '{}'\"\nif self.actual_value is None:\n error_msg = error_msg.format(self.name_param, self.exp_value, '<not found>')\nelse:\n ... | <|body_start_0|>
super().__init__()
self.name_param = name_param
self.exp_value = exp_value
self.actual_value = actual_value
<|end_body_0|>
<|body_start_1|>
error_msg = "Configuration mismatch in {}: expected '{}', actual is '{}'"
if self.actual_value is None:
... | Error caused when the value of parameter received from the remote instance does not match the expected one. | Misconfiguration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Misconfiguration:
"""Error caused when the value of parameter received from the remote instance does not match the expected one."""
def __init__(self, name_param, exp_value, actual_value):
"""name_param (str): name of parameter which caused the error exp_value (str): value expected f... | stack_v2_sparse_classes_36k_train_012043 | 45,075 | permissive | [
{
"docstring": "name_param (str): name of parameter which caused the error exp_value (str): value expected for the parameter actual_value (str): actual value found",
"name": "__init__",
"signature": "def __init__(self, name_param, exp_value, actual_value)"
},
{
"docstring": "String representatio... | 2 | null | Implement the Python class `Misconfiguration` described below.
Class description:
Error caused when the value of parameter received from the remote instance does not match the expected one.
Method signatures and docstrings:
- def __init__(self, name_param, exp_value, actual_value): name_param (str): name of parameter... | Implement the Python class `Misconfiguration` described below.
Class description:
Error caused when the value of parameter received from the remote instance does not match the expected one.
Method signatures and docstrings:
- def __init__(self, name_param, exp_value, actual_value): name_param (str): name of parameter... | 9c9040f6a173af5c495f5447889e9349fa56f234 | <|skeleton|>
class Misconfiguration:
"""Error caused when the value of parameter received from the remote instance does not match the expected one."""
def __init__(self, name_param, exp_value, actual_value):
"""name_param (str): name of parameter which caused the error exp_value (str): value expected f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Misconfiguration:
"""Error caused when the value of parameter received from the remote instance does not match the expected one."""
def __init__(self, name_param, exp_value, actual_value):
"""name_param (str): name of parameter which caused the error exp_value (str): value expected for the parame... | the_stack_v2_python_sparse | tessia/server/lib/post_install.py | tessia-project/tessia | train | 10 |
3d89ae0613d2494b70d6b527647ffee1113c9d46 | [
"query_result = {}\nquerier = wt_uu.CreateGenericWebTestQuerier()\nself.assertEqual(querier._GetRelevantExpectationFilesForQueryResult(query_result), [])",
"query_result = {'expectation_files': ['/posix/path', '/c:/windows/path']}\nquerier = wt_uu.CreateGenericWebTestQuerier()\nself.assertEqual(querier._GetReleva... | <|body_start_0|>
query_result = {}
querier = wt_uu.CreateGenericWebTestQuerier()
self.assertEqual(querier._GetRelevantExpectationFilesForQueryResult(query_result), [])
<|end_body_0|>
<|body_start_1|>
query_result = {'expectation_files': ['/posix/path', '/c:/windows/path']}
queri... | GetRelevantExpectationFilesForQueryResultUnittest | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetRelevantExpectationFilesForQueryResultUnittest:
def testNoFiles(self):
"""Tests that no reported expectation files are handled properly."""
<|body_0|>
def testAbsolutePath(self):
"""Tests that absolute paths are ignored."""
<|body_1|>
def testRelative... | stack_v2_sparse_classes_36k_train_012044 | 5,666 | permissive | [
{
"docstring": "Tests that no reported expectation files are handled properly.",
"name": "testNoFiles",
"signature": "def testNoFiles(self)"
},
{
"docstring": "Tests that absolute paths are ignored.",
"name": "testAbsolutePath",
"signature": "def testAbsolutePath(self)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_train_009383 | Implement the Python class `GetRelevantExpectationFilesForQueryResultUnittest` described below.
Class description:
Implement the GetRelevantExpectationFilesForQueryResultUnittest class.
Method signatures and docstrings:
- def testNoFiles(self): Tests that no reported expectation files are handled properly.
- def test... | Implement the Python class `GetRelevantExpectationFilesForQueryResultUnittest` described below.
Class description:
Implement the GetRelevantExpectationFilesForQueryResultUnittest class.
Method signatures and docstrings:
- def testNoFiles(self): Tests that no reported expectation files are handled properly.
- def test... | fd8a8914ca0183f0add65ae55f04e287543c7d4a | <|skeleton|>
class GetRelevantExpectationFilesForQueryResultUnittest:
def testNoFiles(self):
"""Tests that no reported expectation files are handled properly."""
<|body_0|>
def testAbsolutePath(self):
"""Tests that absolute paths are ignored."""
<|body_1|>
def testRelative... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetRelevantExpectationFilesForQueryResultUnittest:
def testNoFiles(self):
"""Tests that no reported expectation files are handled properly."""
query_result = {}
querier = wt_uu.CreateGenericWebTestQuerier()
self.assertEqual(querier._GetRelevantExpectationFilesForQueryResult(que... | the_stack_v2_python_sparse | third_party/blink/tools/blinkpy/web_tests/stale_expectation_removal/queries_unittest.py | SREERAGI18/chromium | train | 1 | |
037a6fa00e212aab4b67f82144f554664ac83697 | [
"coords = [0, 0, 0]\nif self.direction not in ['x', 'y', 'z']:\n raise ValueError(f'Invalid value for direction {self.direction}')\ncoords['xyz'.index(self.direction)] = self.coord\nx_map, y_map, z_map = (int(np.round(c)) for c in coord_transform(coords[0], coords[1], coords[2], np.linalg.inv(affine)))\nif self.... | <|body_start_0|>
coords = [0, 0, 0]
if self.direction not in ['x', 'y', 'z']:
raise ValueError(f'Invalid value for direction {self.direction}')
coords['xyz'.index(self.direction)] = self.coord
x_map, y_map, z_map = (int(np.round(c)) for c in coord_transform(coords[0], coords[... | An MPL axis-like object that displays a cut of 3D volumes. Parameters ---------- %(ax)s direction : {'x', 'y', 'z'} The directions of the view. coord : :obj:`float` The coordinate along the direction of the cut. | CutAxes | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CutAxes:
"""An MPL axis-like object that displays a cut of 3D volumes. Parameters ---------- %(ax)s direction : {'x', 'y', 'z'} The directions of the view. coord : :obj:`float` The coordinate along the direction of the cut."""
def transform_to_2d(self, data, affine):
"""Cut the 3D vo... | stack_v2_sparse_classes_36k_train_012045 | 21,879 | permissive | [
{
"docstring": "Cut the 3D volume into a 2D slice. Parameters ---------- data : 3D :class:`~numpy.ndarray` The 3D volume to cut. affine : 4x4 :class:`~numpy.ndarray` The affine of the volume.",
"name": "transform_to_2d",
"signature": "def transform_to_2d(self, data, affine)"
},
{
"docstring": "D... | 2 | null | Implement the Python class `CutAxes` described below.
Class description:
An MPL axis-like object that displays a cut of 3D volumes. Parameters ---------- %(ax)s direction : {'x', 'y', 'z'} The directions of the view. coord : :obj:`float` The coordinate along the direction of the cut.
Method signatures and docstrings:... | Implement the Python class `CutAxes` described below.
Class description:
An MPL axis-like object that displays a cut of 3D volumes. Parameters ---------- %(ax)s direction : {'x', 'y', 'z'} The directions of the view. coord : :obj:`float` The coordinate along the direction of the cut.
Method signatures and docstrings:... | f0852e127b620a64af0a1ce02282106ce6f068ba | <|skeleton|>
class CutAxes:
"""An MPL axis-like object that displays a cut of 3D volumes. Parameters ---------- %(ax)s direction : {'x', 'y', 'z'} The directions of the view. coord : :obj:`float` The coordinate along the direction of the cut."""
def transform_to_2d(self, data, affine):
"""Cut the 3D vo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CutAxes:
"""An MPL axis-like object that displays a cut of 3D volumes. Parameters ---------- %(ax)s direction : {'x', 'y', 'z'} The directions of the view. coord : :obj:`float` The coordinate along the direction of the cut."""
def transform_to_2d(self, data, affine):
"""Cut the 3D volume into a 2... | the_stack_v2_python_sparse | nilearn/plotting/displays/_axes.py | nilearn/nilearn | train | 1,049 |
bb8d606dd6fab92e7a643bd2ffe8a380187e108f | [
"super(RelativePositionEmbedding, self).__init__(name=name)\nself._dim = dim\nself._dropout_rate = dropout_rate\nself._r_w_bias = r_w_bias\nself._r_r_bias = r_r_bias\nself._init_scale = init_scale\nself._sinusoidal_pos_emb = SinusoidalPositionEmbedding(dim=dim, reverse_order=True, clamp_len=clamp_len, name=name)",
... | <|body_start_0|>
super(RelativePositionEmbedding, self).__init__(name=name)
self._dim = dim
self._dropout_rate = dropout_rate
self._r_w_bias = r_w_bias
self._r_r_bias = r_r_bias
self._init_scale = init_scale
self._sinusoidal_pos_emb = SinusoidalPositionEmbedding(d... | Position encoding, using relative positions than absolute positions. | RelativePositionEmbedding | [
"Apache-2.0",
"CC-BY-SA-4.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelativePositionEmbedding:
"""Position encoding, using relative positions than absolute positions."""
def __init__(self, dim: int, dropout_rate: float, r_w_bias: jnp.ndarray, r_r_bias: jnp.ndarray, init_scale: float=0.02, clamp_len: Optional[int]=None, name: Optional[str]=None):
"""I... | stack_v2_sparse_classes_36k_train_012046 | 14,391 | permissive | [
{
"docstring": "Initialize a RelativePositionEmbedding. Args: dim: Embedding dimension. dropout_rate: dropout rate. r_w_bias: global content bias. r_r_bias: global positional bias. init_scale: the initialization scale of the RandomNormal used for the linear layer. clamp_len: position beyond clamp_len will be re... | 2 | null | Implement the Python class `RelativePositionEmbedding` described below.
Class description:
Position encoding, using relative positions than absolute positions.
Method signatures and docstrings:
- def __init__(self, dim: int, dropout_rate: float, r_w_bias: jnp.ndarray, r_r_bias: jnp.ndarray, init_scale: float=0.02, cl... | Implement the Python class `RelativePositionEmbedding` described below.
Class description:
Position encoding, using relative positions than absolute positions.
Method signatures and docstrings:
- def __init__(self, dim: int, dropout_rate: float, r_w_bias: jnp.ndarray, r_r_bias: jnp.ndarray, init_scale: float=0.02, cl... | a6ef8053380d6aa19aaae14b93f013ae9762d057 | <|skeleton|>
class RelativePositionEmbedding:
"""Position encoding, using relative positions than absolute positions."""
def __init__(self, dim: int, dropout_rate: float, r_w_bias: jnp.ndarray, r_r_bias: jnp.ndarray, init_scale: float=0.02, clamp_len: Optional[int]=None, name: Optional[str]=None):
"""I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelativePositionEmbedding:
"""Position encoding, using relative positions than absolute positions."""
def __init__(self, dim: int, dropout_rate: float, r_w_bias: jnp.ndarray, r_r_bias: jnp.ndarray, init_scale: float=0.02, clamp_len: Optional[int]=None, name: Optional[str]=None):
"""Initialize a R... | the_stack_v2_python_sparse | wikigraphs/wikigraphs/model/embedding.py | sethuramanio/deepmind-research | train | 1 |
3c225878ce103e156117216a46d2bed2dd051242 | [
"self.dict_size = conf_dict['dict_size']\nself.task_mode = conf_dict['task_mode']\nself.emb_dim = conf_dict['net']['emb_dim']\nself.gru_dim = conf_dict['net']['gru_dim']\nself.hidden_dim = conf_dict['net']['hidden_dim']",
"emb_layer = layers.EmbeddingLayer(self.dict_size, self.emb_dim, 'emb')\nleft_emb = emb_laye... | <|body_start_0|>
self.dict_size = conf_dict['dict_size']
self.task_mode = conf_dict['task_mode']
self.emb_dim = conf_dict['net']['emb_dim']
self.gru_dim = conf_dict['net']['gru_dim']
self.hidden_dim = conf_dict['net']['hidden_dim']
<|end_body_0|>
<|body_start_1|>
emb_lay... | GRU | GRU | [
"Apache-2.0",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRU:
"""GRU"""
def __init__(self, conf_dict):
"""initialize"""
<|body_0|>
def predict(self, left, right):
"""Forward network"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dict_size = conf_dict['dict_size']
self.task_mode = conf_di... | stack_v2_sparse_classes_36k_train_012047 | 2,392 | permissive | [
{
"docstring": "initialize",
"name": "__init__",
"signature": "def __init__(self, conf_dict)"
},
{
"docstring": "Forward network",
"name": "predict",
"signature": "def predict(self, left, right)"
}
] | 2 | null | Implement the Python class `GRU` described below.
Class description:
GRU
Method signatures and docstrings:
- def __init__(self, conf_dict): initialize
- def predict(self, left, right): Forward network | Implement the Python class `GRU` described below.
Class description:
GRU
Method signatures and docstrings:
- def __init__(self, conf_dict): initialize
- def predict(self, left, right): Forward network
<|skeleton|>
class GRU:
"""GRU"""
def __init__(self, conf_dict):
"""initialize"""
<|body_0|... | a60babdf382aba71fe447b3259441b4bed947414 | <|skeleton|>
class GRU:
"""GRU"""
def __init__(self, conf_dict):
"""initialize"""
<|body_0|>
def predict(self, left, right):
"""Forward network"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GRU:
"""GRU"""
def __init__(self, conf_dict):
"""initialize"""
self.dict_size = conf_dict['dict_size']
self.task_mode = conf_dict['task_mode']
self.emb_dim = conf_dict['net']['emb_dim']
self.gru_dim = conf_dict['net']['gru_dim']
self.hidden_dim = conf_dict[... | the_stack_v2_python_sparse | PaddleNLP/shared_modules/models/matching/gru.py | littletomatodonkey/models | train | 5 |
423d9e1b06a17279d62559ce81cd23a3824a1deb | [
"current_matching = initial_matching\nG_prime = G.add_node_attributes(AssignmentProblem.MATCHING_ATTRIBUTE, False).add_edge_attributes(AssignmentProblem.MATCHING_ATTRIBUTE, False)\nwhile True:\n augmenting_path = AssignmentProblem.postprocess_augmenting_path(MaximumCardinalityMatching.compute_augmenting_path(G_p... | <|body_start_0|>
current_matching = initial_matching
G_prime = G.add_node_attributes(AssignmentProblem.MATCHING_ATTRIBUTE, False).add_edge_attributes(AssignmentProblem.MATCHING_ATTRIBUTE, False)
while True:
augmenting_path = AssignmentProblem.postprocess_augmenting_path(MaximumCardin... | Class containing implementation of the maximum cardinality matching algorithm (O(n^3) runtime complexity) | MaximumCardinalityMatching | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaximumCardinalityMatching:
"""Class containing implementation of the maximum cardinality matching algorithm (O(n^3) runtime complexity)"""
def apply(G, initial_matching):
"""Given a BipartiteGraph object and an initial matching, computes and returns a maximum cardinality matching fo... | stack_v2_sparse_classes_36k_train_012048 | 6,397 | no_license | [
{
"docstring": "Given a BipartiteGraph object and an initial matching, computes and returns a maximum cardinality matching for the input graph, represented as a set of pairs where each pair consists of source node and terminal node names in that order",
"name": "apply",
"signature": "def apply(G, initia... | 3 | stack_v2_sparse_classes_30k_train_017952 | Implement the Python class `MaximumCardinalityMatching` described below.
Class description:
Class containing implementation of the maximum cardinality matching algorithm (O(n^3) runtime complexity)
Method signatures and docstrings:
- def apply(G, initial_matching): Given a BipartiteGraph object and an initial matchin... | Implement the Python class `MaximumCardinalityMatching` described below.
Class description:
Class containing implementation of the maximum cardinality matching algorithm (O(n^3) runtime complexity)
Method signatures and docstrings:
- def apply(G, initial_matching): Given a BipartiteGraph object and an initial matchin... | 072244e40f27c1730cb473d0522fa5d1014e034f | <|skeleton|>
class MaximumCardinalityMatching:
"""Class containing implementation of the maximum cardinality matching algorithm (O(n^3) runtime complexity)"""
def apply(G, initial_matching):
"""Given a BipartiteGraph object and an initial matching, computes and returns a maximum cardinality matching fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaximumCardinalityMatching:
"""Class containing implementation of the maximum cardinality matching algorithm (O(n^3) runtime complexity)"""
def apply(G, initial_matching):
"""Given a BipartiteGraph object and an initial matching, computes and returns a maximum cardinality matching for the input g... | the_stack_v2_python_sparse | AssignmentProblem/MaximumCardinalityMatching.py | ranganmostofa/NFL-Roster-Optimization | train | 1 |
63b44eb17f9f6b549f39d6f1c6d24a15f7475733 | [
"super(GE2ELoss, self).__init__()\nself.w = nn.Parameter(torch.tensor(init_w))\nself.b = nn.Parameter(torch.tensor(init_b))\nself.loss_method = loss_method\nassert self.loss_method in ['softmax', 'contrast']\nif self.loss_method == 'softmax':\n self.embed_loss = self.embed_loss_softmax\nif self.loss_method == 'c... | <|body_start_0|>
super(GE2ELoss, self).__init__()
self.w = nn.Parameter(torch.tensor(init_w))
self.b = nn.Parameter(torch.tensor(init_b))
self.loss_method = loss_method
assert self.loss_method in ['softmax', 'contrast']
if self.loss_method == 'softmax':
self.e... | GE2ELoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GE2ELoss:
def __init__(self, init_w=10.0, init_b=-5.0, loss_method='softmax'):
"""Implementation of the Generalized End-to-End loss defined in https://arxiv.org/abs/1710.10467 [1] Accepts an input of size (N, M, D) where N is the number of speakers in the batch, M is the number of uttera... | stack_v2_sparse_classes_36k_train_012049 | 21,208 | no_license | [
{
"docstring": "Implementation of the Generalized End-to-End loss defined in https://arxiv.org/abs/1710.10467 [1] Accepts an input of size (N, M, D) where N is the number of speakers in the batch, M is the number of utterances per speaker, and D is the dimensionality of the embedding vector (e.g. d-vector) Args... | 6 | stack_v2_sparse_classes_30k_train_018928 | Implement the Python class `GE2ELoss` described below.
Class description:
Implement the GE2ELoss class.
Method signatures and docstrings:
- def __init__(self, init_w=10.0, init_b=-5.0, loss_method='softmax'): Implementation of the Generalized End-to-End loss defined in https://arxiv.org/abs/1710.10467 [1] Accepts an ... | Implement the Python class `GE2ELoss` described below.
Class description:
Implement the GE2ELoss class.
Method signatures and docstrings:
- def __init__(self, init_w=10.0, init_b=-5.0, loss_method='softmax'): Implementation of the Generalized End-to-End loss defined in https://arxiv.org/abs/1710.10467 [1] Accepts an ... | eb52842755312a751fd40fce648ca92c3e737720 | <|skeleton|>
class GE2ELoss:
def __init__(self, init_w=10.0, init_b=-5.0, loss_method='softmax'):
"""Implementation of the Generalized End-to-End loss defined in https://arxiv.org/abs/1710.10467 [1] Accepts an input of size (N, M, D) where N is the number of speakers in the batch, M is the number of uttera... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GE2ELoss:
def __init__(self, init_w=10.0, init_b=-5.0, loss_method='softmax'):
"""Implementation of the Generalized End-to-End loss defined in https://arxiv.org/abs/1710.10467 [1] Accepts an input of size (N, M, D) where N is the number of speakers in the batch, M is the number of utterances per speak... | the_stack_v2_python_sparse | libs/components/loss.py | zengchang233/asv_beginner | train | 2 | |
298c61b74bede366911007eb746354a828a41af6 | [
"if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN]:\n tango.Except.throw_exception(f'Command TelescopeOff is not allowed in current state {self.state_model.op_state}.', 'Failed to invoke Off command on CspMasterLeafNode.', 'CspMasterLeafNode.TelescopeOff()', tango.ErrSeverity.ERR)\nreturn True",... | <|body_start_0|>
if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN]:
tango.Except.throw_exception(f'Command TelescopeOff is not allowed in current state {self.state_model.op_state}.', 'Failed to invoke Off command on CspMasterLeafNode.', 'CspMasterLeafNode.TelescopeOff()', tango.ErrS... | A class for CSP Subarray's TelescopeOff() command. Invokes method to stop Delay Calculation. | TelescopeOff | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TelescopeOff:
"""A class for CSP Subarray's TelescopeOff() command. Invokes method to stop Delay Calculation."""
def check_allowed(self):
"""Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device s... | stack_v2_sparse_classes_36k_train_012050 | 3,647 | permissive | [
{
"docstring": "Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device state :rtype: boolean :raises: DevFailed if this command is not allowed to be run in current device state",
"name": "check_allowed",
"signature": ... | 3 | null | Implement the Python class `TelescopeOff` described below.
Class description:
A class for CSP Subarray's TelescopeOff() command. Invokes method to stop Delay Calculation.
Method signatures and docstrings:
- def check_allowed(self): Checks whether this command is allowed to be run in current device state :return: True... | Implement the Python class `TelescopeOff` described below.
Class description:
A class for CSP Subarray's TelescopeOff() command. Invokes method to stop Delay Calculation.
Method signatures and docstrings:
- def check_allowed(self): Checks whether this command is allowed to be run in current device state :return: True... | 7ee65a9c8dada9b28893144b372a398bd0646195 | <|skeleton|>
class TelescopeOff:
"""A class for CSP Subarray's TelescopeOff() command. Invokes method to stop Delay Calculation."""
def check_allowed(self):
"""Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TelescopeOff:
"""A class for CSP Subarray's TelescopeOff() command. Invokes method to stop Delay Calculation."""
def check_allowed(self):
"""Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device state :rtype: ... | the_stack_v2_python_sparse | temp_src/ska_tmc_cspsubarrayleafnode_mid/telescope_off_command.py | ska-telescope/tmc-prototype | train | 4 |
8440b2c052a1363681053e1727822455995c5f99 | [
"for from_, to in zip('∑∫ỹȱŋă', 'elyrna'):\n raw_argument = raw_argument.replace(from_, to)\nargument = re.sub('[^A-Z]', '', raw_argument.upper())\nif not argument:\n raise commands.BadArgument('Please use latin characters to specify a tribe.')\nmatches = []\nfor tribe in cls:\n tribe_name = tribe.name.rep... | <|body_start_0|>
for from_, to in zip('∑∫ỹȱŋă', 'elyrna'):
raw_argument = raw_argument.replace(from_, to)
argument = re.sub('[^A-Z]', '', raw_argument.upper())
if not argument:
raise commands.BadArgument('Please use latin characters to specify a tribe.')
matches =... | An enum for each in-game tribe. | Tribe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tribe:
"""An enum for each in-game tribe."""
async def convert(cls, ctx: commands.Context, raw_argument: str) -> Tribe:
"""Convert a Discord.py argument to a tribe."""
<|body_0|>
def emoji(self) -> str:
"""Get the emoji representing the tribe."""
<|body_1... | stack_v2_sparse_classes_36k_train_012051 | 4,521 | no_license | [
{
"docstring": "Convert a Discord.py argument to a tribe.",
"name": "convert",
"signature": "async def convert(cls, ctx: commands.Context, raw_argument: str) -> Tribe"
},
{
"docstring": "Get the emoji representing the tribe.",
"name": "emoji",
"signature": "def emoji(self) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_015651 | Implement the Python class `Tribe` described below.
Class description:
An enum for each in-game tribe.
Method signatures and docstrings:
- async def convert(cls, ctx: commands.Context, raw_argument: str) -> Tribe: Convert a Discord.py argument to a tribe.
- def emoji(self) -> str: Get the emoji representing the tribe... | Implement the Python class `Tribe` described below.
Class description:
An enum for each in-game tribe.
Method signatures and docstrings:
- async def convert(cls, ctx: commands.Context, raw_argument: str) -> Tribe: Convert a Discord.py argument to a tribe.
- def emoji(self) -> str: Get the emoji representing the tribe... | 05b2689fa191a10feea77afa94320f0b1d088dc0 | <|skeleton|>
class Tribe:
"""An enum for each in-game tribe."""
async def convert(cls, ctx: commands.Context, raw_argument: str) -> Tribe:
"""Convert a Discord.py argument to a tribe."""
<|body_0|>
def emoji(self) -> str:
"""Get the emoji representing the tribe."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tribe:
"""An enum for each in-game tribe."""
async def convert(cls, ctx: commands.Context, raw_argument: str) -> Tribe:
"""Convert a Discord.py argument to a tribe."""
for from_, to in zip('∑∫ỹȱŋă', 'elyrna'):
raw_argument = raw_argument.replace(from_, to)
argument = r... | the_stack_v2_python_sparse | diplo-bot/main/tribes.py | Artemis21/polybots | train | 3 |
8e45e0361a1d45e28f606ae5750d88d0c99a961a | [
"n = len(nums)\nif n <= 1:\n return False\nnums = [num * n for num in nums]\navg = sum(nums) // n\nnums = [num - avg for num in nums]\nleftSums, rightSums = (subsetSum(nums[:n // 2]), subsetSum(nums[n // 2:]))\nif 0 in leftSums or 0 in rightSums:\n return True\nleftSums.discard(sum(nums[:n // 2]))\nrightSums.... | <|body_start_0|>
n = len(nums)
if n <= 1:
return False
nums = [num * n for num in nums]
avg = sum(nums) // n
nums = [num - avg for num in nums]
leftSums, rightSums = (subsetSum(nums[:n // 2]), subsetSum(nums[n // 2:]))
if 0 in leftSums or 0 in rightSum... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def splitArraySameAverage(self, nums: List[int]) -> bool:
"""折半枚举 O(n*2^(n/2)) # !每个数减去平均数后,变成nums中是否存在和为0的非空真子集 1. 左边可以凑出0/右边可以凑出0 2. 左边+右边可以凑出0"""
<|body_0|>
def splitArraySameAverage2(self, nums: List[int]) -> bool:
"""背包dp O(n^2 * sum(nums)) #!集合A的平均值等于... | stack_v2_sparse_classes_36k_train_012052 | 3,763 | no_license | [
{
"docstring": "折半枚举 O(n*2^(n/2)) # !每个数减去平均数后,变成nums中是否存在和为0的非空真子集 1. 左边可以凑出0/右边可以凑出0 2. 左边+右边可以凑出0",
"name": "splitArraySameAverage",
"signature": "def splitArraySameAverage(self, nums: List[int]) -> bool"
},
{
"docstring": "背包dp O(n^2 * sum(nums)) #!集合A的平均值等于B的平均值 <=> #!`集合A的平均值`等于`nums的平均值` ... | 2 | stack_v2_sparse_classes_30k_train_013928 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def splitArraySameAverage(self, nums: List[int]) -> bool: 折半枚举 O(n*2^(n/2)) # !每个数减去平均数后,变成nums中是否存在和为0的非空真子集 1. 左边可以凑出0/右边可以凑出0 2. 左边+右边可以凑出0
- def splitArraySameAverage2(self, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def splitArraySameAverage(self, nums: List[int]) -> bool: 折半枚举 O(n*2^(n/2)) # !每个数减去平均数后,变成nums中是否存在和为0的非空真子集 1. 左边可以凑出0/右边可以凑出0 2. 左边+右边可以凑出0
- def splitArraySameAverage2(self, ... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def splitArraySameAverage(self, nums: List[int]) -> bool:
"""折半枚举 O(n*2^(n/2)) # !每个数减去平均数后,变成nums中是否存在和为0的非空真子集 1. 左边可以凑出0/右边可以凑出0 2. 左边+右边可以凑出0"""
<|body_0|>
def splitArraySameAverage2(self, nums: List[int]) -> bool:
"""背包dp O(n^2 * sum(nums)) #!集合A的平均值等于... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def splitArraySameAverage(self, nums: List[int]) -> bool:
"""折半枚举 O(n*2^(n/2)) # !每个数减去平均数后,变成nums中是否存在和为0的非空真子集 1. 左边可以凑出0/右边可以凑出0 2. 左边+右边可以凑出0"""
n = len(nums)
if n <= 1:
return False
nums = [num * n for num in nums]
avg = sum(nums) // n
... | the_stack_v2_python_sparse | 22_专题/枚举/折半枚举/805. 数组的均值分割-折半枚举子序列和.py | 981377660LMT/algorithm-study | train | 225 | |
c1e0980c580a973589e2c9b9dc4500cf2002ec27 | [
"if not features.has('organizations:incidents', project.organization, actor=request.user):\n raise ResourceDoesNotExist\nreturn self.paginate(request, queryset=AlertRule.objects.fetch_for_project(project), order_by='-date_added', paginator_cls=OffsetPaginator, on_results=lambda x: serialize(x, request.user), def... | <|body_start_0|>
if not features.has('organizations:incidents', project.organization, actor=request.user):
raise ResourceDoesNotExist
return self.paginate(request, queryset=AlertRule.objects.fetch_for_project(project), order_by='-date_added', paginator_cls=OffsetPaginator, on_results=lambda ... | ProjectAlertRuleIndexEndpoint | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectAlertRuleIndexEndpoint:
def get(self, request, project):
"""Fetches alert rules for a project"""
<|body_0|>
def post(self, request, project):
"""Create an alert rule"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not features.has('organiz... | stack_v2_sparse_classes_36k_train_012053 | 1,640 | permissive | [
{
"docstring": "Fetches alert rules for a project",
"name": "get",
"signature": "def get(self, request, project)"
},
{
"docstring": "Create an alert rule",
"name": "post",
"signature": "def post(self, request, project)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021555 | Implement the Python class `ProjectAlertRuleIndexEndpoint` described below.
Class description:
Implement the ProjectAlertRuleIndexEndpoint class.
Method signatures and docstrings:
- def get(self, request, project): Fetches alert rules for a project
- def post(self, request, project): Create an alert rule | Implement the Python class `ProjectAlertRuleIndexEndpoint` described below.
Class description:
Implement the ProjectAlertRuleIndexEndpoint class.
Method signatures and docstrings:
- def get(self, request, project): Fetches alert rules for a project
- def post(self, request, project): Create an alert rule
<|skeleton|... | c0d9ea9be63887654f9bf3bcc386969f2fb0b8a4 | <|skeleton|>
class ProjectAlertRuleIndexEndpoint:
def get(self, request, project):
"""Fetches alert rules for a project"""
<|body_0|>
def post(self, request, project):
"""Create an alert rule"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectAlertRuleIndexEndpoint:
def get(self, request, project):
"""Fetches alert rules for a project"""
if not features.has('organizations:incidents', project.organization, actor=request.user):
raise ResourceDoesNotExist
return self.paginate(request, queryset=AlertRule.obje... | the_stack_v2_python_sparse | src/sentry/incidents/endpoints/project_alert_rule_index.py | kiranps/sentry | train | 1 | |
6138f91b5a19eff11fc95d1f7b40f91b249088d8 | [
"if self.memory:\n if isinstance(self.data, bytes):\n return self.data\nwith helpers.ensure_open(self):\n if not size:\n buffer = b''\n while True:\n chunk = cast(bytes, self.byte_stream.read1())\n buffer += chunk\n if not chunk:\n break\n ... | <|body_start_0|>
if self.memory:
if isinstance(self.data, bytes):
return self.data
with helpers.ensure_open(self):
if not size:
buffer = b''
while True:
chunk = cast(bytes, self.byte_stream.read1())
... | FileResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileResource:
def read_file(self, *, size: Optional[int]=None) -> bytes:
"""Read bytes into memory Returns: any[][]: resource bytes"""
<|body_0|>
def write_file(self, target: Optional[Union[FileResource, str]]=None, **options: Any):
"""Write bytes to the target"""
... | stack_v2_sparse_classes_36k_train_012054 | 1,952 | permissive | [
{
"docstring": "Read bytes into memory Returns: any[][]: resource bytes",
"name": "read_file",
"signature": "def read_file(self, *, size: Optional[int]=None) -> bytes"
},
{
"docstring": "Write bytes to the target",
"name": "write_file",
"signature": "def write_file(self, target: Optional... | 2 | null | Implement the Python class `FileResource` described below.
Class description:
Implement the FileResource class.
Method signatures and docstrings:
- def read_file(self, *, size: Optional[int]=None) -> bytes: Read bytes into memory Returns: any[][]: resource bytes
- def write_file(self, target: Optional[Union[FileResou... | Implement the Python class `FileResource` described below.
Class description:
Implement the FileResource class.
Method signatures and docstrings:
- def read_file(self, *, size: Optional[int]=None) -> bytes: Read bytes into memory Returns: any[][]: resource bytes
- def write_file(self, target: Optional[Union[FileResou... | 740319edeee58f12cc6956a53356f3065ff18cbb | <|skeleton|>
class FileResource:
def read_file(self, *, size: Optional[int]=None) -> bytes:
"""Read bytes into memory Returns: any[][]: resource bytes"""
<|body_0|>
def write_file(self, target: Optional[Union[FileResource, str]]=None, **options: Any):
"""Write bytes to the target"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileResource:
def read_file(self, *, size: Optional[int]=None) -> bytes:
"""Read bytes into memory Returns: any[][]: resource bytes"""
if self.memory:
if isinstance(self.data, bytes):
return self.data
with helpers.ensure_open(self):
if not size:
... | the_stack_v2_python_sparse | frictionless/resources/file.py | frictionlessdata/frictionless-py | train | 295 | |
477fa75cd7db8d7f63034a0a13e33f87bb8e0512 | [
"for anim in reversed(list(self)):\n old_start = anim.startValue()\n old_end = anim.endValue()\n anim.setStartValue(old_end)\n anim.setEndValue(old_start)",
"new = core.MetaObject(self.metaObject()).copy(self)\nfor anim in reversed(list(self)):\n animation = core.MetaObject(anim.get_metaobject()).c... | <|body_start_0|>
for anim in reversed(list(self)):
old_start = anim.startValue()
old_end = anim.endValue()
anim.setStartValue(old_end)
anim.setEndValue(old_start)
<|end_body_0|>
<|body_start_1|>
new = core.MetaObject(self.metaObject()).copy(self)
... | Sequential group of animations. | SequentialAnimationGroup | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequentialAnimationGroup:
"""Sequential group of animations."""
def reverse(self):
"""Reverse animation in-place by switching start and end values."""
<|body_0|>
def reversed(self) -> SequentialAnimationGroup:
"""Return a reversed copy of the animation."""
... | stack_v2_sparse_classes_36k_train_012055 | 1,209 | permissive | [
{
"docstring": "Reverse animation in-place by switching start and end values.",
"name": "reverse",
"signature": "def reverse(self)"
},
{
"docstring": "Return a reversed copy of the animation.",
"name": "reversed",
"signature": "def reversed(self) -> SequentialAnimationGroup"
},
{
... | 3 | null | Implement the Python class `SequentialAnimationGroup` described below.
Class description:
Sequential group of animations.
Method signatures and docstrings:
- def reverse(self): Reverse animation in-place by switching start and end values.
- def reversed(self) -> SequentialAnimationGroup: Return a reversed copy of the... | Implement the Python class `SequentialAnimationGroup` described below.
Class description:
Sequential group of animations.
Method signatures and docstrings:
- def reverse(self): Reverse animation in-place by switching start and end values.
- def reversed(self) -> SequentialAnimationGroup: Return a reversed copy of the... | f00500d992d1befb0f2c2ae62fd2a8aafba7fd45 | <|skeleton|>
class SequentialAnimationGroup:
"""Sequential group of animations."""
def reverse(self):
"""Reverse animation in-place by switching start and end values."""
<|body_0|>
def reversed(self) -> SequentialAnimationGroup:
"""Return a reversed copy of the animation."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequentialAnimationGroup:
"""Sequential group of animations."""
def reverse(self):
"""Reverse animation in-place by switching start and end values."""
for anim in reversed(list(self)):
old_start = anim.startValue()
old_end = anim.endValue()
anim.setStar... | the_stack_v2_python_sparse | prettyqt/core/sequentialanimationgroup.py | phil65/PrettyQt | train | 17 |
d433d513f2b8583146aa8a3ff64c06b3e1e2aa9a | [
"base.Action.__init__(self, self.__loadPlugin)\nself.__frame = frame\nself.__overlayList = overlayList\nself.__displayCtx = displayCtx",
"lastDir = fslsettings.read('loadPluginLastDir')\nif lastDir is None:\n lastDir = os.getcwd()\nmsg = strings.messages[self, 'loadPlugin']\ndlg = wx.FileDialog(self.__frame, m... | <|body_start_0|>
base.Action.__init__(self, self.__loadPlugin)
self.__frame = frame
self.__overlayList = overlayList
self.__displayCtx = displayCtx
<|end_body_0|>
<|body_start_1|>
lastDir = fslsettings.read('loadPluginLastDir')
if lastDir is None:
lastDir = o... | The :class:`LoadPluginAction` class is an :class:`.Action` which allows the user to load/install FSLeyes plugins - see the :mod:`.plugins` module. | LoadPluginAction | [
"BSD-3-Clause",
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadPluginAction:
"""The :class:`LoadPluginAction` class is an :class:`.Action` which allows the user to load/install FSLeyes plugins - see the :mod:`.plugins` module."""
def __init__(self, overlayList, displayCtx, frame):
"""Create a ``LoadPluginAction``. :arg overlayList: The :clas... | stack_v2_sparse_classes_36k_train_012056 | 2,921 | permissive | [
{
"docstring": "Create a ``LoadPluginAction``. :arg overlayList: The :class:`.OverlayList`. :arg displayCtx: The top-level :class:`.DisplayContext`. :arg overlayList: The :class:`.FSLeyesFrame`.",
"name": "__init__",
"signature": "def __init__(self, overlayList, displayCtx, frame)"
},
{
"docstri... | 2 | stack_v2_sparse_classes_30k_train_006854 | Implement the Python class `LoadPluginAction` described below.
Class description:
The :class:`LoadPluginAction` class is an :class:`.Action` which allows the user to load/install FSLeyes plugins - see the :mod:`.plugins` module.
Method signatures and docstrings:
- def __init__(self, overlayList, displayCtx, frame): C... | Implement the Python class `LoadPluginAction` described below.
Class description:
The :class:`LoadPluginAction` class is an :class:`.Action` which allows the user to load/install FSLeyes plugins - see the :mod:`.plugins` module.
Method signatures and docstrings:
- def __init__(self, overlayList, displayCtx, frame): C... | 46ccb4fe2b2346eb57576247f49714032b61307a | <|skeleton|>
class LoadPluginAction:
"""The :class:`LoadPluginAction` class is an :class:`.Action` which allows the user to load/install FSLeyes plugins - see the :mod:`.plugins` module."""
def __init__(self, overlayList, displayCtx, frame):
"""Create a ``LoadPluginAction``. :arg overlayList: The :clas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadPluginAction:
"""The :class:`LoadPluginAction` class is an :class:`.Action` which allows the user to load/install FSLeyes plugins - see the :mod:`.plugins` module."""
def __init__(self, overlayList, displayCtx, frame):
"""Create a ``LoadPluginAction``. :arg overlayList: The :class:`.OverlayLi... | the_stack_v2_python_sparse | fsleyes/actions/loadplugin.py | sanjayankur31/fsleyes | train | 1 |
29fdd07f7e399c87a5025a967bf5f5bbafa1e959 | [
"q = g.session.query(db.Node)\nauth_org_id = self.obtain_organization_id()\nargs = request.args\nfor param in ['organization_id', 'collaboration_id', 'status', 'ip']:\n if param in args:\n q = q.filter(getattr(db.Node, param) == args[param])\nif 'name' in args:\n q = q.filter(db.Node.name.like(args['na... | <|body_start_0|>
q = g.session.query(db.Node)
auth_org_id = self.obtain_organization_id()
args = request.args
for param in ['organization_id', 'collaboration_id', 'status', 'ip']:
if param in args:
q = q.filter(getattr(db.Node, param) == args[param])
i... | Nodes | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nodes:
def get(self):
"""Returns a list of nodes --- description: >- Returns a list of nodes which are part of the organization to which the user or node belongs. In case an administrator account makes this request, all nodes from all organizations are returned. ### Permission Table |Rul... | stack_v2_sparse_classes_36k_train_012057 | 19,400 | permissive | [
{
"docstring": "Returns a list of nodes --- description: >- Returns a list of nodes which are part of the organization to which the user or node belongs. In case an administrator account makes this request, all nodes from all organizations are returned. ### Permission Table |Rule name|Scope|Operation|Assigned t... | 2 | stack_v2_sparse_classes_30k_train_000287 | Implement the Python class `Nodes` described below.
Class description:
Implement the Nodes class.
Method signatures and docstrings:
- def get(self): Returns a list of nodes --- description: >- Returns a list of nodes which are part of the organization to which the user or node belongs. In case an administrator accoun... | Implement the Python class `Nodes` described below.
Class description:
Implement the Nodes class.
Method signatures and docstrings:
- def get(self): Returns a list of nodes --- description: >- Returns a list of nodes which are part of the organization to which the user or node belongs. In case an administrator accoun... | b3ff6e91ac4caeaf31c12c20f73dfc61cfd9baca | <|skeleton|>
class Nodes:
def get(self):
"""Returns a list of nodes --- description: >- Returns a list of nodes which are part of the organization to which the user or node belongs. In case an administrator account makes this request, all nodes from all organizations are returned. ### Permission Table |Rul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Nodes:
def get(self):
"""Returns a list of nodes --- description: >- Returns a list of nodes which are part of the organization to which the user or node belongs. In case an administrator account makes this request, all nodes from all organizations are returned. ### Permission Table |Rule name|Scope|O... | the_stack_v2_python_sparse | vantage6-server/vantage6/server/resource/node.py | vantage6/vantage6 | train | 15 | |
d87574e09b5d6209a73863ef4e1280e6ea6dd87c | [
"self.size = size\nself.q = collections.deque()\nself.total = 0",
"if len(self.q) == self.size:\n self.total -= self.q.popleft()\nself.q.append(val)\nself.total += val\nreturn self.total / len(self.q)"
] | <|body_start_0|>
self.size = size
self.q = collections.deque()
self.total = 0
<|end_body_0|>
<|body_start_1|>
if len(self.q) == self.size:
self.total -= self.q.popleft()
self.q.append(val)
self.total += val
return self.total / len(self.q)
<|end_body_1... | MovingAverage2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage2:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.q = co... | stack_v2_sparse_classes_36k_train_012058 | 2,826 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | null | Implement the Python class `MovingAverage2` described below.
Class description:
Implement the MovingAverage2 class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage2` described below.
Class description:
Implement the MovingAverage2 class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage2:... | 2ffe01713a12090848ed9b75457bf9ee156db84b | <|skeleton|>
class MovingAverage2:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage2:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.q = collections.deque()
self.total = 0
def next(self, val):
""":type val: int :rtype: float"""
if len(self.q) == self.size:
... | the_stack_v2_python_sparse | array/Q346_movingAverage.py | liangming168/leetcode | train | 0 | |
7802ccf1ae818f149878d1b427d361617b71c1f7 | [
"def rserialize(root, string):\n if root is None:\n string += 'None, '\n else:\n string += str(root.val) + ','\n string = rserialize(root.left, string)\n string = rserialize(root.right, string)\n return string\nreturn rserialize(root, '')",
"def rdeserialize(string):\n if s... | <|body_start_0|>
def rserialize(root, string):
if root is None:
string += 'None, '
else:
string += str(root.val) + ','
string = rserialize(root.left, string)
string = rserialize(root.right, string)
return string
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_012059 | 2,525 | 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:... | 786075e0f9f61cf062703bc0b41cc3191d77f033 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def rserialize(root, string):
if root is None:
string += 'None, '
else:
string += str(root.val) + ','
string = rse... | the_stack_v2_python_sparse | 297_BtreeSerialize.py | Anirban2404/LeetCodePractice | train | 1 | |
24f7495a798142882ef92fdd628782106b1b4adc | [
"if k == len(cardPoints):\n return sum(cardPoints)\n\ndef dfs(cards, k, res):\n if k and cards:\n res += max(cards[0] + dfs(cards[1:], k - 1, res), cards[-1] + dfs(cards[:-1], k - 1, res))\n return res\nreturn dfs(cardPoints, k, 0)",
"lens = len(cardPoints)\nif k == lens:\n return sum(cardPoint... | <|body_start_0|>
if k == len(cardPoints):
return sum(cardPoints)
def dfs(cards, k, res):
if k and cards:
res += max(cards[0] + dfs(cards[1:], k - 1, res), cards[-1] + dfs(cards[:-1], k - 1, res))
return res
return dfs(cardPoints, k, 0)
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxScore1(self, cardPoints: List[int], k: int) -> int:
"""DFS超时"""
<|body_0|>
def maxScore2(self, cardPoints: List[int], k: int) -> int:
"""逆向思维,求左右取得最大值,转化为个数为k的连续最小子数组 滑动窗口进行求值"""
<|body_1|>
def maxScore3(self, cardPoints: List[int], k: i... | stack_v2_sparse_classes_36k_train_012060 | 2,182 | no_license | [
{
"docstring": "DFS超时",
"name": "maxScore1",
"signature": "def maxScore1(self, cardPoints: List[int], k: int) -> int"
},
{
"docstring": "逆向思维,求左右取得最大值,转化为个数为k的连续最小子数组 滑动窗口进行求值",
"name": "maxScore2",
"signature": "def maxScore2(self, cardPoints: List[int], k: int) -> int"
},
{
"do... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxScore1(self, cardPoints: List[int], k: int) -> int: DFS超时
- def maxScore2(self, cardPoints: List[int], k: int) -> int: 逆向思维,求左右取得最大值,转化为个数为k的连续最小子数组 滑动窗口进行求值
- def maxScor... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxScore1(self, cardPoints: List[int], k: int) -> int: DFS超时
- def maxScore2(self, cardPoints: List[int], k: int) -> int: 逆向思维,求左右取得最大值,转化为个数为k的连续最小子数组 滑动窗口进行求值
- def maxScor... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def maxScore1(self, cardPoints: List[int], k: int) -> int:
"""DFS超时"""
<|body_0|>
def maxScore2(self, cardPoints: List[int], k: int) -> int:
"""逆向思维,求左右取得最大值,转化为个数为k的连续最小子数组 滑动窗口进行求值"""
<|body_1|>
def maxScore3(self, cardPoints: List[int], k: i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxScore1(self, cardPoints: List[int], k: int) -> int:
"""DFS超时"""
if k == len(cardPoints):
return sum(cardPoints)
def dfs(cards, k, res):
if k and cards:
res += max(cards[0] + dfs(cards[1:], k - 1, res), cards[-1] + dfs(cards[:-1]... | the_stack_v2_python_sparse | 1423_maximum-points-you-can-obtain-from-cards.py | helloocc/algorithm | train | 1 | |
2ca896048ca7bd589f7b9e2c6683912333343845 | [
"row = g.db.query(Machine).get(machine_id)\nif not row:\n log.warning('Requested a non-existant machine: %s', machine_id)\n abort(http_client.NOT_FOUND, description='Machine not found')\nrecord = row.as_dict()\nrecord['url'] = url_for('machines.entry', machine_id=machine_id, _external=True)\nrecord['servers_u... | <|body_start_0|>
row = g.db.query(Machine).get(machine_id)
if not row:
log.warning('Requested a non-existant machine: %s', machine_id)
abort(http_client.NOT_FOUND, description='Machine not found')
record = row.as_dict()
record['url'] = url_for('machines.entry', ma... | Information about specific machines | MachineAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MachineAPI:
"""Information about specific machines"""
def get(self, machine_id):
"""Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json"""
<|body_0|>
def put(self, args, machine_id):
"""Update machine Heartbe... | stack_v2_sparse_classes_36k_train_012061 | 10,491 | permissive | [
{
"docstring": "Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json",
"name": "get",
"signature": "def get(self, machine_id)"
},
{
"docstring": "Update machine Heartbeat and update the machine reference",
"name": "put",
"signature": ... | 2 | stack_v2_sparse_classes_30k_val_000003 | Implement the Python class `MachineAPI` described below.
Class description:
Information about specific machines
Method signatures and docstrings:
- def get(self, machine_id): Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json
- def put(self, args, machine_id): U... | Implement the Python class `MachineAPI` described below.
Class description:
Information about specific machines
Method signatures and docstrings:
- def get(self, machine_id): Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json
- def put(self, args, machine_id): U... | 2771bb46db7fd331448f9db3cfb257fab7f89bcc | <|skeleton|>
class MachineAPI:
"""Information about specific machines"""
def get(self, machine_id):
"""Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json"""
<|body_0|>
def put(self, args, machine_id):
"""Update machine Heartbe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MachineAPI:
"""Information about specific machines"""
def get(self, machine_id):
"""Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json"""
row = g.db.query(Machine).get(machine_id)
if not row:
log.warning('Requeste... | the_stack_v2_python_sparse | driftbase/api/machines.py | directivegames/drift-base | train | 1 |
b2790b1846cc227944ef0ba8a450af4208f9bf30 | [
"list_of_indexes = response.xpath('//*/li[@class=\"list-group-item\"]/a/@href').extract()\nfor index in list_of_indexes:\n yield scrapy.Request(index, callback=self.parse_companies)",
"list_of_companies = response.xpath('//*/div[@class=\"media-body\"]')\nfor company in list_of_companies:\n link = company.xp... | <|body_start_0|>
list_of_indexes = response.xpath('//*/li[@class="list-group-item"]/a/@href').extract()
for index in list_of_indexes:
yield scrapy.Request(index, callback=self.parse_companies)
<|end_body_0|>
<|body_start_1|>
list_of_companies = response.xpath('//*/div[@class="media-... | Spider to get the data from the eurocis | ELounge | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ELounge:
"""Spider to get the data from the eurocis"""
def parse(self, response):
"""Method looks for the indexes :param response: the fully downloaded webpage :return: the iterator over the categories links"""
<|body_0|>
def parse_companies(self, response):
"""M... | stack_v2_sparse_classes_36k_train_012062 | 2,533 | no_license | [
{
"docstring": "Method looks for the indexes :param response: the fully downloaded webpage :return: the iterator over the categories links",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Method get the list of the companies on the webpage and calls itself with the ... | 3 | stack_v2_sparse_classes_30k_train_002793 | Implement the Python class `ELounge` described below.
Class description:
Spider to get the data from the eurocis
Method signatures and docstrings:
- def parse(self, response): Method looks for the indexes :param response: the fully downloaded webpage :return: the iterator over the categories links
- def parse_compani... | Implement the Python class `ELounge` described below.
Class description:
Spider to get the data from the eurocis
Method signatures and docstrings:
- def parse(self, response): Method looks for the indexes :param response: the fully downloaded webpage :return: the iterator over the categories links
- def parse_compani... | 64a7ec204166532fc653f7001f288179e45d1046 | <|skeleton|>
class ELounge:
"""Spider to get the data from the eurocis"""
def parse(self, response):
"""Method looks for the indexes :param response: the fully downloaded webpage :return: the iterator over the categories links"""
<|body_0|>
def parse_companies(self, response):
"""M... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ELounge:
"""Spider to get the data from the eurocis"""
def parse(self, response):
"""Method looks for the indexes :param response: the fully downloaded webpage :return: the iterator over the categories links"""
list_of_indexes = response.xpath('//*/li[@class="list-group-item"]/a/@href').e... | the_stack_v2_python_sparse | AutoScrapy/spiders/elounge.py | SpaceZZ/AutoScrapyProject2 | train | 0 |
970a2e61fbb294a635380fe715ed004677762276 | [
"doc = '登录页面_登录操作'\nself.wait_element_visible(loc.username_ele, doc)\nself.input_text(loc.username_ele, username, doc)\nself.input_text(loc.password_ele, password, doc)\nself.click_element(loc.submit_ele, doc)",
"doc = '登录页面_忘记密码'\nself.wait_element_visible(loc.forget_password_ele, doc)\nself.click_element(loc.fo... | <|body_start_0|>
doc = '登录页面_登录操作'
self.wait_element_visible(loc.username_ele, doc)
self.input_text(loc.username_ele, username, doc)
self.input_text(loc.password_ele, password, doc)
self.click_element(loc.submit_ele, doc)
<|end_body_0|>
<|body_start_1|>
doc = '登录页面_忘记密码'... | 登录页--业务操作封装 | LoginPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginPage:
"""登录页--业务操作封装"""
def login(self, username, password):
"""登录操作"""
<|body_0|>
def forget_password(self):
"""忘记密码"""
<|body_1|>
def isExist_user(self):
"""错误提示"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
doc = '... | stack_v2_sparse_classes_36k_train_012063 | 1,790 | no_license | [
{
"docstring": "登录操作",
"name": "login",
"signature": "def login(self, username, password)"
},
{
"docstring": "忘记密码",
"name": "forget_password",
"signature": "def forget_password(self)"
},
{
"docstring": "错误提示",
"name": "isExist_user",
"signature": "def isExist_user(self)"... | 3 | stack_v2_sparse_classes_30k_train_019081 | Implement the Python class `LoginPage` described below.
Class description:
登录页--业务操作封装
Method signatures and docstrings:
- def login(self, username, password): 登录操作
- def forget_password(self): 忘记密码
- def isExist_user(self): 错误提示 | Implement the Python class `LoginPage` described below.
Class description:
登录页--业务操作封装
Method signatures and docstrings:
- def login(self, username, password): 登录操作
- def forget_password(self): 忘记密码
- def isExist_user(self): 错误提示
<|skeleton|>
class LoginPage:
"""登录页--业务操作封装"""
def login(self, username, pass... | 362c35c790c9068f08ff9b24b8bb183b17a90b73 | <|skeleton|>
class LoginPage:
"""登录页--业务操作封装"""
def login(self, username, password):
"""登录操作"""
<|body_0|>
def forget_password(self):
"""忘记密码"""
<|body_1|>
def isExist_user(self):
"""错误提示"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginPage:
"""登录页--业务操作封装"""
def login(self, username, password):
"""登录操作"""
doc = '登录页面_登录操作'
self.wait_element_visible(loc.username_ele, doc)
self.input_text(loc.username_ele, username, doc)
self.input_text(loc.password_ele, password, doc)
self.click_elem... | the_stack_v2_python_sparse | class_200130_PageObject/PageObjects/login_page.py | zyj16602159899/lemon_class | train | 0 |
d53738302b50526da1e26b96f707854dbf62a5f4 | [
"if not isinstance(data, np.ndarray) or data.ndim != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nd, n = data.shape\nif n < 2:\n raise ValueError('data must contain multiple data points')\nself.mean = np.mean(data, axis=1, keepdims=True)\nY = data - self.mean\nself.cov = np.dot(Y, Y.T) / (n - 1)",... | <|body_start_0|>
if not isinstance(data, np.ndarray) or data.ndim != 2:
raise TypeError('data must be a 2D numpy.ndarray')
d, n = data.shape
if n < 2:
raise ValueError('data must contain multiple data points')
self.mean = np.mean(data, axis=1, keepdims=True)
... | the class pf multinormal | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""the class pf multinormal"""
def __init__(self, data):
"""class constructor"""
<|body_0|>
def pdf(self, x):
"""calculates the PDF at a data point"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not isinstance(data, np.ndarray) ... | stack_v2_sparse_classes_36k_train_012064 | 1,105 | no_license | [
{
"docstring": "class constructor",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "calculates the PDF at a data point",
"name": "pdf",
"signature": "def pdf(self, x)"
}
] | 2 | null | Implement the Python class `MultiNormal` described below.
Class description:
the class pf multinormal
Method signatures and docstrings:
- def __init__(self, data): class constructor
- def pdf(self, x): calculates the PDF at a data point | Implement the Python class `MultiNormal` described below.
Class description:
the class pf multinormal
Method signatures and docstrings:
- def __init__(self, data): class constructor
- def pdf(self, x): calculates the PDF at a data point
<|skeleton|>
class MultiNormal:
"""the class pf multinormal"""
def __in... | 80bf8d3354702f7fb9f79bbb5ed7e00fc19f788d | <|skeleton|>
class MultiNormal:
"""the class pf multinormal"""
def __init__(self, data):
"""class constructor"""
<|body_0|>
def pdf(self, x):
"""calculates the PDF at a data point"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiNormal:
"""the class pf multinormal"""
def __init__(self, data):
"""class constructor"""
if not isinstance(data, np.ndarray) or data.ndim != 2:
raise TypeError('data must be a 2D numpy.ndarray')
d, n = data.shape
if n < 2:
raise ValueError('dat... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | Immaannn2222/holbertonschool-machine_learning | train | 1 |
905ce85614bc980dc7aa3aa91ff8742ed73e6f1b | [
"self.assertEqual(MakeImportStackMessage(['x']), '')\nself.assertEqual(MakeImportStackMessage(['x', 'y']), '\\n y was imported by x')\nself.assertEqual(MakeImportStackMessage(['x', 'y', 'z']), '\\n z was imported by y\\n y was imported by x')",
"interface = FakeIface()\ninterface.mojom_name = 'RendererConfigur... | <|body_start_0|>
self.assertEqual(MakeImportStackMessage(['x']), '')
self.assertEqual(MakeImportStackMessage(['x', 'y']), '\n y was imported by x')
self.assertEqual(MakeImportStackMessage(['x', 'y', 'z']), '\n z was imported by y\n y was imported by x')
<|end_body_0|>
<|body_start_1|>
... | Tests mojo_bindings_generator. | MojoBindingsGeneratorTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MojoBindingsGeneratorTest:
"""Tests mojo_bindings_generator."""
def testMakeImportStackMessage(self):
"""Tests MakeImportStackMessage()."""
<|body_0|>
def testScrambleMethodOrdinals(self):
"""Tests ScrambleMethodOrdinals()."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_012065 | 2,152 | permissive | [
{
"docstring": "Tests MakeImportStackMessage().",
"name": "testMakeImportStackMessage",
"signature": "def testMakeImportStackMessage(self)"
},
{
"docstring": "Tests ScrambleMethodOrdinals().",
"name": "testScrambleMethodOrdinals",
"signature": "def testScrambleMethodOrdinals(self)"
}
] | 2 | null | Implement the Python class `MojoBindingsGeneratorTest` described below.
Class description:
Tests mojo_bindings_generator.
Method signatures and docstrings:
- def testMakeImportStackMessage(self): Tests MakeImportStackMessage().
- def testScrambleMethodOrdinals(self): Tests ScrambleMethodOrdinals(). | Implement the Python class `MojoBindingsGeneratorTest` described below.
Class description:
Tests mojo_bindings_generator.
Method signatures and docstrings:
- def testMakeImportStackMessage(self): Tests MakeImportStackMessage().
- def testScrambleMethodOrdinals(self): Tests ScrambleMethodOrdinals().
<|skeleton|>
clas... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class MojoBindingsGeneratorTest:
"""Tests mojo_bindings_generator."""
def testMakeImportStackMessage(self):
"""Tests MakeImportStackMessage()."""
<|body_0|>
def testScrambleMethodOrdinals(self):
"""Tests ScrambleMethodOrdinals()."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MojoBindingsGeneratorTest:
"""Tests mojo_bindings_generator."""
def testMakeImportStackMessage(self):
"""Tests MakeImportStackMessage()."""
self.assertEqual(MakeImportStackMessage(['x']), '')
self.assertEqual(MakeImportStackMessage(['x', 'y']), '\n y was imported by x')
s... | the_stack_v2_python_sparse | mojo/public/tools/bindings/mojom_bindings_generator_unittest.py | chromium/chromium | train | 17,408 |
f8e0f654cbec8ae73300b356bed3ae00136530fe | [
"uptime_list = [0, 0, 0, 0, 0]\npattern_list = [' ([0-9]+) year', ' ([0-9]+) week', ' ([0-9]+) day', ' ([0-9]+) hour', ' ([0-9]+) minute']\nfor i, a_pattern in enumerate(pattern_list):\n uptime_list[i] = find_uptime_field(a_pattern, uptime_str)\nself.years, self.weeks, self.days, self.hours, self.minutes = uptim... | <|body_start_0|>
uptime_list = [0, 0, 0, 0, 0]
pattern_list = [' ([0-9]+) year', ' ([0-9]+) week', ' ([0-9]+) day', ' ([0-9]+) hour', ' ([0-9]+) minute']
for i, a_pattern in enumerate(pattern_list):
uptime_list[i] = find_uptime_field(a_pattern, uptime_str)
self.years, self.we... | Create an Uptime object for Cisco uptime strings | Uptime | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Uptime:
"""Create an Uptime object for Cisco uptime strings"""
def __init__(self, uptime_str):
"""Initialise uptime object Questions about this code: 1. Unsure here is best to have uptime_str a self.uptime_str as it is unique to the object? 2. If self.uptime_str then the find_uptime_... | stack_v2_sparse_classes_36k_train_012066 | 3,558 | permissive | [
{
"docstring": "Initialise uptime object Questions about this code: 1. Unsure here is best to have uptime_str a self.uptime_str as it is unique to the object? 2. If self.uptime_str then the find_uptime_field needs to be updated to be a object method with self.uptime_str attribute passed instead?",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_007411 | Implement the Python class `Uptime` described below.
Class description:
Create an Uptime object for Cisco uptime strings
Method signatures and docstrings:
- def __init__(self, uptime_str): Initialise uptime object Questions about this code: 1. Unsure here is best to have uptime_str a self.uptime_str as it is unique t... | Implement the Python class `Uptime` described below.
Class description:
Create an Uptime object for Cisco uptime strings
Method signatures and docstrings:
- def __init__(self, uptime_str): Initialise uptime object Questions about this code: 1. Unsure here is best to have uptime_str a self.uptime_str as it is unique t... | eaa52cd58cd2f49e0d5e8ccec3795a1098b08f20 | <|skeleton|>
class Uptime:
"""Create an Uptime object for Cisco uptime strings"""
def __init__(self, uptime_str):
"""Initialise uptime object Questions about this code: 1. Unsure here is best to have uptime_str a self.uptime_str as it is unique to the object? 2. If self.uptime_str then the find_uptime_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Uptime:
"""Create an Uptime object for Cisco uptime strings"""
def __init__(self, uptime_str):
"""Initialise uptime object Questions about this code: 1. Unsure here is best to have uptime_str a self.uptime_str as it is unique to the object? 2. If self.uptime_str then the find_uptime_field needs t... | the_stack_v2_python_sparse | tmp/ch9q2.py | gerards/pynet_learning_python | train | 0 |
5f0d1b987c2726efb211cf861c277753d90622a6 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MobileAppContentFile()",
"from .entity import Entity\nfrom .mobile_app_content_file_upload_state import MobileAppContentFileUploadState\nfrom .entity import Entity\nfrom .mobile_app_content_file_upload_state import MobileAppContentFile... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return MobileAppContentFile()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .mobile_app_content_file_upload_state import MobileAppContentFileUploadState
from .entity i... | Contains properties for a single installer file that is associated with a given mobileAppContent version. | MobileAppContentFile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MobileAppContentFile:
"""Contains properties for a single installer file that is associated with a given mobileAppContent version."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MobileAppContentFile:
"""Creates a new instance of the appropriate class ... | stack_v2_sparse_classes_36k_train_012067 | 4,470 | 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: MobileAppContentFile",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | null | Implement the Python class `MobileAppContentFile` described below.
Class description:
Contains properties for a single installer file that is associated with a given mobileAppContent version.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MobileAppCont... | Implement the Python class `MobileAppContentFile` described below.
Class description:
Contains properties for a single installer file that is associated with a given mobileAppContent version.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MobileAppCont... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class MobileAppContentFile:
"""Contains properties for a single installer file that is associated with a given mobileAppContent version."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MobileAppContentFile:
"""Creates a new instance of the appropriate class ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MobileAppContentFile:
"""Contains properties for a single installer file that is associated with a given mobileAppContent version."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MobileAppContentFile:
"""Creates a new instance of the appropriate class based on disc... | the_stack_v2_python_sparse | msgraph/generated/models/mobile_app_content_file.py | microsoftgraph/msgraph-sdk-python | train | 135 |
5eae4fc521669e25024b4e7526a1b103c984d9a4 | [
"srcdir = tf_cfg.cfg.get('Tempesta', 'srcdir')\nworkdir = tf_cfg.cfg.get('Tempesta', 'workdir')\ntemplate = '%s/etc/js_challenge.tpl' % srcdir\njs_code = '%s/etc/js_challenge.js.tpl' % srcdir\nremote.tempesta.run_cmd('cp %s %s' % (js_code, workdir))\nremote.tempesta.run_cmd('cp %s %s/js1.tpl' % (template, workdir))... | <|body_start_0|>
srcdir = tf_cfg.cfg.get('Tempesta', 'srcdir')
workdir = tf_cfg.cfg.get('Tempesta', 'workdir')
template = '%s/etc/js_challenge.tpl' % srcdir
js_code = '%s/etc/js_challenge.js.tpl' % srcdir
remote.tempesta.run_cmd('cp %s %s' % (js_code, workdir))
remote.tem... | JSChallengeAfterReload | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSChallengeAfterReload:
def prepare_js_templates(self):
"""Templates for JS challenge are modified by start script, create a copy of default template for each vhost."""
<|body_0|>
def test(self):
"""Clients sends the validating request after reload just in time and p... | stack_v2_sparse_classes_36k_train_012068 | 24,777 | no_license | [
{
"docstring": "Templates for JS challenge are modified by start script, create a copy of default template for each vhost.",
"name": "prepare_js_templates",
"signature": "def prepare_js_templates(self)"
},
{
"docstring": "Clients sends the validating request after reload just in time and passes ... | 2 | stack_v2_sparse_classes_30k_train_014030 | Implement the Python class `JSChallengeAfterReload` described below.
Class description:
Implement the JSChallengeAfterReload class.
Method signatures and docstrings:
- def prepare_js_templates(self): Templates for JS challenge are modified by start script, create a copy of default template for each vhost.
- def test(... | Implement the Python class `JSChallengeAfterReload` described below.
Class description:
Implement the JSChallengeAfterReload class.
Method signatures and docstrings:
- def prepare_js_templates(self): Templates for JS challenge are modified by start script, create a copy of default template for each vhost.
- def test(... | d56358ea653dbb367624937197ce5e489abf0b00 | <|skeleton|>
class JSChallengeAfterReload:
def prepare_js_templates(self):
"""Templates for JS challenge are modified by start script, create a copy of default template for each vhost."""
<|body_0|>
def test(self):
"""Clients sends the validating request after reload just in time and p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JSChallengeAfterReload:
def prepare_js_templates(self):
"""Templates for JS challenge are modified by start script, create a copy of default template for each vhost."""
srcdir = tf_cfg.cfg.get('Tempesta', 'srcdir')
workdir = tf_cfg.cfg.get('Tempesta', 'workdir')
template = '%s/... | the_stack_v2_python_sparse | sessions/test_js_challenge.py | tempesta-tech/tempesta-test | train | 13 | |
4dc8b4ffd74e7820e31c62b863b4d643876ba8f5 | [
"self.srcLang = NAME_YAPPN_MAPPINGS[sourceLang]\nself.srcLocale = sourceLocale if sourceLocale else re.sub('-', '_', CULTURE_CODES[sourceLang][0])\nself.tgtLocale = targetLocale if targetLocale else re.sub('-', '_', CULTURE_CODES[targetLang][0])\nself._fullmatch = fullmatch\nself.srcDecimalSymbol = numbers.get_deci... | <|body_start_0|>
self.srcLang = NAME_YAPPN_MAPPINGS[sourceLang]
self.srcLocale = sourceLocale if sourceLocale else re.sub('-', '_', CULTURE_CODES[sourceLang][0])
self.tgtLocale = targetLocale if targetLocale else re.sub('-', '_', CULTURE_CODES[targetLang][0])
self._fullmatch = fullmatch
... | Rule-based percent translation | PercentTranslator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PercentTranslator:
"""Rule-based percent translation"""
def __init__(self, sourceLang, targetLang, sourceLocale, targetLocale, fullmatch=False):
"""Initialize a PercentTranslator instance Args: sourceLang (str): source language in full spelling, e.g., 'English' ignored if sourceLocal... | stack_v2_sparse_classes_36k_train_012069 | 21,856 | no_license | [
{
"docstring": "Initialize a PercentTranslator instance Args: sourceLang (str): source language in full spelling, e.g., 'English' ignored if sourceLocale is provided sourceLocale (str): source locale identifier targetLang (str): target language in full spelling, e.g., 'French' ignored if targetLocale is provide... | 4 | stack_v2_sparse_classes_30k_train_012725 | Implement the Python class `PercentTranslator` described below.
Class description:
Rule-based percent translation
Method signatures and docstrings:
- def __init__(self, sourceLang, targetLang, sourceLocale, targetLocale, fullmatch=False): Initialize a PercentTranslator instance Args: sourceLang (str): source language... | Implement the Python class `PercentTranslator` described below.
Class description:
Rule-based percent translation
Method signatures and docstrings:
- def __init__(self, sourceLang, targetLang, sourceLocale, targetLocale, fullmatch=False): Initialize a PercentTranslator instance Args: sourceLang (str): source language... | 3db60d54f076ea26d45cdbbe194d1cd357f8f1a3 | <|skeleton|>
class PercentTranslator:
"""Rule-based percent translation"""
def __init__(self, sourceLang, targetLang, sourceLocale, targetLocale, fullmatch=False):
"""Initialize a PercentTranslator instance Args: sourceLang (str): source language in full spelling, e.g., 'English' ignored if sourceLocal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PercentTranslator:
"""Rule-based percent translation"""
def __init__(self, sourceLang, targetLang, sourceLocale, targetLocale, fullmatch=False):
"""Initialize a PercentTranslator instance Args: sourceLang (str): source language in full spelling, e.g., 'English' ignored if sourceLocale is provided... | the_stack_v2_python_sparse | tb_utils/rules.py | EthannyDing/text_mining | train | 0 |
5c300ba5c1a2d0c915f4f58de3fe18beb2b6d810 | [
"if column_indexes is None:\n column_indexes = []\nif process_names is None:\n process_names = []\nif user_ids is None:\n user_ids = []\nif filename is None:\n now = datetime.datetime.now()\n current_date = datetime.datetime.strftime(now, '%H%M%S_%m%d%Y')\n self.filename = 'topdata_{0}.txt'.format... | <|body_start_0|>
if column_indexes is None:
column_indexes = []
if process_names is None:
process_names = []
if user_ids is None:
user_ids = []
if filename is None:
now = datetime.datetime.now()
current_date = datetime.datetime.... | TopData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopData:
def __init__(self, filename=None, user_ids=None, process_names=None, column_indexes=None):
"""Initialize the object. Args: filename (str): The name of the output file. Optional. Default value is None. user_ids (list): System user IDs. Optional. Default value is None. process_nam... | stack_v2_sparse_classes_36k_train_012070 | 6,310 | no_license | [
{
"docstring": "Initialize the object. Args: filename (str): The name of the output file. Optional. Default value is None. user_ids (list): System user IDs. Optional. Default value is None. process_names (list): Process names. Optional. Default value is an empty list. column_indexes (list): The index numbers fo... | 3 | stack_v2_sparse_classes_30k_train_006784 | Implement the Python class `TopData` described below.
Class description:
Implement the TopData class.
Method signatures and docstrings:
- def __init__(self, filename=None, user_ids=None, process_names=None, column_indexes=None): Initialize the object. Args: filename (str): The name of the output file. Optional. Defau... | Implement the Python class `TopData` described below.
Class description:
Implement the TopData class.
Method signatures and docstrings:
- def __init__(self, filename=None, user_ids=None, process_names=None, column_indexes=None): Initialize the object. Args: filename (str): The name of the output file. Optional. Defau... | 3060282c7e794fe7d68e1999ca25e418c9aa9d23 | <|skeleton|>
class TopData:
def __init__(self, filename=None, user_ids=None, process_names=None, column_indexes=None):
"""Initialize the object. Args: filename (str): The name of the output file. Optional. Default value is None. user_ids (list): System user IDs. Optional. Default value is None. process_nam... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopData:
def __init__(self, filename=None, user_ids=None, process_names=None, column_indexes=None):
"""Initialize the object. Args: filename (str): The name of the output file. Optional. Default value is None. user_ids (list): System user IDs. Optional. Default value is None. process_names (list): Pro... | the_stack_v2_python_sparse | system_tools.py | rdunningcisco/general | train | 0 | |
7aee97c7f6b32a4010a912bdbe3a2976d521f68f | [
"self.Agent = Agent\nself.alpha = alpha\nself.gamma = gamma\nself.epsilon = epsilon\nself.policy = dict()\nself.Q = dict()\nself.V = dict()\nS = set([(i, j) for i in range(-5, 6) for j in range(-5, 6)])\nfor s in S:\n self.V[s] = numpy.float16(0)\n self.Q[s] = dict()\n self.policy[s] = dict()\n for a in... | <|body_start_0|>
self.Agent = Agent
self.alpha = alpha
self.gamma = gamma
self.epsilon = epsilon
self.policy = dict()
self.Q = dict()
self.V = dict()
S = set([(i, j) for i in range(-5, 6) for j in range(-5, 6)])
for s in S:
self.V[s] = ... | Implementation of functions related to Q-learning. | TeamQLearning | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamQLearning:
"""Implementation of functions related to Q-learning."""
def __init__(self, Agent, alpha, gamma, epsilon):
"""Fill all values of Q based on a given optimistic value."""
<|body_0|>
def updateQ(self, s, a, o, s_prime, r):
"""Perform one step for this... | stack_v2_sparse_classes_36k_train_012071 | 2,158 | no_license | [
{
"docstring": "Fill all values of Q based on a given optimistic value.",
"name": "__init__",
"signature": "def __init__(self, Agent, alpha, gamma, epsilon)"
},
{
"docstring": "Perform one step for this agent for a given state s. Action, resulting state s_prime, and observed reward r are also gi... | 2 | stack_v2_sparse_classes_30k_train_020164 | Implement the Python class `TeamQLearning` described below.
Class description:
Implementation of functions related to Q-learning.
Method signatures and docstrings:
- def __init__(self, Agent, alpha, gamma, epsilon): Fill all values of Q based on a given optimistic value.
- def updateQ(self, s, a, o, s_prime, r): Perf... | Implement the Python class `TeamQLearning` described below.
Class description:
Implementation of functions related to Q-learning.
Method signatures and docstrings:
- def __init__(self, Agent, alpha, gamma, epsilon): Fill all values of Q based on a given optimistic value.
- def updateQ(self, s, a, o, s_prime, r): Perf... | a1bc1f82f2824055d3adcd0c33105556aa4099a8 | <|skeleton|>
class TeamQLearning:
"""Implementation of functions related to Q-learning."""
def __init__(self, Agent, alpha, gamma, epsilon):
"""Fill all values of Q based on a given optimistic value."""
<|body_0|>
def updateQ(self, s, a, o, s_prime, r):
"""Perform one step for this... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamQLearning:
"""Implementation of functions related to Q-learning."""
def __init__(self, Agent, alpha, gamma, epsilon):
"""Fill all values of Q based on a given optimistic value."""
self.Agent = Agent
self.alpha = alpha
self.gamma = gamma
self.epsilon = epsilon
... | the_stack_v2_python_sparse | source/MultiAgent/Minimax/TeamQLearning.py | camielv/UvA-MasterAI-AA | train | 0 |
8289a28dd3a1d29f4d2f50494ac249b3e4294f19 | [
"super(RegionPrediction, self).__init__()\nself.thresh = thresh\nself.class_axis = class_axis",
"conf_obj = class_prob * obj.unsqueeze_(self.class_axis)\nconf_obj[conf_obj <= self.thresh] = 0\nmax_conf_obj, _ = torch.max(conf_obj, self.class_axis)\nreturn torch.cat([conf_obj, max_conf_obj.unsqueeze_(self.class_ax... | <|body_start_0|>
super(RegionPrediction, self).__init__()
self.thresh = thresh
self.class_axis = class_axis
<|end_body_0|>
<|body_start_1|>
conf_obj = class_prob * obj.unsqueeze_(self.class_axis)
conf_obj[conf_obj <= self.thresh] = 0
max_conf_obj, _ = torch.max(conf_obj,... | Caffe RegionPrediction fully compatible class Parameters: thresh - filtering threshold of confidence = class_conf * obj class_axis - axis that corresponds to classes in the torch tensor class_prob - class probability (typically output of softmax) obj - objectness score (typically after Sigmoid) | RegionPrediction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegionPrediction:
"""Caffe RegionPrediction fully compatible class Parameters: thresh - filtering threshold of confidence = class_conf * obj class_axis - axis that corresponds to classes in the torch tensor class_prob - class probability (typically output of softmax) obj - objectness score (typic... | stack_v2_sparse_classes_36k_train_012072 | 1,263 | no_license | [
{
"docstring": "Constructs the RegionPrediction object :param thresh: float, threshold for confidence score (default=0.005) :param class_axis: int",
"name": "__init__",
"signature": "def __init__(self, thresh=0.005, class_axis=1)"
},
{
"docstring": ":param class_prob: class probability (typicall... | 2 | null | Implement the Python class `RegionPrediction` described below.
Class description:
Caffe RegionPrediction fully compatible class Parameters: thresh - filtering threshold of confidence = class_conf * obj class_axis - axis that corresponds to classes in the torch tensor class_prob - class probability (typically output of... | Implement the Python class `RegionPrediction` described below.
Class description:
Caffe RegionPrediction fully compatible class Parameters: thresh - filtering threshold of confidence = class_conf * obj class_axis - axis that corresponds to classes in the torch tensor class_prob - class probability (typically output of... | 7d2a3dd2beff1dbaff1633f04a1dfc96b87545b4 | <|skeleton|>
class RegionPrediction:
"""Caffe RegionPrediction fully compatible class Parameters: thresh - filtering threshold of confidence = class_conf * obj class_axis - axis that corresponds to classes in the torch tensor class_prob - class probability (typically output of softmax) obj - objectness score (typic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegionPrediction:
"""Caffe RegionPrediction fully compatible class Parameters: thresh - filtering threshold of confidence = class_conf * obj class_axis - axis that corresponds to classes in the torch tensor class_prob - class probability (typically output of softmax) obj - objectness score (typically after Si... | the_stack_v2_python_sparse | mtorch/region_prediction.py | liangcht/yolo_objectdetection | train | 0 |
b3bf87a3e3e0d129ffb2e5252ae0b7673545b81b | [
"if scalar_keys is None:\n scalar_keys = []\nif histogram_keys is None:\n histogram_keys = []\nself.scalar_keys = scalar_keys\nself.histogram_keys = histogram_keys\nself.scalar_summaries = []\nself.scalar_summaries_ph = []\nself.histogram_summaries_ph = []\nself.histogram_summaries = []\nwith tf.variable_scop... | <|body_start_0|>
if scalar_keys is None:
scalar_keys = []
if histogram_keys is None:
histogram_keys = []
self.scalar_keys = scalar_keys
self.histogram_keys = histogram_keys
self.scalar_summaries = []
self.scalar_summaries_ph = []
self.histo... | Stats | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stats:
def __init__(self, scalar_keys=None, histogram_keys=None):
"""initialize the placeholders from the input keys, for summary logging :param scalar_keys: ([str]) the name of all the scalar inputs :param histogram_keys: ([str]) the name of all the histogram inputs"""
<|body_0|... | stack_v2_sparse_classes_36k_train_012073 | 2,625 | permissive | [
{
"docstring": "initialize the placeholders from the input keys, for summary logging :param scalar_keys: ([str]) the name of all the scalar inputs :param histogram_keys: ([str]) the name of all the histogram inputs",
"name": "__init__",
"signature": "def __init__(self, scalar_keys=None, histogram_keys=N... | 2 | stack_v2_sparse_classes_30k_train_019129 | Implement the Python class `Stats` described below.
Class description:
Implement the Stats class.
Method signatures and docstrings:
- def __init__(self, scalar_keys=None, histogram_keys=None): initialize the placeholders from the input keys, for summary logging :param scalar_keys: ([str]) the name of all the scalar i... | Implement the Python class `Stats` described below.
Class description:
Implement the Stats class.
Method signatures and docstrings:
- def __init__(self, scalar_keys=None, histogram_keys=None): initialize the placeholders from the input keys, for summary logging :param scalar_keys: ([str]) the name of all the scalar i... | 37663341f60a05943202b77394a4203d070fad95 | <|skeleton|>
class Stats:
def __init__(self, scalar_keys=None, histogram_keys=None):
"""initialize the placeholders from the input keys, for summary logging :param scalar_keys: ([str]) the name of all the scalar inputs :param histogram_keys: ([str]) the name of all the histogram inputs"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stats:
def __init__(self, scalar_keys=None, histogram_keys=None):
"""initialize the placeholders from the input keys, for summary logging :param scalar_keys: ([str]) the name of all the scalar inputs :param histogram_keys: ([str]) the name of all the histogram inputs"""
if scalar_keys is None:... | the_stack_v2_python_sparse | agent_stable_baselines/stable_baselines/gail/statistics.py | Jannkar/doom_actionspace | train | 2 | |
7c1440a4cbdc37ccaabbeca0341e91cbccb3b2a0 | [
"self.parser = parser\ncommand_parser.add_argument('-n', '--noprint', dest='doprint', default=True, action='store_false', help=_(\" Don't attempt to pretty print the object. This is useful if there\\n is some problem with the object and you just want to get an\\n unpickled represen... | <|body_start_0|>
self.parser = parser
command_parser.add_argument('-n', '--noprint', dest='doprint', default=True, action='store_false', help=_(" Don't attempt to pretty print the object. This is useful if there\n is some problem with the object and you just want to get an\n ... | Get information out of a queue file. | QFile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QFile:
"""Get information out of a queue file."""
def add(self, parser, command_parser):
"""See `ICLISubCommand`."""
<|body_0|>
def process(self, args):
"""See `ICLISubCommand`."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.parser = parse... | stack_v2_sparse_classes_36k_train_012074 | 3,206 | no_license | [
{
"docstring": "See `ICLISubCommand`.",
"name": "add",
"signature": "def add(self, parser, command_parser)"
},
{
"docstring": "See `ICLISubCommand`.",
"name": "process",
"signature": "def process(self, args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018099 | Implement the Python class `QFile` described below.
Class description:
Get information out of a queue file.
Method signatures and docstrings:
- def add(self, parser, command_parser): See `ICLISubCommand`.
- def process(self, args): See `ICLISubCommand`. | Implement the Python class `QFile` described below.
Class description:
Get information out of a queue file.
Method signatures and docstrings:
- def add(self, parser, command_parser): See `ICLISubCommand`.
- def process(self, args): See `ICLISubCommand`.
<|skeleton|>
class QFile:
"""Get information out of a queue... | 7edf8148e34b9f73ca6433ceb43a1770f4fa32c1 | <|skeleton|>
class QFile:
"""Get information out of a queue file."""
def add(self, parser, command_parser):
"""See `ICLISubCommand`."""
<|body_0|>
def process(self, args):
"""See `ICLISubCommand`."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QFile:
"""Get information out of a queue file."""
def add(self, parser, command_parser):
"""See `ICLISubCommand`."""
self.parser = parser
command_parser.add_argument('-n', '--noprint', dest='doprint', default=True, action='store_false', help=_(" Don't attempt to pretty ... | the_stack_v2_python_sparse | libs/Mailman/mailman/commands/cli_qfile.py | masomel/py-import-analysis | train | 1 |
829410a63dbacf3d50fd5b47baea8e917f67e405 | [
"def get_level(root, level):\n nonlocal max_level\n if not root:\n max_level = max(max_level, level)\n return\n get_level(root.left, level + 1)\n get_level(root.right, level + 1)\n\ndef level_order(root):\n queue = deque()\n queue.append((root, 0))\n res = []\n while queue:\n ... | <|body_start_0|>
def get_level(root, level):
nonlocal max_level
if not root:
max_level = max(max_level, level)
return
get_level(root.left, level + 1)
get_level(root.right, level + 1)
def level_order(root):
queue... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_012075 | 3,019 | 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:... | cefa2f08667de4d2973274de3ff29a31a7d25eda | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def get_level(root, level):
nonlocal max_level
if not root:
max_level = max(max_level, level)
return
get_level(root.le... | the_stack_v2_python_sparse | LZOF_37/Solution.py | zhangruochi/leetcode | train | 14 | |
45bcd679555a4a2476e9db8c8d79c7bbdc392435 | [
"lst = []\nself.travel(root, lst)\nreturn lst",
"if not root:\n return\nself.travel(root.left, lst)\nlst.append(root.val)\nself.travel(root.right, lst)",
"if not root:\n return []\nresult = []\nst = []\nnode = root\nwhile node or len(st) > 0:\n if node:\n st.append(node)\n node = node.lef... | <|body_start_0|>
lst = []
self.travel(root, lst)
return lst
<|end_body_0|>
<|body_start_1|>
if not root:
return
self.travel(root.left, lst)
lst.append(root.val)
self.travel(root.right, lst)
<|end_body_1|>
<|body_start_2|>
if not root:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def travel(self, root, lst):
""":param root: :param lst: :return:"""
<|body_1|>
def in_order_no_dfs(self, root):
"""中序遍历非递归 :param root: :return:"... | stack_v2_sparse_classes_36k_train_012076 | 1,316 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal",
"signature": "def inorderTraversal(self, root)"
},
{
"docstring": ":param root: :param lst: :return:",
"name": "travel",
"signature": "def travel(self, root, lst)"
},
{
"docstring": "中序遍历非递归 :par... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def travel(self, root, lst): :param root: :param lst: :return:
- def in_order_no_dfs(self, root): 中序遍历非... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def travel(self, root, lst): :param root: :param lst: :return:
- def in_order_no_dfs(self, root): 中序遍历非... | a75310a96d2b165b15d5ee10ec409a17cdc880ba | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def travel(self, root, lst):
""":param root: :param lst: :return:"""
<|body_1|>
def in_order_no_dfs(self, root):
"""中序遍历非递归 :param root: :return:"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
lst = []
self.travel(root, lst)
return lst
def travel(self, root, lst):
""":param root: :param lst: :return:"""
if not root:
return
self.travel(root... | the_stack_v2_python_sparse | leetcode/tree/code/mid.py | skyxyz-lang/CS_Note | train | 0 | |
791a74af899dd38232d5318450866bb178d7daa9 | [
"if not t1:\n return t2\nif not t2:\n return t1\nt1.val += t2.val\nt1.left = self.mergeTrees(t1.left, t2.left)\nt1.right = self.mergeTrees(t1.right, t2.right)\nreturn t1",
"if not t1:\n return t2\nqueue = []\nqueue.append([t1, t2])\nwhile queue:\n t = queue.pop(0)\n if not t[1]:\n continue\n... | <|body_start_0|>
if not t1:
return t2
if not t2:
return t1
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1
<|end_body_0|>
<|body_start_1|>
if not t1:
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTrees1(self, t1, t2):
""":type t1: TreeNode :type t2: TreeNode :rtype: TreeNode"""
<|body_0|>
def mergeTrees(self, t1, t2):
""":type t1: TreeNode :type t2: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_012077 | 1,918 | no_license | [
{
"docstring": ":type t1: TreeNode :type t2: TreeNode :rtype: TreeNode",
"name": "mergeTrees1",
"signature": "def mergeTrees1(self, t1, t2)"
},
{
"docstring": ":type t1: TreeNode :type t2: TreeNode :rtype: TreeNode",
"name": "mergeTrees",
"signature": "def mergeTrees(self, t1, t2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015509 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTrees1(self, t1, t2): :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode
- def mergeTrees(self, t1, t2): :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTrees1(self, t1, t2): :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode
- def mergeTrees(self, t1, t2): :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode
<|sk... | 5f94a60d01dca431025d461d2e50dcf9612dee70 | <|skeleton|>
class Solution:
def mergeTrees1(self, t1, t2):
""":type t1: TreeNode :type t2: TreeNode :rtype: TreeNode"""
<|body_0|>
def mergeTrees(self, t1, t2):
""":type t1: TreeNode :type t2: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTrees1(self, t1, t2):
""":type t1: TreeNode :type t2: TreeNode :rtype: TreeNode"""
if not t1:
return t2
if not t2:
return t1
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.rig... | the_stack_v2_python_sparse | 2.树/617.合并二叉树.py | WJ-Lai/LeetCode-Python-Solution | train | 0 | |
5ee5989f9c06c31628e40f28e0d52ce62308b1ac | [
"url = [op_config['server'], 'apis/ads/publisher', op_config['version'], self.__class__.__name__]\nself.__service = DfpWebService(headers, config, op_config, '/'.join(url), lock, logger)\nsuper(PublisherQueryLanguageService, self).__init__(headers, config, op_config, url, 'adspygoogle.dfp', lock, logger)",
"metho... | <|body_start_0|>
url = [op_config['server'], 'apis/ads/publisher', op_config['version'], self.__class__.__name__]
self.__service = DfpWebService(headers, config, op_config, '/'.join(url), lock, logger)
super(PublisherQueryLanguageService, self).__init__(headers, config, op_config, url, 'adspygoo... | Wrapper for PublisherQueryLanguageService. The PublisherQueryLanguage Service provides operations for executing a PQL statement to retrieve information from the system. | PublisherQueryLanguageService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PublisherQueryLanguageService:
"""Wrapper for PublisherQueryLanguageService. The PublisherQueryLanguage Service provides operations for executing a PQL statement to retrieve information from the system."""
def __init__(self, headers, config, op_config, lock, logger):
"""Inits Publish... | stack_v2_sparse_classes_36k_train_012078 | 3,065 | permissive | [
{
"docstring": "Inits PublisherQueryLanguageService. Args: headers: dict Dictionary object with populated authentication credentials. config: dict Dictionary object with populated configuration values. op_config: dict Dictionary object with additional configuration values for this operation. lock: thread.lock T... | 2 | stack_v2_sparse_classes_30k_train_017274 | Implement the Python class `PublisherQueryLanguageService` described below.
Class description:
Wrapper for PublisherQueryLanguageService. The PublisherQueryLanguage Service provides operations for executing a PQL statement to retrieve information from the system.
Method signatures and docstrings:
- def __init__(self,... | Implement the Python class `PublisherQueryLanguageService` described below.
Class description:
Wrapper for PublisherQueryLanguageService. The PublisherQueryLanguage Service provides operations for executing a PQL statement to retrieve information from the system.
Method signatures and docstrings:
- def __init__(self,... | efa82a8d85cbdc90f030db9d168790c55bd8b12a | <|skeleton|>
class PublisherQueryLanguageService:
"""Wrapper for PublisherQueryLanguageService. The PublisherQueryLanguage Service provides operations for executing a PQL statement to retrieve information from the system."""
def __init__(self, headers, config, op_config, lock, logger):
"""Inits Publish... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PublisherQueryLanguageService:
"""Wrapper for PublisherQueryLanguageService. The PublisherQueryLanguage Service provides operations for executing a PQL statement to retrieve information from the system."""
def __init__(self, headers, config, op_config, lock, logger):
"""Inits PublisherQueryLangua... | the_stack_v2_python_sparse | adspygoogle/dfp/PublisherQueryLanguageService.py | hockeyprincess/google-api-dfp-python | train | 0 |
56e0c155a5436301b405de56681e18dd0c3afcc5 | [
"self.interpreter = tf.lite.Interpreter(model_content=tflite_model)\nself.interpreter.allocate_tensors()\nself.input_details = self.interpreter.get_input_details()\nself.output_details = self.interpreter.get_output_details()",
"if not isinstance(input_tensors, list) and (not isinstance(input_tensors, dict)):\n ... | <|body_start_0|>
self.interpreter = tf.lite.Interpreter(model_content=tflite_model)
self.interpreter.allocate_tensors()
self.input_details = self.interpreter.get_input_details()
self.output_details = self.interpreter.get_output_details()
<|end_body_0|>
<|body_start_1|>
if not is... | A runner to do inference with the TFLite model. | LiteRunner | [
"Apache-2.0",
"dtoa"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LiteRunner:
"""A runner to do inference with the TFLite model."""
def __init__(self, tflite_model: bytearray):
"""Initializes Lite runner from TFLite model buffer. Args: tflite_model: A valid flatbuffer representing the TFLite model."""
<|body_0|>
def run(self, input_ten... | stack_v2_sparse_classes_36k_train_012079 | 12,074 | permissive | [
{
"docstring": "Initializes Lite runner from TFLite model buffer. Args: tflite_model: A valid flatbuffer representing the TFLite model.",
"name": "__init__",
"signature": "def __init__(self, tflite_model: bytearray)"
},
{
"docstring": "Runs inference with the TFLite model. Args: input_tensors: L... | 2 | stack_v2_sparse_classes_30k_train_017702 | Implement the Python class `LiteRunner` described below.
Class description:
A runner to do inference with the TFLite model.
Method signatures and docstrings:
- def __init__(self, tflite_model: bytearray): Initializes Lite runner from TFLite model buffer. Args: tflite_model: A valid flatbuffer representing the TFLite ... | Implement the Python class `LiteRunner` described below.
Class description:
A runner to do inference with the TFLite model.
Method signatures and docstrings:
- def __init__(self, tflite_model: bytearray): Initializes Lite runner from TFLite model buffer. Args: tflite_model: A valid flatbuffer representing the TFLite ... | 007824594bf1d07c7c1467df03a43886f8a4b3ad | <|skeleton|>
class LiteRunner:
"""A runner to do inference with the TFLite model."""
def __init__(self, tflite_model: bytearray):
"""Initializes Lite runner from TFLite model buffer. Args: tflite_model: A valid flatbuffer representing the TFLite model."""
<|body_0|>
def run(self, input_ten... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LiteRunner:
"""A runner to do inference with the TFLite model."""
def __init__(self, tflite_model: bytearray):
"""Initializes Lite runner from TFLite model buffer. Args: tflite_model: A valid flatbuffer representing the TFLite model."""
self.interpreter = tf.lite.Interpreter(model_content... | the_stack_v2_python_sparse | mediapipe/model_maker/python/core/utils/model_util.py | google/mediapipe | train | 23,940 |
1ad46bb4988f06fdd488687f891b345706ed376c | [
"array.append(0)\nstack = [-1]\nmax_area = 0\nfor i, curr in enumerate(array):\n while array[stack[-1]] > curr:\n width = i - stack[-2] - 1\n height = array[stack.pop()]\n area = width * height\n max_area = max(max_area, area)\n stack.append(i)\narray.pop()\nreturn max_area",
"if... | <|body_start_0|>
array.append(0)
stack = [-1]
max_area = 0
for i, curr in enumerate(array):
while array[stack[-1]] > curr:
width = i - stack[-2] - 1
height = array[stack.pop()]
area = width * height
max_area = ma... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largest_rectangle(self, array):
"""Time complexity: O(n). Space complexity: O(n), n is len(array)."""
<|body_0|>
def maximalRectangle(self, matrix):
"""Time complexity: O(n * m). Space complexity: O(n), n, m are number of rows and columns in the matrix.... | stack_v2_sparse_classes_36k_train_012080 | 3,584 | no_license | [
{
"docstring": "Time complexity: O(n). Space complexity: O(n), n is len(array).",
"name": "largest_rectangle",
"signature": "def largest_rectangle(self, array)"
},
{
"docstring": "Time complexity: O(n * m). Space complexity: O(n), n, m are number of rows and columns in the matrix.",
"name": ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largest_rectangle(self, array): Time complexity: O(n). Space complexity: O(n), n is len(array).
- def maximalRectangle(self, matrix): Time complexity: O(n * m). Space complex... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largest_rectangle(self, array): Time complexity: O(n). Space complexity: O(n), n is len(array).
- def maximalRectangle(self, matrix): Time complexity: O(n * m). Space complex... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def largest_rectangle(self, array):
"""Time complexity: O(n). Space complexity: O(n), n is len(array)."""
<|body_0|>
def maximalRectangle(self, matrix):
"""Time complexity: O(n * m). Space complexity: O(n), n, m are number of rows and columns in the matrix.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largest_rectangle(self, array):
"""Time complexity: O(n). Space complexity: O(n), n is len(array)."""
array.append(0)
stack = [-1]
max_area = 0
for i, curr in enumerate(array):
while array[stack[-1]] > curr:
width = i - stack[-2... | the_stack_v2_python_sparse | Matrix_problems/maximal_rectangle.py | vladn90/Algorithms | train | 0 | |
2f2b7af1932dbd80ac3d86c90d052fbdbbf94dd7 | [
"if n < 2:\n return 0\nis_prime = [True] * n\nis_prime[0] = is_prime[1] = False\nfor i in range(2, int(n ** 0.5) + 1):\n if is_prime[i]:\n is_prime[i * i:n:i] = [False] * len(is_prime[i * i:n:i])\nreturn is_prime.count(True)",
"if n < 2:\n return 0\nis_prime = [True] * n\nprimes = []\nfor i in ran... | <|body_start_0|>
if n < 2:
return 0
is_prime = [True] * n
is_prime[0] = is_prime[1] = False
for i in range(2, int(n ** 0.5) + 1):
if is_prime[i]:
is_prime[i * i:n:i] = [False] * len(is_prime[i * i:n:i])
return is_prime.count(True)
<|end_bod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countPrimes_MK1(self, n: int) -> int:
"""埃氏筛"""
<|body_0|>
def countPrimes_MK2(self, n: int) -> int:
"""欧拉筛(线性筛)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 2:
return 0
is_prime = [True] * n
is_pr... | stack_v2_sparse_classes_36k_train_012081 | 921 | no_license | [
{
"docstring": "埃氏筛",
"name": "countPrimes_MK1",
"signature": "def countPrimes_MK1(self, n: int) -> int"
},
{
"docstring": "欧拉筛(线性筛)",
"name": "countPrimes_MK2",
"signature": "def countPrimes_MK2(self, n: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_010222 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes_MK1(self, n: int) -> int: 埃氏筛
- def countPrimes_MK2(self, n: int) -> int: 欧拉筛(线性筛) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes_MK1(self, n: int) -> int: 埃氏筛
- def countPrimes_MK2(self, n: int) -> int: 欧拉筛(线性筛)
<|skeleton|>
class Solution:
def countPrimes_MK1(self, n: int) -> int:
... | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | <|skeleton|>
class Solution:
def countPrimes_MK1(self, n: int) -> int:
"""埃氏筛"""
<|body_0|>
def countPrimes_MK2(self, n: int) -> int:
"""欧拉筛(线性筛)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countPrimes_MK1(self, n: int) -> int:
"""埃氏筛"""
if n < 2:
return 0
is_prime = [True] * n
is_prime[0] = is_prime[1] = False
for i in range(2, int(n ** 0.5) + 1):
if is_prime[i]:
is_prime[i * i:n:i] = [False] * len(is_... | the_stack_v2_python_sparse | 0204. Count Primes/Solution.py | faterazer/LeetCode | train | 4 | |
44aeb2a76e1622f15783e29b7906a0613e671785 | [
"self.access_key = access_key\nself.illustration_endpoint = illustration_endpoint\nself.inception_endpoint = inception_endpoint\nself.js_source = js_source\nif access_key is None:\n self.access_key = Utilities.get_access_key(self.js_source)",
"headers = {'Authorization': self.access_key, 'Content-Type': 'appli... | <|body_start_0|>
self.access_key = access_key
self.illustration_endpoint = illustration_endpoint
self.inception_endpoint = inception_endpoint
self.js_source = js_source
if access_key is None:
self.access_key = Utilities.get_access_key(self.js_source)
<|end_body_0|>
<... | ImageTagger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageTagger:
def __init__(self, access_key=None, illustration_endpoint='https://api.algorithmia.com/v1/web/algo/demo/IllustrationTaggerDemo/0.1.0', inception_endpoint='https://api.algorithmia.com/v1/web/algo/demo/InceptionNetDemo/0.1.0', js_source='https://demos.algorithmia.com/image-tagger/publ... | stack_v2_sparse_classes_36k_train_012082 | 2,824 | no_license | [
{
"docstring": "Public constructor :param endpoint: The main endpoint for Illustration Tagger :param js_source: The javascript source code containing the API Key",
"name": "__init__",
"signature": "def __init__(self, access_key=None, illustration_endpoint='https://api.algorithmia.com/v1/web/algo/demo/Il... | 3 | stack_v2_sparse_classes_30k_train_004216 | Implement the Python class `ImageTagger` described below.
Class description:
Implement the ImageTagger class.
Method signatures and docstrings:
- def __init__(self, access_key=None, illustration_endpoint='https://api.algorithmia.com/v1/web/algo/demo/IllustrationTaggerDemo/0.1.0', inception_endpoint='https://api.algor... | Implement the Python class `ImageTagger` described below.
Class description:
Implement the ImageTagger class.
Method signatures and docstrings:
- def __init__(self, access_key=None, illustration_endpoint='https://api.algorithmia.com/v1/web/algo/demo/IllustrationTaggerDemo/0.1.0', inception_endpoint='https://api.algor... | 57c453625239f28da88b88ddd0ae5f1ecdd4de3c | <|skeleton|>
class ImageTagger:
def __init__(self, access_key=None, illustration_endpoint='https://api.algorithmia.com/v1/web/algo/demo/IllustrationTaggerDemo/0.1.0', inception_endpoint='https://api.algorithmia.com/v1/web/algo/demo/InceptionNetDemo/0.1.0', js_source='https://demos.algorithmia.com/image-tagger/publ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageTagger:
def __init__(self, access_key=None, illustration_endpoint='https://api.algorithmia.com/v1/web/algo/demo/IllustrationTaggerDemo/0.1.0', inception_endpoint='https://api.algorithmia.com/v1/web/algo/demo/InceptionNetDemo/0.1.0', js_source='https://demos.algorithmia.com/image-tagger/public/js/main.js'... | the_stack_v2_python_sparse | alg/coffeehouse_alg/image_tagger/image_tagger.py | intellivoid/CoffeeHousePy | train | 0 | |
b904cb88c9ecceff791a4ec96939146c945b1b1c | [
"super(SoftmaxSelfAttentionEncoder, self).__init__()\nself._attention_mlp = attention_mlp\nself._is_end_padded = is_end_padded",
"att_scores = self._attention_mlp(batch_sequences)\nmask = pwF.create_mask_from_length(batch_sequence_lengths, batch_sequences.size(1), self._is_end_padded).unsqueeze(-1)\nmasked_att_sc... | <|body_start_0|>
super(SoftmaxSelfAttentionEncoder, self).__init__()
self._attention_mlp = attention_mlp
self._is_end_padded = is_end_padded
<|end_body_0|>
<|body_start_1|>
att_scores = self._attention_mlp(batch_sequences)
mask = pwF.create_mask_from_length(batch_sequence_length... | Encodes a sequence using soft-max self-attention. | SoftmaxSelfAttentionEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftmaxSelfAttentionEncoder:
"""Encodes a sequence using soft-max self-attention."""
def __init__(self, attention_mlp, is_end_padded=True):
""":param attention_mlp: MLP object used to generate unnormalized attention score(s). If the last dimension of the tensor returned by the MLP is... | stack_v2_sparse_classes_36k_train_012083 | 1,994 | permissive | [
{
"docstring": ":param attention_mlp: MLP object used to generate unnormalized attention score(s). If the last dimension of the tensor returned by the MLP is larger than 1 then multi-attention is applied. :param is_end_padded: Whether to mask at the end.",
"name": "__init__",
"signature": "def __init__(... | 2 | stack_v2_sparse_classes_30k_train_008140 | Implement the Python class `SoftmaxSelfAttentionEncoder` described below.
Class description:
Encodes a sequence using soft-max self-attention.
Method signatures and docstrings:
- def __init__(self, attention_mlp, is_end_padded=True): :param attention_mlp: MLP object used to generate unnormalized attention score(s). I... | Implement the Python class `SoftmaxSelfAttentionEncoder` described below.
Class description:
Encodes a sequence using soft-max self-attention.
Method signatures and docstrings:
- def __init__(self, attention_mlp, is_end_padded=True): :param attention_mlp: MLP object used to generate unnormalized attention score(s). I... | 57c85161bd6e09961cb7a1e69debc8e3e0bf7d29 | <|skeleton|>
class SoftmaxSelfAttentionEncoder:
"""Encodes a sequence using soft-max self-attention."""
def __init__(self, attention_mlp, is_end_padded=True):
""":param attention_mlp: MLP object used to generate unnormalized attention score(s). If the last dimension of the tensor returned by the MLP is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SoftmaxSelfAttentionEncoder:
"""Encodes a sequence using soft-max self-attention."""
def __init__(self, attention_mlp, is_end_padded=True):
""":param attention_mlp: MLP object used to generate unnormalized attention score(s). If the last dimension of the tensor returned by the MLP is larger than ... | the_stack_v2_python_sparse | pytorch_wrapper/modules/softmax_self_attention_encoder.py | ajaxis001/pytorch-wrapper | train | 1 |
be60462247490fb00bbb1160ce97bfb57c6bb00d | [
"super(RNNEncoder, self).__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)",
"initializer = tf.keras.initializers.Zeros()\ninit_hi... | <|body_start_0|>
super(RNNEncoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
<|end_bod... | RNN Encoder class | RNNEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""RNN Encoder class"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor. Args: vocab (int): the size of the input vocabulary. embedding (int): dimensionality of the embedding vector. units (int): number of hidden units in the RNN cell. batch (int)... | stack_v2_sparse_classes_36k_train_012084 | 2,215 | no_license | [
{
"docstring": "Class constructor. Args: vocab (int): the size of the input vocabulary. embedding (int): dimensionality of the embedding vector. units (int): number of hidden units in the RNN cell. batch (int): the batch size.",
"name": "__init__",
"signature": "def __init__(self, vocab, embedding, unit... | 3 | null | Implement the Python class `RNNEncoder` described below.
Class description:
RNN Encoder class
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor. Args: vocab (int): the size of the input vocabulary. embedding (int): dimensionality of the embedding vector. units (... | Implement the Python class `RNNEncoder` described below.
Class description:
RNN Encoder class
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor. Args: vocab (int): the size of the input vocabulary. embedding (int): dimensionality of the embedding vector. units (... | 5aff923277cfe9f2b5324a773e4e5c3cac810a0c | <|skeleton|>
class RNNEncoder:
"""RNN Encoder class"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor. Args: vocab (int): the size of the input vocabulary. embedding (int): dimensionality of the embedding vector. units (int): number of hidden units in the RNN cell. batch (int)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNEncoder:
"""RNN Encoder class"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor. Args: vocab (int): the size of the input vocabulary. embedding (int): dimensionality of the embedding vector. units (int): number of hidden units in the RNN cell. batch (int): the batch s... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/0-rnn_encoder.py | cmmolanos1/holbertonschool-machine_learning | train | 1 |
fb503cb44b7555f2a5a564b926f72c9aa4f2a1e5 | [
"super(RandomSearch, self).assertions()\nif not isinstance(self.n_selection_iters, int):\n raise TypeError('Parameter `n_selection_iters` must be of type int')",
"self.n_selection_iters = n_selection_iters\nsuper(RandomSearch, self).__init__(optimizer, n_particles, dimensions, options, objective_func, iters, b... | <|body_start_0|>
super(RandomSearch, self).assertions()
if not isinstance(self.n_selection_iters, int):
raise TypeError('Parameter `n_selection_iters` must be of type int')
<|end_body_0|>
<|body_start_1|>
self.n_selection_iters = n_selection_iters
super(RandomSearch, self)._... | Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations. | RandomSearch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomSearch:
"""Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations."""
def assertions(self):
"""Assertion method to check :code:`n_selection_it... | stack_v2_sparse_classes_36k_train_012085 | 4,163 | permissive | [
{
"docstring": "Assertion method to check :code:`n_selection_iters` input Raises ------ TypeError When :code:`n_selection_iters` is not of type int",
"name": "assertions",
"signature": "def assertions(self)"
},
{
"docstring": "Initialize the Search Attributes ---------- n_selection_iters: int nu... | 3 | stack_v2_sparse_classes_30k_train_011171 | Implement the Python class `RandomSearch` described below.
Class description:
Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations.
Method signatures and docstrings:
- def assertio... | Implement the Python class `RandomSearch` described below.
Class description:
Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations.
Method signatures and docstrings:
- def assertio... | 70c969d929bb2dab6211765def0431680fc5cb01 | <|skeleton|>
class RandomSearch:
"""Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations."""
def assertions(self):
"""Assertion method to check :code:`n_selection_it... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomSearch:
"""Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations."""
def assertions(self):
"""Assertion method to check :code:`n_selection_iters` input Ra... | the_stack_v2_python_sparse | pyswarms/utils/search/random_search.py | ljvmiranda921/pyswarms | train | 1,194 |
54b260751be8350f92db5082228b9fa6abb23ce8 | [
"A = numpy.random.randn(3, 3)\nv = numpy.random.randn(2)\nG = givens_matrix_elements(v[0], v[1])\nwith self.assertRaises(ValueError):\n double_givens_rotate(A, G, 0, 1, which='row')\nwith self.assertRaises(ValueError):\n double_givens_rotate(A, G, 0, 1, which='col')",
"A = numpy.random.randn(3, 3)\nv = nump... | <|body_start_0|>
A = numpy.random.randn(3, 3)
v = numpy.random.randn(2)
G = givens_matrix_elements(v[0], v[1])
with self.assertRaises(ValueError):
double_givens_rotate(A, G, 0, 1, which='row')
with self.assertRaises(ValueError):
double_givens_rotate(A, G, ... | DoubleGivensRotateTest | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoubleGivensRotateTest:
def test_odd_dimension(self):
"""Test that it raises an error for odd-dimensional input."""
<|body_0|>
def test_bad_input(self):
"""Test bad input."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
A = numpy.random.randn(3, 3)
... | stack_v2_sparse_classes_36k_train_012086 | 14,005 | permissive | [
{
"docstring": "Test that it raises an error for odd-dimensional input.",
"name": "test_odd_dimension",
"signature": "def test_odd_dimension(self)"
},
{
"docstring": "Test bad input.",
"name": "test_bad_input",
"signature": "def test_bad_input(self)"
}
] | 2 | null | Implement the Python class `DoubleGivensRotateTest` described below.
Class description:
Implement the DoubleGivensRotateTest class.
Method signatures and docstrings:
- def test_odd_dimension(self): Test that it raises an error for odd-dimensional input.
- def test_bad_input(self): Test bad input. | Implement the Python class `DoubleGivensRotateTest` described below.
Class description:
Implement the DoubleGivensRotateTest class.
Method signatures and docstrings:
- def test_odd_dimension(self): Test that it raises an error for odd-dimensional input.
- def test_bad_input(self): Test bad input.
<|skeleton|>
class ... | 788481753c798a72c5cb3aa9f2aa9da3ce3190b0 | <|skeleton|>
class DoubleGivensRotateTest:
def test_odd_dimension(self):
"""Test that it raises an error for odd-dimensional input."""
<|body_0|>
def test_bad_input(self):
"""Test bad input."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DoubleGivensRotateTest:
def test_odd_dimension(self):
"""Test that it raises an error for odd-dimensional input."""
A = numpy.random.randn(3, 3)
v = numpy.random.randn(2)
G = givens_matrix_elements(v[0], v[1])
with self.assertRaises(ValueError):
double_given... | the_stack_v2_python_sparse | src/openfermion/linalg/givens_rotations_test.py | quantumlib/OpenFermion | train | 1,481 | |
ece536c11d7a919bca43def97670c44dd71fee57 | [
"ans = 0\nfor i in range(32):\n sm = 0\n for j in nums:\n sm += j >> i & 1\n ans |= sm % 3 << i\nreturn ans - 2 ** 32 if ans >= 2 ** 31 else ans",
"one = 0\ntwo = 0\nthree = 0\nfor i in range(len(nums)):\n two |= one & nums[i]\n one ^= nums[i]\n three = one & two\n one &= ~three\n t... | <|body_start_0|>
ans = 0
for i in range(32):
sm = 0
for j in nums:
sm += j >> i & 1
ans |= sm % 3 << i
return ans - 2 ** 32 if ans >= 2 ** 31 else ans
<|end_body_0|>
<|body_start_1|>
one = 0
two = 0
three = 0
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumberSlow(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def singleNumberGeneral(self, nums):
""":type nums: List[int] :rtype: ... | stack_v2_sparse_classes_36k_train_012087 | 1,972 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumberSlow",
"signature": "def singleNumberSlow(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": ":type nums... | 3 | stack_v2_sparse_classes_30k_train_005131 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumberSlow(self, nums): :type nums: List[int] :rtype: int
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumberGeneral(self, nums): :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumberSlow(self, nums): :type nums: List[int] :rtype: int
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumberGeneral(self, nums): :type... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def singleNumberSlow(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def singleNumberGeneral(self, nums):
""":type nums: List[int] :rtype: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumberSlow(self, nums):
""":type nums: List[int] :rtype: int"""
ans = 0
for i in range(32):
sm = 0
for j in nums:
sm += j >> i & 1
ans |= sm % 3 << i
return ans - 2 ** 32 if ans >= 2 ** 31 else ans
def... | the_stack_v2_python_sparse | S/SingleNumberII.py | bssrdf/pyleet | train | 2 | |
3244790ad4990bed68e8acafdb4f5be1d19d0e46 | [
"self.last_error = 10000000\nself.best_result = 1000000\nself.start = start\nfirst_anfis_list = []\nself.teaching_inputs = teaching_inputs\nfor i in range(anfis_num):\n new_anfis = Anfis(*start)\n first_anfis_list.append(new_anfis)\nself.best_anfis = first_anfis_list[0]\npopulation = first_anfis_list\nwhile s... | <|body_start_0|>
self.last_error = 10000000
self.best_result = 1000000
self.start = start
first_anfis_list = []
self.teaching_inputs = teaching_inputs
for i in range(anfis_num):
new_anfis = Anfis(*start)
first_anfis_list.append(new_anfis)
s... | Genetic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Genetic:
def __init__(self, teaching_inputs, anfis_num, start):
"""Save in self.best_anfis ANFIS net which give the best answers :param teaching_inputs: list of teaching inputs [[[1. input, 2. input...], output], [...]] :param anfis_num: Number of ANFIS nets using in genetic teaching :pa... | stack_v2_sparse_classes_36k_train_012088 | 12,715 | no_license | [
{
"docstring": "Save in self.best_anfis ANFIS net which give the best answers :param teaching_inputs: list of teaching inputs [[[1. input, 2. input...], output], [...]] :param anfis_num: Number of ANFIS nets using in genetic teaching :param start: starts params of ANIFS net [inputs_len, rules, Tnorm, down_range... | 6 | stack_v2_sparse_classes_30k_train_016278 | Implement the Python class `Genetic` described below.
Class description:
Implement the Genetic class.
Method signatures and docstrings:
- def __init__(self, teaching_inputs, anfis_num, start): Save in self.best_anfis ANFIS net which give the best answers :param teaching_inputs: list of teaching inputs [[[1. input, 2.... | Implement the Python class `Genetic` described below.
Class description:
Implement the Genetic class.
Method signatures and docstrings:
- def __init__(self, teaching_inputs, anfis_num, start): Save in self.best_anfis ANFIS net which give the best answers :param teaching_inputs: list of teaching inputs [[[1. input, 2.... | 6c1d58ea4773c633c45f065b7ef52268d3319762 | <|skeleton|>
class Genetic:
def __init__(self, teaching_inputs, anfis_num, start):
"""Save in self.best_anfis ANFIS net which give the best answers :param teaching_inputs: list of teaching inputs [[[1. input, 2. input...], output], [...]] :param anfis_num: Number of ANFIS nets using in genetic teaching :pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Genetic:
def __init__(self, teaching_inputs, anfis_num, start):
"""Save in self.best_anfis ANFIS net which give the best answers :param teaching_inputs: list of teaching inputs [[[1. input, 2. input...], output], [...]] :param anfis_num: Number of ANFIS nets using in genetic teaching :param start: sta... | the_stack_v2_python_sparse | anfis.py | KatarzynaStudzinska/declib | train | 0 | |
0d9276c2cf6581b251db03f199a29ea51137c4b6 | [
"kernel_init = tf.keras.initializers.Orthogonal(gain=1.0)\nself.model = tf.keras.Sequential()\nself.model.add(tf.keras.layers.Dense(units=hidden, input_shape=(input_dim,), kernel_initializer=kernel_init))\nself.model.add(tf.keras.layers.BatchNormalization())\nself.model.add(tf.keras.layers.Activation(tf.keras.activ... | <|body_start_0|>
kernel_init = tf.keras.initializers.Orthogonal(gain=1.0)
self.model = tf.keras.Sequential()
self.model.add(tf.keras.layers.Dense(units=hidden, input_shape=(input_dim,), kernel_initializer=kernel_init))
self.model.add(tf.keras.layers.BatchNormalization())
self.mod... | Implementation of a discriminator network. | Discriminator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Discriminator:
"""Implementation of a discriminator network."""
def __init__(self, input_dim, hidden=256):
"""Initializes a discriminator. Args: input_dim: size of the input space. hidden: the number of hidden units."""
<|body_0|>
def train(self, agent_data, expert_data,... | stack_v2_sparse_classes_36k_train_012089 | 11,931 | permissive | [
{
"docstring": "Initializes a discriminator. Args: input_dim: size of the input space. hidden: the number of hidden units.",
"name": "__init__",
"signature": "def __init__(self, input_dim, hidden=256)"
},
{
"docstring": "Train the discriminator with data from the current agent and the expert. Ar... | 2 | stack_v2_sparse_classes_30k_train_019997 | Implement the Python class `Discriminator` described below.
Class description:
Implementation of a discriminator network.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden=256): Initializes a discriminator. Args: input_dim: size of the input space. hidden: the number of hidden units.
- def trai... | Implement the Python class `Discriminator` described below.
Class description:
Implementation of a discriminator network.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden=256): Initializes a discriminator. Args: input_dim: size of the input space. hidden: the number of hidden units.
- def trai... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class Discriminator:
"""Implementation of a discriminator network."""
def __init__(self, input_dim, hidden=256):
"""Initializes a discriminator. Args: input_dim: size of the input space. hidden: the number of hidden units."""
<|body_0|>
def train(self, agent_data, expert_data,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Discriminator:
"""Implementation of a discriminator network."""
def __init__(self, input_dim, hidden=256):
"""Initializes a discriminator. Args: input_dim: size of the input space. hidden: the number of hidden units."""
kernel_init = tf.keras.initializers.Orthogonal(gain=1.0)
self... | the_stack_v2_python_sparse | polish/active_imitation/util.py | Ayoob7/google-research | train | 2 |
580261174cb3edbb7202dad6116fda48841dcb92 | [
"target = hook or True\nif cls._config.get(url_name):\n cls._config[url_name][method] = target\nelse:\n cls._config[url_name] = {method: target}",
"resolved = resolve(request.path)\nurl_name = resolved.url_name\nif not (cls._config.get(url_name) and cls._config[url_name].get(request.method)):\n return {}... | <|body_start_0|>
target = hook or True
if cls._config.get(url_name):
cls._config[url_name][method] = target
else:
cls._config[url_name] = {method: target}
<|end_body_0|>
<|body_start_1|>
resolved = resolve(request.path)
url_name = resolved.url_name
... | 删除资源的时候,在处理日志的时候,是无法得到被删除的资源的信息,只能提前获取 | AdditionalInfoBeforeDelete | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdditionalInfoBeforeDelete:
"""删除资源的时候,在处理日志的时候,是无法得到被删除的资源的信息,只能提前获取"""
def register(cls, url_name: str, method: str, hook: HookAbstract=None):
"""注册需要提前获取信息日志类 :param url_name: 正常的urlname,可以用reverse反向解析 :param method: http方法 :param hook: 钩子类,也就是日志处理的类,如果传了这个类,就可以使用类里提供的 get_previou... | stack_v2_sparse_classes_36k_train_012090 | 6,132 | no_license | [
{
"docstring": "注册需要提前获取信息日志类 :param url_name: 正常的urlname,可以用reverse反向解析 :param method: http方法 :param hook: 钩子类,也就是日志处理的类,如果传了这个类,就可以使用类里提供的 get_previous方法获取信息,hook必须继承自HookAbstract接口",
"name": "register",
"signature": "def register(cls, url_name: str, method: str, hook: HookAbstract=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_016363 | Implement the Python class `AdditionalInfoBeforeDelete` described below.
Class description:
删除资源的时候,在处理日志的时候,是无法得到被删除的资源的信息,只能提前获取
Method signatures and docstrings:
- def register(cls, url_name: str, method: str, hook: HookAbstract=None): 注册需要提前获取信息日志类 :param url_name: 正常的urlname,可以用reverse反向解析 :param method: http方法 ... | Implement the Python class `AdditionalInfoBeforeDelete` described below.
Class description:
删除资源的时候,在处理日志的时候,是无法得到被删除的资源的信息,只能提前获取
Method signatures and docstrings:
- def register(cls, url_name: str, method: str, hook: HookAbstract=None): 注册需要提前获取信息日志类 :param url_name: 正常的urlname,可以用reverse反向解析 :param method: http方法 ... | ae1ade20044b59de1e29288fcd61ba0b71d92be3 | <|skeleton|>
class AdditionalInfoBeforeDelete:
"""删除资源的时候,在处理日志的时候,是无法得到被删除的资源的信息,只能提前获取"""
def register(cls, url_name: str, method: str, hook: HookAbstract=None):
"""注册需要提前获取信息日志类 :param url_name: 正常的urlname,可以用reverse反向解析 :param method: http方法 :param hook: 钩子类,也就是日志处理的类,如果传了这个类,就可以使用类里提供的 get_previou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdditionalInfoBeforeDelete:
"""删除资源的时候,在处理日志的时候,是无法得到被删除的资源的信息,只能提前获取"""
def register(cls, url_name: str, method: str, hook: HookAbstract=None):
"""注册需要提前获取信息日志类 :param url_name: 正常的urlname,可以用reverse反向解析 :param method: http方法 :param hook: 钩子类,也就是日志处理的类,如果传了这个类,就可以使用类里提供的 get_previous方法获取信息,hook必... | the_stack_v2_python_sparse | log/log_content/log_generator.py | liushiwen555/unified_management_platform_backend | train | 0 |
51d8ddf36e8da35e289a8c71f068a7de11866157 | [
"prime_factor_5_num = 0\nwhile n / 5 == n / float(5):\n prime_factor_5_num += 1\n n /= 5\nreturn prime_factor_5_num",
"trailing_zero_numbers = 0\nfor i in range(1, n + 1):\n prime_factor_5_num = self.count_prime_factor_5(i)\n trailing_zero_numbers += prime_factor_5_num\nreturn trailing_zero_numbers"
] | <|body_start_0|>
prime_factor_5_num = 0
while n / 5 == n / float(5):
prime_factor_5_num += 1
n /= 5
return prime_factor_5_num
<|end_body_0|>
<|body_start_1|>
trailing_zero_numbers = 0
for i in range(1, n + 1):
prime_factor_5_num = self.count_p... | Status: Time Limit Exceeded Submitted: 0 minutes ago Last executed input: 8362 It's better than solution1, but not good enough. | SolutionFailed_2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionFailed_2:
"""Status: Time Limit Exceeded Submitted: 0 minutes ago Last executed input: 8362 It's better than solution1, but not good enough."""
def count_prime_factor_5(self, n):
"""Count prime factor 5 for positive intergers. 0 is not accepted."""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_012091 | 7,335 | no_license | [
{
"docstring": "Count prime factor 5 for positive intergers. 0 is not accepted.",
"name": "count_prime_factor_5",
"signature": "def count_prime_factor_5(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "trailingZeroes",
"signature": "def trailingZeroes(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015648 | Implement the Python class `SolutionFailed_2` described below.
Class description:
Status: Time Limit Exceeded Submitted: 0 minutes ago Last executed input: 8362 It's better than solution1, but not good enough.
Method signatures and docstrings:
- def count_prime_factor_5(self, n): Count prime factor 5 for positive int... | Implement the Python class `SolutionFailed_2` described below.
Class description:
Status: Time Limit Exceeded Submitted: 0 minutes ago Last executed input: 8362 It's better than solution1, but not good enough.
Method signatures and docstrings:
- def count_prime_factor_5(self, n): Count prime factor 5 for positive int... | 2a7401c6e407db533877de6e20a2b523f7964fdb | <|skeleton|>
class SolutionFailed_2:
"""Status: Time Limit Exceeded Submitted: 0 minutes ago Last executed input: 8362 It's better than solution1, but not good enough."""
def count_prime_factor_5(self, n):
"""Count prime factor 5 for positive intergers. 0 is not accepted."""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolutionFailed_2:
"""Status: Time Limit Exceeded Submitted: 0 minutes ago Last executed input: 8362 It's better than solution1, but not good enough."""
def count_prime_factor_5(self, n):
"""Count prime factor 5 for positive intergers. 0 is not accepted."""
prime_factor_5_num = 0
w... | the_stack_v2_python_sparse | THEORIES/algorithm/leetcode/Y172_Factorial_Trailing_Zeroes.py | bb2qqq/tech_notes | train | 0 |
ed14c6418f01256846b51fcfb941fedaf9355987 | [
"s_length = len(s)\nif s_length < 2:\n return s\nresult_start, result_length = (0, 1)\ncenter1, center2 = (0, 1)\ni = 1\nwhile i < s_length:\n start = center1 - (i - center2)\n if s[i] == s[start]:\n length = i - start + 1\n if length > result_length:\n result_start, result_length ... | <|body_start_0|>
s_length = len(s)
if s_length < 2:
return s
result_start, result_length = (0, 1)
center1, center2 = (0, 1)
i = 1
while i < s_length:
start = center1 - (i - center2)
if s[i] == s[start]:
length = i - star... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome1(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s_length = len(s)
if s_length < 2:
r... | stack_v2_sparse_classes_36k_train_012092 | 4,400 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome1",
"signature": "def longestPalindrome1(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008314 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome1(self, s): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome1(self, s): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def longestPalindrome1(sel... | e07b85a4121f2665393f1176befbdbe06f1e1ad0 | <|skeleton|>
class Solution:
def longestPalindrome1(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome1(self, s):
""":type s: str :rtype: str"""
s_length = len(s)
if s_length < 2:
return s
result_start, result_length = (0, 1)
center1, center2 = (0, 1)
i = 1
while i < s_length:
start = center1 - (i - ... | the_stack_v2_python_sparse | Algorithms/longest-palindromic-substring.py | feilniu/LeetCode | train | 0 | |
a9c3e8ff22889b13c8cbe2d53f05033a446e80b1 | [
"self.hyperv_parameters = hyperv_parameters\nself.nas_parameters = nas_parameters\nself.outlook_parameters = outlook_parameters\nself.physical_parameters = physical_parameters\nself.pure_parameters = pure_parameters\nself.sql_parameters = sql_parameters\nself.vmware_parameters = vmware_parameters",
"if dictionary... | <|body_start_0|>
self.hyperv_parameters = hyperv_parameters
self.nas_parameters = nas_parameters
self.outlook_parameters = outlook_parameters
self.physical_parameters = physical_parameters
self.pure_parameters = pure_parameters
self.sql_parameters = sql_parameters
... | Implementation of the 'Environment Specific Common Job Parameters.' model. Specifies additional parameters that are common to all Protection Sources in a Protection Job created for a particular environment type. Attributes: hyperv_parameters (HypervEnvironmentJobParameters): Specifies job parameters applicable for all ... | EnvironmentSpecificCommonJobParameters | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvironmentSpecificCommonJobParameters:
"""Implementation of the 'Environment Specific Common Job Parameters.' model. Specifies additional parameters that are common to all Protection Sources in a Protection Job created for a particular environment type. Attributes: hyperv_parameters (HypervEnvir... | stack_v2_sparse_classes_36k_train_012093 | 5,930 | permissive | [
{
"docstring": "Constructor for the EnvironmentSpecificCommonJobParameters class",
"name": "__init__",
"signature": "def __init__(self, hyperv_parameters=None, nas_parameters=None, outlook_parameters=None, physical_parameters=None, pure_parameters=None, sql_parameters=None, vmware_parameters=None)"
},... | 2 | stack_v2_sparse_classes_30k_train_006185 | Implement the Python class `EnvironmentSpecificCommonJobParameters` described below.
Class description:
Implementation of the 'Environment Specific Common Job Parameters.' model. Specifies additional parameters that are common to all Protection Sources in a Protection Job created for a particular environment type. Att... | Implement the Python class `EnvironmentSpecificCommonJobParameters` described below.
Class description:
Implementation of the 'Environment Specific Common Job Parameters.' model. Specifies additional parameters that are common to all Protection Sources in a Protection Job created for a particular environment type. Att... | 07c5adee58810979780679065250d82b4b2cdaab | <|skeleton|>
class EnvironmentSpecificCommonJobParameters:
"""Implementation of the 'Environment Specific Common Job Parameters.' model. Specifies additional parameters that are common to all Protection Sources in a Protection Job created for a particular environment type. Attributes: hyperv_parameters (HypervEnvir... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnvironmentSpecificCommonJobParameters:
"""Implementation of the 'Environment Specific Common Job Parameters.' model. Specifies additional parameters that are common to all Protection Sources in a Protection Job created for a particular environment type. Attributes: hyperv_parameters (HypervEnvironmentJobPara... | the_stack_v2_python_sparse | cohesity_management_sdk/models/environment_specific_common_job_parameters.py | hemanshu-cohesity/management-sdk-python | train | 0 |
7e72497d7fa22ff6596bb6ffbb3acbffb32f970e | [
"def partition(p, r):\n x = nums[r]\n i = p - 1\n for j in range(p, r):\n if nums[j] < x:\n i += 1\n nums[i], nums[j] = (nums[j], nums[i])\n nums[i + 1], nums[r] = (nums[r], nums[i + 1])\n return i + 1\n\ndef random_partition(p, r):\n ri = randint(p, r)\n nums[ri], ... | <|body_start_0|>
def partition(p, r):
x = nums[r]
i = p - 1
for j in range(p, r):
if nums[j] < x:
i += 1
nums[i], nums[j] = (nums[j], nums[i])
nums[i + 1], nums[r] = (nums[r], nums[i + 1])
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
"""Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int"""
<|body_0|>
def findKthLargestPQ(self, nums, k):
"""Algorithm: * Heap O(n lg k), kth largest element is the smallest one in the k-size min-he... | stack_v2_sparse_classes_36k_train_012094 | 2,164 | no_license | [
{
"docstring": "Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int",
"name": "findKthLargest",
"signature": "def findKthLargest(self, nums, k)"
},
{
"docstring": "Algorithm: * Heap O(n lg k), kth largest element is the smallest one in the k-size min-heap. :rtype: int",
... | 2 | stack_v2_sparse_classes_30k_val_001047 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int
- def findKthLargestPQ(self, nums, k): Algorithm: * Heap O(n lg k),... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int
- def findKthLargestPQ(self, nums, k): Algorithm: * Heap O(n lg k),... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
"""Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int"""
<|body_0|>
def findKthLargestPQ(self, nums, k):
"""Algorithm: * Heap O(n lg k), kth largest element is the smallest one in the k-size min-he... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findKthLargest(self, nums, k):
"""Algorithm: * Partial quick sort average O(n), worst case O(n^2) :rtype: int"""
def partition(p, r):
x = nums[r]
i = p - 1
for j in range(p, r):
if nums[j] < x:
i += 1
... | the_stack_v2_python_sparse | K/KthLargestElementinanArray.py | bssrdf/pyleet | train | 2 | |
331cd47957951eaa3ae5ba7e1c7b910559cf7160 | [
"tests = [('test_1_input.txt', 42)]\nfor test in tests:\n self.assertEqual(_get_orbit_count(_read_orbits(test[0])), test[1])",
"tests = [('test_2_input.txt', 4)]\nfor test in tests:\n self.assertEqual(_get_min_transfer_count(_read_orbits(test[0])), test[1])"
] | <|body_start_0|>
tests = [('test_1_input.txt', 42)]
for test in tests:
self.assertEqual(_get_orbit_count(_read_orbits(test[0])), test[1])
<|end_body_0|>
<|body_start_1|>
tests = [('test_2_input.txt', 4)]
for test in tests:
self.assertEqual(_get_min_transfer_count... | Tests for day 6. | ChallengeTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChallengeTests:
"""Tests for day 6."""
def test_part1(self):
"""Test part one example values."""
<|body_0|>
def test_part2(self):
"""Test part two example values."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
tests = [('test_1_input.txt', 42)]... | stack_v2_sparse_classes_36k_train_012095 | 3,432 | permissive | [
{
"docstring": "Test part one example values.",
"name": "test_part1",
"signature": "def test_part1(self)"
},
{
"docstring": "Test part two example values.",
"name": "test_part2",
"signature": "def test_part2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010057 | Implement the Python class `ChallengeTests` described below.
Class description:
Tests for day 6.
Method signatures and docstrings:
- def test_part1(self): Test part one example values.
- def test_part2(self): Test part two example values. | Implement the Python class `ChallengeTests` described below.
Class description:
Tests for day 6.
Method signatures and docstrings:
- def test_part1(self): Test part one example values.
- def test_part2(self): Test part two example values.
<|skeleton|>
class ChallengeTests:
"""Tests for day 6."""
def test_pa... | 31c5dda73cc964b2bc54b228bee5c59ab99755cc | <|skeleton|>
class ChallengeTests:
"""Tests for day 6."""
def test_part1(self):
"""Test part one example values."""
<|body_0|>
def test_part2(self):
"""Test part two example values."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChallengeTests:
"""Tests for day 6."""
def test_part1(self):
"""Test part one example values."""
tests = [('test_1_input.txt', 42)]
for test in tests:
self.assertEqual(_get_orbit_count(_read_orbits(test[0])), test[1])
def test_part2(self):
"""Test part two... | the_stack_v2_python_sparse | 2019/day_06/day_06.py | moppius/advent-of-code | train | 0 |
20e34197d6bb789ff5065d68997d71513b188a13 | [
"self.user = user\nself.filter_by_user = kwargs.pop('filter_by_user', True)\nfor facet in self.facets:\n if facet in kwargs:\n kwargs.setdefault('filters', {})[facet] = kwargs.pop(facet)\nfor f in ALL_FACETS:\n if f in kwargs:\n del kwargs[f]\nlog.info('Hacking Elastic to fix search connection p... | <|body_start_0|>
self.user = user
self.filter_by_user = kwargs.pop('filter_by_user', True)
for facet in self.facets:
if facet in kwargs:
kwargs.setdefault('filters', {})[facet] = kwargs.pop(facet)
for f in ALL_FACETS:
if f in kwargs:
... | RTDFacetedSearch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RTDFacetedSearch:
def __init__(self, user, **kwargs):
"""Pass in a user in order to filter search results by privacy. .. warning:: The `self.user` and `self.filter_by_user` attributes aren't currently used on the .org, but are used on the .com."""
<|body_0|>
def query(self, ... | stack_v2_sparse_classes_36k_train_012096 | 7,864 | permissive | [
{
"docstring": "Pass in a user in order to filter search results by privacy. .. warning:: The `self.user` and `self.filter_by_user` attributes aren't currently used on the .org, but are used on the .com.",
"name": "__init__",
"signature": "def __init__(self, user, **kwargs)"
},
{
"docstring": "A... | 2 | stack_v2_sparse_classes_30k_train_006130 | Implement the Python class `RTDFacetedSearch` described below.
Class description:
Implement the RTDFacetedSearch class.
Method signatures and docstrings:
- def __init__(self, user, **kwargs): Pass in a user in order to filter search results by privacy. .. warning:: The `self.user` and `self.filter_by_user` attributes... | Implement the Python class `RTDFacetedSearch` described below.
Class description:
Implement the RTDFacetedSearch class.
Method signatures and docstrings:
- def __init__(self, user, **kwargs): Pass in a user in order to filter search results by privacy. .. warning:: The `self.user` and `self.filter_by_user` attributes... | 649965d7589eb1d30efdc7906c3ee7dc5a9e3656 | <|skeleton|>
class RTDFacetedSearch:
def __init__(self, user, **kwargs):
"""Pass in a user in order to filter search results by privacy. .. warning:: The `self.user` and `self.filter_by_user` attributes aren't currently used on the .org, but are used on the .com."""
<|body_0|>
def query(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RTDFacetedSearch:
def __init__(self, user, **kwargs):
"""Pass in a user in order to filter search results by privacy. .. warning:: The `self.user` and `self.filter_by_user` attributes aren't currently used on the .org, but are used on the .com."""
self.user = user
self.filter_by_user =... | the_stack_v2_python_sparse | readthedocs/search/faceted_search.py | italia/docs.italia.it | train | 19 | |
48aa76410df02a9677ced68c244e33b1338593c7 | [
"RAMSTKDataModel.__init__(self, dao)\nself._user_preferences = {}\nself._configuration = configuration",
"if not self._configuration.get_site_configuration():\n _temp = {'type': self._configuration.RAMSTK_COM_BACKEND}\n self._user_preferences['common_db_info'] = _temp.copy()\n self._user_preferences['com... | <|body_start_0|>
RAMSTKDataModel.__init__(self, dao)
self._user_preferences = {}
self._configuration = configuration
<|end_body_0|>
<|body_start_1|>
if not self._configuration.get_site_configuration():
_temp = {'type': self._configuration.RAMSTK_COM_BACKEND}
self... | Contains the attributes and methods for Program (user) preferences. | UserPreferencesDataModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPreferencesDataModel:
"""Contains the attributes and methods for Program (user) preferences."""
def __init__(self, dao, configuration):
"""Initialize a User Preferences data model instance. :param dao: the data access object for communicating with the RAMSTK Program database. :ty... | stack_v2_sparse_classes_36k_train_012097 | 14,568 | permissive | [
{
"docstring": "Initialize a User Preferences data model instance. :param dao: the data access object for communicating with the RAMSTK Program database. :type dao: :class:`ramstk.dao.DAO.DAO`",
"name": "__init__",
"signature": "def __init__(self, dao, configuration)"
},
{
"docstring": "Retrieve... | 3 | null | Implement the Python class `UserPreferencesDataModel` described below.
Class description:
Contains the attributes and methods for Program (user) preferences.
Method signatures and docstrings:
- def __init__(self, dao, configuration): Initialize a User Preferences data model instance. :param dao: the data access objec... | Implement the Python class `UserPreferencesDataModel` described below.
Class description:
Contains the attributes and methods for Program (user) preferences.
Method signatures and docstrings:
- def __init__(self, dao, configuration): Initialize a User Preferences data model instance. :param dao: the data access objec... | 488ffed8b842399ddcae93007de6c6f1dda23d05 | <|skeleton|>
class UserPreferencesDataModel:
"""Contains the attributes and methods for Program (user) preferences."""
def __init__(self, dao, configuration):
"""Initialize a User Preferences data model instance. :param dao: the data access object for communicating with the RAMSTK Program database. :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserPreferencesDataModel:
"""Contains the attributes and methods for Program (user) preferences."""
def __init__(self, dao, configuration):
"""Initialize a User Preferences data model instance. :param dao: the data access object for communicating with the RAMSTK Program database. :type dao: :clas... | the_stack_v2_python_sparse | src/ramstk/modules/preferences/Model.py | JmiXIII/ramstk | train | 0 |
d5bcba007ead05e02135affdfba3236a100dcdf4 | [
"queryset = super(GenericAPIView, self).get_queryset()\nif isinstance(queryset, BaseQuerySet):\n queryset = queryset.all()\nreturn queryset",
"queryset = self.filter_queryset(self.get_queryset())\nlookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field\nassert lookup_url_kwarg in self.kwargs, 'Expected v... | <|body_start_0|>
queryset = super(GenericAPIView, self).get_queryset()
if isinstance(queryset, BaseQuerySet):
queryset = queryset.all()
return queryset
<|end_body_0|>
<|body_start_1|>
queryset = self.filter_queryset(self.get_queryset())
lookup_url_kwarg = self.lookup... | View to play nice with our Document Serializer | GenericAPIView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericAPIView:
"""View to play nice with our Document Serializer"""
def get_queryset(self):
"""Re evaluate queryset, fixes #63"""
<|body_0|>
def get_object(self):
"""*** Inherited from DRF 3 GenericAPIView, swapped get_object_or_404() with get_document_or_404() ... | stack_v2_sparse_classes_36k_train_012098 | 4,964 | permissive | [
{
"docstring": "Re evaluate queryset, fixes #63",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "*** Inherited from DRF 3 GenericAPIView, swapped get_object_or_404() with get_document_or_404() *** Returns the object the view is displaying. You may want to overri... | 2 | stack_v2_sparse_classes_30k_train_002723 | Implement the Python class `GenericAPIView` described below.
Class description:
View to play nice with our Document Serializer
Method signatures and docstrings:
- def get_queryset(self): Re evaluate queryset, fixes #63
- def get_object(self): *** Inherited from DRF 3 GenericAPIView, swapped get_object_or_404() with g... | Implement the Python class `GenericAPIView` described below.
Class description:
View to play nice with our Document Serializer
Method signatures and docstrings:
- def get_queryset(self): Re evaluate queryset, fixes #63
- def get_object(self): *** Inherited from DRF 3 GenericAPIView, swapped get_object_or_404() with g... | e2f2a66347da307e72ed4b0c841aa053c8e91405 | <|skeleton|>
class GenericAPIView:
"""View to play nice with our Document Serializer"""
def get_queryset(self):
"""Re evaluate queryset, fixes #63"""
<|body_0|>
def get_object(self):
"""*** Inherited from DRF 3 GenericAPIView, swapped get_object_or_404() with get_document_or_404() ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenericAPIView:
"""View to play nice with our Document Serializer"""
def get_queryset(self):
"""Re evaluate queryset, fixes #63"""
queryset = super(GenericAPIView, self).get_queryset()
if isinstance(queryset, BaseQuerySet):
queryset = queryset.all()
return quer... | the_stack_v2_python_sparse | rest_framework_mongoengine/generics.py | BryanAke/django-rest-framework-mongoengine | train | 3 |
9998a750b404fab37d348d384de765575e043ffa | [
"e_amd64.Amd64Emulator.__init__(self)\nv_i_emulator.WorkspaceEmulator.__init__(self, vw, **kwargs)\nself.setEmuOpt('i386:repmax', 1)",
"value = e_amd64.Amd64Emulator.getRegister(self, index)\nif self.op is None:\n return value\nif index not in self.taintregs:\n return value\nif self.isRegUse(self.op, index)... | <|body_start_0|>
e_amd64.Amd64Emulator.__init__(self)
v_i_emulator.WorkspaceEmulator.__init__(self, vw, **kwargs)
self.setEmuOpt('i386:repmax', 1)
<|end_body_0|>
<|body_start_1|>
value = e_amd64.Amd64Emulator.getRegister(self, index)
if self.op is None:
return value
... | Amd64WorkspaceEmulator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Amd64WorkspaceEmulator:
def __init__(self, vw, **kwargs):
"""Please see the base emulator class in vivisect/impemu/emulator.py for the parameters that can be passed through kwargs"""
<|body_0|>
def getRegister(self, index):
"""Return the current value of the specifie... | stack_v2_sparse_classes_36k_train_012099 | 2,683 | permissive | [
{
"docstring": "Please see the base emulator class in vivisect/impemu/emulator.py for the parameters that can be passed through kwargs",
"name": "__init__",
"signature": "def __init__(self, vw, **kwargs)"
},
{
"docstring": "Return the current value of the specified register index.",
"name": ... | 3 | null | Implement the Python class `Amd64WorkspaceEmulator` described below.
Class description:
Implement the Amd64WorkspaceEmulator class.
Method signatures and docstrings:
- def __init__(self, vw, **kwargs): Please see the base emulator class in vivisect/impemu/emulator.py for the parameters that can be passed through kwar... | Implement the Python class `Amd64WorkspaceEmulator` described below.
Class description:
Implement the Amd64WorkspaceEmulator class.
Method signatures and docstrings:
- def __init__(self, vw, **kwargs): Please see the base emulator class in vivisect/impemu/emulator.py for the parameters that can be passed through kwar... | b07e161cc28b19fdda0d047eefafed22c5b00f15 | <|skeleton|>
class Amd64WorkspaceEmulator:
def __init__(self, vw, **kwargs):
"""Please see the base emulator class in vivisect/impemu/emulator.py for the parameters that can be passed through kwargs"""
<|body_0|>
def getRegister(self, index):
"""Return the current value of the specifie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Amd64WorkspaceEmulator:
def __init__(self, vw, **kwargs):
"""Please see the base emulator class in vivisect/impemu/emulator.py for the parameters that can be passed through kwargs"""
e_amd64.Amd64Emulator.__init__(self)
v_i_emulator.WorkspaceEmulator.__init__(self, vw, **kwargs)
... | the_stack_v2_python_sparse | vivisect/impemu/platarch/amd64.py | vivisect/vivisect | train | 833 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.