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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9d4ba6c4491d411508e517591ef8c996e35bae72 | [
"solution = []\nfor i in range(size):\n rand_num = uniform(-size, size)\n solution.append(rand_num)\nreturn np.array(solution)",
"pos = 0\naux_pos = 0\nmatrix = []\npointerB = []\npointerE = []\ncolumns = []\nvalues = []\nfor i in range(0, matrix_length):\n row = []\n pointerB.append(pos)\n aux_pos... | <|body_start_0|>
solution = []
for i in range(size):
rand_num = uniform(-size, size)
solution.append(rand_num)
return np.array(solution)
<|end_body_0|>
<|body_start_1|>
pos = 0
aux_pos = 0
matrix = []
pointerB = []
pointerE = []
... | SparseMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseMatrix:
def gen_vector(size):
"""Creates a random vector given a size. @param size Length of the vector that will be created. @return float128[:]"""
<|body_0|>
def create_sparse_matrix(self, filename, matrix_length, density):
"""Creates a sparse matrix with CSR... | stack_v2_sparse_classes_36k_train_006200 | 4,866 | no_license | [
{
"docstring": "Creates a random vector given a size. @param size Length of the vector that will be created. @return float128[:]",
"name": "gen_vector",
"signature": "def gen_vector(size)"
},
{
"docstring": "Creates a sparse matrix with CSR format (four arrays) @param filename The file name wher... | 4 | stack_v2_sparse_classes_30k_train_012713 | Implement the Python class `SparseMatrix` described below.
Class description:
Implement the SparseMatrix class.
Method signatures and docstrings:
- def gen_vector(size): Creates a random vector given a size. @param size Length of the vector that will be created. @return float128[:]
- def create_sparse_matrix(self, fi... | Implement the Python class `SparseMatrix` described below.
Class description:
Implement the SparseMatrix class.
Method signatures and docstrings:
- def gen_vector(size): Creates a random vector given a size. @param size Length of the vector that will be created. @return float128[:]
- def create_sparse_matrix(self, fi... | b2b89a18260c25134d50c37a4fbb48981de79218 | <|skeleton|>
class SparseMatrix:
def gen_vector(size):
"""Creates a random vector given a size. @param size Length of the vector that will be created. @return float128[:]"""
<|body_0|>
def create_sparse_matrix(self, filename, matrix_length, density):
"""Creates a sparse matrix with CSR... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparseMatrix:
def gen_vector(size):
"""Creates a random vector given a size. @param size Length of the vector that will be created. @return float128[:]"""
solution = []
for i in range(size):
rand_num = uniform(-size, size)
solution.append(rand_num)
retur... | the_stack_v2_python_sparse | project/sparse_matrices/sparse_matrix.py | tllano11/Numerical-Methods | train | 3 | |
da4328ef38c8a5b5ebfb20ce5191885bc39f106d | [
"super(SingleSolutionAnalyzer, self).__init__(args, **kwargs)\nself._solver = None\nif 'plotter_options' in kwargs:\n self._plotter = SingleSolutionPlotter(**kwargs['plotter_options'])\nelse:\n self._plotter = SingleSolutionPlotter()",
"super(SingleSolutionAnalyzer, self).run(**kwargs)\nassert_named_argumen... | <|body_start_0|>
super(SingleSolutionAnalyzer, self).__init__(args, **kwargs)
self._solver = None
if 'plotter_options' in kwargs:
self._plotter = SingleSolutionPlotter(**kwargs['plotter_options'])
else:
self._plotter = SingleSolutionPlotter()
<|end_body_0|>
<|bod... | Analyzer for a single solution instance. For now, it only plots the final solution and the error of each iteration. | SingleSolutionAnalyzer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleSolutionAnalyzer:
"""Analyzer for a single solution instance. For now, it only plots the final solution and the error of each iteration."""
def __init__(self, *args, **kwargs):
"""Parameters ---------- plotter_options : :py:class:`dict` options to be passed on to the plotter"""... | stack_v2_sparse_classes_36k_train_006201 | 2,236 | no_license | [
{
"docstring": "Parameters ---------- plotter_options : :py:class:`dict` options to be passed on to the plotter",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Parameters ---------- solver : :py:class:`.IIterativeTimeSolver` Raises ------ ValueError if... | 3 | stack_v2_sparse_classes_30k_val_000265 | Implement the Python class `SingleSolutionAnalyzer` described below.
Class description:
Analyzer for a single solution instance. For now, it only plots the final solution and the error of each iteration.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Parameters ---------- plotter_options : :... | Implement the Python class `SingleSolutionAnalyzer` described below.
Class description:
Analyzer for a single solution instance. For now, it only plots the final solution and the error of each iteration.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Parameters ---------- plotter_options : :... | 90aed34cf43d633e44f56444f6c5d4fa39619663 | <|skeleton|>
class SingleSolutionAnalyzer:
"""Analyzer for a single solution instance. For now, it only plots the final solution and the error of each iteration."""
def __init__(self, *args, **kwargs):
"""Parameters ---------- plotter_options : :py:class:`dict` options to be passed on to the plotter"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleSolutionAnalyzer:
"""Analyzer for a single solution instance. For now, it only plots the final solution and the error of each iteration."""
def __init__(self, *args, **kwargs):
"""Parameters ---------- plotter_options : :py:class:`dict` options to be passed on to the plotter"""
supe... | the_stack_v2_python_sparse | pypint/plugins/analyzers/single_solution_analyzer.py | Parallel-in-Time/PyPinT | train | 0 |
166573e9f5a6bf8f11d338dc9c5deb7a7de58260 | [
"if not nums:\n return 0\nn = len(nums)\nres = []\nfor i in range(n):\n for j in range(i + 1, n):\n if abs(nums[j] - nums[i]) == k:\n if (nums[i], nums[j]) not in res and (nums[j], nums[i]) not in res:\n res.append((nums[i], nums[j]))\nreturn len(res)",
"if not nums:\n re... | <|body_start_0|>
if not nums:
return 0
n = len(nums)
res = []
for i in range(n):
for j in range(i + 1, n):
if abs(nums[j] - nums[i]) == k:
if (nums[i], nums[j]) not in res and (nums[j], nums[i]) not in res:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findPairs(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findPairs2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
... | stack_v2_sparse_classes_36k_train_006202 | 1,072 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findPairs",
"signature": "def findPairs(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findPairs2",
"signature": "def findPairs2(self, nums, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPairs(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findPairs2(self, nums, k): :type nums: List[int] :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPairs(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findPairs2(self, nums, k): :type nums: List[int] :type k: int :rtype: int
<|skeleton|>
class S... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def findPairs(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findPairs2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findPairs(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
if not nums:
return 0
n = len(nums)
res = []
for i in range(n):
for j in range(i + 1, n):
if abs(nums[j] - nums[i]) == k:
... | the_stack_v2_python_sparse | 532. K-diff Pairs in an Array/pairs.py | Macielyoung/LeetCode | train | 1 | |
a70e8c7d6e009e2e4edd8c0a16d64ea8c954f8b7 | [
"UserModel = get_user_model()\ntry:\n user = UserModel._default_manager.get_by_natural_key(username)\n if user.check_password(password):\n return user\nexcept UserModel.DoesNotExist:\n return None",
"UserModel = get_user_model()\ntry:\n return UserModel.objects.get(pk=user_id)\nexcept UserModel... | <|body_start_0|>
UserModel = get_user_model()
try:
user = UserModel._default_manager.get_by_natural_key(username)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
return None
<|end_body_0|>
<|body_start_1|>
... | This Authentication Backend Authenticates a User Against an Email. | EmailAuthenticationBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailAuthenticationBackend:
"""This Authentication Backend Authenticates a User Against an Email."""
def authenticate(self, username=None, password=None):
"""Authenticate Using the Email/password And Return a User"""
<|body_0|>
def get_user(self, user_id):
"""Ret... | stack_v2_sparse_classes_36k_train_006203 | 2,708 | no_license | [
{
"docstring": "Authenticate Using the Email/password And Return a User",
"name": "authenticate",
"signature": "def authenticate(self, username=None, password=None)"
},
{
"docstring": "Returns a User Against a Given User Id",
"name": "get_user",
"signature": "def get_user(self, user_id)"... | 2 | stack_v2_sparse_classes_30k_train_001839 | Implement the Python class `EmailAuthenticationBackend` described below.
Class description:
This Authentication Backend Authenticates a User Against an Email.
Method signatures and docstrings:
- def authenticate(self, username=None, password=None): Authenticate Using the Email/password And Return a User
- def get_use... | Implement the Python class `EmailAuthenticationBackend` described below.
Class description:
This Authentication Backend Authenticates a User Against an Email.
Method signatures and docstrings:
- def authenticate(self, username=None, password=None): Authenticate Using the Email/password And Return a User
- def get_use... | 3bb9fe2e3fe8d876519631233fb29c7e04e2e8c3 | <|skeleton|>
class EmailAuthenticationBackend:
"""This Authentication Backend Authenticates a User Against an Email."""
def authenticate(self, username=None, password=None):
"""Authenticate Using the Email/password And Return a User"""
<|body_0|>
def get_user(self, user_id):
"""Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailAuthenticationBackend:
"""This Authentication Backend Authenticates a User Against an Email."""
def authenticate(self, username=None, password=None):
"""Authenticate Using the Email/password And Return a User"""
UserModel = get_user_model()
try:
user = UserModel._... | the_stack_v2_python_sparse | accounts/backends.py | Mr4x3/competition_mania | train | 0 |
0d6e5ee3cc02ede6de613b9c96492372e087416d | [
"self.distr = values\nif len(self.distr) == 1:\n self.distr = self.distr[0]\nmaxv = 0\nfor t in self.distr:\n if t[1] > maxv:\n maxv = t[1]\nself.maxv = maxv",
"done = False\nsamp = ''\nwhile not done:\n t = self.distr[randint(0, len(self.distr) - 1)]\n d = randomFloat(0, self.maxv)\n if d <... | <|body_start_0|>
self.distr = values
if len(self.distr) == 1:
self.distr = self.distr[0]
maxv = 0
for t in self.distr:
if t[1] > maxv:
maxv = t[1]
self.maxv = maxv
<|end_body_0|>
<|body_start_1|>
done = False
samp = ''
... | non parametric sampling for categorical attributes using given distribution based on rejection sampling | CategoricalRejectSampler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoricalRejectSampler:
"""non parametric sampling for categorical attributes using given distribution based on rejection sampling"""
def __init__(self, *values):
"""initializer Parameters values : list of tuples which contains a categorical value and the corresponsding distr value... | stack_v2_sparse_classes_36k_train_006204 | 32,264 | permissive | [
{
"docstring": "initializer Parameters values : list of tuples which contains a categorical value and the corresponsding distr value",
"name": "__init__",
"signature": "def __init__(self, *values)"
},
{
"docstring": "samples value",
"name": "sample",
"signature": "def sample(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009241 | Implement the Python class `CategoricalRejectSampler` described below.
Class description:
non parametric sampling for categorical attributes using given distribution based on rejection sampling
Method signatures and docstrings:
- def __init__(self, *values): initializer Parameters values : list of tuples which contai... | Implement the Python class `CategoricalRejectSampler` described below.
Class description:
non parametric sampling for categorical attributes using given distribution based on rejection sampling
Method signatures and docstrings:
- def __init__(self, *values): initializer Parameters values : list of tuples which contai... | 861fd06b6b7abaffe5e8ca795136ab0fbb2234b5 | <|skeleton|>
class CategoricalRejectSampler:
"""non parametric sampling for categorical attributes using given distribution based on rejection sampling"""
def __init__(self, *values):
"""initializer Parameters values : list of tuples which contains a categorical value and the corresponsding distr value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoricalRejectSampler:
"""non parametric sampling for categorical attributes using given distribution based on rejection sampling"""
def __init__(self, *values):
"""initializer Parameters values : list of tuples which contains a categorical value and the corresponsding distr value"""
s... | the_stack_v2_python_sparse | matumizi/matumizi/sampler.py | pranab/whakapai | train | 18 |
888fe82b483a24c97ff26a521d7bd8dca6e887ab | [
"num_labels = np.arange(0, len(np.unique(clt.labels_)) + 1)\nhist, _ = np.histogram(clt.labels_, bins=num_labels)\nhist = hist.astype('float')\nhist /= hist.sum()\nreturn hist",
"image = image.reshape((image.shape[0] * image.shape[1], 3))\nclt = KMeans(n_clusters=n)\nclt.fit(image)\nhist = ColorDetector.__centroi... | <|body_start_0|>
num_labels = np.arange(0, len(np.unique(clt.labels_)) + 1)
hist, _ = np.histogram(clt.labels_, bins=num_labels)
hist = hist.astype('float')
hist /= hist.sum()
return hist
<|end_body_0|>
<|body_start_1|>
image = image.reshape((image.shape[0] * image.shape... | Klasa określająca kolor pojazdu. | ColorDetector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorDetector:
"""Klasa określająca kolor pojazdu."""
def __centroid_histogram(clt):
"""Przydziala wartości histogramu do zdefiniowanych grup. Dokonuje normalizacji nowego histogramu. :param clt: Zdefiniowane przez KMeans grupy. :return: Histogram po przydziale pikseli."""
<|... | stack_v2_sparse_classes_36k_train_006205 | 14,920 | no_license | [
{
"docstring": "Przydziala wartości histogramu do zdefiniowanych grup. Dokonuje normalizacji nowego histogramu. :param clt: Zdefiniowane przez KMeans grupy. :return: Histogram po przydziale pikseli.",
"name": "__centroid_histogram",
"signature": "def __centroid_histogram(clt)"
},
{
"docstring": ... | 5 | stack_v2_sparse_classes_30k_test_000129 | Implement the Python class `ColorDetector` described below.
Class description:
Klasa określająca kolor pojazdu.
Method signatures and docstrings:
- def __centroid_histogram(clt): Przydziala wartości histogramu do zdefiniowanych grup. Dokonuje normalizacji nowego histogramu. :param clt: Zdefiniowane przez KMeans grupy... | Implement the Python class `ColorDetector` described below.
Class description:
Klasa określająca kolor pojazdu.
Method signatures and docstrings:
- def __centroid_histogram(clt): Przydziala wartości histogramu do zdefiniowanych grup. Dokonuje normalizacji nowego histogramu. :param clt: Zdefiniowane przez KMeans grupy... | c8d6be403f12e01d3a2c0ea671363f20eeb08ce4 | <|skeleton|>
class ColorDetector:
"""Klasa określająca kolor pojazdu."""
def __centroid_histogram(clt):
"""Przydziala wartości histogramu do zdefiniowanych grup. Dokonuje normalizacji nowego histogramu. :param clt: Zdefiniowane przez KMeans grupy. :return: Histogram po przydziale pikseli."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColorDetector:
"""Klasa określająca kolor pojazdu."""
def __centroid_histogram(clt):
"""Przydziala wartości histogramu do zdefiniowanych grup. Dokonuje normalizacji nowego histogramu. :param clt: Zdefiniowane przez KMeans grupy. :return: Histogram po przydziale pikseli."""
num_labels = np... | the_stack_v2_python_sparse | src/classify.py | djgrasss/videodetection | train | 0 |
501e6a4fbdbad806606ee746fbd27488c03762d1 | [
"if not s:\n return 0\nif len(s) == 1:\n return 1\noutput = ''\nstart = 0\nend = 1\n\ndef is_unique(s):\n return len(s) == len(set(s))\nwhile end <= len(s):\n substr = s[start:end]\n if is_unique(substr):\n if len(substr) > len(output):\n output = substr\n end += 1\n elif ... | <|body_start_0|>
if not s:
return 0
if len(s) == 1:
return 1
output = ''
start = 0
end = 1
def is_unique(s):
return len(s) == len(set(s))
while end <= len(s):
substr = s[start:end]
if is_unique(substr):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s:
return 0
if l... | stack_v2_sparse_classes_36k_train_006206 | 1,639 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013678 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def lengthOfL... | f3e01ec2012ac6d22709357db27a487d14c50411 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
if not s:
return 0
if len(s) == 1:
return 1
output = ''
start = 0
end = 1
def is_unique(s):
return len(s) == len(set(s))
while en... | the_stack_v2_python_sparse | length_of_longest_substr.py | dan-sf/leetcode | train | 0 | |
358a703907879d29cd734950e558ceb68d0284ff | [
"temp_init = ps7.Position.__init__\n\ndef custom_init(*args):\n test = isinstance(args[1], float) and isinstance(args[2], float)\n msg = 'A Position object must be created using floats.'\n self.assertTrue(test, msg)\n return temp_init(*args)\nps7.Position.__init__ = custom_init\ntemp_seed = random.seed\... | <|body_start_0|>
temp_init = ps7.Position.__init__
def custom_init(*args):
test = isinstance(args[1], float) and isinstance(args[2], float)
msg = 'A Position object must be created using floats.'
self.assertTrue(test, msg)
return temp_init(*args)
... | Problem_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Problem_1:
def test_1(self):
"""-Check if Position objects are created with floats -Check if the random.seed() function isn't being called"""
<|body_0|>
def test_2(self):
"""-Check if the first tile is cleaned -Check if the direction is being defined before position ... | stack_v2_sparse_classes_36k_train_006207 | 9,715 | no_license | [
{
"docstring": "-Check if Position objects are created with floats -Check if the random.seed() function isn't being called",
"name": "test_1",
"signature": "def test_1(self)"
},
{
"docstring": "-Check if the first tile is cleaned -Check if the direction is being defined before position -Check if... | 4 | null | Implement the Python class `Problem_1` described below.
Class description:
Implement the Problem_1 class.
Method signatures and docstrings:
- def test_1(self): -Check if Position objects are created with floats -Check if the random.seed() function isn't being called
- def test_2(self): -Check if the first tile is cle... | Implement the Python class `Problem_1` described below.
Class description:
Implement the Problem_1 class.
Method signatures and docstrings:
- def test_1(self): -Check if Position objects are created with floats -Check if the random.seed() function isn't being called
- def test_2(self): -Check if the first tile is cle... | 5aa496a71d36ffb9892ee6e377bd9f5d0d8e03a0 | <|skeleton|>
class Problem_1:
def test_1(self):
"""-Check if Position objects are created with floats -Check if the random.seed() function isn't being called"""
<|body_0|>
def test_2(self):
"""-Check if the first tile is cleaned -Check if the direction is being defined before position ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Problem_1:
def test_1(self):
"""-Check if Position objects are created with floats -Check if the random.seed() function isn't being called"""
temp_init = ps7.Position.__init__
def custom_init(*args):
test = isinstance(args[1], float) and isinstance(args[2], float)
... | the_stack_v2_python_sparse | pstTestingCode.py | KarenWest/pythonClassProjects | train | 1 | |
3ebf0c731c063736fdb26e7dcab7af14c04c2f37 | [
"directory_path = 'data'\nparallel.drop_data()\nlist1 = parallel.import_data(directory_path, 'products.csv', 'customers.csv')\nself.assertEqual(list1[0][0], 999)\nself.assertEqual(list1[0][1], 0)\nself.assertEqual(list1[0][2], 999)\nself.assertTrue(list1[0][3] > 0)\nself.assertEqual(list1[1][0], 999)\nself.assertEq... | <|body_start_0|>
directory_path = 'data'
parallel.drop_data()
list1 = parallel.import_data(directory_path, 'products.csv', 'customers.csv')
self.assertEqual(list1[0][0], 999)
self.assertEqual(list1[0][1], 0)
self.assertEqual(list1[0][2], 999)
self.assertTrue(list1... | Tests for the database module | LinearTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearTests:
"""Tests for the database module"""
def test_import_data(self):
"""Tests the import_data function"""
<|body_0|>
def test_import_data_thread(self):
"""Tests the import_data function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dir... | stack_v2_sparse_classes_36k_train_006208 | 2,454 | no_license | [
{
"docstring": "Tests the import_data function",
"name": "test_import_data",
"signature": "def test_import_data(self)"
},
{
"docstring": "Tests the import_data function",
"name": "test_import_data_thread",
"signature": "def test_import_data_thread(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013760 | Implement the Python class `LinearTests` described below.
Class description:
Tests for the database module
Method signatures and docstrings:
- def test_import_data(self): Tests the import_data function
- def test_import_data_thread(self): Tests the import_data function | Implement the Python class `LinearTests` described below.
Class description:
Tests for the database module
Method signatures and docstrings:
- def test_import_data(self): Tests the import_data function
- def test_import_data_thread(self): Tests the import_data function
<|skeleton|>
class LinearTests:
"""Tests fo... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class LinearTests:
"""Tests for the database module"""
def test_import_data(self):
"""Tests the import_data function"""
<|body_0|>
def test_import_data_thread(self):
"""Tests the import_data function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearTests:
"""Tests for the database module"""
def test_import_data(self):
"""Tests the import_data function"""
directory_path = 'data'
parallel.drop_data()
list1 = parallel.import_data(directory_path, 'products.csv', 'customers.csv')
self.assertEqual(list1[0][0]... | the_stack_v2_python_sparse | students/amirg/lesson07/assignment/test_parallel.py | JavaRod/SP_Python220B_2019 | train | 1 |
b9d619eb4a3adb89d71ef8ae50e6edf190e5ff85 | [
"Algorithm.__init__(self)\nself.name = 'Bilateral Filter'\nself.parent = 'Preprocessing'\nself.diameter = IntegerSlider('diameter', 1, 20, 1, 1)\nself.sigma_color = FloatSlider('sigmaColor', 0.0, 255.0, 0.1, 30.0)\nself.sigma_space = FloatSlider('sigmaSpace', 0.0, 255.0, 0.1, 30.0)\nself.channel1 = CheckBox('channe... | <|body_start_0|>
Algorithm.__init__(self)
self.name = 'Bilateral Filter'
self.parent = 'Preprocessing'
self.diameter = IntegerSlider('diameter', 1, 20, 1, 1)
self.sigma_color = FloatSlider('sigmaColor', 0.0, 255.0, 0.1, 30.0)
self.sigma_space = FloatSlider('sigmaSpace', 0... | Bilateral Filter algorithm implementation | AlgBody | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlgBody:
"""Bilateral Filter algorithm implementation"""
def __init__(self):
"""Bilateral Filter object constructor. Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriate category | *diameter* : diameter of each pixel neighborhood that is used during fi... | stack_v2_sparse_classes_36k_train_006209 | 3,944 | permissive | [
{
"docstring": "Bilateral Filter object constructor. Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriate category | *diameter* : diameter of each pixel neighborhood that is used during filtering. If it is non-positive, it is computed from sigmaSpace. Consider that a value n is t... | 2 | null | Implement the Python class `AlgBody` described below.
Class description:
Bilateral Filter algorithm implementation
Method signatures and docstrings:
- def __init__(self): Bilateral Filter object constructor. Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriate category | *diameter* : d... | Implement the Python class `AlgBody` described below.
Class description:
Bilateral Filter algorithm implementation
Method signatures and docstrings:
- def __init__(self): Bilateral Filter object constructor. Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriate category | *diameter* : d... | 0dc9becc09da22af3edac90b81b1dd9b1f44fd5b | <|skeleton|>
class AlgBody:
"""Bilateral Filter algorithm implementation"""
def __init__(self):
"""Bilateral Filter object constructor. Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriate category | *diameter* : diameter of each pixel neighborhood that is used during fi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlgBody:
"""Bilateral Filter algorithm implementation"""
def __init__(self):
"""Bilateral Filter object constructor. Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriate category | *diameter* : diameter of each pixel neighborhood that is used during filtering. If i... | the_stack_v2_python_sparse | nefi2/model/algorithms/bilateral.py | andreasfirczynski/NetworkExtractionFromImages | train | 0 |
47a8a465a6a83d067d67917f1fdbb99fe4afc63c | [
"if len(li) <= 0:\n return False\nif len(li) == 1:\n return ListNode(li[0])\nelse:\n root = ListNode(li[0])\n tmp = root\n for i in range(1, len(li)):\n tmp.next = ListNode(li[i])\n tmp = tmp.next\n return root",
"value = []\ntmp = root\nwhile tmp.next != None:\n value.append(st... | <|body_start_0|>
if len(li) <= 0:
return False
if len(li) == 1:
return ListNode(li[0])
else:
root = ListNode(li[0])
tmp = root
for i in range(1, len(li)):
tmp.next = ListNode(li[i])
tmp = tmp.next
... | ListNode_handle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListNode_handle:
def Creatlist(self, li):
"""从列表创建一个链表 :param li: 列表 :return: 头结点"""
<|body_0|>
def print_linked(self, root: ListNode):
"""打印链表 :param root: 头结点 :return: 打印链表"""
<|body_1|>
def length(self, root):
"""计算链表的长度 :param root: :return:"... | stack_v2_sparse_classes_36k_train_006210 | 3,869 | no_license | [
{
"docstring": "从列表创建一个链表 :param li: 列表 :return: 头结点",
"name": "Creatlist",
"signature": "def Creatlist(self, li)"
},
{
"docstring": "打印链表 :param root: 头结点 :return: 打印链表",
"name": "print_linked",
"signature": "def print_linked(self, root: ListNode)"
},
{
"docstring": "计算链表的长度 :pa... | 5 | stack_v2_sparse_classes_30k_train_020258 | Implement the Python class `ListNode_handle` described below.
Class description:
Implement the ListNode_handle class.
Method signatures and docstrings:
- def Creatlist(self, li): 从列表创建一个链表 :param li: 列表 :return: 头结点
- def print_linked(self, root: ListNode): 打印链表 :param root: 头结点 :return: 打印链表
- def length(self, root)... | Implement the Python class `ListNode_handle` described below.
Class description:
Implement the ListNode_handle class.
Method signatures and docstrings:
- def Creatlist(self, li): 从列表创建一个链表 :param li: 列表 :return: 头结点
- def print_linked(self, root: ListNode): 打印链表 :param root: 头结点 :return: 打印链表
- def length(self, root)... | 2ef266ee3175d08d125151c9983b864e6ed3343b | <|skeleton|>
class ListNode_handle:
def Creatlist(self, li):
"""从列表创建一个链表 :param li: 列表 :return: 头结点"""
<|body_0|>
def print_linked(self, root: ListNode):
"""打印链表 :param root: 头结点 :return: 打印链表"""
<|body_1|>
def length(self, root):
"""计算链表的长度 :param root: :return:"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListNode_handle:
def Creatlist(self, li):
"""从列表创建一个链表 :param li: 列表 :return: 头结点"""
if len(li) <= 0:
return False
if len(li) == 1:
return ListNode(li[0])
else:
root = ListNode(li[0])
tmp = root
for i in range(1, len(l... | the_stack_v2_python_sparse | leetcode/0001-0100/0019.删除链表的倒数第n个结点.py | alpharol/algorithm_python3 | train | 1 | |
e898655e67249bc840483dbcc66278be9f245f4f | [
"self.size = size\nself.graph = [[] for _ in range(size)]\nself.cost_edge = [[] for _ in range(size)]",
"assert x < self.size\nassert y < self.size\nself.graph[x].append(y)\nself.graph[y].append(x)\nself.cost_edge[x].append(cost)\nself.cost_edge[y].append(cost)",
"s2 = 1\nwhile 1 << s2 < self.size:\n s2 += 1... | <|body_start_0|>
self.size = size
self.graph = [[] for _ in range(size)]
self.cost_edge = [[] for _ in range(size)]
<|end_body_0|>
<|body_start_1|>
assert x < self.size
assert y < self.size
self.graph[x].append(y)
self.graph[y].append(x)
self.cost_edge[x]... | Lowest Common Ancestor | LCA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LCA:
"""Lowest Common Ancestor"""
def __init__(self, size):
"""保存領域の初期化。 辺に重みがついている時の頂点間の重み計算にはcostを使えます。"""
<|body_0|>
def add_edge(self, x: int, y: int, cost: int=1):
"""木の辺を追加します。"""
<|body_1|>
def init(self):
"""全ての辺を追加した後に、LCAを求める為の初期化をす... | stack_v2_sparse_classes_36k_train_006211 | 3,173 | no_license | [
{
"docstring": "保存領域の初期化。 辺に重みがついている時の頂点間の重み計算にはcostを使えます。",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": "木の辺を追加します。",
"name": "add_edge",
"signature": "def add_edge(self, x: int, y: int, cost: int=1)"
},
{
"docstring": "全ての辺を追加した後に、LCAを求める為の初期化を... | 6 | null | Implement the Python class `LCA` described below.
Class description:
Lowest Common Ancestor
Method signatures and docstrings:
- def __init__(self, size): 保存領域の初期化。 辺に重みがついている時の頂点間の重み計算にはcostを使えます。
- def add_edge(self, x: int, y: int, cost: int=1): 木の辺を追加します。
- def init(self): 全ての辺を追加した後に、LCAを求める為の初期化をする。
- def lca(se... | Implement the Python class `LCA` described below.
Class description:
Lowest Common Ancestor
Method signatures and docstrings:
- def __init__(self, size): 保存領域の初期化。 辺に重みがついている時の頂点間の重み計算にはcostを使えます。
- def add_edge(self, x: int, y: int, cost: int=1): 木の辺を追加します。
- def init(self): 全ての辺を追加した後に、LCAを求める為の初期化をする。
- def lca(se... | f214ef92f13bc5d6b290746d5a94e2faad20d8b0 | <|skeleton|>
class LCA:
"""Lowest Common Ancestor"""
def __init__(self, size):
"""保存領域の初期化。 辺に重みがついている時の頂点間の重み計算にはcostを使えます。"""
<|body_0|>
def add_edge(self, x: int, y: int, cost: int=1):
"""木の辺を追加します。"""
<|body_1|>
def init(self):
"""全ての辺を追加した後に、LCAを求める為の初期化をす... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LCA:
"""Lowest Common Ancestor"""
def __init__(self, size):
"""保存領域の初期化。 辺に重みがついている時の頂点間の重み計算にはcostを使えます。"""
self.size = size
self.graph = [[] for _ in range(size)]
self.cost_edge = [[] for _ in range(size)]
def add_edge(self, x: int, y: int, cost: int=1):
"""... | the_stack_v2_python_sparse | past8/h.py | silphire/atcoder | train | 0 |
a9fbf03c4343d9e0e251ffc65f234739c143cfda | [
"time_elements_structure = self._GetValueFromStructure(structure, 'date_time')\nlog_line = self._GetValueFromStructure(structure, 'log_line', default_value='')\nlog_line = log_line.lstrip().rstrip()\npids = self._GetValueFromStructure(structure, 'pid', default_value=[])\ntime_zone_string = self._GetValueFromStructu... | <|body_start_0|>
time_elements_structure = self._GetValueFromStructure(structure, 'date_time')
log_line = self._GetValueFromStructure(structure, 'log_line', default_value='')
log_line = log_line.lstrip().rstrip()
pids = self._GetValueFromStructure(structure, 'pid', default_value=[])
... | Text parser plugin for PostgreSQL application log files. | PostgreSQLTextPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostgreSQLTextPlugin:
"""Text parser plugin for PostgreSQL application log files."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as s... | stack_v2_sparse_classes_36k_train_006212 | 9,463 | permissive | [
{
"docstring": "Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. key (str): name of the parsed structure. structure (pyparsing.ParseResults): tokens from a parsed log line. Raises: ParseError: if the stru... | 3 | null | Implement the Python class `PostgreSQLTextPlugin` described below.
Class description:
Text parser plugin for PostgreSQL application log files.
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates int... | Implement the Python class `PostgreSQLTextPlugin` described below.
Class description:
Text parser plugin for PostgreSQL application log files.
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates int... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class PostgreSQLTextPlugin:
"""Text parser plugin for PostgreSQL application log files."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostgreSQLTextPlugin:
"""Text parser plugin for PostgreSQL application log files."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and df... | the_stack_v2_python_sparse | plaso/parsers/text_plugins/postgresql.py | log2timeline/plaso | train | 1,506 |
e2f870a282722fcbb33fd24ee9b269ef69147939 | [
"self.dag_application_server_info_list = dag_application_server_info_list\nself.exchange_dag_protection_preference = exchange_dag_protection_preference\nself.guid = guid\nself.name = name",
"if dictionary is None:\n return None\ndag_application_server_info_list = None\nif dictionary.get('dagApplicationServerIn... | <|body_start_0|>
self.dag_application_server_info_list = dag_application_server_info_list
self.exchange_dag_protection_preference = exchange_dag_protection_preference
self.guid = guid
self.name = name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None... | Implementation of the 'DagInfo' model. Specifies the information about the DAG(Database availability group). Attributes: dag_application_server_info_list (list of DagApplicationServerInfo): Specifies the status of all the Exchange Application Servers that are part of this DAG. exchange_dag_protection_preference (Exchan... | DagInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DagInfo:
"""Implementation of the 'DagInfo' model. Specifies the information about the DAG(Database availability group). Attributes: dag_application_server_info_list (list of DagApplicationServerInfo): Specifies the status of all the Exchange Application Servers that are part of this DAG. exchang... | stack_v2_sparse_classes_36k_train_006213 | 3,283 | permissive | [
{
"docstring": "Constructor for the DagInfo class",
"name": "__init__",
"signature": "def __init__(self, dag_application_server_info_list=None, exchange_dag_protection_preference=None, guid=None, name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary ... | 2 | stack_v2_sparse_classes_30k_train_020707 | Implement the Python class `DagInfo` described below.
Class description:
Implementation of the 'DagInfo' model. Specifies the information about the DAG(Database availability group). Attributes: dag_application_server_info_list (list of DagApplicationServerInfo): Specifies the status of all the Exchange Application Ser... | Implement the Python class `DagInfo` described below.
Class description:
Implementation of the 'DagInfo' model. Specifies the information about the DAG(Database availability group). Attributes: dag_application_server_info_list (list of DagApplicationServerInfo): Specifies the status of all the Exchange Application Ser... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DagInfo:
"""Implementation of the 'DagInfo' model. Specifies the information about the DAG(Database availability group). Attributes: dag_application_server_info_list (list of DagApplicationServerInfo): Specifies the status of all the Exchange Application Servers that are part of this DAG. exchang... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DagInfo:
"""Implementation of the 'DagInfo' model. Specifies the information about the DAG(Database availability group). Attributes: dag_application_server_info_list (list of DagApplicationServerInfo): Specifies the status of all the Exchange Application Servers that are part of this DAG. exchange_dag_protect... | the_stack_v2_python_sparse | cohesity_management_sdk/models/dag_info.py | cohesity/management-sdk-python | train | 24 |
51c6e2082128fc69365c5a1b73acbcd1629bfcca | [
"sign = 1 if x >= 0 else -1\nx *= sign\noutput = 0\nwhile x:\n output = output * 10 + x % 10\n x = x // 10\nif output > 2 ** 31 - 1:\n return 0\nelse:\n return output * sign",
"if not x:\n return x\nsign = 1 if x >= 0 else -1\ndigits = str(x * sign)[::-1]\nindex_zeros = -1\nfor i, d in enumerate(di... | <|body_start_0|>
sign = 1 if x >= 0 else -1
x *= sign
output = 0
while x:
output = output * 10 + x % 10
x = x // 10
if output > 2 ** 31 - 1:
return 0
else:
return output * sign
<|end_body_0|>
<|body_start_1|>
if not... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse_naive(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sign = 1 if x >= 0 else -1
x *= sign
output = 0
... | stack_v2_sparse_classes_36k_train_006214 | 1,783 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse_naive",
"signature": "def reverse_naive(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000670 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse_naive(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse_naive(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def reverse(self, x):
""":type x:... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse_naive(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
sign = 1 if x >= 0 else -1
x *= sign
output = 0
while x:
output = output * 10 + x % 10
x = x // 10
if output > 2 ** 31 - 1:
return 0
else:
retu... | the_stack_v2_python_sparse | src/lt_7.py | oxhead/CodingYourWay | train | 0 | |
658191c3bd4ae8d32d86513aefd09e83ebaa9d6a | [
"plls = PlaylistEntry.objects.all()\ndatas = self.getrandoms(len(plls))\nfor ple in plls:\n ple.rank = datas.pop()\n ple.save()",
"datas = range(1, count + 1)\nshuffle(datas)\nreturn datas"
] | <|body_start_0|>
plls = PlaylistEntry.objects.all()
datas = self.getrandoms(len(plls))
for ple in plls:
ple.rank = datas.pop()
ple.save()
<|end_body_0|>
<|body_start_1|>
datas = range(1, count + 1)
shuffle(datas)
return datas
<|end_body_1|>
| Command | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
def handle(self, *args, **options):
"""Handle the command"""
<|body_0|>
def getrandoms(self, count):
"""Get a random array"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
plls = PlaylistEntry.objects.all()
datas = self.getrandoms(le... | stack_v2_sparse_classes_36k_train_006215 | 1,410 | no_license | [
{
"docstring": "Handle the command",
"name": "handle",
"signature": "def handle(self, *args, **options)"
},
{
"docstring": "Get a random array",
"name": "getrandoms",
"signature": "def getrandoms(self, count)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012441 | Implement the Python class `Command` described below.
Class description:
Implement the Command class.
Method signatures and docstrings:
- def handle(self, *args, **options): Handle the command
- def getrandoms(self, count): Get a random array | Implement the Python class `Command` described below.
Class description:
Implement the Command class.
Method signatures and docstrings:
- def handle(self, *args, **options): Handle the command
- def getrandoms(self, count): Get a random array
<|skeleton|>
class Command:
def handle(self, *args, **options):
... | 4919242b0f2442007b50d1ef602a2df6d414a6c6 | <|skeleton|>
class Command:
def handle(self, *args, **options):
"""Handle the command"""
<|body_0|>
def getrandoms(self, count):
"""Get a random array"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
def handle(self, *args, **options):
"""Handle the command"""
plls = PlaylistEntry.objects.all()
datas = self.getrandoms(len(plls))
for ple in plls:
ple.rank = datas.pop()
ple.save()
def getrandoms(self, count):
"""Get a random array... | the_stack_v2_python_sparse | calorine/calorine/caro/management/commands/playlist_shuffle.py | rodo/calorine | train | 1 | |
36aa252916bc632249a8e0bb9a23f716d1ec1a01 | [
"self.capacity = capacity\nself.head = None\nself.tail = None\nself.node_idx = dict()\nself.cache = dict()",
"oldest_node = self.tail\nif self.tail.prev is None:\n self.head = None\n self.tail = None\nelse:\n self.tail = oldest_node.prev\n self.tail.next = None\ndel self.cache[oldest_node.val]\ndel se... | <|body_start_0|>
self.capacity = capacity
self.head = None
self.tail = None
self.node_idx = dict()
self.cache = dict()
<|end_body_0|>
<|body_start_1|>
oldest_node = self.tail
if self.tail.prev is None:
self.head = None
self.tail = None
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity: int):
"""Initialize the LRU Cache with positive size capacity."""
<|body_0|>
def _evict(self):
"""Evict the oldest key-value pair from the cache."""
<|body_1|>
def _update_oldest(self, key: int):
"""Update w... | stack_v2_sparse_classes_36k_train_006216 | 4,835 | no_license | [
{
"docstring": "Initialize the LRU Cache with positive size capacity.",
"name": "__init__",
"signature": "def __init__(self, capacity: int)"
},
{
"docstring": "Evict the oldest key-value pair from the cache.",
"name": "_evict",
"signature": "def _evict(self)"
},
{
"docstring": "U... | 5 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity: int): Initialize the LRU Cache with positive size capacity.
- def _evict(self): Evict the oldest key-value pair from the cache.
- def _update_oldest(... | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity: int): Initialize the LRU Cache with positive size capacity.
- def _evict(self): Evict the oldest key-value pair from the cache.
- def _update_oldest(... | f71a85ec73757c5990c8b17a8e5f2a550a9e5e77 | <|skeleton|>
class LRUCache:
def __init__(self, capacity: int):
"""Initialize the LRU Cache with positive size capacity."""
<|body_0|>
def _evict(self):
"""Evict the oldest key-value pair from the cache."""
<|body_1|>
def _update_oldest(self, key: int):
"""Update w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity: int):
"""Initialize the LRU Cache with positive size capacity."""
self.capacity = capacity
self.head = None
self.tail = None
self.node_idx = dict()
self.cache = dict()
def _evict(self):
"""Evict the oldest key-... | the_stack_v2_python_sparse | hard_collection/design/lru_cache.py | DenisVritov/algorithms | train | 0 | |
4758b46fc3d7eba6bce47d6e671bf1940552519a | [
"my_grid = grid_setup(self.rp, ng=1)\nif my_grid.nx != my_grid.ny:\n msg.fail('need nx = ny for diffusion problems')\nn = int(math.log(my_grid.nx) / math.log(2.0))\nif 2 ** n != my_grid.nx:\n msg.fail('grid needs to be a power of 2')\nbc, _, _ = bc_setup(self.rp)\nfor bnd in [bc.xlb, bc.xrb, bc.ylb, bc.yrb]:\... | <|body_start_0|>
my_grid = grid_setup(self.rp, ng=1)
if my_grid.nx != my_grid.ny:
msg.fail('need nx = ny for diffusion problems')
n = int(math.log(my_grid.nx) / math.log(2.0))
if 2 ** n != my_grid.nx:
msg.fail('grid needs to be a power of 2')
bc, _, _ = bc... | A simulation of diffusion | Simulation | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulation:
"""A simulation of diffusion"""
def initialize(self):
"""Initialize the grid and variables for diffusion and set the initial conditions for the chosen problem."""
<|body_0|>
def method_compute_timestep(self):
"""The diffusion timestep() function compu... | stack_v2_sparse_classes_36k_train_006217 | 4,737 | permissive | [
{
"docstring": "Initialize the grid and variables for diffusion and set the initial conditions for the chosen problem.",
"name": "initialize",
"signature": "def initialize(self)"
},
{
"docstring": "The diffusion timestep() function computes the timestep using the explicit timestep constraint as ... | 4 | stack_v2_sparse_classes_30k_train_018239 | Implement the Python class `Simulation` described below.
Class description:
A simulation of diffusion
Method signatures and docstrings:
- def initialize(self): Initialize the grid and variables for diffusion and set the initial conditions for the chosen problem.
- def method_compute_timestep(self): The diffusion time... | Implement the Python class `Simulation` described below.
Class description:
A simulation of diffusion
Method signatures and docstrings:
- def initialize(self): Initialize the grid and variables for diffusion and set the initial conditions for the chosen problem.
- def method_compute_timestep(self): The diffusion time... | f91789a319caa98dfbc3f496e9953756e6ee3ca9 | <|skeleton|>
class Simulation:
"""A simulation of diffusion"""
def initialize(self):
"""Initialize the grid and variables for diffusion and set the initial conditions for the chosen problem."""
<|body_0|>
def method_compute_timestep(self):
"""The diffusion timestep() function compu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Simulation:
"""A simulation of diffusion"""
def initialize(self):
"""Initialize the grid and variables for diffusion and set the initial conditions for the chosen problem."""
my_grid = grid_setup(self.rp, ng=1)
if my_grid.nx != my_grid.ny:
msg.fail('need nx = ny for di... | the_stack_v2_python_sparse | pyro/diffusion/simulation.py | python-hydro/pyro2 | train | 202 |
daf7ce02d1a3d3a275d7e2a771f708388619e0df | [
"self.log.info('login from Live')\ncode = context.get('code')\nif not code:\n return None\naccess_token = self.get_token(code)\nuser_info = self.get_user_info(access_token)\nname = user_info['name']\nemail = user_info['emails']['account']\nemail_list = [{'name': name, 'email': email, 'verified': 1, 'primary': 1}... | <|body_start_0|>
self.log.info('login from Live')
code = context.get('code')
if not code:
return None
access_token = self.get_token(code)
user_info = self.get_user_info(access_token)
name = user_info['name']
email = user_info['emails']['account']
... | Sign in with live :Example: from client.user.login import LiveLogin LiveLogin() .. notes:: | LiveLogin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LiveLogin:
"""Sign in with live :Example: from client.user.login import LiveLogin LiveLogin() .. notes::"""
def login(self, context):
"""live Login :type context: Context :param context: :rtype: dict :return: token and instance of user"""
<|body_0|>
def get_token(self, c... | stack_v2_sparse_classes_36k_train_006218 | 17,886 | permissive | [
{
"docstring": "live Login :type context: Context :param context: :rtype: dict :return: token and instance of user",
"name": "login",
"signature": "def login(self, context)"
},
{
"docstring": "Get live access token :type code: str :param code: :rtype: str :return: access token and uid",
"nam... | 3 | stack_v2_sparse_classes_30k_train_017865 | Implement the Python class `LiveLogin` described below.
Class description:
Sign in with live :Example: from client.user.login import LiveLogin LiveLogin() .. notes::
Method signatures and docstrings:
- def login(self, context): live Login :type context: Context :param context: :rtype: dict :return: token and instance... | Implement the Python class `LiveLogin` described below.
Class description:
Sign in with live :Example: from client.user.login import LiveLogin LiveLogin() .. notes::
Method signatures and docstrings:
- def login(self, context): live Login :type context: Context :param context: :rtype: dict :return: token and instance... | 945c4fd2755f5b0dea11e54eb649eeb37ec93d01 | <|skeleton|>
class LiveLogin:
"""Sign in with live :Example: from client.user.login import LiveLogin LiveLogin() .. notes::"""
def login(self, context):
"""live Login :type context: Context :param context: :rtype: dict :return: token and instance of user"""
<|body_0|>
def get_token(self, c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LiveLogin:
"""Sign in with live :Example: from client.user.login import LiveLogin LiveLogin() .. notes::"""
def login(self, context):
"""live Login :type context: Context :param context: :rtype: dict :return: token and instance of user"""
self.log.info('login from Live')
code = co... | the_stack_v2_python_sparse | open-hackathon-server/src/hackathon/user/oauth_login.py | kaiyuanshe/open-hackathon | train | 46 |
5ddda2eadf329514114ce23da5994ec001e53221 | [
"assert len(lCfgServos) == len(lMap) == 3, 'There should be 3 joints in a leg'\nself.lServos = lCfgServos[:]\nself.lMap = lMap[:]",
"lIK = ikLegPlane(sqrt(x ** 2 + y ** 2), -z, self.lServos[1], self.lServos[2])\nif not lIK:\n lAngles = (None,) * 3\nelse:\n lAngles = (None,) + lIK[0]\nreturn list(zip(self.lM... | <|body_start_0|>
assert len(lCfgServos) == len(lMap) == 3, 'There should be 3 joints in a leg'
self.lServos = lCfgServos[:]
self.lMap = lMap[:]
<|end_body_0|>
<|body_start_1|>
lIK = ikLegPlane(sqrt(x ** 2 + y ** 2), -z, self.lServos[1], self.lServos[2])
if not lIK:
l... | Leg | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Leg:
def __init__(self, lCfgServos, lMap):
"""lCfgServos is the list of the 3 servos in the leg: hip, femur, tibia lMap is the index of the 3 servos of lCfgServos in the array of servos (convenience)"""
<|body_0|>
def getIndexedAngles(self, x, y, z):
"""x: horizontal... | stack_v2_sparse_classes_36k_train_006219 | 4,789 | no_license | [
{
"docstring": "lCfgServos is the list of the 3 servos in the leg: hip, femur, tibia lMap is the index of the 3 servos of lCfgServos in the array of servos (convenience)",
"name": "__init__",
"signature": "def __init__(self, lCfgServos, lMap)"
},
{
"docstring": "x: horizontal outward the bot y: ... | 2 | stack_v2_sparse_classes_30k_train_012402 | Implement the Python class `Leg` described below.
Class description:
Implement the Leg class.
Method signatures and docstrings:
- def __init__(self, lCfgServos, lMap): lCfgServos is the list of the 3 servos in the leg: hip, femur, tibia lMap is the index of the 3 servos of lCfgServos in the array of servos (convenien... | Implement the Python class `Leg` described below.
Class description:
Implement the Leg class.
Method signatures and docstrings:
- def __init__(self, lCfgServos, lMap): lCfgServos is the list of the 3 servos in the leg: hip, femur, tibia lMap is the index of the 3 servos of lCfgServos in the array of servos (convenien... | 10b5327302b146ce3cd89722d47f42dfd112c5bb | <|skeleton|>
class Leg:
def __init__(self, lCfgServos, lMap):
"""lCfgServos is the list of the 3 servos in the leg: hip, femur, tibia lMap is the index of the 3 servos of lCfgServos in the array of servos (convenience)"""
<|body_0|>
def getIndexedAngles(self, x, y, z):
"""x: horizontal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Leg:
def __init__(self, lCfgServos, lMap):
"""lCfgServos is the list of the 3 servos in the leg: hip, femur, tibia lMap is the index of the 3 servos of lCfgServos in the array of servos (convenience)"""
assert len(lCfgServos) == len(lMap) == 3, 'There should be 3 joints in a leg'
self.... | the_stack_v2_python_sparse | hexapod/hexapod.py | Miaou/BBB | train | 1 | |
28cfe63e21c3b9c788d853e633271f2b80d35eea | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AutomaticRepliesMailTips()",
"from .date_time_time_zone import DateTimeTimeZone\nfrom .locale_info import LocaleInfo\nfrom .date_time_time_zone import DateTimeTimeZone\nfrom .locale_info import LocaleInfo\nfields: Dict[str, Callable[[A... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AutomaticRepliesMailTips()
<|end_body_0|>
<|body_start_1|>
from .date_time_time_zone import DateTimeTimeZone
from .locale_info import LocaleInfo
from .date_time_time_zone import ... | AutomaticRepliesMailTips | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutomaticRepliesMailTips:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AutomaticRepliesMailTips:
"""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 cre... | stack_v2_sparse_classes_36k_train_006220 | 3,738 | 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: AutomaticRepliesMailTips",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimi... | 3 | stack_v2_sparse_classes_30k_train_019867 | Implement the Python class `AutomaticRepliesMailTips` described below.
Class description:
Implement the AutomaticRepliesMailTips class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AutomaticRepliesMailTips: Creates a new instance of the appropriate c... | Implement the Python class `AutomaticRepliesMailTips` described below.
Class description:
Implement the AutomaticRepliesMailTips class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AutomaticRepliesMailTips: Creates a new instance of the appropriate c... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AutomaticRepliesMailTips:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AutomaticRepliesMailTips:
"""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 cre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutomaticRepliesMailTips:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AutomaticRepliesMailTips:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/automatic_replies_mail_tips.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
94883229724aacbea61658f4593af4227778749c | [
"self.nesterov = nesterov\nself.learning_rate = learning_rate\nself.momentum = momentum\nself.accumulated = None",
"worker_ids = list(dict_gradients.keys())\nif self.accumulated is None and self.momentum > 0:\n self.accumulated = []\n for index_layer in range(len(model.keras_model.get_weights())):\n ... | <|body_start_0|>
self.nesterov = nesterov
self.learning_rate = learning_rate
self.momentum = momentum
self.accumulated = None
<|end_body_0|>
<|body_start_1|>
worker_ids = list(dict_gradients.keys())
if self.accumulated is None and self.momentum > 0:
self.accu... | This class implements the Stocastic Gradient Descent optimization approach, run at Master node. It inherits from :class:`GradientOptimizer`. | SGD | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SGD:
"""This class implements the Stocastic Gradient Descent optimization approach, run at Master node. It inherits from :class:`GradientOptimizer`."""
def __init__(self, learning_rate, momentum=0, nesterov=False):
"""Create a :class:`SGD` instance. Parameters ---------- learning_rat... | stack_v2_sparse_classes_36k_train_006221 | 5,766 | permissive | [
{
"docstring": "Create a :class:`SGD` instance. Parameters ---------- learning_rate: float Learning rate for training. momentum: float Optimizer momentum. nesterov: boolean Flag indicating if the momentum optimizer is Nesterov or not.",
"name": "__init__",
"signature": "def __init__(self, learning_rate,... | 2 | stack_v2_sparse_classes_30k_train_014856 | Implement the Python class `SGD` described below.
Class description:
This class implements the Stocastic Gradient Descent optimization approach, run at Master node. It inherits from :class:`GradientOptimizer`.
Method signatures and docstrings:
- def __init__(self, learning_rate, momentum=0, nesterov=False): Create a ... | Implement the Python class `SGD` described below.
Class description:
This class implements the Stocastic Gradient Descent optimization approach, run at Master node. It inherits from :class:`GradientOptimizer`.
Method signatures and docstrings:
- def __init__(self, learning_rate, momentum=0, nesterov=False): Create a ... | ccc0a7674a04ae0d00bedc38893b33184c5f68c6 | <|skeleton|>
class SGD:
"""This class implements the Stocastic Gradient Descent optimization approach, run at Master node. It inherits from :class:`GradientOptimizer`."""
def __init__(self, learning_rate, momentum=0, nesterov=False):
"""Create a :class:`SGD` instance. Parameters ---------- learning_rat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SGD:
"""This class implements the Stocastic Gradient Descent optimization approach, run at Master node. It inherits from :class:`GradientOptimizer`."""
def __init__(self, learning_rate, momentum=0, nesterov=False):
"""Create a :class:`SGD` instance. Parameters ---------- learning_rate: float Lear... | the_stack_v2_python_sparse | MMLL/aggregators/aggregator.py | Musketeer-H2020/MMLL-Robust | train | 0 |
fe4dffe6027b94e6ed0890e24680a99cf1c53c7a | [
"if featurizer is not None and scoring_model is None or (featurizer is None and scoring_model is not None):\n raise ValueError('featurizer/scoring_model must both be set or must both be None.')\nself.base_dir = tempfile.mkdtemp()\nself.pose_generator = pose_generator\nself.featurizer = featurizer\nself.scoring_m... | <|body_start_0|>
if featurizer is not None and scoring_model is None or (featurizer is None and scoring_model is not None):
raise ValueError('featurizer/scoring_model must both be set or must both be None.')
self.base_dir = tempfile.mkdtemp()
self.pose_generator = pose_generator
... | A generic molecular docking class This class provides a docking engine which uses provided models for featurization, pose generation, and scoring. Most pieces of docking software are command line tools that are invoked from the shell. The goal of this class is to provide a python clean API for invoking molecular dockin... | Docker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Docker:
"""A generic molecular docking class This class provides a docking engine which uses provided models for featurization, pose generation, and scoring. Most pieces of docking software are command line tools that are invoked from the shell. The goal of this class is to provide a python clean... | stack_v2_sparse_classes_36k_train_006222 | 6,105 | permissive | [
{
"docstring": "Builds model. Parameters ---------- pose_generator: PoseGenerator The pose generator to use for this model featurizer: ComplexFeaturizer, optional (default None) Featurizer associated with `scoring_model` scoring_model: Model, optional (default None) Should make predictions on molecular complex.... | 2 | stack_v2_sparse_classes_30k_train_019766 | Implement the Python class `Docker` described below.
Class description:
A generic molecular docking class This class provides a docking engine which uses provided models for featurization, pose generation, and scoring. Most pieces of docking software are command line tools that are invoked from the shell. The goal of ... | Implement the Python class `Docker` described below.
Class description:
A generic molecular docking class This class provides a docking engine which uses provided models for featurization, pose generation, and scoring. Most pieces of docking software are command line tools that are invoked from the shell. The goal of ... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class Docker:
"""A generic molecular docking class This class provides a docking engine which uses provided models for featurization, pose generation, and scoring. Most pieces of docking software are command line tools that are invoked from the shell. The goal of this class is to provide a python clean... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Docker:
"""A generic molecular docking class This class provides a docking engine which uses provided models for featurization, pose generation, and scoring. Most pieces of docking software are command line tools that are invoked from the shell. The goal of this class is to provide a python clean API for invo... | the_stack_v2_python_sparse | deepchem/dock/docking.py | deepchem/deepchem | train | 4,876 |
4192c7eb5cf5d6b12824d203e00b1b7624b5eb5d | [
"elements = self.findElements(locator)\ngoods_titles = []\nfor good_element in elements:\n title = good_element.get_attribute(attribute)\n goods_titles.append(title)\nreturn goods_titles",
"goods_titles = self.get_goods_title(locator, attribute)\ngoods_locators = []\nfor title in goods_titles:\n loc = ('... | <|body_start_0|>
elements = self.findElements(locator)
goods_titles = []
for good_element in elements:
title = good_element.get_attribute(attribute)
goods_titles.append(title)
return goods_titles
<|end_body_0|>
<|body_start_1|>
goods_titles = self.get_goo... | GoodsList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoodsList:
def get_goods_title(self, locator, attribute):
"""获取商品列表的title :param locator: 元组--定位一组元素的定位器 :param attribute: 定位的元素中的属性 :return: goods_titles"""
<|body_0|>
def get_goods_loc(self, locator, attribute):
"""获取所有商品列表中所有商品的locator :param locator: 定位一组元素的定位器 :... | stack_v2_sparse_classes_36k_train_006223 | 3,622 | no_license | [
{
"docstring": "获取商品列表的title :param locator: 元组--定位一组元素的定位器 :param attribute: 定位的元素中的属性 :return: goods_titles",
"name": "get_goods_title",
"signature": "def get_goods_title(self, locator, attribute)"
},
{
"docstring": "获取所有商品列表中所有商品的locator :param locator: 定位一组元素的定位器 :param attribute: 定位的元素中的属性 ... | 4 | stack_v2_sparse_classes_30k_train_006184 | Implement the Python class `GoodsList` described below.
Class description:
Implement the GoodsList class.
Method signatures and docstrings:
- def get_goods_title(self, locator, attribute): 获取商品列表的title :param locator: 元组--定位一组元素的定位器 :param attribute: 定位的元素中的属性 :return: goods_titles
- def get_goods_loc(self, locator, ... | Implement the Python class `GoodsList` described below.
Class description:
Implement the GoodsList class.
Method signatures and docstrings:
- def get_goods_title(self, locator, attribute): 获取商品列表的title :param locator: 元组--定位一组元素的定位器 :param attribute: 定位的元素中的属性 :return: goods_titles
- def get_goods_loc(self, locator, ... | d66b111e6e75998742d0215a475c66e74d9510e0 | <|skeleton|>
class GoodsList:
def get_goods_title(self, locator, attribute):
"""获取商品列表的title :param locator: 元组--定位一组元素的定位器 :param attribute: 定位的元素中的属性 :return: goods_titles"""
<|body_0|>
def get_goods_loc(self, locator, attribute):
"""获取所有商品列表中所有商品的locator :param locator: 定位一组元素的定位器 :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoodsList:
def get_goods_title(self, locator, attribute):
"""获取商品列表的title :param locator: 元组--定位一组元素的定位器 :param attribute: 定位的元素中的属性 :return: goods_titles"""
elements = self.findElements(locator)
goods_titles = []
for good_element in elements:
title = good_element.g... | the_stack_v2_python_sparse | page/goods_list_bak.py | dxiaodong/test_web | train | 0 | |
07c4bd4e80ea842cae4f704604a523daefbd87ef | [
"super().__init__(env)\nassert hasattr(env, 'action_space'), 'The environment must specify an action space. https://www.gymlibrary.dev/content/environment_creation/'\ncheck_action_space(env.action_space)\nassert hasattr(env, 'observation_space'), 'The environment must specify an observation space. https://www.gymli... | <|body_start_0|>
super().__init__(env)
assert hasattr(env, 'action_space'), 'The environment must specify an action space. https://www.gymlibrary.dev/content/environment_creation/'
check_action_space(env.action_space)
assert hasattr(env, 'observation_space'), 'The environment must specif... | A passive environment checker wrapper that surrounds the step, reset and render functions to check they follow the gym API. | PassiveEnvChecker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PassiveEnvChecker:
"""A passive environment checker wrapper that surrounds the step, reset and render functions to check they follow the gym API."""
def __init__(self, env):
"""Initialises the wrapper with the environments, run the observation and action space tests."""
<|bod... | stack_v2_sparse_classes_36k_train_006224 | 2,306 | permissive | [
{
"docstring": "Initialises the wrapper with the environments, run the observation and action space tests.",
"name": "__init__",
"signature": "def __init__(self, env)"
},
{
"docstring": "Steps through the environment that on the first call will run the `passive_env_step_check`.",
"name": "st... | 4 | null | Implement the Python class `PassiveEnvChecker` described below.
Class description:
A passive environment checker wrapper that surrounds the step, reset and render functions to check they follow the gym API.
Method signatures and docstrings:
- def __init__(self, env): Initialises the wrapper with the environments, run... | Implement the Python class `PassiveEnvChecker` described below.
Class description:
A passive environment checker wrapper that surrounds the step, reset and render functions to check they follow the gym API.
Method signatures and docstrings:
- def __init__(self, env): Initialises the wrapper with the environments, run... | 53d784eafed28d31ec41c36ebd9eee14b0dc6d41 | <|skeleton|>
class PassiveEnvChecker:
"""A passive environment checker wrapper that surrounds the step, reset and render functions to check they follow the gym API."""
def __init__(self, env):
"""Initialises the wrapper with the environments, run the observation and action space tests."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PassiveEnvChecker:
"""A passive environment checker wrapper that surrounds the step, reset and render functions to check they follow the gym API."""
def __init__(self, env):
"""Initialises the wrapper with the environments, run the observation and action space tests."""
super().__init__(e... | the_stack_v2_python_sparse | gym/wrappers/env_checker.py | thomascherickal/gym | train | 2 |
56350e7c20912489efd336c60c14596482f91cb8 | [
"query = request.GET.get('query')\nbook_results = popular_books = []\nif query:\n book_results = book_search.search(query)[:5]\nif len(book_results) < 5:\n popular_books = models.Edition.objects.exclude(Q(parent_work__in=[b.parent_work for b in book_results])).annotate(Count('shelfbook')).order_by('-shelfbook... | <|body_start_0|>
query = request.GET.get('query')
book_results = popular_books = []
if query:
book_results = book_search.search(query)[:5]
if len(book_results) < 5:
popular_books = models.Edition.objects.exclude(Q(parent_work__in=[b.parent_work for b in book_resul... | name a book, any book, we gotta start somewhere | GetStartedBooks | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetStartedBooks:
"""name a book, any book, we gotta start somewhere"""
def get(self, request):
"""info about a book"""
<|body_0|>
def post(self, request):
"""shelve some books"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
query = request.GET.g... | stack_v2_sparse_classes_36k_train_006225 | 4,117 | no_license | [
{
"docstring": "info about a book",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "shelve some books",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `GetStartedBooks` described below.
Class description:
name a book, any book, we gotta start somewhere
Method signatures and docstrings:
- def get(self, request): info about a book
- def post(self, request): shelve some books | Implement the Python class `GetStartedBooks` described below.
Class description:
name a book, any book, we gotta start somewhere
Method signatures and docstrings:
- def get(self, request): info about a book
- def post(self, request): shelve some books
<|skeleton|>
class GetStartedBooks:
"""name a book, any book,... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class GetStartedBooks:
"""name a book, any book, we gotta start somewhere"""
def get(self, request):
"""info about a book"""
<|body_0|>
def post(self, request):
"""shelve some books"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetStartedBooks:
"""name a book, any book, we gotta start somewhere"""
def get(self, request):
"""info about a book"""
query = request.GET.get('query')
book_results = popular_books = []
if query:
book_results = book_search.search(query)[:5]
if len(book_... | the_stack_v2_python_sparse | bookwyrm/views/get_started.py | bookwyrm-social/bookwyrm | train | 1,398 |
2159e44606e17e840b13b4532e15ac1a98a46e66 | [
"response = cache.get('class_resource {} {} {} {} new'.format(semester, year, abbreviation, course_number))\nif response:\n print('Cache hit in class resource')\n return response\nresponse = self._request(semester=semester, year=year, abbreviation=abbreviation, course_number=course_number)\ncache.set('class_r... | <|body_start_0|>
response = cache.get('class_resource {} {} {} {} new'.format(semester, year, abbreviation, course_number))
if response:
print('Cache hit in class resource')
return response
response = self._request(semester=semester, year=year, abbreviation=abbreviation, ... | Interface with SIS Class API. | SISClassResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SISClassResource:
"""Interface with SIS Class API."""
def get(self, semester, year, course_id, abbreviation, course_number, log=False):
"""Fetch (cached) SIS Class API response."""
<|body_0|>
def _request(self, semester, year, abbreviation, course_number):
"""Fet... | stack_v2_sparse_classes_36k_train_006226 | 2,751 | permissive | [
{
"docstring": "Fetch (cached) SIS Class API response.",
"name": "get",
"signature": "def get(self, semester, year, course_id, abbreviation, course_number, log=False)"
},
{
"docstring": "Fetch SIS Class API response. Docs: https://api-central.berkeley.edu/api/45/interactive-docs",
"name": "_... | 2 | stack_v2_sparse_classes_30k_test_000943 | Implement the Python class `SISClassResource` described below.
Class description:
Interface with SIS Class API.
Method signatures and docstrings:
- def get(self, semester, year, course_id, abbreviation, course_number, log=False): Fetch (cached) SIS Class API response.
- def _request(self, semester, year, abbreviation... | Implement the Python class `SISClassResource` described below.
Class description:
Interface with SIS Class API.
Method signatures and docstrings:
- def get(self, semester, year, course_id, abbreviation, course_number, log=False): Fetch (cached) SIS Class API response.
- def _request(self, semester, year, abbreviation... | 34578dc14c8e5c2cfb28f8d6710e791cdd773d59 | <|skeleton|>
class SISClassResource:
"""Interface with SIS Class API."""
def get(self, semester, year, course_id, abbreviation, course_number, log=False):
"""Fetch (cached) SIS Class API response."""
<|body_0|>
def _request(self, semester, year, abbreviation, course_number):
"""Fet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SISClassResource:
"""Interface with SIS Class API."""
def get(self, semester, year, course_id, abbreviation, course_number, log=False):
"""Fetch (cached) SIS Class API response."""
response = cache.get('class_resource {} {} {} {} new'.format(semester, year, abbreviation, course_number))
... | the_stack_v2_python_sparse | backend/catalog/resource/sis_class.py | AviFS/berkeleytime | train | 0 |
b912b6c10818fd94deaf560322ffe25073772f4b | [
"super(ConfigurationContext, self).__init__(**kw)\nself.hash = OPTION_CONTEXT.hash\nself.files = OPTION_CONTEXT.files[:]",
"super(ConfigurationContext, self).execute()\nself.store_options()\nif Options.options.tidy == 'force' or (Options.options.tidy == 'auto' and Options.options.compilers == [] and (Options.opti... | <|body_start_0|>
super(ConfigurationContext, self).__init__(**kw)
self.hash = OPTION_CONTEXT.hash
self.files = OPTION_CONTEXT.files[:]
<|end_body_0|>
<|body_start_1|>
super(ConfigurationContext, self).execute()
self.store_options()
if Options.options.tidy == 'force' or (... | ConfigurationContext subclass, which allows to store the current environment used for configure so it can be restored during a reconfigure. | ConfigurationContext | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigurationContext:
"""ConfigurationContext subclass, which allows to store the current environment used for configure so it can be restored during a reconfigure."""
def __init__(self, **kw):
"""main init"""
<|body_0|>
def execute(self):
"""Executes the configu... | stack_v2_sparse_classes_36k_train_006227 | 16,259 | permissive | [
{
"docstring": "main init",
"name": "__init__",
"signature": "def __init__(self, **kw)"
},
{
"docstring": "Executes the configuration, then stores the current status that can be checked during the reconfiguration step",
"name": "execute",
"signature": "def execute(self)"
},
{
"do... | 4 | null | Implement the Python class `ConfigurationContext` described below.
Class description:
ConfigurationContext subclass, which allows to store the current environment used for configure so it can be restored during a reconfigure.
Method signatures and docstrings:
- def __init__(self, **kw): main init
- def execute(self):... | Implement the Python class `ConfigurationContext` described below.
Class description:
ConfigurationContext subclass, which allows to store the current environment used for configure so it can be restored during a reconfigure.
Method signatures and docstrings:
- def __init__(self, **kw): main init
- def execute(self):... | 1b3831d494ee06b0bd74a8227c939dd774b91226 | <|skeleton|>
class ConfigurationContext:
"""ConfigurationContext subclass, which allows to store the current environment used for configure so it can be restored during a reconfigure."""
def __init__(self, **kw):
"""main init"""
<|body_0|>
def execute(self):
"""Executes the configu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigurationContext:
"""ConfigurationContext subclass, which allows to store the current environment used for configure so it can be restored during a reconfigure."""
def __init__(self, **kw):
"""main init"""
super(ConfigurationContext, self).__init__(**kw)
self.hash = OPTION_CON... | the_stack_v2_python_sparse | mak/build_framework/options/commands.py | bugengine/BugEngine | train | 4 |
98f6110626e9a95ea5fb2398c0896f733570f358 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Origin Groups management service. | OriginGroupServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OriginGroupServiceServicer:
"""Origin Groups management service."""
def Get(self, request, context):
"""Gets origin group with specified origin group id."""
<|body_0|>
def List(self, request, context):
"""Lists origins of origin group."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_006228 | 10,369 | permissive | [
{
"docstring": "Gets origin group with specified origin group id.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Lists origins of origin group.",
"name": "List",
"signature": "def List(self, request, context)"
},
{
"docstring": "Creates origin ... | 5 | null | Implement the Python class `OriginGroupServiceServicer` described below.
Class description:
Origin Groups management service.
Method signatures and docstrings:
- def Get(self, request, context): Gets origin group with specified origin group id.
- def List(self, request, context): Lists origins of origin group.
- def ... | Implement the Python class `OriginGroupServiceServicer` described below.
Class description:
Origin Groups management service.
Method signatures and docstrings:
- def Get(self, request, context): Gets origin group with specified origin group id.
- def List(self, request, context): Lists origins of origin group.
- def ... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class OriginGroupServiceServicer:
"""Origin Groups management service."""
def Get(self, request, context):
"""Gets origin group with specified origin group id."""
<|body_0|>
def List(self, request, context):
"""Lists origins of origin group."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OriginGroupServiceServicer:
"""Origin Groups management service."""
def Get(self, request, context):
"""Gets origin group with specified origin group id."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedE... | the_stack_v2_python_sparse | yandex/cloud/cdn/v1/origin_group_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
1b6fc78f538268ebf731cebc48ca5c2304f56234 | [
"if not root:\n return\nlst = []\nself.dfs_traverse(root, lst)\nlst = lst[1:]\nroot.left = None\ncur = root\nfor node in lst:\n node.left = None\n node.right = None\n cur.right = node\n cur = cur.right",
"if not root:\n return\nlst.append(root)\nself.dfs_traverse(root.left, lst)\nself.dfs_traver... | <|body_start_0|>
if not root:
return
lst = []
self.dfs_traverse(root, lst)
lst = lst[1:]
root.left = None
cur = root
for node in lst:
node.left = None
node.right = None
cur.right = node
cur = cur.right
<|... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten_data_structure(self, root):
""":param root: TreeNode :return: nothing, do it in place"""
<|body_0|>
def dfs_traverse(self, root, lst):
"""pre_order traverse"""
<|body_1|>
def flatten(self, root):
"""pre-order should be easy ... | stack_v2_sparse_classes_36k_train_006229 | 2,826 | permissive | [
{
"docstring": ":param root: TreeNode :return: nothing, do it in place",
"name": "flatten_data_structure",
"signature": "def flatten_data_structure(self, root)"
},
{
"docstring": "pre_order traverse",
"name": "dfs_traverse",
"signature": "def dfs_traverse(self, root, lst)"
},
{
"... | 4 | stack_v2_sparse_classes_30k_train_008309 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten_data_structure(self, root): :param root: TreeNode :return: nothing, do it in place
- def dfs_traverse(self, root, lst): pre_order traverse
- def flatten(self, root): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten_data_structure(self, root): :param root: TreeNode :return: nothing, do it in place
- def dfs_traverse(self, root, lst): pre_order traverse
- def flatten(self, root): ... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def flatten_data_structure(self, root):
""":param root: TreeNode :return: nothing, do it in place"""
<|body_0|>
def dfs_traverse(self, root, lst):
"""pre_order traverse"""
<|body_1|>
def flatten(self, root):
"""pre-order should be easy ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten_data_structure(self, root):
""":param root: TreeNode :return: nothing, do it in place"""
if not root:
return
lst = []
self.dfs_traverse(root, lst)
lst = lst[1:]
root.left = None
cur = root
for node in lst:
... | the_stack_v2_python_sparse | 114 Flatten Binary Tree to Linked List.py | Aminaba123/LeetCode | train | 1 | |
cfe285216ca51335a5f1f6ec561afcdb71c7197b | [
"self._plots = 0\nself._filename = filename\nself._x_label = x_label\nself._record_label = record_label\nself._order_by = order_by\nself._heat_map_value = heat_map_value\nself._heat_map_label = heat_map_label\nselector.select = self._update_counter(selector.select)",
"@wraps(select)\ndef inner(population, *args, ... | <|body_start_0|>
self._plots = 0
self._filename = filename
self._x_label = x_label
self._record_label = record_label
self._order_by = order_by
self._heat_map_value = heat_map_value
self._heat_map_label = heat_map_label
selector.select = self._update_counte... | Plots which molecule records a :class:`.Selector` selects. Examples -------- *Plotting Which Molecule Records Got Selected* .. testcode:: plotting-which-molecule-records-got-selected import stk # Make a selector. roulette = stk.Roulette(num_batches=10) # Make a population. population = tuple( stk.MoleculeRecord( topolo... | SelectionPlotter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelectionPlotter:
"""Plots which molecule records a :class:`.Selector` selects. Examples -------- *Plotting Which Molecule Records Got Selected* .. testcode:: plotting-which-molecule-records-got-selected import stk # Make a selector. roulette = stk.Roulette(num_batches=10) # Make a population. po... | stack_v2_sparse_classes_36k_train_006230 | 7,598 | permissive | [
{
"docstring": "Initialize a :class:`.SelectionPlotter` instance. Parameters ---------- filename : :class:`str` The basename of the files. This means it should not include file extensions. selector : :class:`.Selector` The :class:`.Selector` whose selection of molecule records is plotted. x_label : :class:`str`... | 3 | null | Implement the Python class `SelectionPlotter` described below.
Class description:
Plots which molecule records a :class:`.Selector` selects. Examples -------- *Plotting Which Molecule Records Got Selected* .. testcode:: plotting-which-molecule-records-got-selected import stk # Make a selector. roulette = stk.Roulette(... | Implement the Python class `SelectionPlotter` described below.
Class description:
Plots which molecule records a :class:`.Selector` selects. Examples -------- *Plotting Which Molecule Records Got Selected* .. testcode:: plotting-which-molecule-records-got-selected import stk # Make a selector. roulette = stk.Roulette(... | 46f70cd000890ca7c2312cc0fdbab306565f1400 | <|skeleton|>
class SelectionPlotter:
"""Plots which molecule records a :class:`.Selector` selects. Examples -------- *Plotting Which Molecule Records Got Selected* .. testcode:: plotting-which-molecule-records-got-selected import stk # Make a selector. roulette = stk.Roulette(num_batches=10) # Make a population. po... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelectionPlotter:
"""Plots which molecule records a :class:`.Selector` selects. Examples -------- *Plotting Which Molecule Records Got Selected* .. testcode:: plotting-which-molecule-records-got-selected import stk # Make a selector. roulette = stk.Roulette(num_batches=10) # Make a population. population = tu... | the_stack_v2_python_sparse | src/stk/ea/plotters/selection.py | supramolecular-toolkit/stk | train | 22 |
4706d237d2ee0175b52db1317cea8ac003768a34 | [
"predLog = np.nan_to_num(-np.log(a))\ncEntropyMat = np.multiply(y, predLog)\nreturn 1.0 / self.nExamples * np.sum(cEntropyMat)",
"if self.endNode:\n grad = np.ones(self.inputA.shape)\nelse:\n grad = np.zeros(self.inputA.shape)\n for out in self.outputs:\n grad += out.getGradient(self)\nreturn grad... | <|body_start_0|>
predLog = np.nan_to_num(-np.log(a))
cEntropyMat = np.multiply(y, predLog)
return 1.0 / self.nExamples * np.sum(cEntropyMat)
<|end_body_0|>
<|body_start_1|>
if self.endNode:
grad = np.ones(self.inputA.shape)
else:
grad = np.zeros(self.inpu... | Evaliate the CrossEntropy cost given the labels, works with softmax activation ONLY CrossEntropyCostSoftmax(self, inputA, labels) Attributes ---------- name : str Name of the operation result : np.array Output of the operation testing : bool Flag specifying if the operation is in testing (making prefictions: True) or t... | CrossEntropyCostSoftmax | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossEntropyCostSoftmax:
"""Evaliate the CrossEntropy cost given the labels, works with softmax activation ONLY CrossEntropyCostSoftmax(self, inputA, labels) Attributes ---------- name : str Name of the operation result : np.array Output of the operation testing : bool Flag specifying if the oper... | stack_v2_sparse_classes_36k_train_006231 | 3,898 | permissive | [
{
"docstring": "Perform costOperation Parameters ---------- a : np.array Predictions y : np.array Data labels Returns ------- np.array Output data",
"name": "perform",
"signature": "def perform(self, a, y)"
},
{
"docstring": "Find out the gradient with respect to the parameter Parameters -------... | 2 | stack_v2_sparse_classes_30k_test_001191 | Implement the Python class `CrossEntropyCostSoftmax` described below.
Class description:
Evaliate the CrossEntropy cost given the labels, works with softmax activation ONLY CrossEntropyCostSoftmax(self, inputA, labels) Attributes ---------- name : str Name of the operation result : np.array Output of the operation tes... | Implement the Python class `CrossEntropyCostSoftmax` described below.
Class description:
Evaliate the CrossEntropy cost given the labels, works with softmax activation ONLY CrossEntropyCostSoftmax(self, inputA, labels) Attributes ---------- name : str Name of the operation result : np.array Output of the operation tes... | ec8488444b44d0bd54498bf917ee42d821643ee8 | <|skeleton|>
class CrossEntropyCostSoftmax:
"""Evaliate the CrossEntropy cost given the labels, works with softmax activation ONLY CrossEntropyCostSoftmax(self, inputA, labels) Attributes ---------- name : str Name of the operation result : np.array Output of the operation testing : bool Flag specifying if the oper... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrossEntropyCostSoftmax:
"""Evaliate the CrossEntropy cost given the labels, works with softmax activation ONLY CrossEntropyCostSoftmax(self, inputA, labels) Attributes ---------- name : str Name of the operation result : np.array Output of the operation testing : bool Flag specifying if the operation is in t... | the_stack_v2_python_sparse | graphAttack/operations/costOperations.py | Houkime/graphAttack | train | 0 |
d950d9748cdc9bce2d11c273d50eb8e09539f5ce | [
"min_len = float('inf')\nfor i in range(len(nums)):\n cur_sum = 0\n for j in range(i, len(nums)):\n cur_sum += nums[j]\n if cur_sum >= target:\n min_len = min(min_len, j - i + 1)\n break\nreturn min_len if min_len != float('inf') else 0",
"i = 0\ncur_sum = 0\nmin_len = fl... | <|body_start_0|>
min_len = float('inf')
for i in range(len(nums)):
cur_sum = 0
for j in range(i, len(nums)):
cur_sum += nums[j]
if cur_sum >= target:
min_len = min(min_len, j - i + 1)
break
return min... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
"""暴力破解法 两个for循环 i表示开始位置,j表示结束位置"""
<|body_0|>
def minSubArrayLen_2(self, target: int, nums: List[int]) -> int:
"""双指针法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
min_len ... | stack_v2_sparse_classes_36k_train_006232 | 1,699 | no_license | [
{
"docstring": "暴力破解法 两个for循环 i表示开始位置,j表示结束位置",
"name": "minSubArrayLen",
"signature": "def minSubArrayLen(self, target: int, nums: List[int]) -> int"
},
{
"docstring": "双指针法",
"name": "minSubArrayLen_2",
"signature": "def minSubArrayLen_2(self, target: int, nums: List[int]) -> int"
}
... | 2 | stack_v2_sparse_classes_30k_test_000539 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen(self, target: int, nums: List[int]) -> int: 暴力破解法 两个for循环 i表示开始位置,j表示结束位置
- def minSubArrayLen_2(self, target: int, nums: List[int]) -> int: 双指针法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen(self, target: int, nums: List[int]) -> int: 暴力破解法 两个for循环 i表示开始位置,j表示结束位置
- def minSubArrayLen_2(self, target: int, nums: List[int]) -> int: 双指针法
<|skeleton|>... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
"""暴力破解法 两个for循环 i表示开始位置,j表示结束位置"""
<|body_0|>
def minSubArrayLen_2(self, target: int, nums: List[int]) -> int:
"""双指针法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
"""暴力破解法 两个for循环 i表示开始位置,j表示结束位置"""
min_len = float('inf')
for i in range(len(nums)):
cur_sum = 0
for j in range(i, len(nums)):
cur_sum += nums[j]
if cur_sum... | the_stack_v2_python_sparse | code_thinking/arrays/209_minimum_size_subarray_sum.py | EachenKuang/LeetCode | train | 28 | |
92b013fdaf0b39ed548772e0e42e10461c0a196f | [
"record = None\nattachmentsDao = AttachmentsDao()\nid = request.uid\nrecord = attachmentsDao.getById(id)\nreturn record",
"attachments = None\nattachmentsDao = AttachmentsDao()\ntry:\n attachments = attachmentsDao.add(args)\nexcept Exception as e:\n abort(500, e)\nreturn attachments",
"result = False\nids... | <|body_start_0|>
record = None
attachmentsDao = AttachmentsDao()
id = request.uid
record = attachmentsDao.getById(id)
return record
<|end_body_0|>
<|body_start_1|>
attachments = None
attachmentsDao = AttachmentsDao()
try:
attachments = attachm... | attachments module resource main service: add/delete/edit/view | AttachmentsAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttachmentsAPI:
"""attachments module resource main service: add/delete/edit/view"""
def get(self, args):
"""view"""
<|body_0|>
def post(self, args):
"""add"""
<|body_1|>
def delete(self, args):
"""delete"""
<|body_2|>
def put(se... | stack_v2_sparse_classes_36k_train_006233 | 8,558 | permissive | [
{
"docstring": "view",
"name": "get",
"signature": "def get(self, args)"
},
{
"docstring": "add",
"name": "post",
"signature": "def post(self, args)"
},
{
"docstring": "delete",
"name": "delete",
"signature": "def delete(self, args)"
},
{
"docstring": "edit",
... | 4 | null | Implement the Python class `AttachmentsAPI` described below.
Class description:
attachments module resource main service: add/delete/edit/view
Method signatures and docstrings:
- def get(self, args): view
- def post(self, args): add
- def delete(self, args): delete
- def put(self, args): edit | Implement the Python class `AttachmentsAPI` described below.
Class description:
attachments module resource main service: add/delete/edit/view
Method signatures and docstrings:
- def get(self, args): view
- def post(self, args): add
- def delete(self, args): delete
- def put(self, args): edit
<|skeleton|>
class Atta... | 0fb1b604185a8bd8b72c1d2d527fb94bbaf46a86 | <|skeleton|>
class AttachmentsAPI:
"""attachments module resource main service: add/delete/edit/view"""
def get(self, args):
"""view"""
<|body_0|>
def post(self, args):
"""add"""
<|body_1|>
def delete(self, args):
"""delete"""
<|body_2|>
def put(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttachmentsAPI:
"""attachments module resource main service: add/delete/edit/view"""
def get(self, args):
"""view"""
record = None
attachmentsDao = AttachmentsDao()
id = request.uid
record = attachmentsDao.getById(id)
return record
def post(self, args)... | the_stack_v2_python_sparse | app/modules/attachments/resource.py | daitouli/baoaiback | train | 0 |
bfc1228fbd81ebe4c9fd4a2582d533067dc879d2 | [
"if not nums:\n return\nfor i in range(1, len(nums)):\n if nums[i - 1] > nums[i]:\n return i - 1\nreturn len(nums) - 1",
"if not nums:\n return\nreturn self.search(nums, 0, len(nums) - 1)",
"if l == r:\n return l\nmid = (l + r) // 2\nif nums[mid] > nums[mid + 1]:\n return self.search(nums,... | <|body_start_0|>
if not nums:
return
for i in range(1, len(nums)):
if nums[i - 1] > nums[i]:
return i - 1
return len(nums) - 1
<|end_body_0|>
<|body_start_1|>
if not nums:
return
return self.search(nums, 0, len(nums) - 1)
<|end... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findPeakElement_1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def search(self, nums, l, r):
""":type nums: List[int] :type l, r:... | stack_v2_sparse_classes_36k_train_006234 | 2,735 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findPeakElement",
"signature": "def findPeakElement(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findPeakElement_1",
"signature": "def findPeakElement_1(self, nums)"
},
{
"docstring": ":t... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPeakElement(self, nums): :type nums: List[int] :rtype: int
- def findPeakElement_1(self, nums): :type nums: List[int] :rtype: int
- def search(self, nums, l, r): :type nu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPeakElement(self, nums): :type nums: List[int] :rtype: int
- def findPeakElement_1(self, nums): :type nums: List[int] :rtype: int
- def search(self, nums, l, r): :type nu... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findPeakElement_1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def search(self, nums, l, r):
""":type nums: List[int] :type l, r:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return
for i in range(1, len(nums)):
if nums[i - 1] > nums[i]:
return i - 1
return len(nums) - 1
def findPeakElement_1(self, nums):
... | the_stack_v2_python_sparse | Solutions/0162_findPeakElement.py | YoupengLi/leetcode-sorting | train | 3 | |
8920ecfd443ead81f77ca84c73a87e410a21e397 | [
"if isinstance(values, dict):\n self.validate_acl_data(values)\n email_names = self.parse_sync_service_acl(values)\n from ggrc.utils import user_generator as ug\n existing_people = {p.email: p for p in ug.load_people_with_emails(email_names)}\n absent_emails = set(email_names) - set(existing_people)\... | <|body_start_0|>
if isinstance(values, dict):
self.validate_acl_data(values)
email_names = self.parse_sync_service_acl(values)
from ggrc.utils import user_generator as ug
existing_people = {p.email: p for p in ug.load_people_with_emails(email_names)}
a... | Overrided Roleable mixin for Synchronizable models. It replace access_control_list setter to allow set ACL data in sync service format. | RoleableSynchronizable | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleableSynchronizable:
"""Overrided Roleable mixin for Synchronizable models. It replace access_control_list setter to allow set ACL data in sync service format."""
def access_control_list(self, values):
"""Setter function for access control list. Args: values: List of access contro... | stack_v2_sparse_classes_36k_train_006235 | 5,365 | permissive | [
{
"docstring": "Setter function for access control list. Args: values: List of access control roles or dicts containing json representation of custom attribute values.",
"name": "access_control_list",
"signature": "def access_control_list(self, values)"
},
{
"docstring": "Check if received data ... | 4 | stack_v2_sparse_classes_30k_train_020075 | Implement the Python class `RoleableSynchronizable` described below.
Class description:
Overrided Roleable mixin for Synchronizable models. It replace access_control_list setter to allow set ACL data in sync service format.
Method signatures and docstrings:
- def access_control_list(self, values): Setter function for... | Implement the Python class `RoleableSynchronizable` described below.
Class description:
Overrided Roleable mixin for Synchronizable models. It replace access_control_list setter to allow set ACL data in sync service format.
Method signatures and docstrings:
- def access_control_list(self, values): Setter function for... | f99bfdaa11ad30643d7bc9af67bd84436d298cfa | <|skeleton|>
class RoleableSynchronizable:
"""Overrided Roleable mixin for Synchronizable models. It replace access_control_list setter to allow set ACL data in sync service format."""
def access_control_list(self, values):
"""Setter function for access control list. Args: values: List of access contro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleableSynchronizable:
"""Overrided Roleable mixin for Synchronizable models. It replace access_control_list setter to allow set ACL data in sync service format."""
def access_control_list(self, values):
"""Setter function for access control list. Args: values: List of access control roles or di... | the_stack_v2_python_sparse | src/ggrc/models/mixins/synchronizable.py | pavelglebov/ggrc-core | train | 1 |
abee5b7ce469825ae16fb8fa2002ee71659ee035 | [
"self.policy = policy\nself.base_rate = base_rate\nself.gamma = gamma\nself.power = power\nself.max_steps = max_steps\nself.step_values = step_values\nif self.step_values:\n self.stepvalues_list = map(float, step_values.split(','))\nelse:\n self.stepvalues_list = []\nif self.max_steps < len(self.stepvalues_li... | <|body_start_0|>
self.policy = policy
self.base_rate = base_rate
self.gamma = gamma
self.power = power
self.max_steps = max_steps
self.step_values = step_values
if self.step_values:
self.stepvalues_list = map(float, step_values.split(','))
else... | This class contains details of learning rate policies that are used in caffe. Calculates and returns the current learning rate. The currently implemented learning rate policies are as follows: - fixed: always return base_lr. - step: return base_lr * gamma ^ (floor(iter / step)) - exp: return base_lr * gamma ^ iter - in... | LRPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRPolicy:
"""This class contains details of learning rate policies that are used in caffe. Calculates and returns the current learning rate. The currently implemented learning rate policies are as follows: - fixed: always return base_lr. - step: return base_lr * gamma ^ (floor(iter / step)) - exp... | stack_v2_sparse_classes_36k_train_006236 | 6,721 | permissive | [
{
"docstring": "Initialize a learning rate policy Args: policy: Learning rate policy base_rate: Base learning rate gamma: parameter to compute learning rate power: parameter to compute learning rate max_steps: parameter to compute learning rate step_values: parameter(s) to compute learning rate. should be a str... | 2 | stack_v2_sparse_classes_30k_train_008922 | Implement the Python class `LRPolicy` described below.
Class description:
This class contains details of learning rate policies that are used in caffe. Calculates and returns the current learning rate. The currently implemented learning rate policies are as follows: - fixed: always return base_lr. - step: return base_... | Implement the Python class `LRPolicy` described below.
Class description:
This class contains details of learning rate policies that are used in caffe. Calculates and returns the current learning rate. The currently implemented learning rate policies are as follows: - fixed: always return base_lr. - step: return base_... | ad44695a459adc389a886ec72ca92ae190b0d30a | <|skeleton|>
class LRPolicy:
"""This class contains details of learning rate policies that are used in caffe. Calculates and returns the current learning rate. The currently implemented learning rate policies are as follows: - fixed: always return base_lr. - step: return base_lr * gamma ^ (floor(iter / step)) - exp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRPolicy:
"""This class contains details of learning rate policies that are used in caffe. Calculates and returns the current learning rate. The currently implemented learning rate policies are as follows: - fixed: always return base_lr. - step: return base_lr * gamma ^ (floor(iter / step)) - exp: return base... | the_stack_v2_python_sparse | deepstacks/utils/lr_policy.py | guoxuesong/deepstacks | train | 2 |
8155f8ec1eb3fc1ba26bbf257529659022ee2c37 | [
"langCode = {'arabic': 'ar', 'bengali': 'bn', 'bulgarian': 'bg', 'chinese': 'zh-CN', 'croatian': 'hr', 'czech': 'cs', 'danish': 'da', 'dutch': 'nl', 'english': 'en', 'finnish': 'fi', 'french': 'fr', 'german': 'de', 'greek': 'el', 'gujarati': 'gu', 'hindi': 'hi', 'italian': 'it', 'japanese': 'ja', 'korean': 'ko', 'n... | <|body_start_0|>
langCode = {'arabic': 'ar', 'bengali': 'bn', 'bulgarian': 'bg', 'chinese': 'zh-CN', 'croatian': 'hr', 'czech': 'cs', 'danish': 'da', 'dutch': 'nl', 'english': 'en', 'finnish': 'fi', 'french': 'fr', 'german': 'de', 'greek': 'el', 'gujarati': 'gu', 'hindi': 'hi', 'italian': 'it', 'japanese': 'ja'... | This class uses the Beautiful Soup library to scrape the information from the HTML source code from Google Translate. It also offers a way to consume the AJAX result of the translation, however encoding on Windows won't work well right now so it's recommended to use the scraping method. | translator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class translator:
"""This class uses the Beautiful Soup library to scrape the information from the HTML source code from Google Translate. It also offers a way to consume the AJAX result of the translation, however encoding on Windows won't work well right now so it's recommended to use the scraping me... | stack_v2_sparse_classes_36k_train_006237 | 3,559 | no_license | [
{
"docstring": "Returns translated text that is scraped from Google Translate's HTML source code.",
"name": "fromHtml",
"signature": "def fromHtml(self, text, languageFrom, languageTo)"
},
{
"docstring": "Returns a simple string translating the text from \"languageFrom\" to \"LanguageTo\" using ... | 2 | null | Implement the Python class `translator` described below.
Class description:
This class uses the Beautiful Soup library to scrape the information from the HTML source code from Google Translate. It also offers a way to consume the AJAX result of the translation, however encoding on Windows won't work well right now so ... | Implement the Python class `translator` described below.
Class description:
This class uses the Beautiful Soup library to scrape the information from the HTML source code from Google Translate. It also offers a way to consume the AJAX result of the translation, however encoding on Windows won't work well right now so ... | 0d653cb9659fe750cf676a70035ab67176179905 | <|skeleton|>
class translator:
"""This class uses the Beautiful Soup library to scrape the information from the HTML source code from Google Translate. It also offers a way to consume the AJAX result of the translation, however encoding on Windows won't work well right now so it's recommended to use the scraping me... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class translator:
"""This class uses the Beautiful Soup library to scrape the information from the HTML source code from Google Translate. It also offers a way to consume the AJAX result of the translation, however encoding on Windows won't work well right now so it's recommended to use the scraping method."""
... | the_stack_v2_python_sparse | python_exercises/18Practice/translator2.py | vineel2014/Pythonfiles | train | 1 |
04e78601b28c15f759f2235e7fbf545436aeed28 | [
"self.redis = None\nif isinstance(cid, TaskClassification):\n self.classification = cid\nelse:\n self.classification = self.get_classification_model(cid)",
"if cid == '' or cid is None:\n return None\nclassification = TaskClassification.objects.get_once(pk=cid)\nif classification is None:\n raise Task... | <|body_start_0|>
self.redis = None
if isinstance(cid, TaskClassification):
self.classification = cid
else:
self.classification = self.get_classification_model(cid)
<|end_body_0|>
<|body_start_1|>
if cid == '' or cid is None:
return None
classi... | TaskClassificationLogic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskClassificationLogic:
def __init__(self, auth, cid):
"""INIT :param auth: :param cid:"""
<|body_0|>
def get_classification_model(self, cid):
"""获取分类 :param cid: :return:"""
<|body_1|>
def get_classification_info(self):
"""获取分类信息 :return:"""
... | stack_v2_sparse_classes_36k_train_006238 | 3,246 | no_license | [
{
"docstring": "INIT :param auth: :param cid:",
"name": "__init__",
"signature": "def __init__(self, auth, cid)"
},
{
"docstring": "获取分类 :param cid: :return:",
"name": "get_classification_model",
"signature": "def get_classification_model(self, cid)"
},
{
"docstring": "获取分类信息 :re... | 5 | stack_v2_sparse_classes_30k_train_005724 | Implement the Python class `TaskClassificationLogic` described below.
Class description:
Implement the TaskClassificationLogic class.
Method signatures and docstrings:
- def __init__(self, auth, cid): INIT :param auth: :param cid:
- def get_classification_model(self, cid): 获取分类 :param cid: :return:
- def get_classifi... | Implement the Python class `TaskClassificationLogic` described below.
Class description:
Implement the TaskClassificationLogic class.
Method signatures and docstrings:
- def __init__(self, auth, cid): INIT :param auth: :param cid:
- def get_classification_model(self, cid): 获取分类 :param cid: :return:
- def get_classifi... | 7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b | <|skeleton|>
class TaskClassificationLogic:
def __init__(self, auth, cid):
"""INIT :param auth: :param cid:"""
<|body_0|>
def get_classification_model(self, cid):
"""获取分类 :param cid: :return:"""
<|body_1|>
def get_classification_info(self):
"""获取分类信息 :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskClassificationLogic:
def __init__(self, auth, cid):
"""INIT :param auth: :param cid:"""
self.redis = None
if isinstance(cid, TaskClassification):
self.classification = cid
else:
self.classification = self.get_classification_model(cid)
def get_cl... | the_stack_v2_python_sparse | FireHydrant/server/task/logics/classification.py | shoogoome/FireHydrant | train | 4 | |
fd4c9014ccb1d9084554c9d439d882b10a43f6a6 | [
"my_grid = grid_setup(self.rp, ng=4)\nmy_data = patch.CellCenterData2d(my_grid)\nbc = bc_setup(self.rp)[0]\nmy_data.register_var('density', bc)\nmy_data.create()\nself.cc_data = my_data\nif self.rp.get_param('particles.do_particles') == 1:\n n_particles = self.rp.get_param('particles.n_particles')\n particle_... | <|body_start_0|>
my_grid = grid_setup(self.rp, ng=4)
my_data = patch.CellCenterData2d(my_grid)
bc = bc_setup(self.rp)[0]
my_data.register_var('density', bc)
my_data.create()
self.cc_data = my_data
if self.rp.get_param('particles.do_particles') == 1:
n_... | Simulation | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulation:
def initialize(self):
"""Initialize the grid and variables for advection and set the initial conditions for the chosen problem."""
<|body_0|>
def method_compute_timestep(self):
"""Compute the advective timestep (CFL) constraint. We use the driver.cfl para... | stack_v2_sparse_classes_36k_train_006239 | 4,620 | permissive | [
{
"docstring": "Initialize the grid and variables for advection and set the initial conditions for the chosen problem.",
"name": "initialize",
"signature": "def initialize(self)"
},
{
"docstring": "Compute the advective timestep (CFL) constraint. We use the driver.cfl parameter to control what f... | 4 | stack_v2_sparse_classes_30k_train_004755 | Implement the Python class `Simulation` described below.
Class description:
Implement the Simulation class.
Method signatures and docstrings:
- def initialize(self): Initialize the grid and variables for advection and set the initial conditions for the chosen problem.
- def method_compute_timestep(self): Compute the ... | Implement the Python class `Simulation` described below.
Class description:
Implement the Simulation class.
Method signatures and docstrings:
- def initialize(self): Initialize the grid and variables for advection and set the initial conditions for the chosen problem.
- def method_compute_timestep(self): Compute the ... | f91789a319caa98dfbc3f496e9953756e6ee3ca9 | <|skeleton|>
class Simulation:
def initialize(self):
"""Initialize the grid and variables for advection and set the initial conditions for the chosen problem."""
<|body_0|>
def method_compute_timestep(self):
"""Compute the advective timestep (CFL) constraint. We use the driver.cfl para... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Simulation:
def initialize(self):
"""Initialize the grid and variables for advection and set the initial conditions for the chosen problem."""
my_grid = grid_setup(self.rp, ng=4)
my_data = patch.CellCenterData2d(my_grid)
bc = bc_setup(self.rp)[0]
my_data.register_var('d... | the_stack_v2_python_sparse | pyro/advection/simulation.py | python-hydro/pyro2 | train | 202 | |
c793207626c423bbf2cc159ffc8d8a5e88c08c86 | [
"self.base_currency = base_currency\nself.currency = currency\nself.value = value\nself.key = key\nself.from_date = from_date\nself.to_date = to_date",
"if not self.to_date:\n self.to_date = date.today()\nrates = []\nfor i in range((self.to_date - self.from_date).days + 1):\n rate, created = Rate.objects.ge... | <|body_start_0|>
self.base_currency = base_currency
self.currency = currency
self.value = value
self.key = key
self.from_date = from_date
self.to_date = to_date
<|end_body_0|>
<|body_start_1|>
if not self.to_date:
self.to_date = date.today()
r... | Rate that is applied to a range of dates | BulkRate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BulkRate:
"""Rate that is applied to a range of dates"""
def __init__(self, base_currency, currency, value, key, from_date, to_date):
"""Initialize :param key: key for user :param base_currency: destination currency :param currency: source currency"""
<|body_0|>
def to_r... | stack_v2_sparse_classes_36k_train_006240 | 16,208 | permissive | [
{
"docstring": "Initialize :param key: key for user :param base_currency: destination currency :param currency: source currency",
"name": "__init__",
"signature": "def __init__(self, base_currency, currency, value, key, from_date, to_date)"
},
{
"docstring": "Create rates in the database",
"... | 2 | stack_v2_sparse_classes_30k_train_020231 | Implement the Python class `BulkRate` described below.
Class description:
Rate that is applied to a range of dates
Method signatures and docstrings:
- def __init__(self, base_currency, currency, value, key, from_date, to_date): Initialize :param key: key for user :param base_currency: destination currency :param curr... | Implement the Python class `BulkRate` described below.
Class description:
Rate that is applied to a range of dates
Method signatures and docstrings:
- def __init__(self, base_currency, currency, value, key, from_date, to_date): Initialize :param key: key for user :param base_currency: destination currency :param curr... | 23cc075377d47ac631634cd71fd0e7d6b0a57bad | <|skeleton|>
class BulkRate:
"""Rate that is applied to a range of dates"""
def __init__(self, base_currency, currency, value, key, from_date, to_date):
"""Initialize :param key: key for user :param base_currency: destination currency :param currency: source currency"""
<|body_0|>
def to_r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BulkRate:
"""Rate that is applied to a range of dates"""
def __init__(self, base_currency, currency, value, key, from_date, to_date):
"""Initialize :param key: key for user :param base_currency: destination currency :param currency: source currency"""
self.base_currency = base_currency
... | the_stack_v2_python_sparse | src/geocurrency/rates/models.py | fmeurou/geocurrency | train | 5 |
384726029f9bf08f99578ef841034fb6cf11569b | [
"Parametre.__init__(self, 'chasser', 'hunt')\nself.schema = '<nom_familier>'\nself.aide_courte = 'demande au fammilier de chasser'\nself.aide_longue = \"Cette commande permet d'ordonner à un familier de chasser. Un familier carnivore a besoin de recevoir cet ordre pour chercher du petit gibier avant de se nourrir. ... | <|body_start_0|>
Parametre.__init__(self, 'chasser', 'hunt')
self.schema = '<nom_familier>'
self.aide_courte = 'demande au fammilier de chasser'
self.aide_longue = "Cette commande permet d'ordonner à un familier de chasser. Un familier carnivore a besoin de recevoir cet ordre pour cherch... | Commande 'familier chasser'. | PrmChasser | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmChasser:
"""Commande 'familier chasser'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametr... | stack_v2_sparse_classes_36k_train_006241 | 4,209 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000207 | Implement the Python class `PrmChasser` described below.
Class description:
Commande 'familier chasser'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmChasser` described below.
Class description:
Commande 'familier chasser'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmChasser:
"""Commande 'fami... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmChasser:
"""Commande 'familier chasser'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmChasser:
"""Commande 'familier chasser'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'chasser', 'hunt')
self.schema = '<nom_familier>'
self.aide_courte = 'demande au fammilier de chasser'
self.aide_longue = "Cette commande per... | the_stack_v2_python_sparse | src/secondaires/familier/commandes/familier/chasser.py | vincent-lg/tsunami | train | 5 |
cd38af8d67b75fc21adcf7080585632955b826a5 | [
"self.Whf = np.random.normal(size=(i + h, h))\nself.Whb = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(2 * h, o))\nself.bhf = np.zeros((1, h))\nself.bhb = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"h_matrix = np.concatenate((h_prev.T, x_t.T), axis=0)\nh_next = np.tanh(np.matmul(h_matri... | <|body_start_0|>
self.Whf = np.random.normal(size=(i + h, h))
self.Whb = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(2 * h, o))
self.bhf = np.zeros((1, h))
self.bhb = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
... | BidirectionalCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BidirectionalCell:
def __init__(self, i, h, o):
"""class constructor :param i: dim of data :param h: dim of hidden states :param o: dim outputs Notes: Public Instances: Whf and bhf: for the hidden states forward direction Whb and bhb: for hiden states backward direction Wy and by: for ou... | stack_v2_sparse_classes_36k_train_006242 | 1,733 | no_license | [
{
"docstring": "class constructor :param i: dim of data :param h: dim of hidden states :param o: dim outputs Notes: Public Instances: Whf and bhf: for the hidden states forward direction Whb and bhb: for hiden states backward direction Wy and by: for outputs Notes: Weights: initialized using random normal dist ... | 2 | null | Implement the Python class `BidirectionalCell` described below.
Class description:
Implement the BidirectionalCell class.
Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor :param i: dim of data :param h: dim of hidden states :param o: dim outputs Notes: Public Instances: Whf and bhf: ... | Implement the Python class `BidirectionalCell` described below.
Class description:
Implement the BidirectionalCell class.
Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor :param i: dim of data :param h: dim of hidden states :param o: dim outputs Notes: Public Instances: Whf and bhf: ... | 4ac942126918c7acaa9ef88d18efe299b2f726fe | <|skeleton|>
class BidirectionalCell:
def __init__(self, i, h, o):
"""class constructor :param i: dim of data :param h: dim of hidden states :param o: dim outputs Notes: Public Instances: Whf and bhf: for the hidden states forward direction Whb and bhb: for hiden states backward direction Wy and by: for ou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BidirectionalCell:
def __init__(self, i, h, o):
"""class constructor :param i: dim of data :param h: dim of hidden states :param o: dim outputs Notes: Public Instances: Whf and bhf: for the hidden states forward direction Whb and bhb: for hiden states backward direction Wy and by: for outputs Notes: W... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/5-bi_forward.py | DracoMindz/holbertonschool-machine_learning | train | 2 | |
394991724f347c0c8bbbbded860cd6d2f14c4a57 | [
"global app\napp = tgpIntergral_page(self.dr)\napp.click_nav_recommend()\napp.click_intergral_icon()",
"app = tgpIntergral_page(self.dr)\napp.click_nav_recommend()\napp.click_intergral_icon()",
"app = tgpIntergral_page(self.dr)\napp.click_nav_recommend()\napp.click_intergral_icon()\napp.click_intergral_commodit... | <|body_start_0|>
global app
app = tgpIntergral_page(self.dr)
app.click_nav_recommend()
app.click_intergral_icon()
<|end_body_0|>
<|body_start_1|>
app = tgpIntergral_page(self.dr)
app.click_nav_recommend()
app.click_intergral_icon()
<|end_body_1|>
<|body_start_2|... | tgpIntergral_test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tgpIntergral_test:
def test1_intergral_checkIn(self):
"""积分商城打卡 :return:"""
<|body_0|>
def test2_intergral_treasure(self):
"""参与积分商城明日宝藏 :return:"""
<|body_1|>
def test3_intergral_exchange(self):
"""积分商城兑换商品"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_006243 | 1,101 | no_license | [
{
"docstring": "积分商城打卡 :return:",
"name": "test1_intergral_checkIn",
"signature": "def test1_intergral_checkIn(self)"
},
{
"docstring": "参与积分商城明日宝藏 :return:",
"name": "test2_intergral_treasure",
"signature": "def test2_intergral_treasure(self)"
},
{
"docstring": "积分商城兑换商品",
"... | 3 | null | Implement the Python class `tgpIntergral_test` described below.
Class description:
Implement the tgpIntergral_test class.
Method signatures and docstrings:
- def test1_intergral_checkIn(self): 积分商城打卡 :return:
- def test2_intergral_treasure(self): 参与积分商城明日宝藏 :return:
- def test3_intergral_exchange(self): 积分商城兑换商品 | Implement the Python class `tgpIntergral_test` described below.
Class description:
Implement the tgpIntergral_test class.
Method signatures and docstrings:
- def test1_intergral_checkIn(self): 积分商城打卡 :return:
- def test2_intergral_treasure(self): 参与积分商城明日宝藏 :return:
- def test3_intergral_exchange(self): 积分商城兑换商品
<|s... | 8e82a6051c22d6d9480b9f60aefad347d927c592 | <|skeleton|>
class tgpIntergral_test:
def test1_intergral_checkIn(self):
"""积分商城打卡 :return:"""
<|body_0|>
def test2_intergral_treasure(self):
"""参与积分商城明日宝藏 :return:"""
<|body_1|>
def test3_intergral_exchange(self):
"""积分商城兑换商品"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class tgpIntergral_test:
def test1_intergral_checkIn(self):
"""积分商城打卡 :return:"""
global app
app = tgpIntergral_page(self.dr)
app.click_nav_recommend()
app.click_intergral_icon()
def test2_intergral_treasure(self):
"""参与积分商城明日宝藏 :return:"""
app = tgpInter... | the_stack_v2_python_sparse | Po/testapp/tgpIntergral_test.py | Felixshao/UiAutomation | train | 1 | |
e93939c9ca190ed35a4fd62c9b8d984d5e9e8445 | [
"def with_return():\n return 'expected return value'\n\ndef with_raise():\n raise KeyError('expected exception')\nwith threaded_run('test_run_subroutine') as runner:\n result = runner.run_payload(with_return, flavour=flavour)\n assert result == with_return()\n with pytest.raises(KeyError):\n r... | <|body_start_0|>
def with_return():
return 'expected return value'
def with_raise():
raise KeyError('expected exception')
with threaded_run('test_run_subroutine') as runner:
result = runner.run_payload(with_return, flavour=flavour)
assert result =... | TestMetaRunner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMetaRunner:
def test_run_subroutine(self, flavour):
"""Test executing a subroutine"""
<|body_0|>
def test_run_coroutine(self, flavour):
"""Test executing a coroutine"""
<|body_1|>
def test_return_subroutine(self, flavour):
"""Test that return... | stack_v2_sparse_classes_36k_train_006244 | 4,574 | permissive | [
{
"docstring": "Test executing a subroutine",
"name": "test_run_subroutine",
"signature": "def test_run_subroutine(self, flavour)"
},
{
"docstring": "Test executing a coroutine",
"name": "test_run_coroutine",
"signature": "def test_run_coroutine(self, flavour)"
},
{
"docstring": ... | 6 | stack_v2_sparse_classes_30k_train_021513 | Implement the Python class `TestMetaRunner` described below.
Class description:
Implement the TestMetaRunner class.
Method signatures and docstrings:
- def test_run_subroutine(self, flavour): Test executing a subroutine
- def test_run_coroutine(self, flavour): Test executing a coroutine
- def test_return_subroutine(s... | Implement the Python class `TestMetaRunner` described below.
Class description:
Implement the TestMetaRunner class.
Method signatures and docstrings:
- def test_run_subroutine(self, flavour): Test executing a subroutine
- def test_run_coroutine(self, flavour): Test executing a coroutine
- def test_return_subroutine(s... | 606add92be5ed48ce68bb57ef0baa2002c663a51 | <|skeleton|>
class TestMetaRunner:
def test_run_subroutine(self, flavour):
"""Test executing a subroutine"""
<|body_0|>
def test_run_coroutine(self, flavour):
"""Test executing a coroutine"""
<|body_1|>
def test_return_subroutine(self, flavour):
"""Test that return... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestMetaRunner:
def test_run_subroutine(self, flavour):
"""Test executing a subroutine"""
def with_return():
return 'expected return value'
def with_raise():
raise KeyError('expected exception')
with threaded_run('test_run_subroutine') as runner:
... | the_stack_v2_python_sparse | cobald_tests/utility/concurrent/test_meta_runner.py | MatterMiners/cobald | train | 8 | |
7a63f333c783129ef9db683591e049f1cd48cdae | [
"assert voters, 'Cannot initialize without voters.'\nsuper().__init__(allow_all_abstain=allow_all_abstain, cascade_authorization=cascade_authorization)\nif not isinstance(voters, Iterable):\n self.__voters = [voters]\nelse:\n self.__voters = voters",
"if not self.supports(expression, attribute):\n raise ... | <|body_start_0|>
assert voters, 'Cannot initialize without voters.'
super().__init__(allow_all_abstain=allow_all_abstain, cascade_authorization=cascade_authorization)
if not isinstance(voters, Iterable):
self.__voters = [voters]
else:
self.__voters = voters
<|end_... | A decision manager that requires all voters to either grant access or abstain -- one AccessVote.Denied will deny access for the authentication. | UnanimousDecisionManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnanimousDecisionManager:
"""A decision manager that requires all voters to either grant access or abstain -- one AccessVote.Denied will deny access for the authentication."""
def __init__(self, voters, allow_all_abstain=False, cascade_authorization=True):
"""Creates a new decision m... | stack_v2_sparse_classes_36k_train_006245 | 12,706 | permissive | [
{
"docstring": "Creates a new decision manager. Args: voters: the voters used to make access decisions. Accepts either a single voter or an iterable collection of voters.",
"name": "__init__",
"signature": "def __init__(self, voters, allow_all_abstain=False, cascade_authorization=True)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_015432 | Implement the Python class `UnanimousDecisionManager` described below.
Class description:
A decision manager that requires all voters to either grant access or abstain -- one AccessVote.Denied will deny access for the authentication.
Method signatures and docstrings:
- def __init__(self, voters, allow_all_abstain=Fal... | Implement the Python class `UnanimousDecisionManager` described below.
Class description:
A decision manager that requires all voters to either grant access or abstain -- one AccessVote.Denied will deny access for the authentication.
Method signatures and docstrings:
- def __init__(self, voters, allow_all_abstain=Fal... | 08e012f39b1ae4c435830e817167037d10f5db32 | <|skeleton|>
class UnanimousDecisionManager:
"""A decision manager that requires all voters to either grant access or abstain -- one AccessVote.Denied will deny access for the authentication."""
def __init__(self, voters, allow_all_abstain=False, cascade_authorization=True):
"""Creates a new decision m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnanimousDecisionManager:
"""A decision manager that requires all voters to either grant access or abstain -- one AccessVote.Denied will deny access for the authentication."""
def __init__(self, voters, allow_all_abstain=False, cascade_authorization=True):
"""Creates a new decision manager. Args:... | the_stack_v2_python_sparse | dorthy/security/access.py | kurtrwall/dorthy | train | 0 |
36ad7430c95f11c2f64541af2bf295b1c7c06306 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ContentType()",
"from .column_definition import ColumnDefinition\nfrom .column_link import ColumnLink\nfrom .content_type_order import ContentTypeOrder\nfrom .document_set import DocumentSet\nfrom .document_set_content import DocumentS... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ContentType()
<|end_body_0|>
<|body_start_1|>
from .column_definition import ColumnDefinition
from .column_link import ColumnLink
from .content_type_order import ContentTypeOrder... | ContentType | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentType:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ContentType:
"""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: Co... | stack_v2_sparse_classes_36k_train_006246 | 8,458 | 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: ContentType",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(p... | 3 | null | Implement the Python class `ContentType` described below.
Class description:
Implement the ContentType class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ContentType: Creates a new instance of the appropriate class based on discriminator value Args:... | Implement the Python class `ContentType` described below.
Class description:
Implement the ContentType class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ContentType: Creates a new instance of the appropriate class based on discriminator value Args:... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ContentType:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ContentType:
"""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: Co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContentType:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ContentType:
"""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: ContentType"""
... | the_stack_v2_python_sparse | msgraph/generated/models/content_type.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
c07a07bb63a2c34a50128264527ca1ccfcc2ee94 | [
"arr = [-1 for n in nums]\nfor n in nums:\n arr[n - 1] += 1\nreturn [i + 1 for i in range(len(arr)) if arr[i] == 1]",
"ans = []\nfor n in nums:\n n = abs(n)\n if nums[n - 1] > 0:\n nums[n - 1] = -nums[n - 1]\n else:\n ans.append(n)\nreturn ans"
] | <|body_start_0|>
arr = [-1 for n in nums]
for n in nums:
arr[n - 1] += 1
return [i + 1 for i in range(len(arr)) if arr[i] == 1]
<|end_body_0|>
<|body_start_1|>
ans = []
for n in nums:
n = abs(n)
if nums[n - 1] > 0:
nums[n - 1] ... | Strat 1 (naive) - O(n) time, O(n) space Runtime: 324 ms, faster than 94.16% of Python online submissions for Find All Duplicates in an Array. Memory Usage: 20.1 MB, less than 40.00% of Python online submissions for Find All Duplicates in an Array. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Strat 1 (naive) - O(n) time, O(n) space Runtime: 324 ms, faster than 94.16% of Python online submissions for Find All Duplicates in an Array. Memory Usage: 20.1 MB, less than 40.00% of Python online submissions for Find All Duplicates in an Array."""
def findDuplicates(self, num... | stack_v2_sparse_classes_36k_train_006247 | 2,294 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findDuplicates",
"signature": "def findDuplicates(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findDuplicates",
"signature": "def findDuplicates(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Strat 1 (naive) - O(n) time, O(n) space Runtime: 324 ms, faster than 94.16% of Python online submissions for Find All Duplicates in an Array. Memory Usage: 20.1 MB, less than 40.00% of Python online submissions for Find All Duplicates in an Arra... | Implement the Python class `Solution` described below.
Class description:
Strat 1 (naive) - O(n) time, O(n) space Runtime: 324 ms, faster than 94.16% of Python online submissions for Find All Duplicates in an Array. Memory Usage: 20.1 MB, less than 40.00% of Python online submissions for Find All Duplicates in an Arra... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
"""Strat 1 (naive) - O(n) time, O(n) space Runtime: 324 ms, faster than 94.16% of Python online submissions for Find All Duplicates in an Array. Memory Usage: 20.1 MB, less than 40.00% of Python online submissions for Find All Duplicates in an Array."""
def findDuplicates(self, num... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Strat 1 (naive) - O(n) time, O(n) space Runtime: 324 ms, faster than 94.16% of Python online submissions for Find All Duplicates in an Array. Memory Usage: 20.1 MB, less than 40.00% of Python online submissions for Find All Duplicates in an Array."""
def findDuplicates(self, nums):
"... | the_stack_v2_python_sparse | 442-duplicates_in_array.py | stevestar888/leetcode-problems | train | 2 |
6acd67f521908eb7412e578fe21ecf4c488717f1 | [
"assert SimRast.shape == ObsRast.shape, 'Rasters does not have same dimension'\nif type(SimMask) == int:\n SimMask = np.ones_like(SimRast).astype(bool)\nif type(ObsMask) == int:\n ObsMask = np.ones_like(ObsRast).astype(bool)\nif type(AreaMask) == int:\n AreaMask = np.ones_like(SimRast).astype(bool)\nassert... | <|body_start_0|>
assert SimRast.shape == ObsRast.shape, 'Rasters does not have same dimension'
if type(SimMask) == int:
SimMask = np.ones_like(SimRast).astype(bool)
if type(ObsMask) == int:
ObsMask = np.ones_like(ObsRast).astype(bool)
if type(AreaMask) == int:
... | Verification | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Verification:
def __init__(self, SimRast, ObsRast, SimMask=0, ObsMask=0, AreaMask=0):
""":param SimRast: Simulation Raster :param ObsRast: Observation Raster :param SimMask: Mask for Simulation, must not be declared (e.g. areas which shall not taken into account) :param ObsMask: Mask for... | stack_v2_sparse_classes_36k_train_006248 | 17,681 | no_license | [
{
"docstring": ":param SimRast: Simulation Raster :param ObsRast: Observation Raster :param SimMask: Mask for Simulation, must not be declared (e.g. areas which shall not taken into account) :param ObsMask: Mask for observation, must not be declared (e.g. Cloudmask for landsat data) :param AreaMask: Mask for in... | 6 | stack_v2_sparse_classes_30k_train_003226 | Implement the Python class `Verification` described below.
Class description:
Implement the Verification class.
Method signatures and docstrings:
- def __init__(self, SimRast, ObsRast, SimMask=0, ObsMask=0, AreaMask=0): :param SimRast: Simulation Raster :param ObsRast: Observation Raster :param SimMask: Mask for Simu... | Implement the Python class `Verification` described below.
Class description:
Implement the Verification class.
Method signatures and docstrings:
- def __init__(self, SimRast, ObsRast, SimMask=0, ObsMask=0, AreaMask=0): :param SimRast: Simulation Raster :param ObsRast: Observation Raster :param SimMask: Mask for Simu... | 2592cfb035de32fad69deacdcc0a1b9cfd7a829d | <|skeleton|>
class Verification:
def __init__(self, SimRast, ObsRast, SimMask=0, ObsMask=0, AreaMask=0):
""":param SimRast: Simulation Raster :param ObsRast: Observation Raster :param SimMask: Mask for Simulation, must not be declared (e.g. areas which shall not taken into account) :param ObsMask: Mask for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Verification:
def __init__(self, SimRast, ObsRast, SimMask=0, ObsMask=0, AreaMask=0):
""":param SimRast: Simulation Raster :param ObsRast: Observation Raster :param SimMask: Mask for Simulation, must not be declared (e.g. areas which shall not taken into account) :param ObsMask: Mask for observation, ... | the_stack_v2_python_sparse | compare_snow_cover/compare_snow_cover.py | SiegmannGiS/master2 | train | 0 | |
d6fa244248a93c8492999f611a5b7acd6cbf3588 | [
"self.cancelEmoji = cancelEmoji\noptions[cancelEmoji] = NonSaveableReactionMenuOption('cancel', cancelEmoji, self.delete, None)\nsuper(CancellableReactionMenu, self).__init__(msg, options=options, titleTxt=titleTxt, desc=desc, col=col, footerTxt=footerTxt, img=img, thumb=thumb, icon=icon, authorName=authorName, tim... | <|body_start_0|>
self.cancelEmoji = cancelEmoji
options[cancelEmoji] = NonSaveableReactionMenuOption('cancel', cancelEmoji, self.delete, None)
super(CancellableReactionMenu, self).__init__(msg, options=options, titleTxt=titleTxt, desc=desc, col=col, footerTxt=footerTxt, img=img, thumb=thumb, ico... | A simple ReactionMenu extension that adds an extra 'cancel' option to your given options dictionary. The 'cancel' option will call the menu's delete method. No extra restrictions beyond targetMember/targetRole are placed on members who may cancel the menu. If CancellableReactionMenu is extended into a saveable menu cla... | CancellableReactionMenu | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CancellableReactionMenu:
"""A simple ReactionMenu extension that adds an extra 'cancel' option to your given options dictionary. The 'cancel' option will call the menu's delete method. No extra restrictions beyond targetMember/targetRole are placed on members who may cancel the menu. If Cancellab... | stack_v2_sparse_classes_36k_train_006249 | 34,501 | permissive | [
{
"docstring": ":param discord.Message msg: the message where this menu is embedded :param options: A dictionary storing all of the menu's options and their behaviour (Default {}) :type options: dict[lib.emojis.dumbEmoji, ReactionMenuOption] :param lib.emojis.dumbEmoji emoji: The emoji members should react with... | 2 | stack_v2_sparse_classes_30k_train_016366 | Implement the Python class `CancellableReactionMenu` described below.
Class description:
A simple ReactionMenu extension that adds an extra 'cancel' option to your given options dictionary. The 'cancel' option will call the menu's delete method. No extra restrictions beyond targetMember/targetRole are placed on member... | Implement the Python class `CancellableReactionMenu` described below.
Class description:
A simple ReactionMenu extension that adds an extra 'cancel' option to your given options dictionary. The 'cancel' option will call the menu's delete method. No extra restrictions beyond targetMember/targetRole are placed on member... | b4fe3d765b764ab169284ce0869a810825013389 | <|skeleton|>
class CancellableReactionMenu:
"""A simple ReactionMenu extension that adds an extra 'cancel' option to your given options dictionary. The 'cancel' option will call the menu's delete method. No extra restrictions beyond targetMember/targetRole are placed on members who may cancel the menu. If Cancellab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CancellableReactionMenu:
"""A simple ReactionMenu extension that adds an extra 'cancel' option to your given options dictionary. The 'cancel' option will call the menu's delete method. No extra restrictions beyond targetMember/targetRole are placed on members who may cancel the menu. If CancellableReactionMen... | the_stack_v2_python_sparse | BB/reactionMenus/ReactionMenu.py | Trimatix/GOF2BountyBot | train | 7 |
6f61215dfc2adcccbefaad64fcaee2d0605802a9 | [
"if column_filter == 'All':\n pass\nelif column_filter:\n if column_filter == 'private':\n query = query.filter(model.History.users_shared_with == None)\n query = query.filter(model.History.importable == False)\n elif column_filter == 'shared':\n query = query.filter(model.History.user... | <|body_start_0|>
if column_filter == 'All':
pass
elif column_filter:
if column_filter == 'private':
query = query.filter(model.History.users_shared_with == None)
query = query.filter(model.History.importable == False)
elif column_filter... | SharingColumn | [
"CC-BY-2.5",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharingColumn:
def filter(self, db_session, query, column_filter):
"""Modify query to filter histories by sharing status."""
<|body_0|>
def get_accepted_filters(self):
"""Returns a list of accepted filters for this column."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_006250 | 16,192 | permissive | [
{
"docstring": "Modify query to filter histories by sharing status.",
"name": "filter",
"signature": "def filter(self, db_session, query, column_filter)"
},
{
"docstring": "Returns a list of accepted filters for this column.",
"name": "get_accepted_filters",
"signature": "def get_accepte... | 2 | stack_v2_sparse_classes_30k_train_003617 | Implement the Python class `SharingColumn` described below.
Class description:
Implement the SharingColumn class.
Method signatures and docstrings:
- def filter(self, db_session, query, column_filter): Modify query to filter histories by sharing status.
- def get_accepted_filters(self): Returns a list of accepted fil... | Implement the Python class `SharingColumn` described below.
Class description:
Implement the SharingColumn class.
Method signatures and docstrings:
- def filter(self, db_session, query, column_filter): Modify query to filter histories by sharing status.
- def get_accepted_filters(self): Returns a list of accepted fil... | 7b679ea17ba294893cc560354d759cfd61c0b450 | <|skeleton|>
class SharingColumn:
def filter(self, db_session, query, column_filter):
"""Modify query to filter histories by sharing status."""
<|body_0|>
def get_accepted_filters(self):
"""Returns a list of accepted filters for this column."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SharingColumn:
def filter(self, db_session, query, column_filter):
"""Modify query to filter histories by sharing status."""
if column_filter == 'All':
pass
elif column_filter:
if column_filter == 'private':
query = query.filter(model.History.use... | the_stack_v2_python_sparse | lib/galaxy/web/controllers/page.py | msGenDev/Yeps-EURAC | train | 0 | |
16051a91223d7978e5c99620c7968c5f602f0e2b | [
"i, j = (problem.matching_prospects['i'], problem.matching_prospects['j'])\ncouriers_routes_vars = np.vectorize(self._build_int_bool_var, otypes=[np.object])(i, j, engine_model)\nunique_routes = np.unique(j)\nsupply_courier = np.array(['supply'])\nsupply_routes_combinations = np.array(np.array(np.meshgrid(supply_co... | <|body_start_0|>
i, j = (problem.matching_prospects['i'], problem.matching_prospects['j'])
couriers_routes_vars = np.vectorize(self._build_int_bool_var, otypes=[np.object])(i, j, engine_model)
unique_routes = np.unique(j)
supply_courier = np.array(['supply'])
supply_routes_combin... | Class that enables the construction of an optimization model for matching | MIPOptimizationModelBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MIPOptimizationModelBuilder:
"""Class that enables the construction of an optimization model for matching"""
def _build_variables(self, problem: MatchingProblem, engine_model: Union[LpProblem, Model]) -> np.ndarray:
"""Method to build the model decision variables, which are integer v... | stack_v2_sparse_classes_36k_train_006251 | 2,365 | no_license | [
{
"docstring": "Method to build the model decision variables, which are integer variables",
"name": "_build_variables",
"signature": "def _build_variables(self, problem: MatchingProblem, engine_model: Union[LpProblem, Model]) -> np.ndarray"
},
{
"docstring": "Method to build the model's linear o... | 3 | null | Implement the Python class `MIPOptimizationModelBuilder` described below.
Class description:
Class that enables the construction of an optimization model for matching
Method signatures and docstrings:
- def _build_variables(self, problem: MatchingProblem, engine_model: Union[LpProblem, Model]) -> np.ndarray: Method t... | Implement the Python class `MIPOptimizationModelBuilder` described below.
Class description:
Class that enables the construction of an optimization model for matching
Method signatures and docstrings:
- def _build_variables(self, problem: MatchingProblem, engine_model: Union[LpProblem, Model]) -> np.ndarray: Method t... | 94656681006f7bbc32b2f1970e288944c52d308a | <|skeleton|>
class MIPOptimizationModelBuilder:
"""Class that enables the construction of an optimization model for matching"""
def _build_variables(self, problem: MatchingProblem, engine_model: Union[LpProblem, Model]) -> np.ndarray:
"""Method to build the model decision variables, which are integer v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MIPOptimizationModelBuilder:
"""Class that enables the construction of an optimization model for matching"""
def _build_variables(self, problem: MatchingProblem, engine_model: Union[LpProblem, Model]) -> np.ndarray:
"""Method to build the model decision variables, which are integer variables"""
... | the_stack_v2_python_sparse | services/optimization_service/model/mip_model_builder.py | DanielG1397/mdrp-sim | train | 0 |
9aae18ba05fe5c0994b0e5994893120a8b13fbad | [
"nums_sored = sorted(nums)\ni, j = (0, len(nums) - 1)\nwhile i < j:\n if nums[i] == nums_sored[i]:\n i += 1\n elif nums[j] == nums_sored[j]:\n j -= 1\n elif i == j:\n return 0\n else:\n return j - i + 1\nreturn 0",
"left = len(nums)\nright = 0\nstack = []\nfor i in range(le... | <|body_start_0|>
nums_sored = sorted(nums)
i, j = (0, len(nums) - 1)
while i < j:
if nums[i] == nums_sored[i]:
i += 1
elif nums[j] == nums_sored[j]:
j -= 1
elif i == j:
return 0
else:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortest_unsorted_continuous_subarray(self, nums: List[int]) -> bool:
"""求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度"""
<|body_0|>
def shortest_unsorted_continuous_subarray2(self, nums: List[int]) -> bool:
"""求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度"""... | stack_v2_sparse_classes_36k_train_006252 | 2,871 | permissive | [
{
"docstring": "求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度",
"name": "shortest_unsorted_continuous_subarray",
"signature": "def shortest_unsorted_continuous_subarray(self, nums: List[int]) -> bool"
},
{
"docstring": "求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度",
"name": "shortest_unsorted_con... | 2 | stack_v2_sparse_classes_30k_train_015283 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortest_unsorted_continuous_subarray(self, nums: List[int]) -> bool: 求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度
- def shortest_unsorted_continuous_subarray2(self, nums: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortest_unsorted_continuous_subarray(self, nums: List[int]) -> bool: 求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度
- def shortest_unsorted_continuous_subarray2(self, nums: List... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def shortest_unsorted_continuous_subarray(self, nums: List[int]) -> bool:
"""求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度"""
<|body_0|>
def shortest_unsorted_continuous_subarray2(self, nums: List[int]) -> bool:
"""求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def shortest_unsorted_continuous_subarray(self, nums: List[int]) -> bool:
"""求最短不连续子数组 Args: nums: 数据 Returns: 不连续子数组长度"""
nums_sored = sorted(nums)
i, j = (0, len(nums) - 1)
while i < j:
if nums[i] == nums_sored[i]:
i += 1
elif... | the_stack_v2_python_sparse | src/leetcodepython/array/shortest_unsorted_continuous_subarray_581.py | zhangyu345293721/leetcode | train | 101 | |
10079e811d53a1a9c77aa61902b755811ae66e00 | [
"from world.dominion.models import RPEvent\nqs = CharacterHealthStatus.objects.get_recovery_queryset()\nroom_ids = RPEvent.objects.active_events().gm_or_prp().values_list('location', flat=True)\nfor status in qs:\n if status.character.db_location_id in room_ids:\n continue\n try:\n if status.cha... | <|body_start_0|>
from world.dominion.models import RPEvent
qs = CharacterHealthStatus.objects.get_recovery_queryset()
room_ids = RPEvent.objects.active_events().gm_or_prp().values_list('location', flat=True)
for status in qs:
if status.character.db_location_id in room_ids:
... | This is a singleton - it should be a table with only a single row. It connects to a script that calls it at periodic intervals. It runs calls for recovery checks or revive attempts for the health status of characters. | RecoveryRunner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecoveryRunner:
"""This is a singleton - it should be a table with only a single row. It connects to a script that calls it at periodic intervals. It runs calls for recovery checks or revive attempts for the health status of characters."""
def run_recovery_checks(self):
"""Called by ... | stack_v2_sparse_classes_36k_train_006253 | 30,992 | permissive | [
{
"docstring": "Called by our script, this runs recovery checks for every damaged character",
"name": "run_recovery_checks",
"signature": "def run_recovery_checks(self)"
},
{
"docstring": "Called by our script, this runs revive checks for every unconscious character",
"name": "run_revive_che... | 2 | null | Implement the Python class `RecoveryRunner` described below.
Class description:
This is a singleton - it should be a table with only a single row. It connects to a script that calls it at periodic intervals. It runs calls for recovery checks or revive attempts for the health status of characters.
Method signatures an... | Implement the Python class `RecoveryRunner` described below.
Class description:
This is a singleton - it should be a table with only a single row. It connects to a script that calls it at periodic intervals. It runs calls for recovery checks or revive attempts for the health status of characters.
Method signatures an... | 363a1f14fd1a640580a4bf4486a1afe776757557 | <|skeleton|>
class RecoveryRunner:
"""This is a singleton - it should be a table with only a single row. It connects to a script that calls it at periodic intervals. It runs calls for recovery checks or revive attempts for the health status of characters."""
def run_recovery_checks(self):
"""Called by ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecoveryRunner:
"""This is a singleton - it should be a table with only a single row. It connects to a script that calls it at periodic intervals. It runs calls for recovery checks or revive attempts for the health status of characters."""
def run_recovery_checks(self):
"""Called by our script, t... | the_stack_v2_python_sparse | world/conditions/models.py | Arx-Game/arxcode | train | 52 |
5ab9d65e6ca1b72b2a485763ee4a015f5db71c3f | [
"super(MoveBaseGoal, self).__init__()\nself.header = std_msgs.msg.Header()\nself.header.frame_id = 'base_link_path'\nself.duration = duration\nself.n_steps = n_steps\nself.gait_type = gait_type\nself.base_goal = geometry_msgs.msg.Pose()\nself.base_goal.position.x = 0.3\nself.base_goal.position.y = 0.0\nself.base_go... | <|body_start_0|>
super(MoveBaseGoal, self).__init__()
self.header = std_msgs.msg.Header()
self.header.frame_id = 'base_link_path'
self.duration = duration
self.n_steps = n_steps
self.gait_type = gait_type
self.base_goal = geometry_msgs.msg.Pose()
self.base... | Extends sweetie_bot_clop_generator.msg.MoveBaseGoal. | MoveBaseGoal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoveBaseGoal:
"""Extends sweetie_bot_clop_generator.msg.MoveBaseGoal."""
def __init__(self, gait_type='walk_overlap', n_steps=4, duration=4, nominal_height=0.2025):
"""Create MoveBaseGoal message with default field values."""
<|body_0|>
def setTargetBaseShift(self, x, y,... | stack_v2_sparse_classes_36k_train_006254 | 6,478 | no_license | [
{
"docstring": "Create MoveBaseGoal message with default field values.",
"name": "__init__",
"signature": "def __init__(self, gait_type='walk_overlap', n_steps=4, duration=4, nominal_height=0.2025)"
},
{
"docstring": "Set target base pose in path coordinate system (\"base_link_path\" frame). The... | 5 | null | Implement the Python class `MoveBaseGoal` described below.
Class description:
Extends sweetie_bot_clop_generator.msg.MoveBaseGoal.
Method signatures and docstrings:
- def __init__(self, gait_type='walk_overlap', n_steps=4, duration=4, nominal_height=0.2025): Create MoveBaseGoal message with default field values.
- de... | Implement the Python class `MoveBaseGoal` described below.
Class description:
Extends sweetie_bot_clop_generator.msg.MoveBaseGoal.
Method signatures and docstrings:
- def __init__(self, gait_type='walk_overlap', n_steps=4, duration=4, nominal_height=0.2025): Create MoveBaseGoal message with default field values.
- de... | f15f9cb01f2763d0b9d62624a400a01961609762 | <|skeleton|>
class MoveBaseGoal:
"""Extends sweetie_bot_clop_generator.msg.MoveBaseGoal."""
def __init__(self, gait_type='walk_overlap', n_steps=4, duration=4, nominal_height=0.2025):
"""Create MoveBaseGoal message with default field values."""
<|body_0|>
def setTargetBaseShift(self, x, y,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MoveBaseGoal:
"""Extends sweetie_bot_clop_generator.msg.MoveBaseGoal."""
def __init__(self, gait_type='walk_overlap', n_steps=4, duration=4, nominal_height=0.2025):
"""Create MoveBaseGoal message with default field values."""
super(MoveBaseGoal, self).__init__()
self.header = std_... | the_stack_v2_python_sparse | behavior/sweetie_bot_clop_generator/pysrc/sweetie_bot_clop_generator/clopper.py | sweetie-bot-project/sweetie_bot | train | 9 |
da9302d0f79550134f36f63fe32f9f12f72d4ce6 | [
"for name in self.success_urls:\n if name in form.data:\n self.success_url = self.success_urls[name]\n break\nreturn HttpResponseRedirect(self.get_success_url())",
"if self.success_url:\n url = force_text(self.success_url)\nelse:\n raise ImproperlyConfigured(_('No URL to redirect to. Provid... | <|body_start_0|>
for name in self.success_urls:
if name in form.data:
self.success_url = self.success_urls[name]
break
return HttpResponseRedirect(self.get_success_url())
<|end_body_0|>
<|body_start_1|>
if self.success_url:
url = force_tex... | A mixin that supports submit-specific success redirection. Either specify one success_url, or provide dict with names of submit actions given in template as keys Example: In template: <input type="submit" name="create_new" value="Create"/> <input type="submit" name="delete" value="Delete"/> View: MyMultiSubmitView(Mult... | MultiRedirectMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiRedirectMixin:
"""A mixin that supports submit-specific success redirection. Either specify one success_url, or provide dict with names of submit actions given in template as keys Example: In template: <input type="submit" name="create_new" value="Create"/> <input type="submit" name="delete"... | stack_v2_sparse_classes_36k_train_006255 | 1,344 | no_license | [
{
"docstring": "Form is valid: Pick the url and redirect.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Returns the supplied success URL.",
"name": "get_success_url",
"signature": "def get_success_url(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000124 | Implement the Python class `MultiRedirectMixin` described below.
Class description:
A mixin that supports submit-specific success redirection. Either specify one success_url, or provide dict with names of submit actions given in template as keys Example: In template: <input type="submit" name="create_new" value="Creat... | Implement the Python class `MultiRedirectMixin` described below.
Class description:
A mixin that supports submit-specific success redirection. Either specify one success_url, or provide dict with names of submit actions given in template as keys Example: In template: <input type="submit" name="create_new" value="Creat... | df662e8f1110fd0ae3a90549bd6f54d2ee6b04be | <|skeleton|>
class MultiRedirectMixin:
"""A mixin that supports submit-specific success redirection. Either specify one success_url, or provide dict with names of submit actions given in template as keys Example: In template: <input type="submit" name="create_new" value="Create"/> <input type="submit" name="delete"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiRedirectMixin:
"""A mixin that supports submit-specific success redirection. Either specify one success_url, or provide dict with names of submit actions given in template as keys Example: In template: <input type="submit" name="create_new" value="Create"/> <input type="submit" name="delete" value="Delet... | the_stack_v2_python_sparse | catalogue/mixins.py | csdbrass/CSDLibrary | train | 0 |
aaf58129fcd54526d4b1119381b4ccb0a2687400 | [
"the_user = db.query(User).filter(User.email == user.email).first()\nif the_user:\n raise HTTPException(status_code=400, detail='Email already exists')\nnew_user = User(firstname=user.firstname, lastname=user.lastname, email=user.email, password=Hash().bcrypt(user.password))\ndb.add(new_user)\ndb.commit()\ndb.re... | <|body_start_0|>
the_user = db.query(User).filter(User.email == user.email).first()
if the_user:
raise HTTPException(status_code=400, detail='Email already exists')
new_user = User(firstname=user.firstname, lastname=user.lastname, email=user.email, password=Hash().bcrypt(user.passwor... | UserService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserService:
def register_user(user: user.UserPost, db: Session):
"""register a new user"""
<|body_0|>
def authenticate_user(user: user.UserLogin, db: Session):
"""Authenticate a user"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
the_user = db.que... | stack_v2_sparse_classes_36k_train_006256 | 1,594 | no_license | [
{
"docstring": "register a new user",
"name": "register_user",
"signature": "def register_user(user: user.UserPost, db: Session)"
},
{
"docstring": "Authenticate a user",
"name": "authenticate_user",
"signature": "def authenticate_user(user: user.UserLogin, db: Session)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014184 | Implement the Python class `UserService` described below.
Class description:
Implement the UserService class.
Method signatures and docstrings:
- def register_user(user: user.UserPost, db: Session): register a new user
- def authenticate_user(user: user.UserLogin, db: Session): Authenticate a user | Implement the Python class `UserService` described below.
Class description:
Implement the UserService class.
Method signatures and docstrings:
- def register_user(user: user.UserPost, db: Session): register a new user
- def authenticate_user(user: user.UserLogin, db: Session): Authenticate a user
<|skeleton|>
class... | e5fa368a46ce527b206ec286be05bc2372043c70 | <|skeleton|>
class UserService:
def register_user(user: user.UserPost, db: Session):
"""register a new user"""
<|body_0|>
def authenticate_user(user: user.UserLogin, db: Session):
"""Authenticate a user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserService:
def register_user(user: user.UserPost, db: Session):
"""register a new user"""
the_user = db.query(User).filter(User.email == user.email).first()
if the_user:
raise HTTPException(status_code=400, detail='Email already exists')
new_user = User(firstname=... | the_stack_v2_python_sparse | backend/services/user.py | mutuajoseph/GainIt | train | 3 | |
caee2ddbd5f8c37bf1deef5633b9c77e353ecd45 | [
"super(Classifier, self).__init__()\nself.fc1 = nn.Linear(in_features, mid_features)\nself.fc2 = nn.Linear(mid_features, mid_features)\nself.fc3 = nn.Linear(mid_features, out_features)",
"x = F.relu(self.fc1(x))\nx = F.relu(self.fc2(x))\nx = F.dropout(x)\nx = self.fc3(x)\nreturn F.log_softmax(x, dim=-1)"
] | <|body_start_0|>
super(Classifier, self).__init__()
self.fc1 = nn.Linear(in_features, mid_features)
self.fc2 = nn.Linear(mid_features, mid_features)
self.fc3 = nn.Linear(mid_features, out_features)
<|end_body_0|>
<|body_start_1|>
x = F.relu(self.fc1(x))
x = F.relu(self.f... | Classifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Classifier:
def __init__(self, in_features, mid_features, out_features):
"""Predicts the final answer to the question, based on the question and the attention. :param in_features: input size of the first feed forward layer :param mid_features: input size of the intermediates feed forward... | stack_v2_sparse_classes_36k_train_006257 | 7,763 | permissive | [
{
"docstring": "Predicts the final answer to the question, based on the question and the attention. :param in_features: input size of the first feed forward layer :param mid_features: input size of the intermediates feed forward layers :param out_features: output size",
"name": "__init__",
"signature": ... | 2 | null | Implement the Python class `Classifier` described below.
Class description:
Implement the Classifier class.
Method signatures and docstrings:
- def __init__(self, in_features, mid_features, out_features): Predicts the final answer to the question, based on the question and the attention. :param in_features: input siz... | Implement the Python class `Classifier` described below.
Class description:
Implement the Classifier class.
Method signatures and docstrings:
- def __init__(self, in_features, mid_features, out_features): Predicts the final answer to the question, based on the question and the attention. :param in_features: input siz... | c655c88cc6aec4d0724c19ea95209f1c2dd6770d | <|skeleton|>
class Classifier:
def __init__(self, in_features, mid_features, out_features):
"""Predicts the final answer to the question, based on the question and the attention. :param in_features: input size of the first feed forward layer :param mid_features: input size of the intermediates feed forward... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Classifier:
def __init__(self, in_features, mid_features, out_features):
"""Predicts the final answer to the question, based on the question and the attention. :param in_features: input size of the first feed forward layer :param mid_features: input size of the intermediates feed forward layers :param... | the_stack_v2_python_sparse | models/multi_hops_attention/multi_hops_attention.py | aasseman/mi-prometheus | train | 0 | |
4110e5cc6fb282d5f1d85ae46d1991e8e46a6a14 | [
"self.post_script = post_script\nself.pre_script = pre_script\nself.uptier_params = uptier_params",
"if dictionary is None:\n return None\npost_script = cohesity_management_sdk.models.remote_script_proto.RemoteScriptProto.from_dictionary(dictionary.get('postScript')) if dictionary.get('postScript') else None\n... | <|body_start_0|>
self.post_script = post_script
self.pre_script = pre_script
self.uptier_params = uptier_params
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
post_script = cohesity_management_sdk.models.remote_script_proto.RemoteScriptProto.from_... | Implementation of the 'RestoreTaskAdditionalParams' model. Message to encapsulate the additional parameters associated with a restore task. Attributes: post_script (RemoteScriptProto): Post-script that must be executed after finishing the restore. pre_script (RemoteScriptProto): Pre-script that must be executed before ... | RestoreTaskAdditionalParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreTaskAdditionalParams:
"""Implementation of the 'RestoreTaskAdditionalParams' model. Message to encapsulate the additional parameters associated with a restore task. Attributes: post_script (RemoteScriptProto): Post-script that must be executed after finishing the restore. pre_script (Remot... | stack_v2_sparse_classes_36k_train_006258 | 2,579 | permissive | [
{
"docstring": "Constructor for the RestoreTaskAdditionalParams class",
"name": "__init__",
"signature": "def __init__(self, post_script=None, pre_script=None, uptier_params=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary ... | 2 | null | Implement the Python class `RestoreTaskAdditionalParams` described below.
Class description:
Implementation of the 'RestoreTaskAdditionalParams' model. Message to encapsulate the additional parameters associated with a restore task. Attributes: post_script (RemoteScriptProto): Post-script that must be executed after f... | Implement the Python class `RestoreTaskAdditionalParams` described below.
Class description:
Implementation of the 'RestoreTaskAdditionalParams' model. Message to encapsulate the additional parameters associated with a restore task. Attributes: post_script (RemoteScriptProto): Post-script that must be executed after f... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreTaskAdditionalParams:
"""Implementation of the 'RestoreTaskAdditionalParams' model. Message to encapsulate the additional parameters associated with a restore task. Attributes: post_script (RemoteScriptProto): Post-script that must be executed after finishing the restore. pre_script (Remot... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoreTaskAdditionalParams:
"""Implementation of the 'RestoreTaskAdditionalParams' model. Message to encapsulate the additional parameters associated with a restore task. Attributes: post_script (RemoteScriptProto): Post-script that must be executed after finishing the restore. pre_script (RemoteScriptProto)... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_task_additional_params.py | cohesity/management-sdk-python | train | 24 |
baa827a956be4c1d29a3463f5e42c548de3b71b2 | [
"self.comment = comment\nself.policy = policy\nself.protocol = protocol\nself.dest_port = dest_port\nself.dest_cidr = dest_cidr",
"if dictionary is None:\n return None\npolicy = dictionary.get('policy')\nprotocol = dictionary.get('protocol')\ndest_cidr = dictionary.get('destCidr')\ncomment = dictionary.get('co... | <|body_start_0|>
self.comment = comment
self.policy = policy
self.protocol = protocol
self.dest_port = dest_port
self.dest_cidr = dest_cidr
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
policy = dictionary.get('policy')
pr... | Implementation of the 'Rule8' model. TODO: type model description here. Attributes: comment (string): Description of the rule (optional) policy (string): 'allow' or 'deny' traffic specified by this rule protocol (string): The type of protocol (must be 'tcp', 'udp', 'icmp' or 'any') dest_port (string): Comma-separated l... | Rule8Model | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule8Model:
"""Implementation of the 'Rule8' model. TODO: type model description here. Attributes: comment (string): Description of the rule (optional) policy (string): 'allow' or 'deny' traffic specified by this rule protocol (string): The type of protocol (must be 'tcp', 'udp', 'icmp' or 'any')... | stack_v2_sparse_classes_36k_train_006259 | 2,576 | permissive | [
{
"docstring": "Constructor for the Rule8Model class",
"name": "__init__",
"signature": "def __init__(self, policy=None, protocol=None, dest_cidr=None, comment=None, dest_port=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionar... | 2 | null | Implement the Python class `Rule8Model` described below.
Class description:
Implementation of the 'Rule8' model. TODO: type model description here. Attributes: comment (string): Description of the rule (optional) policy (string): 'allow' or 'deny' traffic specified by this rule protocol (string): The type of protocol ... | Implement the Python class `Rule8Model` described below.
Class description:
Implementation of the 'Rule8' model. TODO: type model description here. Attributes: comment (string): Description of the rule (optional) policy (string): 'allow' or 'deny' traffic specified by this rule protocol (string): The type of protocol ... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class Rule8Model:
"""Implementation of the 'Rule8' model. TODO: type model description here. Attributes: comment (string): Description of the rule (optional) policy (string): 'allow' or 'deny' traffic specified by this rule protocol (string): The type of protocol (must be 'tcp', 'udp', 'icmp' or 'any')... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rule8Model:
"""Implementation of the 'Rule8' model. TODO: type model description here. Attributes: comment (string): Description of the rule (optional) policy (string): 'allow' or 'deny' traffic specified by this rule protocol (string): The type of protocol (must be 'tcp', 'udp', 'icmp' or 'any') dest_port (s... | the_stack_v2_python_sparse | meraki/models/rule8_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
444c933da2aa8a9ba07727fc24653096bed66861 | [
"self.device = device\nself.conn_cmd = conn_cmd\nself.device.conn_cmd = conn_cmd",
"bft_pexpect_helper.spawn.__init__(self.device, command='/bin/bash', args=['-c', self.conn_cmd])\ntry:\n result = self.device.expect(['assword:', 'ser2net.*\\r\\n', 'OpenGear Serial Server', 'to access the port escape menu'])\ne... | <|body_start_0|>
self.device = device
self.conn_cmd = conn_cmd
self.device.conn_cmd = conn_cmd
<|end_body_0|>
<|body_start_1|>
bft_pexpect_helper.spawn.__init__(self.device, command='/bin/bash', args=['-c', self.conn_cmd])
try:
result = self.device.expect(['assword:'... | The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board. | Ser2NetConnection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ser2NetConnection:
"""The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board."""
def __init__(self, device=None, conn_cmd=None, **kwarg... | stack_v2_sparse_classes_36k_train_006260 | 2,190 | permissive | [
{
"docstring": "This method initializes the class instance to open a pexpect session. :param device: device to connect, defaults to None :type device: object :param conn_cmd: conn_cmd to connect to device, defaults to None :type conn_cmd: string :param **kwargs: args to be used :type **kwargs: dict",
"name"... | 3 | stack_v2_sparse_classes_30k_train_013657 | Implement the Python class `Ser2NetConnection` described below.
Class description:
The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board.
Method signatures and ... | Implement the Python class `Ser2NetConnection` described below.
Class description:
The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board.
Method signatures and ... | 100521fde1fb67536682cafecc2f91a6e2e8a6f8 | <|skeleton|>
class Ser2NetConnection:
"""The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board."""
def __init__(self, device=None, conn_cmd=None, **kwarg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ser2NetConnection:
"""The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board."""
def __init__(self, device=None, conn_cmd=None, **kwargs):
"... | the_stack_v2_python_sparse | boardfarm/devices/ser2net_connection.py | mattsm/boardfarm | train | 45 |
ef0b2001a6fcc9e6832332aa952d345c674c2056 | [
"super(SpatialNet, self).__init__()\nif arch == 's2vt':\n self.caption_net = S2VTModel(glove_loader, dropout_p, hidden_size, vid_feat_size, max_len)\nelif arch == 's2vt-att':\n self.caption_net = S2VTAttModel(glove_loader, dropout_p, hidden_size, vid_feat_size, max_len)\nelse:\n raise NotImplementedError('... | <|body_start_0|>
super(SpatialNet, self).__init__()
if arch == 's2vt':
self.caption_net = S2VTModel(glove_loader, dropout_p, hidden_size, vid_feat_size, max_len)
elif arch == 's2vt-att':
self.caption_net = S2VTAttModel(glove_loader, dropout_p, hidden_size, vid_feat_size, ... | Spatial attention networks using YOLOv3 as backbone | SpatialNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialNet:
"""Spatial attention networks using YOLOv3 as backbone"""
def __init__(self, glove_loader, dropout_p, hidden_size, vid_feat_size, max_len, arch):
"""Args: glove_loader: GLoVe embedding loader dropout_p: Dropout probability for intermediate dropout layers hidden_size: Size... | stack_v2_sparse_classes_36k_train_006261 | 5,316 | no_license | [
{
"docstring": "Args: glove_loader: GLoVe embedding loader dropout_p: Dropout probability for intermediate dropout layers hidden_size: Size of the intermediate linear layers vid_feat_size: Size of the video features max_len: Max length to rollout arch: video captioning network ['s2vt' | 's2vt-att']",
"name"... | 2 | stack_v2_sparse_classes_30k_train_021240 | Implement the Python class `SpatialNet` described below.
Class description:
Spatial attention networks using YOLOv3 as backbone
Method signatures and docstrings:
- def __init__(self, glove_loader, dropout_p, hidden_size, vid_feat_size, max_len, arch): Args: glove_loader: GLoVe embedding loader dropout_p: Dropout prob... | Implement the Python class `SpatialNet` described below.
Class description:
Spatial attention networks using YOLOv3 as backbone
Method signatures and docstrings:
- def __init__(self, glove_loader, dropout_p, hidden_size, vid_feat_size, max_len, arch): Args: glove_loader: GLoVe embedding loader dropout_p: Dropout prob... | 5f347de39f5583cd043c6f572178da08f7c0de94 | <|skeleton|>
class SpatialNet:
"""Spatial attention networks using YOLOv3 as backbone"""
def __init__(self, glove_loader, dropout_p, hidden_size, vid_feat_size, max_len, arch):
"""Args: glove_loader: GLoVe embedding loader dropout_p: Dropout probability for intermediate dropout layers hidden_size: Size... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpatialNet:
"""Spatial attention networks using YOLOv3 as backbone"""
def __init__(self, glove_loader, dropout_p, hidden_size, vid_feat_size, max_len, arch):
"""Args: glove_loader: GLoVe embedding loader dropout_p: Dropout probability for intermediate dropout layers hidden_size: Size of the inter... | the_stack_v2_python_sparse | model/SpatialNet.py | AmmieQi/pytorch-video-caption-rationale | train | 0 |
ec2de037caa934fae26890a823a4795a64c0cc2f | [
"try:\n sh.zfs('list', '-t', 'volume', self.name)\nexcept sh.ErrorReturnCode_1:\n return False\nreturn True",
"try:\n opts = ['create']\n if sparse:\n opts.append('-s')\n if block_size:\n opts.extend(['-b', block_size])\n if mkparent:\n opts.append('-p')\n opts.extend(['-... | <|body_start_0|>
try:
sh.zfs('list', '-t', 'volume', self.name)
except sh.ErrorReturnCode_1:
return False
return True
<|end_body_0|>
<|body_start_1|>
try:
opts = ['create']
if sparse:
opts.append('-s')
if block_... | Volume | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Volume:
def exists(self):
"""Checks if volume exists. volume = Volume('dpool/tmp/test0') volume.exists()"""
<|body_0|>
def create(self, size, sparse=False, block_size=None, mkparent=False):
"""Creates storage volume. volume = Volume('dpool/tmp/test0') volume.create()... | stack_v2_sparse_classes_36k_train_006262 | 13,193 | no_license | [
{
"docstring": "Checks if volume exists. volume = Volume('dpool/tmp/test0') volume.exists()",
"name": "exists",
"signature": "def exists(self)"
},
{
"docstring": "Creates storage volume. volume = Volume('dpool/tmp/test0') volume.create()",
"name": "create",
"signature": "def create(self,... | 4 | stack_v2_sparse_classes_30k_train_018840 | Implement the Python class `Volume` described below.
Class description:
Implement the Volume class.
Method signatures and docstrings:
- def exists(self): Checks if volume exists. volume = Volume('dpool/tmp/test0') volume.exists()
- def create(self, size, sparse=False, block_size=None, mkparent=False): Creates storage... | Implement the Python class `Volume` described below.
Class description:
Implement the Volume class.
Method signatures and docstrings:
- def exists(self): Checks if volume exists. volume = Volume('dpool/tmp/test0') volume.exists()
- def create(self, size, sparse=False, block_size=None, mkparent=False): Creates storage... | 9bc47e6eeff2944f98a0db4fcab32c5dd95fd025 | <|skeleton|>
class Volume:
def exists(self):
"""Checks if volume exists. volume = Volume('dpool/tmp/test0') volume.exists()"""
<|body_0|>
def create(self, size, sparse=False, block_size=None, mkparent=False):
"""Creates storage volume. volume = Volume('dpool/tmp/test0') volume.create()... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Volume:
def exists(self):
"""Checks if volume exists. volume = Volume('dpool/tmp/test0') volume.exists()"""
try:
sh.zfs('list', '-t', 'volume', self.name)
except sh.ErrorReturnCode_1:
return False
return True
def create(self, size, sparse=False, blo... | the_stack_v2_python_sparse | solarsanweb/storage/dataset.py | akatrevorjay/solarsanweb | train | 1 | |
c80b7956fa0bf97525d3d975235fba44712a339e | [
"ans = ''\ni = 0\ndominoes = list(dominoes)\nwhile i < len(dominoes):\n if dominoes[i] == '.':\n if i + 1 < len(dominoes) and dominoes[i + 1] == 'L':\n ans += 'L'\n else:\n ans += '.'\n i += 1\n elif dominoes[i] == 'L':\n ans += 'L'\n i += 1\n elif i... | <|body_start_0|>
ans = ''
i = 0
dominoes = list(dominoes)
while i < len(dominoes):
if dominoes[i] == '.':
if i + 1 < len(dominoes) and dominoes[i + 1] == 'L':
ans += 'L'
else:
ans += '.'
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pushDominoes(self, dominoes):
""":type dominoes: str :rtype: str"""
<|body_0|>
def pushDominoes2(self, dominoes):
""":type dominoes: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = ''
i = 0
dominoe... | stack_v2_sparse_classes_36k_train_006263 | 1,783 | no_license | [
{
"docstring": ":type dominoes: str :rtype: str",
"name": "pushDominoes",
"signature": "def pushDominoes(self, dominoes)"
},
{
"docstring": ":type dominoes: str :rtype: str",
"name": "pushDominoes2",
"signature": "def pushDominoes2(self, dominoes)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006828 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pushDominoes(self, dominoes): :type dominoes: str :rtype: str
- def pushDominoes2(self, dominoes): :type dominoes: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pushDominoes(self, dominoes): :type dominoes: str :rtype: str
- def pushDominoes2(self, dominoes): :type dominoes: str :rtype: str
<|skeleton|>
class Solution:
def push... | 143aa25f92f3827aa379f29c67a9b7ec3757fef9 | <|skeleton|>
class Solution:
def pushDominoes(self, dominoes):
""":type dominoes: str :rtype: str"""
<|body_0|>
def pushDominoes2(self, dominoes):
""":type dominoes: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pushDominoes(self, dominoes):
""":type dominoes: str :rtype: str"""
ans = ''
i = 0
dominoes = list(dominoes)
while i < len(dominoes):
if dominoes[i] == '.':
if i + 1 < len(dominoes) and dominoes[i + 1] == 'L':
... | the_stack_v2_python_sparse | py/leetcode_py/contest/85/838.py | imsure/tech-interview-prep | train | 0 | |
63fbd1b34b2ff4ce29eb2cd8ac26d2f9b9de7c35 | [
"try:\n if Utils.is_valid_user(request, _id):\n user = User.objects.get(id=_id)\n serializer = UserSerializer(user, context={'request': request})\n return Utils.dispatch_success(OK, serializer.data)\n else:\n return Utils.dispatch_failure(UNAUTHORIZED_ACCESS)\nexcept User.DoesNotEx... | <|body_start_0|>
try:
if Utils.is_valid_user(request, _id):
user = User.objects.get(id=_id)
serializer = UserSerializer(user, context={'request': request})
return Utils.dispatch_success(OK, serializer.data)
else:
return Util... | Retrieve, update or delete a user interface | UserDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDetail:
"""Retrieve, update or delete a user interface"""
def get(self, request, _id):
"""Gets the Detail of a user by their ID"""
<|body_0|>
def put(self, request, _id):
"""Updates the user by their ID"""
<|body_1|>
def delete(self, _id, format=... | stack_v2_sparse_classes_36k_train_006264 | 45,124 | no_license | [
{
"docstring": "Gets the Detail of a user by their ID",
"name": "get",
"signature": "def get(self, request, _id)"
},
{
"docstring": "Updates the user by their ID",
"name": "put",
"signature": "def put(self, request, _id)"
},
{
"docstring": "Deletes the user by their ID",
"nam... | 3 | stack_v2_sparse_classes_30k_train_009736 | Implement the Python class `UserDetail` described below.
Class description:
Retrieve, update or delete a user interface
Method signatures and docstrings:
- def get(self, request, _id): Gets the Detail of a user by their ID
- def put(self, request, _id): Updates the user by their ID
- def delete(self, _id, format=None... | Implement the Python class `UserDetail` described below.
Class description:
Retrieve, update or delete a user interface
Method signatures and docstrings:
- def get(self, request, _id): Gets the Detail of a user by their ID
- def put(self, request, _id): Updates the user by their ID
- def delete(self, _id, format=None... | dbcf886a7cf2d2fb12400a0f1b3e85e8da5cd56b | <|skeleton|>
class UserDetail:
"""Retrieve, update or delete a user interface"""
def get(self, request, _id):
"""Gets the Detail of a user by their ID"""
<|body_0|>
def put(self, request, _id):
"""Updates the user by their ID"""
<|body_1|>
def delete(self, _id, format=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserDetail:
"""Retrieve, update or delete a user interface"""
def get(self, request, _id):
"""Gets the Detail of a user by their ID"""
try:
if Utils.is_valid_user(request, _id):
user = User.objects.get(id=_id)
serializer = UserSerializer(user, c... | the_stack_v2_python_sparse | Python/ixcoin_backend/api/accounts/views.py | ionixx-tech/ix_code_samples | train | 0 |
05c093bca295c9ce42b50af1c663f703bde07509 | [
"self.R = r\nself.G = g\nself.B = b\nself.sample_spacing = sample_spacing\nself.samples_x, self.samples_y = r.shape\nself.center_x = self.samples_x // 2\nself.center_y = self.samples_y // 2\nself.ext_x = sample_spacing * self.center_x\nself.ext_y = sample_spacing * self.center_y\nself.synthetic = synthetic",
"lim... | <|body_start_0|>
self.R = r
self.G = g
self.B = b
self.sample_spacing = sample_spacing
self.samples_x, self.samples_y = r.shape
self.center_x = self.samples_x // 2
self.center_y = self.samples_y // 2
self.ext_x = sample_spacing * self.center_x
self... | RGB images | RGBImage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RGBImage:
"""RGB images"""
def __init__(self, r, g, b, sample_spacing, synthetic=True):
"""creates a new RGB image Args: r (`Image`): array for the red channel. g (`Image`): array for the green channel. b (`Image`): array for the blue channel. sample_spacing (`float`): spacing betwee... | stack_v2_sparse_classes_36k_train_006265 | 15,805 | permissive | [
{
"docstring": "creates a new RGB image Args: r (`Image`): array for the red channel. g (`Image`): array for the green channel. b (`Image`): array for the blue channel. sample_spacing (`float`): spacing between samples, in microns. synthetic (`bool`): whether or not the image is synthetic. Real images are upsid... | 6 | stack_v2_sparse_classes_30k_train_013823 | Implement the Python class `RGBImage` described below.
Class description:
RGB images
Method signatures and docstrings:
- def __init__(self, r, g, b, sample_spacing, synthetic=True): creates a new RGB image Args: r (`Image`): array for the red channel. g (`Image`): array for the green channel. b (`Image`): array for t... | Implement the Python class `RGBImage` described below.
Class description:
RGB images
Method signatures and docstrings:
- def __init__(self, r, g, b, sample_spacing, synthetic=True): creates a new RGB image Args: r (`Image`): array for the red channel. g (`Image`): array for the green channel. b (`Image`): array for t... | 0716710317cd057d33283eb4551df59c6c65579c | <|skeleton|>
class RGBImage:
"""RGB images"""
def __init__(self, r, g, b, sample_spacing, synthetic=True):
"""creates a new RGB image Args: r (`Image`): array for the red channel. g (`Image`): array for the green channel. b (`Image`): array for the blue channel. sample_spacing (`float`): spacing betwee... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RGBImage:
"""RGB images"""
def __init__(self, r, g, b, sample_spacing, synthetic=True):
"""creates a new RGB image Args: r (`Image`): array for the red channel. g (`Image`): array for the green channel. b (`Image`): array for the blue channel. sample_spacing (`float`): spacing between samples, in... | the_stack_v2_python_sparse | prysm/objects.py | MichaelMauderer/prysm | train | 0 |
84ca6ffd7994517b9735b1b6b3844aa37c67c2c6 | [
"l, r = (0, len(nums) - 1)\nwhile l <= r:\n m = (l + r) // 2\n if nums[m] < target:\n l = m + 1\n else:\n r = m - 1\nif l == len(nums) or nums[l] != target:\n return [-1, -1]\nretl = l\nl, r = (0, len(nums) - 1)\nwhile l <= r:\n m = (l + r) // 2\n if nums[m] <= target:\n l = m... | <|body_start_0|>
l, r = (0, len(nums) - 1)
while l <= r:
m = (l + r) // 2
if nums[m] < target:
l = m + 1
else:
r = m - 1
if l == len(nums) or nums[l] != target:
return [-1, -1]
retl = l
l, r = (0, len... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchRange_lowerandupperboundbinarysearch(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def searchRange_myself(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
... | stack_v2_sparse_classes_36k_train_006266 | 1,649 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "searchRange_lowerandupperboundbinarysearch",
"signature": "def searchRange_lowerandupperboundbinarysearch(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"... | 2 | stack_v2_sparse_classes_30k_train_020669 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange_lowerandupperboundbinarysearch(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def searchRange_myself(self, nums, target): :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange_lowerandupperboundbinarysearch(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def searchRange_myself(self, nums, target): :type ... | a7916e0818b0853ec75e24724bde94c49234c7dc | <|skeleton|>
class Solution:
def searchRange_lowerandupperboundbinarysearch(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def searchRange_myself(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchRange_lowerandupperboundbinarysearch(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
l, r = (0, len(nums) - 1)
while l <= r:
m = (l + r) // 2
if nums[m] < target:
l = m + 1
else... | the_stack_v2_python_sparse | 34.py | KevinWangTHU/LeetCode | train | 0 | |
1ec205724032467c9c22fa6c21828829fd81a532 | [
"if not nums:\n return False\n_set = set(nums)\nreturn len(_set) != len(nums)",
"if not nums:\n return False\nnum_idx = {}\nfor idx, num in enumerate(nums):\n if num not in num_idx:\n num_idx[num] = idx\n continue\n if idx - num_idx[num] <= k:\n return True\n num_idx[num] = idx... | <|body_start_0|>
if not nums:
return False
_set = set(nums)
return len(_set) != len(nums)
<|end_body_0|>
<|body_start_1|>
if not nums:
return False
num_idx = {}
for idx, num in enumerate(nums):
if num not in num_idx:
nu... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsDuplicate(self, nums):
"""https://leetcode.com/problems/contains-duplicate/ :type nums: List[int] :rtype: bool"""
<|body_0|>
def containsDuplicate_ii(self, nums, k):
"""https://leetcode.com/problems/contains-duplicate-ii/ :type nums: List[int] :... | stack_v2_sparse_classes_36k_train_006267 | 884 | permissive | [
{
"docstring": "https://leetcode.com/problems/contains-duplicate/ :type nums: List[int] :rtype: bool",
"name": "containsDuplicate",
"signature": "def containsDuplicate(self, nums)"
},
{
"docstring": "https://leetcode.com/problems/contains-duplicate-ii/ :type nums: List[int] :rtype: bool",
"n... | 2 | stack_v2_sparse_classes_30k_train_011301 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsDuplicate(self, nums): https://leetcode.com/problems/contains-duplicate/ :type nums: List[int] :rtype: bool
- def containsDuplicate_ii(self, nums, k): https://leetcod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsDuplicate(self, nums): https://leetcode.com/problems/contains-duplicate/ :type nums: List[int] :rtype: bool
- def containsDuplicate_ii(self, nums, k): https://leetcod... | 88f0a0eb377fbf9d233e599736c740bb83b8ccef | <|skeleton|>
class Solution:
def containsDuplicate(self, nums):
"""https://leetcode.com/problems/contains-duplicate/ :type nums: List[int] :rtype: bool"""
<|body_0|>
def containsDuplicate_ii(self, nums, k):
"""https://leetcode.com/problems/contains-duplicate-ii/ :type nums: List[int] :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containsDuplicate(self, nums):
"""https://leetcode.com/problems/contains-duplicate/ :type nums: List[int] :rtype: bool"""
if not nums:
return False
_set = set(nums)
return len(_set) != len(nums)
def containsDuplicate_ii(self, nums, k):
"""... | the_stack_v2_python_sparse | array_function/contains_duplicate.py | lycheng/leetcode | train | 0 | |
26785751065b87146ccd135f98b0c68a1ef80a91 | [
"url = '/api/v1.2/graph-connections/%d/job-manager/%d/upload-file/next-step' % (graph_id, job_id)\ncode, res = Request().request(method='put', path=url, types='hubble')\nreturn (code, res)",
"url = '/api/v1.2/graph-connections/%d/job-manager/%d/file-mappings/next-step' % (graph_id, job_id)\ncode, res = Request().... | <|body_start_0|>
url = '/api/v1.2/graph-connections/%d/job-manager/%d/upload-file/next-step' % (graph_id, job_id)
code, res = Request().request(method='put', path=url, types='hubble')
return (code, res)
<|end_body_0|>
<|body_start_1|>
url = '/api/v1.2/graph-connections/%d/job-manager/%d... | 导入过程中会有下一步的操作 | Step | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Step:
"""导入过程中会有下一步的操作"""
def upload_file_next_step(graph_id, job_id, auth=None):
"""上传文件完成,点击下一步 :param auth: :param graph_id: :param job_id:导入任务ID :return:"""
<|body_0|>
def mapping_complete_next_step(graph_id, job_id, auth=None):
"""设置映射完成,点击下一步 :param auth: :... | stack_v2_sparse_classes_36k_train_006268 | 26,078 | no_license | [
{
"docstring": "上传文件完成,点击下一步 :param auth: :param graph_id: :param job_id:导入任务ID :return:",
"name": "upload_file_next_step",
"signature": "def upload_file_next_step(graph_id, job_id, auth=None)"
},
{
"docstring": "设置映射完成,点击下一步 :param auth: :param graph_id: :param job_id:导入任务ID :return:",
"nam... | 2 | stack_v2_sparse_classes_30k_train_014758 | Implement the Python class `Step` described below.
Class description:
导入过程中会有下一步的操作
Method signatures and docstrings:
- def upload_file_next_step(graph_id, job_id, auth=None): 上传文件完成,点击下一步 :param auth: :param graph_id: :param job_id:导入任务ID :return:
- def mapping_complete_next_step(graph_id, job_id, auth=None): 设置映射完成... | Implement the Python class `Step` described below.
Class description:
导入过程中会有下一步的操作
Method signatures and docstrings:
- def upload_file_next_step(graph_id, job_id, auth=None): 上传文件完成,点击下一步 :param auth: :param graph_id: :param job_id:导入任务ID :return:
- def mapping_complete_next_step(graph_id, job_id, auth=None): 设置映射完成... | 89e5b34ab925bcc0bbc4ad63302e96c62a420399 | <|skeleton|>
class Step:
"""导入过程中会有下一步的操作"""
def upload_file_next_step(graph_id, job_id, auth=None):
"""上传文件完成,点击下一步 :param auth: :param graph_id: :param job_id:导入任务ID :return:"""
<|body_0|>
def mapping_complete_next_step(graph_id, job_id, auth=None):
"""设置映射完成,点击下一步 :param auth: :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Step:
"""导入过程中会有下一步的操作"""
def upload_file_next_step(graph_id, job_id, auth=None):
"""上传文件完成,点击下一步 :param auth: :param graph_id: :param job_id:导入任务ID :return:"""
url = '/api/v1.2/graph-connections/%d/job-manager/%d/upload-file/next-step' % (graph_id, job_id)
code, res = Request().r... | the_stack_v2_python_sparse | src/common/hubble_api.py | hugegraph/hugegraph-test | train | 1 |
368f3d65b3dcbbfb9b9ff08b82a8748cb8826381 | [
"super().setUp()\nself.signup(self.CURRICULUM_ADMIN_EMAIL, self.CURRICULUM_ADMIN_USERNAME)\nself.signup(self.ALBERT_EMAIL, self.ALBERT_NAME)\nself.admin_id = self.get_user_id_from_email(self.CURRICULUM_ADMIN_EMAIL)\nself.albert_id = self.get_user_id_from_email(self.ALBERT_EMAIL)\nself.albert = user_services.get_use... | <|body_start_0|>
super().setUp()
self.signup(self.CURRICULUM_ADMIN_EMAIL, self.CURRICULUM_ADMIN_USERNAME)
self.signup(self.ALBERT_EMAIL, self.ALBERT_NAME)
self.admin_id = self.get_user_id_from_email(self.CURRICULUM_ADMIN_EMAIL)
self.albert_id = self.get_user_id_from_email(self.AL... | Test functions for getting displayable featured exploration summary dicts. | FeaturedExplorationDisplayableSummariesTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeaturedExplorationDisplayableSummariesTest:
"""Test functions for getting displayable featured exploration summary dicts."""
def setUp(self) -> None:
"""Populate the database of explorations and their summaries. The sequence of events is: - (1) Albert creates EXP_ID_1. - (2) Albert ... | stack_v2_sparse_classes_36k_train_006269 | 47,358 | permissive | [
{
"docstring": "Populate the database of explorations and their summaries. The sequence of events is: - (1) Albert creates EXP_ID_1. - (2) Albert creates EXP_ID_2. - (3) Albert publishes EXP_ID_1. - (4) Albert publishes EXP_ID_2. - (5) Admin user is set up.",
"name": "setUp",
"signature": "def setUp(sel... | 3 | stack_v2_sparse_classes_30k_train_013111 | Implement the Python class `FeaturedExplorationDisplayableSummariesTest` described below.
Class description:
Test functions for getting displayable featured exploration summary dicts.
Method signatures and docstrings:
- def setUp(self) -> None: Populate the database of explorations and their summaries. The sequence o... | Implement the Python class `FeaturedExplorationDisplayableSummariesTest` described below.
Class description:
Test functions for getting displayable featured exploration summary dicts.
Method signatures and docstrings:
- def setUp(self) -> None: Populate the database of explorations and their summaries. The sequence o... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class FeaturedExplorationDisplayableSummariesTest:
"""Test functions for getting displayable featured exploration summary dicts."""
def setUp(self) -> None:
"""Populate the database of explorations and their summaries. The sequence of events is: - (1) Albert creates EXP_ID_1. - (2) Albert ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeaturedExplorationDisplayableSummariesTest:
"""Test functions for getting displayable featured exploration summary dicts."""
def setUp(self) -> None:
"""Populate the database of explorations and their summaries. The sequence of events is: - (1) Albert creates EXP_ID_1. - (2) Albert creates EXP_I... | the_stack_v2_python_sparse | core/domain/summary_services_test.py | oppia/oppia | train | 6,172 |
b987288ced37df5ad4d24205178835718bb069cd | [
"\"\"\"counter\"\"\"\nself.__i = 0\n'time x y coordinates for turning points in bonnmotion trace'\nself.__data = []\n'speed value for each turn'\nself.__speed = 1\nself.x = 0\nself.y = 0\nself.id = len(self.ghosts)\nwith gzip.open(tracefile, 'rt') as file:\n j = 0\n for line in file:\n rargs = [(',\\n'... | <|body_start_0|>
"""counter"""
self.__i = 0
'time x y coordinates for turning points in bonnmotion trace'
self.__data = []
'speed value for each turn'
self.__speed = 1
self.x = 0
self.y = 0
self.id = len(self.ghosts)
with gzip.open(tracefil... | all ghosts | Ghost | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ghost:
"""all ghosts"""
def __init__(self, transformation, tracefile, nodenumber, **kwargs):
"""Initialize Ghost. Processes the bonnmotion trace. :param transformation: Transformation object to transform Geo to screen coords :param tracefile: bonnmotion tracefile :param nodenumber: n... | stack_v2_sparse_classes_36k_train_006270 | 3,381 | no_license | [
{
"docstring": "Initialize Ghost. Processes the bonnmotion trace. :param transformation: Transformation object to transform Geo to screen coords :param tracefile: bonnmotion tracefile :param nodenumber: number of node which should be taken in bonnmotion trace :param kwargs:",
"name": "__init__",
"signat... | 2 | stack_v2_sparse_classes_30k_train_010354 | Implement the Python class `Ghost` described below.
Class description:
all ghosts
Method signatures and docstrings:
- def __init__(self, transformation, tracefile, nodenumber, **kwargs): Initialize Ghost. Processes the bonnmotion trace. :param transformation: Transformation object to transform Geo to screen coords :p... | Implement the Python class `Ghost` described below.
Class description:
all ghosts
Method signatures and docstrings:
- def __init__(self, transformation, tracefile, nodenumber, **kwargs): Initialize Ghost. Processes the bonnmotion trace. :param transformation: Transformation object to transform Geo to screen coords :p... | 43314baad7a33087b914db4406a05b4ed1cb392c | <|skeleton|>
class Ghost:
"""all ghosts"""
def __init__(self, transformation, tracefile, nodenumber, **kwargs):
"""Initialize Ghost. Processes the bonnmotion trace. :param transformation: Transformation object to transform Geo to screen coords :param tracefile: bonnmotion tracefile :param nodenumber: n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ghost:
"""all ghosts"""
def __init__(self, transformation, tracefile, nodenumber, **kwargs):
"""Initialize Ghost. Processes the bonnmotion trace. :param transformation: Transformation object to transform Geo to screen coords :param tracefile: bonnmotion tracefile :param nodenumber: number of node... | the_stack_v2_python_sparse | tools/Ghost.py | hegerdes/RealWorldPacman | train | 0 |
f1dc1d67d71adc23dad91ea1ba96677645e59ab3 | [
"log.debug('renew subscribe')\nif not service.event_sid or service.event_sid == '':\n return\nself.callback = callback\nself.cargo = cargo\nself.service = service\naddr = '%s%s' % (service.url_base, service.event_sub_url)\nPaddr = parse_url(addr)\nheaders = {}\nheaders['HOST'] = '%s:%d' % (Paddr.hostname, Paddr.... | <|body_start_0|>
log.debug('renew subscribe')
if not service.event_sid or service.event_sid == '':
return
self.callback = callback
self.cargo = cargo
self.service = service
addr = '%s%s' % (service.url_base, service.event_sub_url)
Paddr = parse_url(add... | Wrapper for renew an event subscription. | RenewSubscribeRequest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RenewSubscribeRequest:
"""Wrapper for renew an event subscription."""
def __init__(self, service, event_host, callback, cargo):
"""Constructor for the RenewSubscribeRequest class. @param service: service that is renewing the subscribe @param event_host: 2-tuple (host, port) of the ev... | stack_v2_sparse_classes_36k_train_006271 | 17,901 | permissive | [
{
"docstring": "Constructor for the RenewSubscribeRequest class. @param service: service that is renewing the subscribe @param event_host: 2-tuple (host, port) of the event listener server @param callback: callback @param cargo: callback parameters @type service: Service @type event_host: tuple @type callback: ... | 3 | null | Implement the Python class `RenewSubscribeRequest` described below.
Class description:
Wrapper for renew an event subscription.
Method signatures and docstrings:
- def __init__(self, service, event_host, callback, cargo): Constructor for the RenewSubscribeRequest class. @param service: service that is renewing the su... | Implement the Python class `RenewSubscribeRequest` described below.
Class description:
Wrapper for renew an event subscription.
Method signatures and docstrings:
- def __init__(self, service, event_host, callback, cargo): Constructor for the RenewSubscribeRequest class. @param service: service that is renewing the su... | 69f9c870369085f4440033201e2fb263a463a523 | <|skeleton|>
class RenewSubscribeRequest:
"""Wrapper for renew an event subscription."""
def __init__(self, service, event_host, callback, cargo):
"""Constructor for the RenewSubscribeRequest class. @param service: service that is renewing the subscribe @param event_host: 2-tuple (host, port) of the ev... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RenewSubscribeRequest:
"""Wrapper for renew an event subscription."""
def __init__(self, service, event_host, callback, cargo):
"""Constructor for the RenewSubscribeRequest class. @param service: service that is renewing the subscribe @param event_host: 2-tuple (host, port) of the event listener ... | the_stack_v2_python_sparse | WebBrickLibs/brisa/upnp/control_point/service.py | AndyThirtover/wb_gateway | train | 0 |
dcd5ab7a27c33f863062a70db62305f87e1637b4 | [
"rev = 0\nsign = False\nif x < 0:\n sign = True\n x = -1 * x\nwhile x:\n rev = rev * 10 + x % 10\n x = x // 10\n if sign:\n if -1 * rev < N_MAX:\n return 0\n elif rev > P_MAX:\n return 0\nif sign:\n rev *= -1\nreturn rev",
"rev = 0\nsign = x < 0 and -1 or 1\nx = abs(x... | <|body_start_0|>
rev = 0
sign = False
if x < 0:
sign = True
x = -1 * x
while x:
rev = rev * 10 + x % 10
x = x // 10
if sign:
if -1 * rev < N_MAX:
return 0
elif rev > P_MAX:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x: int) -> int:
""":type x:int :rtype :int"""
<|body_0|>
def reverse(self, x: int) -> int:
""":type x:int :rtype :int"""
<|body_1|>
def reverse1(self, x: int) -> int:
""":type x:int :rtype :int"""
<|body_2|>
<... | stack_v2_sparse_classes_36k_train_006272 | 1,625 | no_license | [
{
"docstring": ":type x:int :rtype :int",
"name": "reverse",
"signature": "def reverse(self, x: int) -> int"
},
{
"docstring": ":type x:int :rtype :int",
"name": "reverse",
"signature": "def reverse(self, x: int) -> int"
},
{
"docstring": ":type x:int :rtype :int",
"name": "r... | 3 | stack_v2_sparse_classes_30k_train_016564 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x: int) -> int: :type x:int :rtype :int
- def reverse(self, x: int) -> int: :type x:int :rtype :int
- def reverse1(self, x: int) -> int: :type x:int :rtype :int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x: int) -> int: :type x:int :rtype :int
- def reverse(self, x: int) -> int: :type x:int :rtype :int
- def reverse1(self, x: int) -> int: :type x:int :rtype :int... | f154f80edf91c20e8b596e29e4e9f904c6a3f2bc | <|skeleton|>
class Solution:
def reverse(self, x: int) -> int:
""":type x:int :rtype :int"""
<|body_0|>
def reverse(self, x: int) -> int:
""":type x:int :rtype :int"""
<|body_1|>
def reverse1(self, x: int) -> int:
""":type x:int :rtype :int"""
<|body_2|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse(self, x: int) -> int:
""":type x:int :rtype :int"""
rev = 0
sign = False
if x < 0:
sign = True
x = -1 * x
while x:
rev = rev * 10 + x % 10
x = x // 10
if sign:
if -1 * rev ... | the_stack_v2_python_sparse | leetcode/Easy/7_reverse.py | huchangchun/learn-python3 | train | 0 | |
65dddc8b19ad30c142dfd1fdaae696e4b4285780 | [
"self.path = path\nself.glob = glob\nself.load_hidden = load_hidden\nself.loader_cls = loader_cls\nself.silent_errors = silent_errors",
"p = Path(self.path)\ndocs = []\nfor i in p.glob(self.glob):\n if i.is_file():\n if _is_visible(i.relative_to(p)) or self.load_hidden:\n try:\n ... | <|body_start_0|>
self.path = path
self.glob = glob
self.load_hidden = load_hidden
self.loader_cls = loader_cls
self.silent_errors = silent_errors
<|end_body_0|>
<|body_start_1|>
p = Path(self.path)
docs = []
for i in p.glob(self.glob):
if i.is... | Loading logic for loading documents from a directory. | DirectoryLoader | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectoryLoader:
"""Loading logic for loading documents from a directory."""
def __init__(self, path: str, glob: str='**/[!.]*', silent_errors: bool=False, load_hidden: bool=False, loader_cls: FILE_LOADER_TYPE=UnstructuredFileLoader):
"""Initialize with path to directory and how to g... | stack_v2_sparse_classes_36k_train_006273 | 1,809 | permissive | [
{
"docstring": "Initialize with path to directory and how to glob over it.",
"name": "__init__",
"signature": "def __init__(self, path: str, glob: str='**/[!.]*', silent_errors: bool=False, load_hidden: bool=False, loader_cls: FILE_LOADER_TYPE=UnstructuredFileLoader)"
},
{
"docstring": "Load doc... | 2 | stack_v2_sparse_classes_30k_train_017917 | Implement the Python class `DirectoryLoader` described below.
Class description:
Loading logic for loading documents from a directory.
Method signatures and docstrings:
- def __init__(self, path: str, glob: str='**/[!.]*', silent_errors: bool=False, load_hidden: bool=False, loader_cls: FILE_LOADER_TYPE=UnstructuredFi... | Implement the Python class `DirectoryLoader` described below.
Class description:
Loading logic for loading documents from a directory.
Method signatures and docstrings:
- def __init__(self, path: str, glob: str='**/[!.]*', silent_errors: bool=False, load_hidden: bool=False, loader_cls: FILE_LOADER_TYPE=UnstructuredFi... | b8f29af7f3c24cf3a4554bebfa2053064467fbdb | <|skeleton|>
class DirectoryLoader:
"""Loading logic for loading documents from a directory."""
def __init__(self, path: str, glob: str='**/[!.]*', silent_errors: bool=False, load_hidden: bool=False, loader_cls: FILE_LOADER_TYPE=UnstructuredFileLoader):
"""Initialize with path to directory and how to g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirectoryLoader:
"""Loading logic for loading documents from a directory."""
def __init__(self, path: str, glob: str='**/[!.]*', silent_errors: bool=False, load_hidden: bool=False, loader_cls: FILE_LOADER_TYPE=UnstructuredFileLoader):
"""Initialize with path to directory and how to glob over it."... | the_stack_v2_python_sparse | langchain/document_loaders/directory.py | microsoft/MM-REACT | train | 705 |
700d7b3df1a5f97a4598fdb8caf9d8e18b5e0c5e | [
"self.pb = ProgressBar(**kwargs)\nself.pool = pool\nself.update_interval = update_interval",
"task = self.pool._cache[job._job]\nn_tasks = task._number_left * task._chunksize\nself.pb.end_value = n_tasks\nself.pb.start()\nwhile task._number_left > 0:\n self.pb.progress(n_tasks - task._number_left * task._chunk... | <|body_start_0|>
self.pb = ProgressBar(**kwargs)
self.pool = pool
self.update_interval = update_interval
<|end_body_0|>
<|body_start_1|>
task = self.pool._cache[job._job]
n_tasks = task._number_left * task._chunksize
self.pb.end_value = n_tasks
self.pb.start()
... | PoolProgress | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoolProgress:
def __init__(self, pool, update_interval=3, **kwargs):
"""Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of workers **kwargs (dict): Additional arguments to ProgressBar update_interval (int, optional): Defaul... | stack_v2_sparse_classes_36k_train_006274 | 4,267 | permissive | [
{
"docstring": "Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of workers **kwargs (dict): Additional arguments to ProgressBar update_interval (int, optional): Defaults to 3. Interval in seconds",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_train_019212 | Implement the Python class `PoolProgress` described below.
Class description:
Implement the PoolProgress class.
Method signatures and docstrings:
- def __init__(self, pool, update_interval=3, **kwargs): Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of... | Implement the Python class `PoolProgress` described below.
Class description:
Implement the PoolProgress class.
Method signatures and docstrings:
- def __init__(self, pool, update_interval=3, **kwargs): Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of... | 30d37a8dd0fca0a7d9a1ed0553b2a3346dfc53e3 | <|skeleton|>
class PoolProgress:
def __init__(self, pool, update_interval=3, **kwargs):
"""Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of workers **kwargs (dict): Additional arguments to ProgressBar update_interval (int, optional): Defaul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PoolProgress:
def __init__(self, pool, update_interval=3, **kwargs):
"""Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of workers **kwargs (dict): Additional arguments to ProgressBar update_interval (int, optional): Defaults to 3. Inter... | the_stack_v2_python_sparse | utils/progress.py | JakobHavtorn/nn | train | 1 | |
2d6c9660aa12c47b11e1c9855ea4c35387fb17b7 | [
"self.exact_dates = exact_dates\nself.granularity = granularity\nself.multiplier = multiplier",
"if dictionary is None:\n return None\nexact_dates = cohesity_management_sdk.models.granularity_bucket_exact_dates_info.GranularityBucket_ExactDatesInfo.from_dictionary(dictionary.get('exactDates')) if dictionary.ge... | <|body_start_0|>
self.exact_dates = exact_dates
self.granularity = granularity
self.multiplier = multiplier
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
exact_dates = cohesity_management_sdk.models.granularity_bucket_exact_dates_info.Granularity... | Implementation of the 'GranularityBucket' model. Message that specifies the frequency granularity at which to copy the snapshots from a backup job's runs. Attributes: exact_dates (GranularityBucket_ExactDatesInfo): Date information for granularity of type kExactDates. Sequence of specific dates on which snapshots need ... | GranularityBucket | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GranularityBucket:
"""Implementation of the 'GranularityBucket' model. Message that specifies the frequency granularity at which to copy the snapshots from a backup job's runs. Attributes: exact_dates (GranularityBucket_ExactDatesInfo): Date information for granularity of type kExactDates. Sequen... | stack_v2_sparse_classes_36k_train_006275 | 2,889 | permissive | [
{
"docstring": "Constructor for the GranularityBucket class",
"name": "__init__",
"signature": "def __init__(self, exact_dates=None, granularity=None, multiplier=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representati... | 2 | null | Implement the Python class `GranularityBucket` described below.
Class description:
Implementation of the 'GranularityBucket' model. Message that specifies the frequency granularity at which to copy the snapshots from a backup job's runs. Attributes: exact_dates (GranularityBucket_ExactDatesInfo): Date information for ... | Implement the Python class `GranularityBucket` described below.
Class description:
Implementation of the 'GranularityBucket' model. Message that specifies the frequency granularity at which to copy the snapshots from a backup job's runs. Attributes: exact_dates (GranularityBucket_ExactDatesInfo): Date information for ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class GranularityBucket:
"""Implementation of the 'GranularityBucket' model. Message that specifies the frequency granularity at which to copy the snapshots from a backup job's runs. Attributes: exact_dates (GranularityBucket_ExactDatesInfo): Date information for granularity of type kExactDates. Sequen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GranularityBucket:
"""Implementation of the 'GranularityBucket' model. Message that specifies the frequency granularity at which to copy the snapshots from a backup job's runs. Attributes: exact_dates (GranularityBucket_ExactDatesInfo): Date information for granularity of type kExactDates. Sequence of specifi... | the_stack_v2_python_sparse | cohesity_management_sdk/models/granularity_bucket.py | cohesity/management-sdk-python | train | 24 |
7c4f99fdee1da42a6cf4a3429a5a9c57a2ab683b | [
"if data is not None:\n assert len(data.shape) >= 2\n self.mean = data.mean(axis=0)\n self.std = data.std(axis=0)\n self.nobservations = data.shape[0]\n self.ndimensions = data.shape[1]\nelse:\n self.nobservations = 0",
"if self.nobservations == 0:\n self.__init__(data)\nelse:\n assert len... | <|body_start_0|>
if data is not None:
assert len(data.shape) >= 2
self.mean = data.mean(axis=0)
self.std = data.std(axis=0)
self.nobservations = data.shape[0]
self.ndimensions = data.shape[1]
else:
self.nobservations = 0
<|end_body_... | StatsRecorder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatsRecorder:
def __init__(self, data=None):
"""data: ndarray, shape (nobservations, ndimensions)"""
<|body_0|>
def update(self, data):
"""data: ndarray, shape (nobservations, ndimensions)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if data is ... | stack_v2_sparse_classes_36k_train_006276 | 3,934 | no_license | [
{
"docstring": "data: ndarray, shape (nobservations, ndimensions)",
"name": "__init__",
"signature": "def __init__(self, data=None)"
},
{
"docstring": "data: ndarray, shape (nobservations, ndimensions)",
"name": "update",
"signature": "def update(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002191 | Implement the Python class `StatsRecorder` described below.
Class description:
Implement the StatsRecorder class.
Method signatures and docstrings:
- def __init__(self, data=None): data: ndarray, shape (nobservations, ndimensions)
- def update(self, data): data: ndarray, shape (nobservations, ndimensions) | Implement the Python class `StatsRecorder` described below.
Class description:
Implement the StatsRecorder class.
Method signatures and docstrings:
- def __init__(self, data=None): data: ndarray, shape (nobservations, ndimensions)
- def update(self, data): data: ndarray, shape (nobservations, ndimensions)
<|skeleton... | 05a8c6451e8f95ab89351b09c015e2b6a3bb2d6a | <|skeleton|>
class StatsRecorder:
def __init__(self, data=None):
"""data: ndarray, shape (nobservations, ndimensions)"""
<|body_0|>
def update(self, data):
"""data: ndarray, shape (nobservations, ndimensions)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatsRecorder:
def __init__(self, data=None):
"""data: ndarray, shape (nobservations, ndimensions)"""
if data is not None:
assert len(data.shape) >= 2
self.mean = data.mean(axis=0)
self.std = data.std(axis=0)
self.nobservations = data.shape[0]
... | the_stack_v2_python_sparse | utils/batch_statistics.py | YuqiaoBai/cia_ssd | train | 1 | |
aa5acaf380f48378dab96e2b4263ebbe03706b65 | [
"if 'context' in data and len(data) == 2:\n\n def _inflate(x):\n return DictSerializable.class_mapping[x['type']].build(x)\n key = next((k for k in data if k != 'context'))\n idx = make_index([_inflate(x) for x in data['context'] + [data[key]]])\n lst = [idx[k] for k in idx]\n substitute_objec... | <|body_start_0|>
if 'context' in data and len(data) == 2:
def _inflate(x):
return DictSerializable.class_mapping[x['type']].build(x)
key = next((k for k in data if k != 'context'))
idx = make_index([_inflate(x) for x in data['context'] + [data[key]]])
... | A reference to a resource by UID. | GEMDResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GEMDResource:
"""A reference to a resource by UID."""
def build(cls, data: dict) -> GEMDSelf:
"""Convert a raw, nested dictionary into Objects."""
<|body_0|>
def as_dict(self) -> dict:
"""Dump to a dictionary (useful for interoperability with gemd). Because of th... | stack_v2_sparse_classes_36k_train_006277 | 3,870 | permissive | [
{
"docstring": "Convert a raw, nested dictionary into Objects.",
"name": "build",
"signature": "def build(cls, data: dict) -> GEMDSelf"
},
{
"docstring": "Dump to a dictionary (useful for interoperability with gemd). Because of the _key mapping in Property, __dict__'s keys are fundamentally diff... | 2 | stack_v2_sparse_classes_30k_train_018839 | Implement the Python class `GEMDResource` described below.
Class description:
A reference to a resource by UID.
Method signatures and docstrings:
- def build(cls, data: dict) -> GEMDSelf: Convert a raw, nested dictionary into Objects.
- def as_dict(self) -> dict: Dump to a dictionary (useful for interoperability with... | Implement the Python class `GEMDResource` described below.
Class description:
A reference to a resource by UID.
Method signatures and docstrings:
- def build(cls, data: dict) -> GEMDSelf: Convert a raw, nested dictionary into Objects.
- def as_dict(self) -> dict: Dump to a dictionary (useful for interoperability with... | 43898bfc66edbe10fab00f614ee68c9ea20c4c52 | <|skeleton|>
class GEMDResource:
"""A reference to a resource by UID."""
def build(cls, data: dict) -> GEMDSelf:
"""Convert a raw, nested dictionary into Objects."""
<|body_0|>
def as_dict(self) -> dict:
"""Dump to a dictionary (useful for interoperability with gemd). Because of th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GEMDResource:
"""A reference to a resource by UID."""
def build(cls, data: dict) -> GEMDSelf:
"""Convert a raw, nested dictionary into Objects."""
if 'context' in data and len(data) == 2:
def _inflate(x):
return DictSerializable.class_mapping[x['type']].build(... | the_stack_v2_python_sparse | src/citrine/_rest/resource.py | CitrineInformatics/citrine-python | train | 30 |
87d338108646b822e705e67591f31e7335f90f67 | [
"if not email:\n raise ValueError(_('The Email must be set'))\nemail = self.normalize_email(email)\nuser = self.model(email=email, **extra_fields)\nuser.set_password(password)\nuser.save()\nreturn user",
"extra_fields.setdefault('is_staff', True)\nextra_fields.setdefault('is_superuser', True)\nextra_fields.set... | <|body_start_0|>
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
<|end_body_0|>
<|body_start_1|>
extra_fi... | CustomUserManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create_superuser(self, email, password, **extra_fields):
"""Create and save a SuperUser with the given email and ... | stack_v2_sparse_classes_36k_train_006278 | 2,810 | permissive | [
{
"docstring": "Create and save a User with the given email and password.",
"name": "create_user",
"signature": "def create_user(self, email, password, **extra_fields)"
},
{
"docstring": "Create and save a SuperUser with the given email and password.",
"name": "create_superuser",
"signat... | 2 | stack_v2_sparse_classes_30k_train_004609 | Implement the Python class `CustomUserManager` described below.
Class description:
Implement the CustomUserManager class.
Method signatures and docstrings:
- def create_user(self, email, password, **extra_fields): Create and save a User with the given email and password.
- def create_superuser(self, email, password, ... | Implement the Python class `CustomUserManager` described below.
Class description:
Implement the CustomUserManager class.
Method signatures and docstrings:
- def create_user(self, email, password, **extra_fields): Create and save a User with the given email and password.
- def create_superuser(self, email, password, ... | 309e711992f9b8aaf41d0f18f3920c3b31533b9c | <|skeleton|>
class CustomUserManager:
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create_superuser(self, email, password, **extra_fields):
"""Create and save a SuperUser with the given email and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomUserManager:
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, *... | the_stack_v2_python_sparse | mysite/accounts/models.py | Lee-Geon-Yeong/py_pro | train | 0 | |
54312d5acfa0455b1212c6a2bde3f1bfe40dd0ac | [
"x, y = tuple_xy\nw, h = tuple_wh\nif orientation == wda.LANDSCAPE:\n x, y = (h - y, x)\nelif orientation == wda.LANDSCAPE_RIGHT:\n x, y = (y, w - x)\nelif orientation == wda.PORTRAIT_UPSIDEDOWN:\n x, y = (w - x, h - y)\nelif orientation == wda.PORTRAIT:\n x, y = (x, y)\nreturn (x, y)",
"x, y = tuple_... | <|body_start_0|>
x, y = tuple_xy
w, h = tuple_wh
if orientation == wda.LANDSCAPE:
x, y = (h - y, x)
elif orientation == wda.LANDSCAPE_RIGHT:
x, y = (y, w - x)
elif orientation == wda.PORTRAIT_UPSIDEDOWN:
x, y = (w - x, h - y)
elif orien... | transform the coordinates (x, y) by orientation (upright <--> original) | XYTransformer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XYTransformer:
"""transform the coordinates (x, y) by orientation (upright <--> original)"""
def up_2_ori(tuple_xy, tuple_wh, orientation):
"""Transform the coordinates upright --> original Args: tuple_xy: coordinates (x, y) tuple_wh: current screen width and height orientation: orie... | stack_v2_sparse_classes_36k_train_006279 | 4,803 | permissive | [
{
"docstring": "Transform the coordinates upright --> original Args: tuple_xy: coordinates (x, y) tuple_wh: current screen width and height orientation: orientation Returns: transformed coordinates (x, y)",
"name": "up_2_ori",
"signature": "def up_2_ori(tuple_xy, tuple_wh, orientation)"
},
{
"do... | 2 | null | Implement the Python class `XYTransformer` described below.
Class description:
transform the coordinates (x, y) by orientation (upright <--> original)
Method signatures and docstrings:
- def up_2_ori(tuple_xy, tuple_wh, orientation): Transform the coordinates upright --> original Args: tuple_xy: coordinates (x, y) tu... | Implement the Python class `XYTransformer` described below.
Class description:
transform the coordinates (x, y) by orientation (upright <--> original)
Method signatures and docstrings:
- def up_2_ori(tuple_xy, tuple_wh, orientation): Transform the coordinates upright --> original Args: tuple_xy: coordinates (x, y) tu... | bf49dfad0be05125df75c64ea47a282132bc03d5 | <|skeleton|>
class XYTransformer:
"""transform the coordinates (x, y) by orientation (upright <--> original)"""
def up_2_ori(tuple_xy, tuple_wh, orientation):
"""Transform the coordinates upright --> original Args: tuple_xy: coordinates (x, y) tuple_wh: current screen width and height orientation: orie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XYTransformer:
"""transform the coordinates (x, y) by orientation (upright <--> original)"""
def up_2_ori(tuple_xy, tuple_wh, orientation):
"""Transform the coordinates upright --> original Args: tuple_xy: coordinates (x, y) tuple_wh: current screen width and height orientation: orientation Retur... | the_stack_v2_python_sparse | airtest/core/ios/rotation.py | AirtestProject/Airtest | train | 7,580 |
38f6a2490e8d8450180c7e0a05f7d1b8cfcd0c40 | [
"self.loss = None\nself.y = None\nself.t = None",
"self.t = t\nself.y = softmax(x)\nself.loss = cross_entropy_error(self.y, self.t)\nreturn self.loss",
"batch_size = self.t.shape[0]\ndx = (self.y - self.t) * (dout / batch_size)\nreturn dx"
] | <|body_start_0|>
self.loss = None
self.y = None
self.t = None
<|end_body_0|>
<|body_start_1|>
self.t = t
self.y = softmax(x)
self.loss = cross_entropy_error(self.y, self.t)
return self.loss
<|end_body_1|>
<|body_start_2|>
batch_size = self.t.shape[0]
... | SoftmaxWithLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftmaxWithLoss:
def __init__(self):
"""Softmax-with-Lossレイヤー"""
<|body_0|>
def forward(self, x, t):
"""順伝播 Args: x (numpy.ndarray): 入力 t (numpy.ndarray): 教師データ Returns: float: 交差エントロピー誤差"""
<|body_1|>
def backward(self, dout=1):
"""逆伝播 Args: dou... | stack_v2_sparse_classes_36k_train_006280 | 1,130 | no_license | [
{
"docstring": "Softmax-with-Lossレイヤー",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "順伝播 Args: x (numpy.ndarray): 入力 t (numpy.ndarray): 教師データ Returns: float: 交差エントロピー誤差",
"name": "forward",
"signature": "def forward(self, x, t)"
},
{
"docstring": "逆伝播 ... | 3 | stack_v2_sparse_classes_30k_train_003038 | Implement the Python class `SoftmaxWithLoss` described below.
Class description:
Implement the SoftmaxWithLoss class.
Method signatures and docstrings:
- def __init__(self): Softmax-with-Lossレイヤー
- def forward(self, x, t): 順伝播 Args: x (numpy.ndarray): 入力 t (numpy.ndarray): 教師データ Returns: float: 交差エントロピー誤差
- def backw... | Implement the Python class `SoftmaxWithLoss` described below.
Class description:
Implement the SoftmaxWithLoss class.
Method signatures and docstrings:
- def __init__(self): Softmax-with-Lossレイヤー
- def forward(self, x, t): 順伝播 Args: x (numpy.ndarray): 入力 t (numpy.ndarray): 教師データ Returns: float: 交差エントロピー誤差
- def backw... | 72b364ad4da8485a201ebdaaa430fd2e95681b0a | <|skeleton|>
class SoftmaxWithLoss:
def __init__(self):
"""Softmax-with-Lossレイヤー"""
<|body_0|>
def forward(self, x, t):
"""順伝播 Args: x (numpy.ndarray): 入力 t (numpy.ndarray): 教師データ Returns: float: 交差エントロピー誤差"""
<|body_1|>
def backward(self, dout=1):
"""逆伝播 Args: dou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SoftmaxWithLoss:
def __init__(self):
"""Softmax-with-Lossレイヤー"""
self.loss = None
self.y = None
self.t = None
def forward(self, x, t):
"""順伝播 Args: x (numpy.ndarray): 入力 t (numpy.ndarray): 教師データ Returns: float: 交差エントロピー誤差"""
self.t = t
self.y = soft... | the_stack_v2_python_sparse | Dfz/Cp5/c5_5_softmax_with_loss.py | masa-k0101/Self-Study_python | train | 1 | |
d2c2b13e48775424e9f4192350abbe2bb051f888 | [
"self.auth_url = 'http://' + ip + ':' + port + '/oauth2/token'\nself.rest_prefix = 'http://' + ip + ':' + port + '/rests/'\nself.auth_data = 'grant_type=password&username=' + username\nself.auth_data += '&password=' + password + '&scope=' + scope\nself.auth_header = {'Content-Type': 'application/x-www-form-urlencod... | <|body_start_0|>
self.auth_url = 'http://' + ip + ':' + port + '/oauth2/token'
self.rest_prefix = 'http://' + ip + ':' + port + '/rests/'
self.auth_data = 'grant_type=password&username=' + username
self.auth_data += '&password=' + password + '&scope=' + scope
self.auth_header = {... | Handling of restconf requests using token-based authentication, one session per request. | _TokenClosingSession | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TokenClosingSession:
"""Handling of restconf requests using token-based authentication, one session per request."""
def __init__(self, ip, username, password, scope, port='8181'):
"""Prepare session initialization data using hardcoded text."""
<|body_0|>
def refresh_tok... | stack_v2_sparse_classes_36k_train_006281 | 9,914 | no_license | [
{
"docstring": "Prepare session initialization data using hardcoded text.",
"name": "__init__",
"signature": "def __init__(self, ip, username, password, scope, port='8181')"
},
{
"docstring": "Reset session, invoke call to get token, parse it and remember.",
"name": "refresh_token",
"sig... | 4 | stack_v2_sparse_classes_30k_train_019748 | Implement the Python class `_TokenClosingSession` described below.
Class description:
Handling of restconf requests using token-based authentication, one session per request.
Method signatures and docstrings:
- def __init__(self, ip, username, password, scope, port='8181'): Prepare session initialization data using h... | Implement the Python class `_TokenClosingSession` described below.
Class description:
Handling of restconf requests using token-based authentication, one session per request.
Method signatures and docstrings:
- def __init__(self, ip, username, password, scope, port='8181'): Prepare session initialization data using h... | ff1bb51a8a14f89ceefd91c6fc535a4bce78e0de | <|skeleton|>
class _TokenClosingSession:
"""Handling of restconf requests using token-based authentication, one session per request."""
def __init__(self, ip, username, password, scope, port='8181'):
"""Prepare session initialization data using hardcoded text."""
<|body_0|>
def refresh_tok... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _TokenClosingSession:
"""Handling of restconf requests using token-based authentication, one session per request."""
def __init__(self, ip, username, password, scope, port='8181'):
"""Prepare session initialization data using hardcoded text."""
self.auth_url = 'http://' + ip + ':' + port ... | the_stack_v2_python_sparse | csit/libraries/AuthStandalone.py | opendaylight/integration-test | train | 29 |
4667e0fbbd5a42e62590676f96510975751a0b6b | [
"try:\n print('in try')\n print(request)\n datatable_server_processing = query_events_by_args(request, **request.query_params)\n print('datatable', datatable_server_processing)\n serializer = EventSerializer(datatable_server_processing['items'], many=True)\n result = dict()\n result['data'] = s... | <|body_start_0|>
try:
print('in try')
print(request)
datatable_server_processing = query_events_by_args(request, **request.query_params)
print('datatable', datatable_server_processing)
serializer = EventSerializer(datatable_server_processing['items'], ... | ClassRegisterDataView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassRegisterDataView:
def get(self, request):
"""Get attendance list"""
<|body_0|>
def post(self, request):
"""Save presenties"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
print('in try')
print(request)
d... | stack_v2_sparse_classes_36k_train_006282 | 43,717 | no_license | [
{
"docstring": "Get attendance list",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Save presenties",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `ClassRegisterDataView` described below.
Class description:
Implement the ClassRegisterDataView class.
Method signatures and docstrings:
- def get(self, request): Get attendance list
- def post(self, request): Save presenties | Implement the Python class `ClassRegisterDataView` described below.
Class description:
Implement the ClassRegisterDataView class.
Method signatures and docstrings:
- def get(self, request): Get attendance list
- def post(self, request): Save presenties
<|skeleton|>
class ClassRegisterDataView:
def get(self, req... | 367cccca72f0eae6c3ccb70fabb371dc905f915e | <|skeleton|>
class ClassRegisterDataView:
def get(self, request):
"""Get attendance list"""
<|body_0|>
def post(self, request):
"""Save presenties"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassRegisterDataView:
def get(self, request):
"""Get attendance list"""
try:
print('in try')
print(request)
datatable_server_processing = query_events_by_args(request, **request.query_params)
print('datatable', datatable_server_processing)
... | the_stack_v2_python_sparse | course/views/course_booking_view.py | vshaladhav97/first_kick | train | 0 | |
4461b2eba907b9afb6292ad0ef79f692485cc5db | [
"super(LstmEncoderModel, self).__init__()\nself.padding_idx = padding_idx\nself.embedding = nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx)\nself.dropout = nn.Dropout(p=dropout_rate)\nself.lstm_encoder = nn.LSTM(emb_dim, hidden_size, num_layers=n_layers, direction='bidirectional')",
"token_embed = self... | <|body_start_0|>
super(LstmEncoderModel, self).__init__()
self.padding_idx = padding_idx
self.embedding = nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx)
self.dropout = nn.Dropout(p=dropout_rate)
self.lstm_encoder = nn.LSTM(emb_dim, hidden_size, num_layers=n_layers, di... | LstmEncoderModel | LstmEncoderModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LstmEncoderModel:
"""LstmEncoderModel"""
def __init__(self, vocab_size, emb_dim=128, hidden_size=1024, n_layers=3, padding_idx=0, epsilon=1e-05, dropout_rate=0.1):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_006283 | 17,522 | permissive | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self, vocab_size, emb_dim=128, hidden_size=1024, n_layers=3, padding_idx=0, epsilon=1e-05, dropout_rate=0.1)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, input, pos)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001454 | Implement the Python class `LstmEncoderModel` described below.
Class description:
LstmEncoderModel
Method signatures and docstrings:
- def __init__(self, vocab_size, emb_dim=128, hidden_size=1024, n_layers=3, padding_idx=0, epsilon=1e-05, dropout_rate=0.1): __init__
- def forward(self, input, pos): forward | Implement the Python class `LstmEncoderModel` described below.
Class description:
LstmEncoderModel
Method signatures and docstrings:
- def __init__(self, vocab_size, emb_dim=128, hidden_size=1024, n_layers=3, padding_idx=0, epsilon=1e-05, dropout_rate=0.1): __init__
- def forward(self, input, pos): forward
<|skeleto... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class LstmEncoderModel:
"""LstmEncoderModel"""
def __init__(self, vocab_size, emb_dim=128, hidden_size=1024, n_layers=3, padding_idx=0, epsilon=1e-05, dropout_rate=0.1):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LstmEncoderModel:
"""LstmEncoderModel"""
def __init__(self, vocab_size, emb_dim=128, hidden_size=1024, n_layers=3, padding_idx=0, epsilon=1e-05, dropout_rate=0.1):
"""__init__"""
super(LstmEncoderModel, self).__init__()
self.padding_idx = padding_idx
self.embedding = nn.Em... | the_stack_v2_python_sparse | pahelix/model_zoo/protein_sequence_model.py | PaddlePaddle/PaddleHelix | train | 771 |
45a05e88726ce5825532888dcfa09a0f0038e6f2 | [
"rval = []\nfor role in trans.sa_session.query(trans.app.model.Role).filter(trans.app.model.Role.table.c.deleted == false()):\n if trans.user_is_admin or trans.app.security_agent.ok_to_display(trans.user, role):\n item = role.to_dict(value_mapper={'id': trans.security.encode_id})\n encoded_id = tra... | <|body_start_0|>
rval = []
for role in trans.sa_session.query(trans.app.model.Role).filter(trans.app.model.Role.table.c.deleted == false()):
if trans.user_is_admin or trans.app.security_agent.ok_to_display(trans.user, role):
item = role.to_dict(value_mapper={'id': trans.secur... | RoleAPIController | [
"CC-BY-2.5",
"AFL-2.1",
"AFL-3.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleAPIController:
def index(self, trans, **kwd):
"""GET /api/roles Displays a collection (list) of roles."""
<|body_0|>
def show(self, trans, id, **kwd):
"""GET /api/roles/{encoded_role_id} Displays information about a role."""
<|body_1|>
def create(sel... | stack_v2_sparse_classes_36k_train_006284 | 3,686 | permissive | [
{
"docstring": "GET /api/roles Displays a collection (list) of roles.",
"name": "index",
"signature": "def index(self, trans, **kwd)"
},
{
"docstring": "GET /api/roles/{encoded_role_id} Displays information about a role.",
"name": "show",
"signature": "def show(self, trans, id, **kwd)"
... | 3 | null | Implement the Python class `RoleAPIController` described below.
Class description:
Implement the RoleAPIController class.
Method signatures and docstrings:
- def index(self, trans, **kwd): GET /api/roles Displays a collection (list) of roles.
- def show(self, trans, id, **kwd): GET /api/roles/{encoded_role_id} Displa... | Implement the Python class `RoleAPIController` described below.
Class description:
Implement the RoleAPIController class.
Method signatures and docstrings:
- def index(self, trans, **kwd): GET /api/roles Displays a collection (list) of roles.
- def show(self, trans, id, **kwd): GET /api/roles/{encoded_role_id} Displa... | d194520fdfe08e48c0b3d0d2299cd2adcb8f5952 | <|skeleton|>
class RoleAPIController:
def index(self, trans, **kwd):
"""GET /api/roles Displays a collection (list) of roles."""
<|body_0|>
def show(self, trans, id, **kwd):
"""GET /api/roles/{encoded_role_id} Displays information about a role."""
<|body_1|>
def create(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleAPIController:
def index(self, trans, **kwd):
"""GET /api/roles Displays a collection (list) of roles."""
rval = []
for role in trans.sa_session.query(trans.app.model.Role).filter(trans.app.model.Role.table.c.deleted == false()):
if trans.user_is_admin or trans.app.secu... | the_stack_v2_python_sparse | lib/galaxy/webapps/galaxy/api/roles.py | bwlang/galaxy | train | 0 | |
0dd8d35b1a7dffeb1a7d520cf0808b1481716214 | [
"super().__init__()\nn_blocks = len(channels) - 1\nif type(kernel_size) is not list:\n kernel_size = [kernel_size] * n_blocks\nif stride is None:\n stride = kernel_size\nelif type(stride) is not list:\n stride = [stride] * n_blocks\nif type(num_layers) is not list:\n num_layers = [num_layers] * n_blocks... | <|body_start_0|>
super().__init__()
n_blocks = len(channels) - 1
if type(kernel_size) is not list:
kernel_size = [kernel_size] * n_blocks
if stride is None:
stride = kernel_size
elif type(stride) is not list:
stride = [stride] * n_blocks
... | TDCDecoder2d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TDCDecoder2d:
def __init__(self, channels, kernel_size, stride=None, num_layers=2, bias=False, nonlinear='relu', eps=EPS):
"""Args: channels <list<int>> kernel_size <tuple<int,int>> or <list<tuple<int,int>>> stride <tuple<int,int>> or <list<tuple<int,int>>> num_layers <int> or <list<int>... | stack_v2_sparse_classes_36k_train_006285 | 14,668 | no_license | [
{
"docstring": "Args: channels <list<int>> kernel_size <tuple<int,int>> or <list<tuple<int,int>>> stride <tuple<int,int>> or <list<tuple<int,int>>> num_layers <int> or <list<int>> nonlinear <str> or <list<str>>",
"name": "__init__",
"signature": "def __init__(self, channels, kernel_size, stride=None, nu... | 2 | null | Implement the Python class `TDCDecoder2d` described below.
Class description:
Implement the TDCDecoder2d class.
Method signatures and docstrings:
- def __init__(self, channels, kernel_size, stride=None, num_layers=2, bias=False, nonlinear='relu', eps=EPS): Args: channels <list<int>> kernel_size <tuple<int,int>> or <l... | Implement the Python class `TDCDecoder2d` described below.
Class description:
Implement the TDCDecoder2d class.
Method signatures and docstrings:
- def __init__(self, channels, kernel_size, stride=None, num_layers=2, bias=False, nonlinear='relu', eps=EPS): Args: channels <list<int>> kernel_size <tuple<int,int>> or <l... | 4f7f77406cf580785ebf932d78069e7d6e35b765 | <|skeleton|>
class TDCDecoder2d:
def __init__(self, channels, kernel_size, stride=None, num_layers=2, bias=False, nonlinear='relu', eps=EPS):
"""Args: channels <list<int>> kernel_size <tuple<int,int>> or <list<tuple<int,int>>> stride <tuple<int,int>> or <list<tuple<int,int>>> num_layers <int> or <list<int>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TDCDecoder2d:
def __init__(self, channels, kernel_size, stride=None, num_layers=2, bias=False, nonlinear='relu', eps=EPS):
"""Args: channels <list<int>> kernel_size <tuple<int,int>> or <list<tuple<int,int>>> stride <tuple<int,int>> or <list<tuple<int,int>>> num_layers <int> or <list<int>> nonlinear <s... | the_stack_v2_python_sparse | egs/musdb18/cunet_choi/src/adhoc_model.py | shelly-tang/DNN-based_source_separation | train | 0 | |
9bffb6baca0fc17cbc9217f9188266ebb2f493d7 | [
"parser.add_argument('--skip-evpc', default=True, help=SUPPRESS)\nparser.add_argument('config', help='The botoform YAML config template.')\nparser.add_argument('-e', '--extra-vars', default=list(), action='append', metavar='key=val', help='Extra Jinja2 context: --extra-vars key=val,key2=val2,key3=val3')\nparser.add... | <|body_start_0|>
parser.add_argument('--skip-evpc', default=True, help=SUPPRESS)
parser.add_argument('config', help='The botoform YAML config template.')
parser.add_argument('-e', '--extra-vars', default=list(), action='append', metavar='key=val', help='Extra Jinja2 context: --extra-vars key=val... | Create a new VPC and related services, modeled from YAML template. This is a :ref:`class plugin` for the :ref:`bf` tool. | Create | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Create:
"""Create a new VPC and related services, modeled from YAML template. This is a :ref:`class plugin` for the :ref:`bf` tool."""
def setup_parser(parser):
"""Accepts a subparser and attaches additional arguments and flags. :param parser: An ArgumentParser sub parser. Reference:... | stack_v2_sparse_classes_36k_train_006286 | 2,126 | no_license | [
{
"docstring": "Accepts a subparser and attaches additional arguments and flags. :param parser: An ArgumentParser sub parser. Reference: https://docs.python.org/3/library/argparse.html :returns: None",
"name": "setup_parser",
"signature": "def setup_parser(parser)"
},
{
"docstring": "Creates a n... | 2 | stack_v2_sparse_classes_30k_train_006490 | Implement the Python class `Create` described below.
Class description:
Create a new VPC and related services, modeled from YAML template. This is a :ref:`class plugin` for the :ref:`bf` tool.
Method signatures and docstrings:
- def setup_parser(parser): Accepts a subparser and attaches additional arguments and flags... | Implement the Python class `Create` described below.
Class description:
Create a new VPC and related services, modeled from YAML template. This is a :ref:`class plugin` for the :ref:`bf` tool.
Method signatures and docstrings:
- def setup_parser(parser): Accepts a subparser and attaches additional arguments and flags... | 06eb39db41d922e34fc7eac0e95a78630c7094de | <|skeleton|>
class Create:
"""Create a new VPC and related services, modeled from YAML template. This is a :ref:`class plugin` for the :ref:`bf` tool."""
def setup_parser(parser):
"""Accepts a subparser and attaches additional arguments and flags. :param parser: An ArgumentParser sub parser. Reference:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Create:
"""Create a new VPC and related services, modeled from YAML template. This is a :ref:`class plugin` for the :ref:`bf` tool."""
def setup_parser(parser):
"""Accepts a subparser and attaches additional arguments and flags. :param parser: An ArgumentParser sub parser. Reference: https://docs... | the_stack_v2_python_sparse | botoform/plugins/create.py | ihgbuildcia/botoform | train | 1 |
98c13f6904e9569bae18bb2f8cd49abdf5f98cc2 | [
"count = 0\nwhile n:\n if n & 1 == 1:\n count += 1\n n = n >> 1\n if count > 1:\n return False\nif count == 0:\n return False\nreturn True",
"if n == 0:\n return False\ncount = 0\nfor i in range(2):\n count += 1\n n = n & n - 1\n if n == 0:\n break\nif count != 1:\n ... | <|body_start_0|>
count = 0
while n:
if n & 1 == 1:
count += 1
n = n >> 1
if count > 1:
return False
if count == 0:
return False
return True
<|end_body_0|>
<|body_start_1|>
if n == 0:
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfTwo3(self, n: int) -> bool:
"""位运算 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1. 计算1的个数是否为1"""
<|body_0|>
def isPowerOfTwo2(self, n: int) -> bool:
"""位运算(推荐) 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1。 计算1的个数是否为1"""
<|body_1... | stack_v2_sparse_classes_36k_train_006287 | 1,448 | no_license | [
{
"docstring": "位运算 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1. 计算1的个数是否为1",
"name": "isPowerOfTwo3",
"signature": "def isPowerOfTwo3(self, n: int) -> bool"
},
{
"docstring": "位运算(推荐) 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1。 计算1的个数是否为1",
"name": "isPowerOfTwo2",
"signatu... | 3 | stack_v2_sparse_classes_30k_test_000880 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo3(self, n: int) -> bool: 位运算 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1. 计算1的个数是否为1
- def isPowerOfTwo2(self, n: int) -> bool: 位运算(推荐) 1 2 10 2 100 4 1000 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo3(self, n: int) -> bool: 位运算 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1. 计算1的个数是否为1
- def isPowerOfTwo2(self, n: int) -> bool: 位运算(推荐) 1 2 10 2 100 4 1000 ... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def isPowerOfTwo3(self, n: int) -> bool:
"""位运算 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1. 计算1的个数是否为1"""
<|body_0|>
def isPowerOfTwo2(self, n: int) -> bool:
"""位运算(推荐) 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1。 计算1的个数是否为1"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPowerOfTwo3(self, n: int) -> bool:
"""位运算 1 2 10 2 100 4 1000 8 10000 16 如上所述,2的幂的二进制仅包含一个1. 计算1的个数是否为1"""
count = 0
while n:
if n & 1 == 1:
count += 1
n = n >> 1
if count > 1:
return False
if c... | the_stack_v2_python_sparse | leetcode/231_2的幂.py | tenqaz/crazy_arithmetic | train | 0 | |
f59b754b66baab6ab3dcdf44ceb9ea99fb257a98 | [
"super().__init__()\nif encoder_fn is None:\n encoder_fn = PointNet_LocalPool()\nif feature_sampler_fn is None:\n feature_sampler_fn = FeatureSampler2D()\nif nif_model is None:\n nif_model = ConvolutionalOccupancyNetworksModel()\nif rendering_fn is None:\n rendering_fn = PointRenderer()\nself.feature_en... | <|body_start_0|>
super().__init__()
if encoder_fn is None:
encoder_fn = PointNet_LocalPool()
if feature_sampler_fn is None:
feature_sampler_fn = FeatureSampler2D()
if nif_model is None:
nif_model = ConvolutionalOccupancyNetworksModel()
if rende... | This is the main pipeline function for the Convolutional Occupancy Networks: https://arxiv.org/abs/2003.04618 This class takes the noisy point cloud, applies an encoding function (i.e. PointNet) to extract features from inputs, projects the points to 2D plane(s) or 3D grid, optionally applies an auto-encoder network in... | ConvolutionalOccupancyNetworks | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvolutionalOccupancyNetworks:
"""This is the main pipeline function for the Convolutional Occupancy Networks: https://arxiv.org/abs/2003.04618 This class takes the noisy point cloud, applies an encoding function (i.e. PointNet) to extract features from inputs, projects the points to 2D plane(s)... | stack_v2_sparse_classes_36k_train_006288 | 4,219 | permissive | [
{
"docstring": "Args: encoder_fn (instance): The function instance that is called in order to encode the input points. Default is `PointNet_LocalPool`. feature_sampler_fn (instance): The function instance that is called in order to sample the features on a plane or on a grid. The sampler has to match the 2D/3D ... | 2 | null | Implement the Python class `ConvolutionalOccupancyNetworks` described below.
Class description:
This is the main pipeline function for the Convolutional Occupancy Networks: https://arxiv.org/abs/2003.04618 This class takes the noisy point cloud, applies an encoding function (i.e. PointNet) to extract features from inp... | Implement the Python class `ConvolutionalOccupancyNetworks` described below.
Class description:
This is the main pipeline function for the Convolutional Occupancy Networks: https://arxiv.org/abs/2003.04618 This class takes the noisy point cloud, applies an encoding function (i.e. PointNet) to extract features from inp... | da3680cce7e8fc4c194f13a1528cddbad9a18ab0 | <|skeleton|>
class ConvolutionalOccupancyNetworks:
"""This is the main pipeline function for the Convolutional Occupancy Networks: https://arxiv.org/abs/2003.04618 This class takes the noisy point cloud, applies an encoding function (i.e. PointNet) to extract features from inputs, projects the points to 2D plane(s)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvolutionalOccupancyNetworks:
"""This is the main pipeline function for the Convolutional Occupancy Networks: https://arxiv.org/abs/2003.04618 This class takes the noisy point cloud, applies an encoding function (i.e. PointNet) to extract features from inputs, projects the points to 2D plane(s) or 3D grid, ... | the_stack_v2_python_sparse | pynif3d/pipeline/con.py | pfnet/pynif3d | train | 72 |
ff890c55a8e0f80916b893ac39c98080cf131e61 | [
"super().__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.num_filters = num_filters\nself.num_pool_layers = num_pool_layers\nself.dropout_probability = dropout_probability\nself.down_sample_layers = nn.ModuleList([ConvBlock(in_channels, num_filters, dropout_probability)])\nch = num... | <|body_start_0|>
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.num_filters = num_filters
self.num_pool_layers = num_pool_layers
self.dropout_probability = dropout_probability
self.down_sample_layers = nn.ModuleList([ConvBl... | PyTorch implementation of a U-Net model based on [1]_. References ---------- .. [1] Ronneberger, Olaf, et al. “U-Net: Convolutional Networks for Biomedical Image Segmentation.” Medical Image Computing and Computer-Assisted Intervention – MICCAI 2015, edited by Nassir Navab et al., Springer International Publishing, 201... | UnetModel2d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnetModel2d:
"""PyTorch implementation of a U-Net model based on [1]_. References ---------- .. [1] Ronneberger, Olaf, et al. “U-Net: Convolutional Networks for Biomedical Image Segmentation.” Medical Image Computing and Computer-Assisted Intervention – MICCAI 2015, edited by Nassir Navab et al.,... | stack_v2_sparse_classes_36k_train_006289 | 15,262 | permissive | [
{
"docstring": "Inits :class:`UnetModel2d`. Parameters ---------- in_channels: int Number of input channels to the u-net. out_channels: int Number of output channels to the u-net. num_filters: int Number of output channels of the first convolutional layer. num_pool_layers: int Number of down-sampling and up-sam... | 2 | stack_v2_sparse_classes_30k_train_001900 | Implement the Python class `UnetModel2d` described below.
Class description:
PyTorch implementation of a U-Net model based on [1]_. References ---------- .. [1] Ronneberger, Olaf, et al. “U-Net: Convolutional Networks for Biomedical Image Segmentation.” Medical Image Computing and Computer-Assisted Intervention – MICC... | Implement the Python class `UnetModel2d` described below.
Class description:
PyTorch implementation of a U-Net model based on [1]_. References ---------- .. [1] Ronneberger, Olaf, et al. “U-Net: Convolutional Networks for Biomedical Image Segmentation.” Medical Image Computing and Computer-Assisted Intervention – MICC... | 2a4c29342bc52a404aae097bc2654fb4323e1ac8 | <|skeleton|>
class UnetModel2d:
"""PyTorch implementation of a U-Net model based on [1]_. References ---------- .. [1] Ronneberger, Olaf, et al. “U-Net: Convolutional Networks for Biomedical Image Segmentation.” Medical Image Computing and Computer-Assisted Intervention – MICCAI 2015, edited by Nassir Navab et al.,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnetModel2d:
"""PyTorch implementation of a U-Net model based on [1]_. References ---------- .. [1] Ronneberger, Olaf, et al. “U-Net: Convolutional Networks for Biomedical Image Segmentation.” Medical Image Computing and Computer-Assisted Intervention – MICCAI 2015, edited by Nassir Navab et al., Springer Int... | the_stack_v2_python_sparse | direct/nn/unet/unet_2d.py | NKI-AI/direct | train | 151 |
a9cb6a3513a09023b92674b7bae47bd27cbaeac7 | [
"self.gpf_core.float()\nself.likelihood.train()\noptimizer = torch.optim.Adam([{'params': self.gpf_core.parameters()}], lr=0.1)\nmll = gpytorch.mlls.ExactMarginalLogLikelihood(self.likelihood, self.gpf_core)\nfor _ in range(500):\n optimizer.zero_grad()\n output = self.gpf_core(self.tensor_x)\n loss = -mll... | <|body_start_0|>
self.gpf_core.float()
self.likelihood.train()
optimizer = torch.optim.Adam([{'params': self.gpf_core.parameters()}], lr=0.1)
mll = gpytorch.mlls.ExactMarginalLogLikelihood(self.likelihood, self.gpf_core)
for _ in range(500):
optimizer.zero_grad()
... | PytorchGPFitter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PytorchGPFitter:
def fit_gp(self):
"""Fit the GP according to options."""
<|body_0|>
def get_next_gp(self):
"""Get the next GP from previously fitted. Returns: GPWrapper object."""
<|body_1|>
def _init_gpf(self):
"""Initialize the GP fitter."""
... | stack_v2_sparse_classes_36k_train_006290 | 6,453 | permissive | [
{
"docstring": "Fit the GP according to options.",
"name": "fit_gp",
"signature": "def fit_gp(self)"
},
{
"docstring": "Get the next GP from previously fitted. Returns: GPWrapper object.",
"name": "get_next_gp",
"signature": "def get_next_gp(self)"
},
{
"docstring": "Initialize t... | 3 | stack_v2_sparse_classes_30k_train_011439 | Implement the Python class `PytorchGPFitter` described below.
Class description:
Implement the PytorchGPFitter class.
Method signatures and docstrings:
- def fit_gp(self): Fit the GP according to options.
- def get_next_gp(self): Get the next GP from previously fitted. Returns: GPWrapper object.
- def _init_gpf(self)... | Implement the Python class `PytorchGPFitter` described below.
Class description:
Implement the PytorchGPFitter class.
Method signatures and docstrings:
- def fit_gp(self): Fit the GP according to options.
- def get_next_gp(self): Get the next GP from previously fitted. Returns: GPWrapper object.
- def _init_gpf(self)... | fb330ec4ac2ed0f6167eebd849c23fe61692c11c | <|skeleton|>
class PytorchGPFitter:
def fit_gp(self):
"""Fit the GP according to options."""
<|body_0|>
def get_next_gp(self):
"""Get the next GP from previously fitted. Returns: GPWrapper object."""
<|body_1|>
def _init_gpf(self):
"""Initialize the GP fitter."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PytorchGPFitter:
def fit_gp(self):
"""Fit the GP according to options."""
self.gpf_core.float()
self.likelihood.train()
optimizer = torch.optim.Adam([{'params': self.gpf_core.parameters()}], lr=0.1)
mll = gpytorch.mlls.ExactMarginalLogLikelihood(self.likelihood, self.gp... | the_stack_v2_python_sparse | src/gp/gpytorch_interface.py | haowenCS/OCBO_offline | train | 0 | |
0760607db001d6263f43dfdb167b2b48d408668a | [
"super(MultiLoss, self).__init__(*losses)\nself.loss_fn = []\nfor loss in losses:\n self.loss_fn.append(loss)",
"outputs = None\nfor model in self.loss_fn:\n if outputs is None:\n outputs = model(output, target)\n else:\n outputs = outputs + model(output, target)\nreturn outputs"
] | <|body_start_0|>
super(MultiLoss, self).__init__(*losses)
self.loss_fn = []
for loss in losses:
self.loss_fn.append(loss)
<|end_body_0|>
<|body_start_1|>
outputs = None
for model in self.loss_fn:
if outputs is None:
outputs = model(output,... | Define Multi loss creator for base. | MultiLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiLoss:
"""Define Multi loss creator for base."""
def __init__(self, *losses):
"""Initialize loss."""
<|body_0|>
def call(self, output, target):
"""Sum all loss of predict and groundtruth."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_36k_train_006291 | 1,238 | permissive | [
{
"docstring": "Initialize loss.",
"name": "__init__",
"signature": "def __init__(self, *losses)"
},
{
"docstring": "Sum all loss of predict and groundtruth.",
"name": "call",
"signature": "def call(self, output, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010080 | Implement the Python class `MultiLoss` described below.
Class description:
Define Multi loss creator for base.
Method signatures and docstrings:
- def __init__(self, *losses): Initialize loss.
- def call(self, output, target): Sum all loss of predict and groundtruth. | Implement the Python class `MultiLoss` described below.
Class description:
Define Multi loss creator for base.
Method signatures and docstrings:
- def __init__(self, *losses): Initialize loss.
- def call(self, output, target): Sum all loss of predict and groundtruth.
<|skeleton|>
class MultiLoss:
"""Define Multi... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class MultiLoss:
"""Define Multi loss creator for base."""
def __init__(self, *losses):
"""Initialize loss."""
<|body_0|>
def call(self, output, target):
"""Sum all loss of predict and groundtruth."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiLoss:
"""Define Multi loss creator for base."""
def __init__(self, *losses):
"""Initialize loss."""
super(MultiLoss, self).__init__(*losses)
self.loss_fn = []
for loss in losses:
self.loss_fn.append(loss)
def call(self, output, target):
"""Sum... | the_stack_v2_python_sparse | zeus/modules/loss/multiloss.py | huawei-noah/xingtian | train | 308 |
74df4ebd080ed135ec49785ba8ed8164e310451c | [
"dicom_file = DICOMImporter.open_dicom_file('test_dicom/test_dicom.dcm')\ndicom_pixel_arr = DICOMImporter.get_dicom_pixel_array(dicom_file)\nself.assertTrue(dicom_file, not None)\nself.assertFalse(dicom_pixel_arr.all(), None)",
"dicom_file = DICOMImporter.open_dicom_file('test_dicom/test_dicom.dcm')\ndicom_pixel_... | <|body_start_0|>
dicom_file = DICOMImporter.open_dicom_file('test_dicom/test_dicom.dcm')
dicom_pixel_arr = DICOMImporter.get_dicom_pixel_array(dicom_file)
self.assertTrue(dicom_file, not None)
self.assertFalse(dicom_pixel_arr.all(), None)
<|end_body_0|>
<|body_start_1|>
dicom_fi... | DataProcessingTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataProcessingTests:
def test_dicom_importer(self):
"""Handles testing the dicom importer to ensure it's able to import the test file Preconditions: No test file has been loaded Postconditions: Test file has successfully been loaded"""
<|body_0|>
def test_contrast_adjust(sel... | stack_v2_sparse_classes_36k_train_006292 | 3,283 | no_license | [
{
"docstring": "Handles testing the dicom importer to ensure it's able to import the test file Preconditions: No test file has been loaded Postconditions: Test file has successfully been loaded",
"name": "test_dicom_importer",
"signature": "def test_dicom_importer(self)"
},
{
"docstring": "Handl... | 4 | stack_v2_sparse_classes_30k_train_013609 | Implement the Python class `DataProcessingTests` described below.
Class description:
Implement the DataProcessingTests class.
Method signatures and docstrings:
- def test_dicom_importer(self): Handles testing the dicom importer to ensure it's able to import the test file Preconditions: No test file has been loaded Po... | Implement the Python class `DataProcessingTests` described below.
Class description:
Implement the DataProcessingTests class.
Method signatures and docstrings:
- def test_dicom_importer(self): Handles testing the dicom importer to ensure it's able to import the test file Preconditions: No test file has been loaded Po... | d665ca405bdf35fdb57f8149a10b90be82d8de22 | <|skeleton|>
class DataProcessingTests:
def test_dicom_importer(self):
"""Handles testing the dicom importer to ensure it's able to import the test file Preconditions: No test file has been loaded Postconditions: Test file has successfully been loaded"""
<|body_0|>
def test_contrast_adjust(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataProcessingTests:
def test_dicom_importer(self):
"""Handles testing the dicom importer to ensure it's able to import the test file Preconditions: No test file has been loaded Postconditions: Test file has successfully been loaded"""
dicom_file = DICOMImporter.open_dicom_file('test_dicom/tes... | the_stack_v2_python_sparse | BSSCSFramework/data_proc_tests.py | wezleysherman/TBI-NN-421 | train | 3 | |
072a9010e93fdc08754c447269121d117e034df4 | [
"if self.dbconn.version < 90100:\n return\nfor ext in self.fetch():\n self[ext.key()] = ext",
"for key in inexts:\n if not key.startswith('extension '):\n raise KeyError('Unrecognized object type: %s' % key)\n ext = key[10:]\n inexten = inexts[key]\n self[ext] = Extension(name=ext, descri... | <|body_start_0|>
if self.dbconn.version < 90100:
return
for ext in self.fetch():
self[ext.key()] = ext
<|end_body_0|>
<|body_start_1|>
for key in inexts:
if not key.startswith('extension '):
raise KeyError('Unrecognized object type: %s' % key)... | The collection of extensions in a database | ExtensionDict | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtensionDict:
"""The collection of extensions in a database"""
def _from_catalog(self):
"""Initialize the dictionary of extensions by querying the catalogs"""
<|body_0|>
def from_map(self, inexts, langtempls, newdb):
"""Initalize the dictionary of extensions by ... | stack_v2_sparse_classes_36k_train_006293 | 4,548 | permissive | [
{
"docstring": "Initialize the dictionary of extensions by querying the catalogs",
"name": "_from_catalog",
"signature": "def _from_catalog(self)"
},
{
"docstring": "Initalize the dictionary of extensions by converting the input map :param inexts: YAML map defining the extensions :param langtemp... | 4 | stack_v2_sparse_classes_30k_train_008729 | Implement the Python class `ExtensionDict` described below.
Class description:
The collection of extensions in a database
Method signatures and docstrings:
- def _from_catalog(self): Initialize the dictionary of extensions by querying the catalogs
- def from_map(self, inexts, langtempls, newdb): Initalize the diction... | Implement the Python class `ExtensionDict` described below.
Class description:
The collection of extensions in a database
Method signatures and docstrings:
- def _from_catalog(self): Initialize the dictionary of extensions by querying the catalogs
- def from_map(self, inexts, langtempls, newdb): Initalize the diction... | 0133f3bc522890e0564d27de6791824acb4d2773 | <|skeleton|>
class ExtensionDict:
"""The collection of extensions in a database"""
def _from_catalog(self):
"""Initialize the dictionary of extensions by querying the catalogs"""
<|body_0|>
def from_map(self, inexts, langtempls, newdb):
"""Initalize the dictionary of extensions by ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExtensionDict:
"""The collection of extensions in a database"""
def _from_catalog(self):
"""Initialize the dictionary of extensions by querying the catalogs"""
if self.dbconn.version < 90100:
return
for ext in self.fetch():
self[ext.key()] = ext
def fr... | the_stack_v2_python_sparse | pyrseas/dbobject/extension.py | vayerx/Pyrseas | train | 1 |
e28751b131546e9205365e8af12dc30edb87fd3c | [
"if about:\n about = about.decode('utf-8')\n\ndef run():\n try:\n result = SecureObjectAPI(session.auth.user).create(about)\n except PermissionDeniedError as error:\n session.log.exception(error)\n raise TUnauthorized()\n return str(result)\nreturn session.transact.run(run)",
"obj... | <|body_start_0|>
if about:
about = about.decode('utf-8')
def run():
try:
result = SecureObjectAPI(session.auth.user).create(about)
except PermissionDeniedError as error:
session.log.exception(error)
raise TUnauthorized(... | FacadeObjectMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FacadeObjectMixin:
def createObject(self, session, about=None):
"""Create an object. If an about value is given and it already exists, this will return the object ID that matches the L{AboutTagValue}. @param session: The L{AuthenticatedSession} for the request. @param about: Optionally, ... | stack_v2_sparse_classes_36k_train_006294 | 2,605 | permissive | [
{
"docstring": "Create an object. If an about value is given and it already exists, this will return the object ID that matches the L{AboutTagValue}. @param session: The L{AuthenticatedSession} for the request. @param about: Optionally, a C{str} for an L{AboutTagValue.value}. @raise TUnauthorized: Raised if the... | 2 | null | Implement the Python class `FacadeObjectMixin` described below.
Class description:
Implement the FacadeObjectMixin class.
Method signatures and docstrings:
- def createObject(self, session, about=None): Create an object. If an about value is given and it already exists, this will return the object ID that matches the... | Implement the Python class `FacadeObjectMixin` described below.
Class description:
Implement the FacadeObjectMixin class.
Method signatures and docstrings:
- def createObject(self, session, about=None): Create an object. If an about value is given and it already exists, this will return the object ID that matches the... | b5a8c8349f3eaf3364cc4efba4736c3e33b30d96 | <|skeleton|>
class FacadeObjectMixin:
def createObject(self, session, about=None):
"""Create an object. If an about value is given and it already exists, this will return the object ID that matches the L{AboutTagValue}. @param session: The L{AuthenticatedSession} for the request. @param about: Optionally, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FacadeObjectMixin:
def createObject(self, session, about=None):
"""Create an object. If an about value is given and it already exists, this will return the object ID that matches the L{AboutTagValue}. @param session: The L{AuthenticatedSession} for the request. @param about: Optionally, a C{str} for a... | the_stack_v2_python_sparse | fluiddb/api/object.py | fluidinfo/fluiddb | train | 3 | |
5e03adcad67aef73b6801d5bf8aad51652f4b4eb | [
"n = logits.shape[-1]\nbin1, bin2, w2 = self._calc_bin(logits, target)\nw = F.one_hot(bin1, num_classes=n).to(logits.dtype)\nw = 1 - w.cumsum(dim=-1)\nB = _get_indexer(target.shape)\nw[B + (bin2,)] = w2\nw[B + (bin1,)] = 1\ncross_entropy = F.binary_cross_entropy_with_logits(logits, w, reduction='none')\nkld = cross... | <|body_start_0|>
n = logits.shape[-1]
bin1, bin2, w2 = self._calc_bin(logits, target)
w = F.one_hot(bin1, num_classes=n).to(logits.dtype)
w = 1 - w.cumsum(dim=-1)
B = _get_indexer(target.shape)
w[B + (bin2,)] = w2
w[B + (bin1,)] = 1
cross_entropy = F.binar... | A loss for predicting the distribution of a scalar. The target is assumed to be in the range ``[-(n-1)//2, n//2]``, where ``n=logits.shape[-1]``. The logits are used to calculate the probabilities of being greater than or equal to each of these ``n`` values. If a target value y is not an integer, it is treated as havin... | OrderedDiscreteRegressionLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderedDiscreteRegressionLoss:
"""A loss for predicting the distribution of a scalar. The target is assumed to be in the range ``[-(n-1)//2, n//2]``, where ``n=logits.shape[-1]``. The logits are used to calculate the probabilities of being greater than or equal to each of these ``n`` values. If a... | stack_v2_sparse_classes_36k_train_006295 | 31,133 | permissive | [
{
"docstring": "Caculate the loss. Args: logits: shape is [B, n] target: the shape is [B] Returns: loss with the same shape as target",
"name": "__call__",
"signature": "def __call__(self, logits: torch.Tensor, target: torch.Tensor)"
},
{
"docstring": "Calculate the expected predition in the unt... | 3 | stack_v2_sparse_classes_30k_train_007670 | Implement the Python class `OrderedDiscreteRegressionLoss` described below.
Class description:
A loss for predicting the distribution of a scalar. The target is assumed to be in the range ``[-(n-1)//2, n//2]``, where ``n=logits.shape[-1]``. The logits are used to calculate the probabilities of being greater than or eq... | Implement the Python class `OrderedDiscreteRegressionLoss` described below.
Class description:
A loss for predicting the distribution of a scalar. The target is assumed to be in the range ``[-(n-1)//2, n//2]``, where ``n=logits.shape[-1]``. The logits are used to calculate the probabilities of being greater than or eq... | b00ff2fa5e660de31020338ba340263183fbeaa4 | <|skeleton|>
class OrderedDiscreteRegressionLoss:
"""A loss for predicting the distribution of a scalar. The target is assumed to be in the range ``[-(n-1)//2, n//2]``, where ``n=logits.shape[-1]``. The logits are used to calculate the probabilities of being greater than or equal to each of these ``n`` values. If a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrderedDiscreteRegressionLoss:
"""A loss for predicting the distribution of a scalar. The target is assumed to be in the range ``[-(n-1)//2, n//2]``, where ``n=logits.shape[-1]``. The logits are used to calculate the probabilities of being greater than or equal to each of these ``n`` values. If a target value... | the_stack_v2_python_sparse | alf/utils/losses.py | HorizonRobotics/alf | train | 288 |
0e23729a0b717e5d4401017098a58d28d27fbcec | [
"column = self.defaultcolumn if column is None else column\nidx0, idx1 = self.indices\nret = pd.DataFrame(_square_to_square(self[idx0].values, self[idx1].values, self[column].values))\nret.index.name = idx0\nret.columns.name = idx1\nreturn ret",
"column = 'coef' if column is None else column\nidx0, idx1 = cls().i... | <|body_start_0|>
column = self.defaultcolumn if column is None else column
idx0, idx1 = self.indices
ret = pd.DataFrame(_square_to_square(self[idx0].values, self[idx1].values, self[column].values))
ret.index.name = idx0
ret.columns.name = idx1
return ret
<|end_body_0|>
<... | Base class for square matrices. | _Square | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Square:
"""Base class for square matrices."""
def square(self, column=None):
"""Return a square DataFrame of the square matrix."""
<|body_0|>
def from_square(cls, square, column=None):
"""Create a square matrix DataFrame from a square array."""
<|body_1|... | stack_v2_sparse_classes_36k_train_006296 | 7,607 | permissive | [
{
"docstring": "Return a square DataFrame of the square matrix.",
"name": "square",
"signature": "def square(self, column=None)"
},
{
"docstring": "Create a square matrix DataFrame from a square array.",
"name": "from_square",
"signature": "def from_square(cls, square, column=None)"
}
... | 2 | null | Implement the Python class `_Square` described below.
Class description:
Base class for square matrices.
Method signatures and docstrings:
- def square(self, column=None): Return a square DataFrame of the square matrix.
- def from_square(cls, square, column=None): Create a square matrix DataFrame from a square array. | Implement the Python class `_Square` described below.
Class description:
Base class for square matrices.
Method signatures and docstrings:
- def square(self, column=None): Return a square DataFrame of the square matrix.
- def from_square(cls, square, column=None): Create a square matrix DataFrame from a square array.... | 2e87bae3e043e6958129fc823c83ab0b46add8b5 | <|skeleton|>
class _Square:
"""Base class for square matrices."""
def square(self, column=None):
"""Return a square DataFrame of the square matrix."""
<|body_0|>
def from_square(cls, square, column=None):
"""Create a square matrix DataFrame from a square array."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Square:
"""Base class for square matrices."""
def square(self, column=None):
"""Return a square DataFrame of the square matrix."""
column = self.defaultcolumn if column is None else column
idx0, idx1 = self.indices
ret = pd.DataFrame(_square_to_square(self[idx0].values, s... | the_stack_v2_python_sparse | exatomic/core/matrices.py | exa-analytics/exatomic | train | 15 |
c934d4dab89d877b173c1f1e222ddf0aaccaa7c9 | [
"pw = validated_data['user']['password']\nif instance.user.check_password(pw):\n instance.user.set_password(pw)\nelse:\n raise serializers.ValidationError(gs.WRONG_PASSWORD)\ninstance.user.email = validated_data['user']['email']\ninstance.user.username = validated_data['user']['username']\ninstance.save()\nva... | <|body_start_0|>
pw = validated_data['user']['password']
if instance.user.check_password(pw):
instance.user.set_password(pw)
else:
raise serializers.ValidationError(gs.WRONG_PASSWORD)
instance.user.email = validated_data['user']['email']
instance.user.user... | SupervisorSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupervisorSerializer:
def update(self, instance, validated_data):
"""Overwrite update() to set related user instance values"""
<|body_0|>
def create(self, validated_data):
"""Manually generate user instance to be added to the one-2-one field"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_006297 | 18,716 | no_license | [
{
"docstring": "Overwrite update() to set related user instance values",
"name": "update",
"signature": "def update(self, instance, validated_data)"
},
{
"docstring": "Manually generate user instance to be added to the one-2-one field",
"name": "create",
"signature": "def create(self, va... | 2 | stack_v2_sparse_classes_30k_test_000599 | Implement the Python class `SupervisorSerializer` described below.
Class description:
Implement the SupervisorSerializer class.
Method signatures and docstrings:
- def update(self, instance, validated_data): Overwrite update() to set related user instance values
- def create(self, validated_data): Manually generate u... | Implement the Python class `SupervisorSerializer` described below.
Class description:
Implement the SupervisorSerializer class.
Method signatures and docstrings:
- def update(self, instance, validated_data): Overwrite update() to set related user instance values
- def create(self, validated_data): Manually generate u... | 88c51e6216fadcb8369170dca4450563333e4b31 | <|skeleton|>
class SupervisorSerializer:
def update(self, instance, validated_data):
"""Overwrite update() to set related user instance values"""
<|body_0|>
def create(self, validated_data):
"""Manually generate user instance to be added to the one-2-one field"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SupervisorSerializer:
def update(self, instance, validated_data):
"""Overwrite update() to set related user instance values"""
pw = validated_data['user']['password']
if instance.user.check_password(pw):
instance.user.set_password(pw)
else:
raise seriali... | the_stack_v2_python_sparse | restapi/serializer.py | MaximilianFranz/temas-db | train | 0 | |
2f0517b0467fb7ff58a7e093df28a13235618a65 | [
"newclass = super(PersistableRegistry, cls).__new__(cls, clsname, bases, attrs)\nSIMPLEML_REGISTRY.register(newclass)\nreturn newclass",
"cls = super().__call__(*args, **kwargs)\nif hasattr(cls, '__post_init__'):\n cls.__post_init__()\nreturn cls"
] | <|body_start_0|>
newclass = super(PersistableRegistry, cls).__new__(cls, clsname, bases, attrs)
SIMPLEML_REGISTRY.register(newclass)
return newclass
<|end_body_0|>
<|body_start_1|>
cls = super().__call__(*args, **kwargs)
if hasattr(cls, '__post_init__'):
cls.__post_i... | Meta class to register SimpleML persistables. expected to be set as metaclass for all persistable types | PersistableRegistry | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersistableRegistry:
"""Meta class to register SimpleML persistables. expected to be set as metaclass for all persistable types"""
def __new__(cls, clsname, bases, attrs):
"""Metaclass implementation. Called on import of referenced subclasses (not called on construction of classes)""... | stack_v2_sparse_classes_36k_train_006298 | 2,857 | permissive | [
{
"docstring": "Metaclass implementation. Called on import of referenced subclasses (not called on construction of classes)",
"name": "__new__",
"signature": "def __new__(cls, clsname, bases, attrs)"
},
{
"docstring": "Overwrite constructor call to add post init hook (called when constructing re... | 2 | stack_v2_sparse_classes_30k_train_006836 | Implement the Python class `PersistableRegistry` described below.
Class description:
Meta class to register SimpleML persistables. expected to be set as metaclass for all persistable types
Method signatures and docstrings:
- def __new__(cls, clsname, bases, attrs): Metaclass implementation. Called on import of refere... | Implement the Python class `PersistableRegistry` described below.
Class description:
Meta class to register SimpleML persistables. expected to be set as metaclass for all persistable types
Method signatures and docstrings:
- def __new__(cls, clsname, bases, attrs): Metaclass implementation. Called on import of refere... | c7cdf1fa90b373025da48aa85bf9f0d3792ce494 | <|skeleton|>
class PersistableRegistry:
"""Meta class to register SimpleML persistables. expected to be set as metaclass for all persistable types"""
def __new__(cls, clsname, bases, attrs):
"""Metaclass implementation. Called on import of referenced subclasses (not called on construction of classes)""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersistableRegistry:
"""Meta class to register SimpleML persistables. expected to be set as metaclass for all persistable types"""
def __new__(cls, clsname, bases, attrs):
"""Metaclass implementation. Called on import of referenced subclasses (not called on construction of classes)"""
new... | the_stack_v2_python_sparse | simpleml/registries/persistable_registry.py | eyadgaran/SimpleML | train | 15 |
2895520e72ab70b2b5b438dc036517858b6d8e96 | [
"err_m1 = 'style_image must be a numpy.ndarray with shape (h, w, 3)'\nerr_m2 = 'content_image must be a numpy.ndarray with shape (h, w, 3)'\nif not isinstance(style_image, np.ndarray):\n raise TypeError(err_m1)\nif len(style_image.shape) != 3 or style_image.shape[2] != 3:\n raise TypeError(err_m1)\nif not isi... | <|body_start_0|>
err_m1 = 'style_image must be a numpy.ndarray with shape (h, w, 3)'
err_m2 = 'content_image must be a numpy.ndarray with shape (h, w, 3)'
if not isinstance(style_image, np.ndarray):
raise TypeError(err_m1)
if len(style_image.shape) != 3 or style_image.shape[2... | Performs task for neural style transfer | NST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NST:
"""Performs task for neural style transfer"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta:... | stack_v2_sparse_classes_36k_train_006299 | 2,925 | no_license | [
{
"docstring": "constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta: weight for style cost",
"name": "__init__",
"signature": "def __init__(self, style_image, content_image, alpha=10000.0, beta=1)"... | 2 | stack_v2_sparse_classes_30k_train_009731 | Implement the Python class `NST` described below.
Class description:
Performs task for neural style transfer
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): constructor @style_image: image used as style reference, np.ndarray @content_image: image used as cont... | Implement the Python class `NST` described below.
Class description:
Performs task for neural style transfer
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): constructor @style_image: image used as style reference, np.ndarray @content_image: image used as cont... | e20b284d5f1841952104d7d9a0274cff80eb304d | <|skeleton|>
class NST:
"""Performs task for neural style transfer"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NST:
"""Performs task for neural style transfer"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta: weight for s... | the_stack_v2_python_sparse | supervised_learning/0x0C-neural_style_transfer/0-neural_style.py | jgadelugo/holbertonschool-machine_learning | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.