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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a97d04663c98faf08f6ac2c7cf5c7e7db5b5f4a0 | [
"smach.State.__init__(self, outcomes=['succeeded', 'failed'])\nself._robot = robot\nself._srv = rospy.ServiceProxy(robot.robot_name + '/ed/fit_entity_in_image', FitEntityInImage)\nself._entity_str = entity_str",
"self._robot.head.reset()\nself._robot.head.wait_for_motion_done(5.0)\nrospy.sleep(rospy.Duration(1.0)... | <|body_start_0|>
smach.State.__init__(self, outcomes=['succeeded', 'failed'])
self._robot = robot
self._srv = rospy.ServiceProxy(robot.robot_name + '/ed/fit_entity_in_image', FitEntityInImage)
self._entity_str = entity_str
<|end_body_0|>
<|body_start_1|>
self._robot.head.reset()... | Fits an entity | FitEntity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FitEntity:
"""Fits an entity"""
def __init__(self, robot, entity_str):
"""Constructor :param robot: robot object :param entity_str: string with the entity type to fit"""
<|body_0|>
def execute(self, userdata=None):
"""Executes the state"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_013500 | 1,370 | no_license | [
{
"docstring": "Constructor :param robot: robot object :param entity_str: string with the entity type to fit",
"name": "__init__",
"signature": "def __init__(self, robot, entity_str)"
},
{
"docstring": "Executes the state",
"name": "execute",
"signature": "def execute(self, userdata=None... | 2 | stack_v2_sparse_classes_30k_train_014225 | Implement the Python class `FitEntity` described below.
Class description:
Fits an entity
Method signatures and docstrings:
- def __init__(self, robot, entity_str): Constructor :param robot: robot object :param entity_str: string with the entity type to fit
- def execute(self, userdata=None): Executes the state | Implement the Python class `FitEntity` described below.
Class description:
Fits an entity
Method signatures and docstrings:
- def __init__(self, robot, entity_str): Constructor :param robot: robot object :param entity_str: string with the entity type to fit
- def execute(self, userdata=None): Executes the state
<|sk... | d4705c553f4711be792b37730658b481cc05eca1 | <|skeleton|>
class FitEntity:
"""Fits an entity"""
def __init__(self, robot, entity_str):
"""Constructor :param robot: robot object :param entity_str: string with the entity type to fit"""
<|body_0|>
def execute(self, userdata=None):
"""Executes the state"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FitEntity:
"""Fits an entity"""
def __init__(self, robot, entity_str):
"""Constructor :param robot: robot object :param entity_str: string with the entity type to fit"""
smach.State.__init__(self, outcomes=['succeeded', 'failed'])
self._robot = robot
self._srv = rospy.Serv... | the_stack_v2_python_sparse | challenge_storing_groceries/src/challenge_storing_groceries/fit_entity.py | SamAlexandrov/tue_robocup | train | 0 |
a86b02581f06d22d5907fefdb2ff7bb64f911b59 | [
"self.func = func\nself.jac = jac\nself.xdata = np.array(xdata)\nself.ydata = np.array(ydata)\nself.curve_fit_kwargs = kwargs\nself.popt, self.pcov = optimize.curve_fit(self.func, self.xdata, self.ydata, **self.curve_fit_kwargs)",
"y = np.array(list(map(lambda _: self.func(_, *self.popt), x)))\nsigma = np.array(l... | <|body_start_0|>
self.func = func
self.jac = jac
self.xdata = np.array(xdata)
self.ydata = np.array(ydata)
self.curve_fit_kwargs = kwargs
self.popt, self.pcov = optimize.curve_fit(self.func, self.xdata, self.ydata, **self.curve_fit_kwargs)
<|end_body_0|>
<|body_start_1|>... | Fit a 1-variable scalar function to data points and evaluate with uncertainty. (see scipy.optimize.curve_fit) | CurveFit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurveFit:
"""Fit a 1-variable scalar function to data points and evaluate with uncertainty. (see scipy.optimize.curve_fit)"""
def __init__(self, func, xdata, ydata, jac=None, **kwargs):
"""Fit curve to data points. (see scipy.optimize.curve_fit) Parameters ---------- func : callable ... | stack_v2_sparse_classes_36k_train_013501 | 35,535 | permissive | [
{
"docstring": "Fit curve to data points. (see scipy.optimize.curve_fit) Parameters ---------- func : callable scalar function Model function, f(x, ...), taking the independent variable as the first argument and the parameters to fit as separate remaining arguments. xdata : float array-like x-data to fit. ydata... | 3 | stack_v2_sparse_classes_30k_train_018820 | Implement the Python class `CurveFit` described below.
Class description:
Fit a 1-variable scalar function to data points and evaluate with uncertainty. (see scipy.optimize.curve_fit)
Method signatures and docstrings:
- def __init__(self, func, xdata, ydata, jac=None, **kwargs): Fit curve to data points. (see scipy.o... | Implement the Python class `CurveFit` described below.
Class description:
Fit a 1-variable scalar function to data points and evaluate with uncertainty. (see scipy.optimize.curve_fit)
Method signatures and docstrings:
- def __init__(self, func, xdata, ydata, jac=None, **kwargs): Fit curve to data points. (see scipy.o... | 99107a0d4935296b673f67469c1e2bd258954b9b | <|skeleton|>
class CurveFit:
"""Fit a 1-variable scalar function to data points and evaluate with uncertainty. (see scipy.optimize.curve_fit)"""
def __init__(self, func, xdata, ydata, jac=None, **kwargs):
"""Fit curve to data points. (see scipy.optimize.curve_fit) Parameters ---------- func : callable ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CurveFit:
"""Fit a 1-variable scalar function to data points and evaluate with uncertainty. (see scipy.optimize.curve_fit)"""
def __init__(self, func, xdata, ydata, jac=None, **kwargs):
"""Fit curve to data points. (see scipy.optimize.curve_fit) Parameters ---------- func : callable scalar functi... | the_stack_v2_python_sparse | maths.py | yketa/active_work | train | 1 |
c04b77031f4830aea5281031d539843413e662a2 | [
"self.d = {}\nself.dict = dictionary = set(dictionary)\nfor word in dictionary:\n wordLen = len(word)\n if wordLen > 2:\n key = word[0] + str(wordLen - 2) + word[-1]\n self.d[key] = self.d.get(key, 0) + 1\n else:\n self.d[word] = self.d.get(word, 0) + 1",
"wordLen = len(word)\nkey = ... | <|body_start_0|>
self.d = {}
self.dict = dictionary = set(dictionary)
for word in dictionary:
wordLen = len(word)
if wordLen > 2:
key = word[0] + str(wordLen - 2) + word[-1]
self.d[key] = self.d.get(key, 0) + 1
else:
... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
"""check if a word is unique. :type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_013502 | 989 | no_license | [
{
"docstring": "initialize your data structure here. :type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": "check if a word is unique. :type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
... | 2 | stack_v2_sparse_classes_30k_train_003574 | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str]
- def isUnique(self, word): check if a word is unique. :type word: str ... | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str]
- def isUnique(self, word): check if a word is unique. :type word: str ... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
"""check if a word is unique. :type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
self.d = {}
self.dict = dictionary = set(dictionary)
for word in dictionary:
wordLen = len(word)
if wordLen > 2:
key = w... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/lc-all-solutions/288.unique-word-abbreviation/unique-word-abbreviation.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
7a637e74580c41b54e764f0a7cae1888dc230744 | [
"super(CXTEBD, self).__init__()\nself.finetune_ebd = finetune_ebd\nself.return_seq = return_seq\nprint('{}, Loading pretrained bert'.format(datetime.datetime.now().strftime('%02y/%02m/%02d %H:%M:%S')), flush=True)\nself.model = BertModel.from_pretrained(pretrained_model_name_or_path, cache_dir=cache_dir)\nself.embe... | <|body_start_0|>
super(CXTEBD, self).__init__()
self.finetune_ebd = finetune_ebd
self.return_seq = return_seq
print('{}, Loading pretrained bert'.format(datetime.datetime.now().strftime('%02y/%02m/%02d %H:%M:%S')), flush=True)
self.model = BertModel.from_pretrained(pretrained_mod... | An embedding layer directly returns precomputed BERT embeddings. | CXTEBD | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CXTEBD:
"""An embedding layer directly returns precomputed BERT embeddings."""
def __init__(self, pretrained_model_name_or_path=None, cache_dir=None, finetune_ebd=False, return_seq=False):
"""pretrained_model_name_or_path, cache_dir: check huggingface's codebase for details finetune_... | stack_v2_sparse_classes_36k_train_013503 | 2,597 | permissive | [
{
"docstring": "pretrained_model_name_or_path, cache_dir: check huggingface's codebase for details finetune_ebd: finetuning bert representation or not during meta-training return_seq: return a sequence of bert representations, or [cls]",
"name": "__init__",
"signature": "def __init__(self, pretrained_mo... | 3 | stack_v2_sparse_classes_30k_train_008698 | Implement the Python class `CXTEBD` described below.
Class description:
An embedding layer directly returns precomputed BERT embeddings.
Method signatures and docstrings:
- def __init__(self, pretrained_model_name_or_path=None, cache_dir=None, finetune_ebd=False, return_seq=False): pretrained_model_name_or_path, cach... | Implement the Python class `CXTEBD` described below.
Class description:
An embedding layer directly returns precomputed BERT embeddings.
Method signatures and docstrings:
- def __init__(self, pretrained_model_name_or_path=None, cache_dir=None, finetune_ebd=False, return_seq=False): pretrained_model_name_or_path, cach... | cd7e4659fc9761a8af046e824853aa338b22f2f6 | <|skeleton|>
class CXTEBD:
"""An embedding layer directly returns precomputed BERT embeddings."""
def __init__(self, pretrained_model_name_or_path=None, cache_dir=None, finetune_ebd=False, return_seq=False):
"""pretrained_model_name_or_path, cache_dir: check huggingface's codebase for details finetune_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CXTEBD:
"""An embedding layer directly returns precomputed BERT embeddings."""
def __init__(self, pretrained_model_name_or_path=None, cache_dir=None, finetune_ebd=False, return_seq=False):
"""pretrained_model_name_or_path, cache_dir: check huggingface's codebase for details finetune_ebd: finetuni... | the_stack_v2_python_sparse | src/embedding/cxtebd.py | phymucs/460d60d2c25a118c67dcbfdd37f27d6c | train | 1 |
fe4e7595c00d0fb5b48d964fdad37150a6d2088a | [
"self.input_data_description = input_data_description\nself.name = 'random_sparse_projection'\nself.new_input_data_description = {}\nself.input_data_description = input_data_description\nNI = input_data_description['NI']\nNtimes = int(float(NI) / float(NF))\nP = np.eye(NF)\nfor k in range(Ntimes):\n P = np.hstac... | <|body_start_0|>
self.input_data_description = input_data_description
self.name = 'random_sparse_projection'
self.new_input_data_description = {}
self.input_data_description = input_data_description
NI = input_data_description['NI']
Ntimes = int(float(NI) / float(NF))
... | random_projection_sparse_model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class random_projection_sparse_model:
def __init__(self, input_data_description, NF):
"""Parameters ---------- input_data_description: dict Description of the input features NF: int Number of features to extract"""
<|body_0|>
def transform(self, X):
"""Transform sparse dat... | stack_v2_sparse_classes_36k_train_013504 | 1,874 | permissive | [
{
"docstring": "Parameters ---------- input_data_description: dict Description of the input features NF: int Number of features to extract",
"name": "__init__",
"signature": "def __init__(self, input_data_description, NF)"
},
{
"docstring": "Transform sparse data reducing its dimensionality usin... | 2 | null | Implement the Python class `random_projection_sparse_model` described below.
Class description:
Implement the random_projection_sparse_model class.
Method signatures and docstrings:
- def __init__(self, input_data_description, NF): Parameters ---------- input_data_description: dict Description of the input features N... | Implement the Python class `random_projection_sparse_model` described below.
Class description:
Implement the random_projection_sparse_model class.
Method signatures and docstrings:
- def __init__(self, input_data_description, NF): Parameters ---------- input_data_description: dict Description of the input features N... | ccc0a7674a04ae0d00bedc38893b33184c5f68c6 | <|skeleton|>
class random_projection_sparse_model:
def __init__(self, input_data_description, NF):
"""Parameters ---------- input_data_description: dict Description of the input features NF: int Number of features to extract"""
<|body_0|>
def transform(self, X):
"""Transform sparse dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class random_projection_sparse_model:
def __init__(self, input_data_description, NF):
"""Parameters ---------- input_data_description: dict Description of the input features NF: int Number of features to extract"""
self.input_data_description = input_data_description
self.name = 'random_spar... | the_stack_v2_python_sparse | MMLL/preprocessors/random_projection_sparse.py | Musketeer-H2020/MMLL-Robust | train | 0 | |
231b9c86fcad9a224466518886a8356e98813ff4 | [
"for arg in self.non_number_values:\n self.assertRaises(TypeError, prev1.perfect_numbers_list, arg)\nfor arg, val in self.perfect_numbers_values:\n self.assertEqual(prev1.perfect_numbers_list(arg), val)",
"for arg in self.non_number_values:\n self.assertRaises(TypeError, prev1.perfect_numbers_fun, arg)\n... | <|body_start_0|>
for arg in self.non_number_values:
self.assertRaises(TypeError, prev1.perfect_numbers_list, arg)
for arg, val in self.perfect_numbers_values:
self.assertEqual(prev1.perfect_numbers_list(arg), val)
<|end_body_0|>
<|body_start_1|>
for arg in self.non_numbe... | TestPerfectNumbers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPerfectNumbers:
def test_perfect_numbers_list(self):
"""Testing perfect_numbers_list function"""
<|body_0|>
def test_perfect_numbers_fun(self):
"""Testing perfect_numbers_fun function"""
<|body_1|>
def test_perfect_numbers_iter(self):
"""Test... | stack_v2_sparse_classes_36k_train_013505 | 8,451 | no_license | [
{
"docstring": "Testing perfect_numbers_list function",
"name": "test_perfect_numbers_list",
"signature": "def test_perfect_numbers_list(self)"
},
{
"docstring": "Testing perfect_numbers_fun function",
"name": "test_perfect_numbers_fun",
"signature": "def test_perfect_numbers_fun(self)"
... | 3 | stack_v2_sparse_classes_30k_train_009536 | Implement the Python class `TestPerfectNumbers` described below.
Class description:
Implement the TestPerfectNumbers class.
Method signatures and docstrings:
- def test_perfect_numbers_list(self): Testing perfect_numbers_list function
- def test_perfect_numbers_fun(self): Testing perfect_numbers_fun function
- def te... | Implement the Python class `TestPerfectNumbers` described below.
Class description:
Implement the TestPerfectNumbers class.
Method signatures and docstrings:
- def test_perfect_numbers_list(self): Testing perfect_numbers_list function
- def test_perfect_numbers_fun(self): Testing perfect_numbers_fun function
- def te... | 0cd4bbe3feb63b248d643303433f9fb2fc2def79 | <|skeleton|>
class TestPerfectNumbers:
def test_perfect_numbers_list(self):
"""Testing perfect_numbers_list function"""
<|body_0|>
def test_perfect_numbers_fun(self):
"""Testing perfect_numbers_fun function"""
<|body_1|>
def test_perfect_numbers_iter(self):
"""Test... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPerfectNumbers:
def test_perfect_numbers_list(self):
"""Testing perfect_numbers_list function"""
for arg in self.non_number_values:
self.assertRaises(TypeError, prev1.perfect_numbers_list, arg)
for arg, val in self.perfect_numbers_values:
self.assertEqual(pr... | the_stack_v2_python_sparse | Python - advanced course/Solutions/9/9.1.py | maxymilianz/CS-at-University-of-Wroclaw | train | 0 | |
392e13a14c9614d39a6ae478afd18406c5ce23eb | [
"print('Received GET on resource /books/<book_id>')\nif book_id.isdigit():\n a_book = BookChecker.get_book(book_id)\n return (a_book, 200)\nelse:\n abort(400, 'Invalid input received for book_id')",
"print('Received PUT on resource /books/<book_id>')\nif book_id.isdigit():\n request_body = request.get... | <|body_start_0|>
print('Received GET on resource /books/<book_id>')
if book_id.isdigit():
a_book = BookChecker.get_book(book_id)
return (a_book, 200)
else:
abort(400, 'Invalid input received for book_id')
<|end_body_0|>
<|body_start_1|>
print('Receive... | BookRecord | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookRecord:
def get(self, book_id):
"""Gets a specific book record based on book_id. :param book_id: Record of a book. :return: JSON of requested book record according to model full_book_marshaller."""
<|body_0|>
def put(self, book_id):
"""Updates an existing Book re... | stack_v2_sparse_classes_36k_train_013506 | 14,158 | no_license | [
{
"docstring": "Gets a specific book record based on book_id. :param book_id: Record of a book. :return: JSON of requested book record according to model full_book_marshaller.",
"name": "get",
"signature": "def get(self, book_id)"
},
{
"docstring": "Updates an existing Book record based on book_... | 3 | stack_v2_sparse_classes_30k_train_002607 | Implement the Python class `BookRecord` described below.
Class description:
Implement the BookRecord class.
Method signatures and docstrings:
- def get(self, book_id): Gets a specific book record based on book_id. :param book_id: Record of a book. :return: JSON of requested book record according to model full_book_ma... | Implement the Python class `BookRecord` described below.
Class description:
Implement the BookRecord class.
Method signatures and docstrings:
- def get(self, book_id): Gets a specific book record based on book_id. :param book_id: Record of a book. :return: JSON of requested book record according to model full_book_ma... | 4c3fdf41a43a56c253faecacac5f9d977d9c99be | <|skeleton|>
class BookRecord:
def get(self, book_id):
"""Gets a specific book record based on book_id. :param book_id: Record of a book. :return: JSON of requested book record according to model full_book_marshaller."""
<|body_0|>
def put(self, book_id):
"""Updates an existing Book re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookRecord:
def get(self, book_id):
"""Gets a specific book record based on book_id. :param book_id: Record of a book. :return: JSON of requested book record according to model full_book_marshaller."""
print('Received GET on resource /books/<book_id>')
if book_id.isdigit():
... | the_stack_v2_python_sparse | apis/books_api.py | neu-seattle-cs5500-fall18/book-library-web-service-scrumptious | train | 0 | |
e3876a5cd38e7fac9a759dccb6292b624bba5118 | [
"extra_fields = kwargs.pop('extra', 0)\nsuper(AddCodingTestForm, self).__init__(*args, **kwargs)\nself.fields['total_testcases_count'].initial = extra_fields\nfor index in range(int(extra_fields)):\n self.fields['testcases_{index}'.format(index=index)] = forms.CharField()\n self.fields['outputs_{index}'.forma... | <|body_start_0|>
extra_fields = kwargs.pop('extra', 0)
super(AddCodingTestForm, self).__init__(*args, **kwargs)
self.fields['total_testcases_count'].initial = extra_fields
for index in range(int(extra_fields)):
self.fields['testcases_{index}'.format(index=index)] = forms.Char... | coding test form | AddCodingTestForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddCodingTestForm:
"""coding test form"""
def __init__(self, *args, **kwargs):
"""Testcases"""
<|body_0|>
def clean_title(self):
"""Check title is not empty"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
extra_fields = kwargs.pop('extra', 0)
... | stack_v2_sparse_classes_36k_train_013507 | 8,285 | no_license | [
{
"docstring": "Testcases",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check title is not empty",
"name": "clean_title",
"signature": "def clean_title(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000669 | Implement the Python class `AddCodingTestForm` described below.
Class description:
coding test form
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Testcases
- def clean_title(self): Check title is not empty | Implement the Python class `AddCodingTestForm` described below.
Class description:
coding test form
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Testcases
- def clean_title(self): Check title is not empty
<|skeleton|>
class AddCodingTestForm:
"""coding test form"""
def __init__(s... | 65d9aa549a0d76f58cb89cac5da4a3085a2efd97 | <|skeleton|>
class AddCodingTestForm:
"""coding test form"""
def __init__(self, *args, **kwargs):
"""Testcases"""
<|body_0|>
def clean_title(self):
"""Check title is not empty"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddCodingTestForm:
"""coding test form"""
def __init__(self, *args, **kwargs):
"""Testcases"""
extra_fields = kwargs.pop('extra', 0)
super(AddCodingTestForm, self).__init__(*args, **kwargs)
self.fields['total_testcases_count'].initial = extra_fields
for index in ra... | the_stack_v2_python_sparse | nitortest/forms.py | ManishSinghFartyal/InternalGit | train | 0 |
1e78fb593976798c604b74277e5196ac48a4878b | [
"url_user_get = 'https://api.weixin.qq.com/cgi-bin/user/get'\nres = self.get(url_user_get, {'next_openid': None})\nreturn res['data']['openid']",
"url_user_info = 'https://api.weixin.qq.com/cgi-bin/user/info'\nparams = {'openid': openid, 'lang': 'zh_CN'}\nreturn self.get(url_user_info, params)",
"url_user_batch... | <|body_start_0|>
url_user_get = 'https://api.weixin.qq.com/cgi-bin/user/get'
res = self.get(url_user_get, {'next_openid': None})
return res['data']['openid']
<|end_body_0|>
<|body_start_1|>
url_user_info = 'https://api.weixin.qq.com/cgi-bin/user/info'
params = {'openid': openid,... | 微信用户管理 | WxUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WxUserManager:
"""微信用户管理"""
def user_list(self):
"""获取用户列表,一次最多返回10000条 :return: openid 列表"""
<|body_0|>
def user_info(self, openid: str):
"""获取用户信息"""
<|body_1|>
def user_batch(self, users: list):
"""批量获取用户信息,最多支持一次拉取100条。 :param users: open... | stack_v2_sparse_classes_36k_train_013508 | 3,667 | no_license | [
{
"docstring": "获取用户列表,一次最多返回10000条 :return: openid 列表",
"name": "user_list",
"signature": "def user_list(self)"
},
{
"docstring": "获取用户信息",
"name": "user_info",
"signature": "def user_info(self, openid: str)"
},
{
"docstring": "批量获取用户信息,最多支持一次拉取100条。 :param users: openid 列表 :ret... | 4 | null | Implement the Python class `WxUserManager` described below.
Class description:
微信用户管理
Method signatures and docstrings:
- def user_list(self): 获取用户列表,一次最多返回10000条 :return: openid 列表
- def user_info(self, openid: str): 获取用户信息
- def user_batch(self, users: list): 批量获取用户信息,最多支持一次拉取100条。 :param users: openid 列表 :return:
... | Implement the Python class `WxUserManager` described below.
Class description:
微信用户管理
Method signatures and docstrings:
- def user_list(self): 获取用户列表,一次最多返回10000条 :return: openid 列表
- def user_info(self, openid: str): 获取用户信息
- def user_batch(self, users: list): 批量获取用户信息,最多支持一次拉取100条。 :param users: openid 列表 :return:
... | 7316880e2444a8af02e2f44af38dd7ae708ccbb6 | <|skeleton|>
class WxUserManager:
"""微信用户管理"""
def user_list(self):
"""获取用户列表,一次最多返回10000条 :return: openid 列表"""
<|body_0|>
def user_info(self, openid: str):
"""获取用户信息"""
<|body_1|>
def user_batch(self, users: list):
"""批量获取用户信息,最多支持一次拉取100条。 :param users: open... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WxUserManager:
"""微信用户管理"""
def user_list(self):
"""获取用户列表,一次最多返回10000条 :return: openid 列表"""
url_user_get = 'https://api.weixin.qq.com/cgi-bin/user/get'
res = self.get(url_user_get, {'next_openid': None})
return res['data']['openid']
def user_info(self, openid: str):... | the_stack_v2_python_sparse | web_flask/weixin/user.py | aiportal/zb123 | train | 0 |
f72162b5d60b1464e83040f7016d23b5e3b7d3fa | [
"length_of_first = len(first)\nfirst = int(first)\nif not num:\n return\nfor i in range(len(num) - length_of_first + 1):\n second = int(num[:i + 1])\n if i > 0 and num[0] == '0':\n return\n sum_ = str(first + second)\n if num[i + 1:].startswith(sum_):\n length = len(sum_) + i + 1\n ... | <|body_start_0|>
length_of_first = len(first)
first = int(first)
if not num:
return
for i in range(len(num) - length_of_first + 1):
second = int(num[:i + 1])
if i > 0 and num[0] == '0':
return
sum_ = str(first + second)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def recursion(self, first, num):
""":type first: str :type num: str"""
<|body_0|>
def isAdditiveNumber(self, num):
""":type num: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length_of_first = len(first)
first = ... | stack_v2_sparse_classes_36k_train_013509 | 1,661 | no_license | [
{
"docstring": ":type first: str :type num: str",
"name": "recursion",
"signature": "def recursion(self, first, num)"
},
{
"docstring": ":type num: str :rtype: bool",
"name": "isAdditiveNumber",
"signature": "def isAdditiveNumber(self, num)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recursion(self, first, num): :type first: str :type num: str
- def isAdditiveNumber(self, num): :type num: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recursion(self, first, num): :type first: str :type num: str
- def isAdditiveNumber(self, num): :type num: str :rtype: bool
<|skeleton|>
class Solution:
def recursion(s... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def recursion(self, first, num):
""":type first: str :type num: str"""
<|body_0|>
def isAdditiveNumber(self, num):
""":type num: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def recursion(self, first, num):
""":type first: str :type num: str"""
length_of_first = len(first)
first = int(first)
if not num:
return
for i in range(len(num) - length_of_first + 1):
second = int(num[:i + 1])
if i > 0 and... | the_stack_v2_python_sparse | python/leetcode/306_Additive_Number.py | bobcaoge/my-code | train | 0 | |
cf8a116697673bf82f4ee3b417d97aabd2fcfe51 | [
"self.dicts = {}\nlists = []\nfor index, item in enumerate(intervals):\n self.dicts[item.start] = index\n lists.append(item.start)\nprint(self.dicts)\nprint(lists)\nlists = sorted(lists)\nresult = []\nfor i in intervals:\n a = i.end\n if a > lists[-1]:\n result.append(-1)\n else:\n x_in... | <|body_start_0|>
self.dicts = {}
lists = []
for index, item in enumerate(intervals):
self.dicts[item.start] = index
lists.append(item.start)
print(self.dicts)
print(lists)
lists = sorted(lists)
result = []
for i in intervals:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findRightInterval(self, intervals):
""":type intervals: List[Interval] :rtype: List[int] 275ms"""
<|body_0|>
def findRightInterval_1(self, intervals):
""":type intervals: List[Interval] :rtype: List[int] 562ms"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_013510 | 3,048 | no_license | [
{
"docstring": ":type intervals: List[Interval] :rtype: List[int] 275ms",
"name": "findRightInterval",
"signature": "def findRightInterval(self, intervals)"
},
{
"docstring": ":type intervals: List[Interval] :rtype: List[int] 562ms",
"name": "findRightInterval_1",
"signature": "def findR... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRightInterval(self, intervals): :type intervals: List[Interval] :rtype: List[int] 275ms
- def findRightInterval_1(self, intervals): :type intervals: List[Interval] :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRightInterval(self, intervals): :type intervals: List[Interval] :rtype: List[int] 275ms
- def findRightInterval_1(self, intervals): :type intervals: List[Interval] :rtype... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def findRightInterval(self, intervals):
""":type intervals: List[Interval] :rtype: List[int] 275ms"""
<|body_0|>
def findRightInterval_1(self, intervals):
""":type intervals: List[Interval] :rtype: List[int] 562ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findRightInterval(self, intervals):
""":type intervals: List[Interval] :rtype: List[int] 275ms"""
self.dicts = {}
lists = []
for index, item in enumerate(intervals):
self.dicts[item.start] = index
lists.append(item.start)
print(self... | the_stack_v2_python_sparse | FindRightInterval_MID_436.py | 953250587/leetcode-python | train | 2 | |
e2620161df419491b68784c7a8aa8cb69e659f43 | [
"allowed_types = [FeatureType.MASK_TIMELESS]\nself.feature = next(self._parse_features(feature, new_names=True, allowed_feature_types=allowed_types)())\nif np.isscalar(bins):\n bins = [bins]\nif not isinstance(bins, list) or not all((isinstance(bi, float) for bi in bins)) or np.any(np.diff(bins) <= 0) or (bins[0... | <|body_start_0|>
allowed_types = [FeatureType.MASK_TIMELESS]
self.feature = next(self._parse_features(feature, new_names=True, allowed_feature_types=allowed_types)())
if np.isscalar(bins):
bins = [bins]
if not isinstance(bins, list) or not all((isinstance(bi, float) for bi in... | Randomly assign each pixel or groups of pixels to multiple subsets (e.g., test/train/validate). Input pixels are defined by an input feature (e.g., MASK_TIMELESS with polygon ids, connected component ids, or similar), that groups together pixels with similar properties. There are three modes of split operation: - :attr... | TrainTestSplitTask | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainTestSplitTask:
"""Randomly assign each pixel or groups of pixels to multiple subsets (e.g., test/train/validate). Input pixels are defined by an input feature (e.g., MASK_TIMELESS with polygon ids, connected component ids, or similar), that groups together pixels with similar properties. The... | stack_v2_sparse_classes_36k_train_013511 | 5,258 | permissive | [
{
"docstring": ":param feature: The input feature out of which to generate the train mask. :type feature: (FeatureType, feature_name, new_name) :param bins: Cumulative probabilities of all value classes or a single float, representing a fraction. :type bins: a float or list of floats :param split_type: Valye sp... | 2 | stack_v2_sparse_classes_30k_train_018034 | Implement the Python class `TrainTestSplitTask` described below.
Class description:
Randomly assign each pixel or groups of pixels to multiple subsets (e.g., test/train/validate). Input pixels are defined by an input feature (e.g., MASK_TIMELESS with polygon ids, connected component ids, or similar), that groups toget... | Implement the Python class `TrainTestSplitTask` described below.
Class description:
Randomly assign each pixel or groups of pixels to multiple subsets (e.g., test/train/validate). Input pixels are defined by an input feature (e.g., MASK_TIMELESS with polygon ids, connected component ids, or similar), that groups toget... | 148189e2b92e06059b87f223b596255ccafac86d | <|skeleton|>
class TrainTestSplitTask:
"""Randomly assign each pixel or groups of pixels to multiple subsets (e.g., test/train/validate). Input pixels are defined by an input feature (e.g., MASK_TIMELESS with polygon ids, connected component ids, or similar), that groups together pixels with similar properties. The... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainTestSplitTask:
"""Randomly assign each pixel or groups of pixels to multiple subsets (e.g., test/train/validate). Input pixels are defined by an input feature (e.g., MASK_TIMELESS with polygon ids, connected component ids, or similar), that groups together pixels with similar properties. There are three ... | the_stack_v2_python_sparse | ml_tools/eolearn/ml_tools/train_test_split.py | wouellette/eo-learn | train | 2 |
550da59976b1d217fe001b84e088bc2b4e2f1b4e | [
"self._globalTagName = None\ncheckConnectionString(connectionString)\nself._connectionString = connectionString\nself._authPath = authPath\nself._dbStarted = False\nself.fwLoad = condDB.FWIncantation()",
"isReconnected = False\nif authPath != None and self._authPath != authPath:\n self._authPath = authPath\n ... | <|body_start_0|>
self._globalTagName = None
checkConnectionString(connectionString)
self._connectionString = connectionString
self._authPath = authPath
self._dbStarted = False
self.fwLoad = condDB.FWIncantation()
<|end_body_0|>
<|body_start_1|>
isReconnected = Fa... | This class allows to connect to the database account hosting Global Tags, load one of them, and check its contents. | GlobalTagChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlobalTagChecker:
"""This class allows to connect to the database account hosting Global Tags, load one of them, and check its contents."""
def __init__(self, connectionString, authPath):
"""Parameters: connectionString: connection string for connecting to the account hosting Global ... | stack_v2_sparse_classes_36k_train_013512 | 19,420 | no_license | [
{
"docstring": "Parameters: connectionString: connection string for connecting to the account hosting Global Tags; authPath: path to authentication key.",
"name": "__init__",
"signature": "def __init__(self, connectionString, authPath)"
},
{
"docstring": "Initiates the connection to the GT datab... | 3 | null | Implement the Python class `GlobalTagChecker` described below.
Class description:
This class allows to connect to the database account hosting Global Tags, load one of them, and check its contents.
Method signatures and docstrings:
- def __init__(self, connectionString, authPath): Parameters: connectionString: connec... | Implement the Python class `GlobalTagChecker` described below.
Class description:
This class allows to connect to the database account hosting Global Tags, load one of them, and check its contents.
Method signatures and docstrings:
- def __init__(self, connectionString, authPath): Parameters: connectionString: connec... | b6a99f2e2c4e50fb508a9a50969629353bb97a9d | <|skeleton|>
class GlobalTagChecker:
"""This class allows to connect to the database account hosting Global Tags, load one of them, and check its contents."""
def __init__(self, connectionString, authPath):
"""Parameters: connectionString: connection string for connecting to the account hosting Global ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GlobalTagChecker:
"""This class allows to connect to the database account hosting Global Tags, load one of them, and check its contents."""
def __init__(self, connectionString, authPath):
"""Parameters: connectionString: connection string for connecting to the account hosting Global Tags; authPat... | the_stack_v2_python_sparse | common/conditionDatabase.py | RREYESAL/RPC_HVScan | train | 0 |
bc8c9e4d8919109ba0a9da677baf5fb179b80045 | [
"if not manufacturer:\n manufacturer = 'Unknown'\nif newProductName:\n productName = newProductName\nprodobj = self.getDmdRoot('Manufacturers').createHardwareProduct(productName, manufacturer, **kwargs)\nself.setProductClass(prodobj)\nif REQUEST:\n messaging.IMessageSender(self).sendToBrowser('Product Set'... | <|body_start_0|>
if not manufacturer:
manufacturer = 'Unknown'
if newProductName:
productName = newProductName
prodobj = self.getDmdRoot('Manufacturers').createHardwareProduct(productName, manufacturer, **kwargs)
self.setProductClass(prodobj)
if REQUEST:
... | Hardware object | Hardware | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hardware:
"""Hardware object"""
def setProduct(self, productName, manufacturer='Unknown', newProductName='', REQUEST=None, **kwargs):
"""Set the product class of this software."""
<|body_0|>
def setProductKey(self, prodKey, manufacturer=None):
"""Set the product ... | stack_v2_sparse_classes_36k_train_013513 | 2,994 | no_license | [
{
"docstring": "Set the product class of this software.",
"name": "setProduct",
"signature": "def setProduct(self, productName, manufacturer='Unknown', newProductName='', REQUEST=None, **kwargs)"
},
{
"docstring": "Set the product class of this software by its productKey.",
"name": "setProdu... | 2 | stack_v2_sparse_classes_30k_train_014885 | Implement the Python class `Hardware` described below.
Class description:
Hardware object
Method signatures and docstrings:
- def setProduct(self, productName, manufacturer='Unknown', newProductName='', REQUEST=None, **kwargs): Set the product class of this software.
- def setProductKey(self, prodKey, manufacturer=No... | Implement the Python class `Hardware` described below.
Class description:
Hardware object
Method signatures and docstrings:
- def setProduct(self, productName, manufacturer='Unknown', newProductName='', REQUEST=None, **kwargs): Set the product class of this software.
- def setProductKey(self, prodKey, manufacturer=No... | 1ea508c3d2b51742bc3b448c445cd0a3dba9e798 | <|skeleton|>
class Hardware:
"""Hardware object"""
def setProduct(self, productName, manufacturer='Unknown', newProductName='', REQUEST=None, **kwargs):
"""Set the product class of this software."""
<|body_0|>
def setProductKey(self, prodKey, manufacturer=None):
"""Set the product ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Hardware:
"""Hardware object"""
def setProduct(self, productName, manufacturer='Unknown', newProductName='', REQUEST=None, **kwargs):
"""Set the product class of this software."""
if not manufacturer:
manufacturer = 'Unknown'
if newProductName:
productName ... | the_stack_v2_python_sparse | Products/ZenModel/Hardware.py | zenoss/zenoss-prodbin | train | 27 |
16735da1a755908f562d3d59cf5ed009f837f213 | [
"cpu = os.popen('top -bi -n 2 -d 0.02').read().split('\\n\\n\\n')[1].split('\\n')[2]\nwith sjapi.connection() as db:\n csxx = {'id': get_uuid(), 'ssdxid': self.dxid, 'nr': cpu, 'jlsj': get_strftime2(), 'cjpzid': self.cjpzid, 'ip': self.zjip, 'cjmc': 'cpu', 'zbbm': 'get_cpu()'}\n ModSql.yw_jkgl_001.execute_sql... | <|body_start_0|>
cpu = os.popen('top -bi -n 2 -d 0.02').read().split('\n\n\n')[1].split('\n')[2]
with sjapi.connection() as db:
csxx = {'id': get_uuid(), 'ssdxid': self.dxid, 'nr': cpu, 'jlsj': get_strftime2(), 'cjpzid': self.cjpzid, 'ip': self.zjip, 'cjmc': 'cpu', 'zbbm': 'get_cpu()'}
... | Computer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Computer:
def get_cpu(self):
"""获取CPU使用情况"""
<|body_0|>
def get_ram(self):
"""获取内存使用情况"""
<|body_1|>
def get_io(self):
"""获取磁盘I/O繁忙率"""
<|body_2|>
def get_filesystem(self):
"""获取文件系统使用率"""
<|body_3|>
def get_virt... | stack_v2_sparse_classes_36k_train_013514 | 16,132 | no_license | [
{
"docstring": "获取CPU使用情况",
"name": "get_cpu",
"signature": "def get_cpu(self)"
},
{
"docstring": "获取内存使用情况",
"name": "get_ram",
"signature": "def get_ram(self)"
},
{
"docstring": "获取磁盘I/O繁忙率",
"name": "get_io",
"signature": "def get_io(self)"
},
{
"docstring": "获... | 6 | stack_v2_sparse_classes_30k_train_011235 | Implement the Python class `Computer` described below.
Class description:
Implement the Computer class.
Method signatures and docstrings:
- def get_cpu(self): 获取CPU使用情况
- def get_ram(self): 获取内存使用情况
- def get_io(self): 获取磁盘I/O繁忙率
- def get_filesystem(self): 获取文件系统使用率
- def get_virtual(self): 获取虚拟内存使用情况
- def get_proc... | Implement the Python class `Computer` described below.
Class description:
Implement the Computer class.
Method signatures and docstrings:
- def get_cpu(self): 获取CPU使用情况
- def get_ram(self): 获取内存使用情况
- def get_io(self): 获取磁盘I/O繁忙率
- def get_filesystem(self): 获取文件系统使用率
- def get_virtual(self): 获取虚拟内存使用情况
- def get_proc... | 68ddf3df6d2cd731e6634b09d27aff4c22debd8e | <|skeleton|>
class Computer:
def get_cpu(self):
"""获取CPU使用情况"""
<|body_0|>
def get_ram(self):
"""获取内存使用情况"""
<|body_1|>
def get_io(self):
"""获取磁盘I/O繁忙率"""
<|body_2|>
def get_filesystem(self):
"""获取文件系统使用率"""
<|body_3|>
def get_virt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Computer:
def get_cpu(self):
"""获取CPU使用情况"""
cpu = os.popen('top -bi -n 2 -d 0.02').read().split('\n\n\n')[1].split('\n')[2]
with sjapi.connection() as db:
csxx = {'id': get_uuid(), 'ssdxid': self.dxid, 'nr': cpu, 'jlsj': get_strftime2(), 'cjpzid': self.cjpzid, 'ip': self.z... | the_stack_v2_python_sparse | zh_manage/apps/_init/oa/yw_jkgl/yw_jkgl_001/yw_jkgl_001.py | yizhong120110/CPOS | train | 0 | |
a0c3e32fe7eab37f7cfd55657a324d2ab871bf9a | [
"query = cls.get_in_range(start=start, end=end, feeling_ids=feeling_ids).filter(missing_data=False)\nquery = query.values('feeling').annotate(models.Avg('percent')).order_by('feeling')\nresult = {}\nfor row in query:\n result[row['feeling']] = row['percent__avg']\nreturn result",
"query = cls.get_in_range(star... | <|body_start_0|>
query = cls.get_in_range(start=start, end=end, feeling_ids=feeling_ids).filter(missing_data=False)
query = query.values('feeling').annotate(models.Avg('percent')).order_by('feeling')
result = {}
for row in query:
result[row['feeling']] = row['percent__avg']
... | A class for storing the percent of tweets for a given feeling in a given time frame. | FeelingPercent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeelingPercent:
"""A class for storing the percent of tweets for a given feeling in a given time frame."""
def get_average_percents(cls, start=None, end=None, feeling_ids=None):
"""Gets the average percentage for each feeling in an interval."""
<|body_0|>
def get_percent... | stack_v2_sparse_classes_36k_train_013515 | 13,110 | permissive | [
{
"docstring": "Gets the average percentage for each feeling in an interval.",
"name": "get_average_percents",
"signature": "def get_average_percents(cls, start=None, end=None, feeling_ids=None)"
},
{
"docstring": "Gets FeelingPercents over an interval. Applies sorting etc to generate data usefu... | 4 | stack_v2_sparse_classes_30k_train_013319 | Implement the Python class `FeelingPercent` described below.
Class description:
A class for storing the percent of tweets for a given feeling in a given time frame.
Method signatures and docstrings:
- def get_average_percents(cls, start=None, end=None, feeling_ids=None): Gets the average percentage for each feeling i... | Implement the Python class `FeelingPercent` described below.
Class description:
A class for storing the percent of tweets for a given feeling in a given time frame.
Method signatures and docstrings:
- def get_average_percents(cls, start=None, end=None, feeling_ids=None): Gets the average percentage for each feeling i... | 51dc00478f05841f3726edf5f7da7e0a46ae66e8 | <|skeleton|>
class FeelingPercent:
"""A class for storing the percent of tweets for a given feeling in a given time frame."""
def get_average_percents(cls, start=None, end=None, feeling_ids=None):
"""Gets the average percentage for each feeling in an interval."""
<|body_0|>
def get_percent... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeelingPercent:
"""A class for storing the percent of tweets for a given feeling in a given time frame."""
def get_average_percents(cls, start=None, end=None, feeling_ids=None):
"""Gets the average percentage for each feeling in an interval."""
query = cls.get_in_range(start=start, end=en... | the_stack_v2_python_sparse | twitter_feels/apps/thermometer/models.py | michaelbrooks/twitter-feels | train | 1 |
a5036c87377c480434bfac8ad373167775c106ea | [
"while start <= end:\n mid = (start + end) // 2\n if array[mid] == target:\n return mid\n elif array[mid] < target:\n start = mid + 1\n else:\n end = mid - 1\nreturn -1",
"if not array:\n return -1\nn = len(array)\nstart, end = (0, n - 1)\nwhile start <= end:\n mid = (start ... | <|body_start_0|>
while start <= end:
mid = (start + end) // 2
if array[mid] == target:
return mid
elif array[mid] < target:
start = mid + 1
else:
end = mid - 1
return -1
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def binary_search(self, array, start, end, target):
"""Helper function for search function(below). Binary searches array from start to end, returns index of element equal to target of there's one, otherwise returns -1. Time complexity: O(lg(n)). Space complexity: O(1), n is len... | stack_v2_sparse_classes_36k_train_013516 | 3,729 | no_license | [
{
"docstring": "Helper function for search function(below). Binary searches array from start to end, returns index of element equal to target of there's one, otherwise returns -1. Time complexity: O(lg(n)). Space complexity: O(1), n is len(array).",
"name": "binary_search",
"signature": "def binary_sear... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binary_search(self, array, start, end, target): Helper function for search function(below). Binary searches array from start to end, returns index of element equal to target ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binary_search(self, array, start, end, target): Helper function for search function(below). Binary searches array from start to end, returns index of element equal to target ... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def binary_search(self, array, start, end, target):
"""Helper function for search function(below). Binary searches array from start to end, returns index of element equal to target of there's one, otherwise returns -1. Time complexity: O(lg(n)). Space complexity: O(1), n is len... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def binary_search(self, array, start, end, target):
"""Helper function for search function(below). Binary searches array from start to end, returns index of element equal to target of there's one, otherwise returns -1. Time complexity: O(lg(n)). Space complexity: O(1), n is len(array)."""
... | the_stack_v2_python_sparse | Binary_Search/search_rotated_sorted_array.py | vladn90/Algorithms | train | 0 | |
4aa63c4221059587c1717673660e15da41e8851b | [
"if not nums or len(nums) == 0:\n return 0\nmax_so_far, max_at_here = (nums[0], nums[0])\nfor n in nums[1:]:\n max_at_here = max(0, max_at_here) + n\n max_so_far = max(max_so_far, max_at_here)\nreturn max_so_far",
"max_at_here = nums[0]\nmax_so_far = [max_at_here]\nfor i in range(1, len(nums)):\n if m... | <|body_start_0|>
if not nums or len(nums) == 0:
return 0
max_so_far, max_at_here = (nums[0], nums[0])
for n in nums[1:]:
max_at_here = max(0, max_at_here) + n
max_so_far = max(max_so_far, max_at_here)
return max_so_far
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArraySlow(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArrayA(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def maxSubArrayB(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_36k_train_013517 | 1,236 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArraySlow",
"signature": "def maxSubArraySlow(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArrayA",
"signature": "def maxSubArrayA(self, nums)"
},
{
"docstring": ":type nums: ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArraySlow(self, nums): :type nums: List[int] :rtype: int
- def maxSubArrayA(self, nums): :type nums: List[int] :rtype: int
- def maxSubArrayB(self, nums): :type nums: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArraySlow(self, nums): :type nums: List[int] :rtype: int
- def maxSubArrayA(self, nums): :type nums: List[int] :rtype: int
- def maxSubArrayB(self, nums): :type nums: L... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def maxSubArraySlow(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArrayA(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def maxSubArrayB(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArraySlow(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums or len(nums) == 0:
return 0
max_so_far, max_at_here = (nums[0], nums[0])
for n in nums[1:]:
max_at_here = max(0, max_at_here) + n
max_so_far = max(... | the_stack_v2_python_sparse | top_interview_questions/easy_collection/dynamic_programming/maximum_subarray.py | hwc1824/LeetCodeSolution | train | 0 | |
da8ccc9e706518b82ad59d7d6a2af0e0e84ef5ff | [
"record = cls.get_or_none(cls.user_id == user_id, cls.group_id == group_id)\nif record is not None:\n return record.UserLevel\nelse:\n return None",
"record, _ = cls.get_or_create(user_id=user_id, group_id=group_id)\nrecord.UserLevel = level\nrecord.save()",
"record = cls.get_or_none(cls.user_id == user_i... | <|body_start_0|>
record = cls.get_or_none(cls.user_id == user_id, cls.group_id == group_id)
if record is not None:
return record.UserLevel
else:
return None
<|end_body_0|>
<|body_start_1|>
record, _ = cls.get_or_create(user_id=user_id, group_id=group_id)
... | UserLevel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserLevel:
async def get_uer_level(cls, user_id: int, group_id: int) -> int:
""":说明 获取权限等级,如果没有则返回None :参数 * user_id:用户QQ * group_id:QQ群号 :返回 * int:权限等级 * None:"""
<|body_0|>
async def set_level(cls, user_id: int, group_id: int, level: int) -> None:
""":说明 设置权限,如果没有则... | stack_v2_sparse_classes_36k_train_013518 | 1,914 | permissive | [
{
"docstring": ":说明 获取权限等级,如果没有则返回None :参数 * user_id:用户QQ * group_id:QQ群号 :返回 * int:权限等级 * None:",
"name": "get_uer_level",
"signature": "async def get_uer_level(cls, user_id: int, group_id: int) -> int"
},
{
"docstring": ":说明 设置权限,如果没有则创建记录 :参数 * user_id:用户QQ * group_id:QQ群号 * level:权限等级",
... | 3 | stack_v2_sparse_classes_30k_train_001468 | Implement the Python class `UserLevel` described below.
Class description:
Implement the UserLevel class.
Method signatures and docstrings:
- async def get_uer_level(cls, user_id: int, group_id: int) -> int: :说明 获取权限等级,如果没有则返回None :参数 * user_id:用户QQ * group_id:QQ群号 :返回 * int:权限等级 * None:
- async def set_level(cls, us... | Implement the Python class `UserLevel` described below.
Class description:
Implement the UserLevel class.
Method signatures and docstrings:
- async def get_uer_level(cls, user_id: int, group_id: int) -> int: :说明 获取权限等级,如果没有则返回None :参数 * user_id:用户QQ * group_id:QQ群号 :返回 * int:权限等级 * None:
- async def set_level(cls, us... | 8bb989aceb1a89569f2fcb804c73f7b650feb1f0 | <|skeleton|>
class UserLevel:
async def get_uer_level(cls, user_id: int, group_id: int) -> int:
""":说明 获取权限等级,如果没有则返回None :参数 * user_id:用户QQ * group_id:QQ群号 :返回 * int:权限等级 * None:"""
<|body_0|>
async def set_level(cls, user_id: int, group_id: int, level: int) -> None:
""":说明 设置权限,如果没有则... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserLevel:
async def get_uer_level(cls, user_id: int, group_id: int) -> int:
""":说明 获取权限等级,如果没有则返回None :参数 * user_id:用户QQ * group_id:QQ群号 :返回 * int:权限等级 * None:"""
record = cls.get_or_none(cls.user_id == user_id, cls.group_id == group_id)
if record is not None:
return recor... | the_stack_v2_python_sparse | modules/user_level.py | JustUndertaker/tuanzi_bot | train | 8 | |
31c7a42a3ba3190cf7bef1a1172555fae4fafb0e | [
"res = 0\nleft = 0\nlastpos = dict()\nfor i in xrange(len(s)):\n if s[i] in lastpos and lastpos[s[i]] >= left:\n left = lastpos[s[i]] + 1\n lastpos[s[i]] = i\n if i - left + 1 > res:\n res = i - left + 1\nreturn res",
"max_len = 0\nleft = 0\nlast_pos = {}\nfor i in xrange(len(s)):\n if s... | <|body_start_0|>
res = 0
left = 0
lastpos = dict()
for i in xrange(len(s)):
if s[i] in lastpos and lastpos[s[i]] >= left:
left = lastpos[s[i]] + 1
lastpos[s[i]] = i
if i - left + 1 > res:
res = i - left + 1
retur... | 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|>
res = 0
left = 0
lastpos = ... | stack_v2_sparse_classes_36k_train_013519 | 1,074 | 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 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int | 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... | 6582b0f138a19f9d4a005eda298ecb1488eb0d2e | <|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"""
res = 0
left = 0
lastpos = dict()
for i in xrange(len(s)):
if s[i] in lastpos and lastpos[s[i]] >= left:
left = lastpos[s[i]] + 1
lastpos[s[i]] = i
... | the_stack_v2_python_sparse | String/3.py | ShangruZhong/leetcode | train | 0 | |
44555fba81f56524330a9195180a06f99ea1b950 | [
"self.title = 'Convert Miles to KM Program'\nself.root = Builder.load_file('convert_miles_km.kv')\nreturn self.root",
"miles = self.get_valid_miles()\nkm = miles * MILES_TO_KM\nself.root.ids.km_output.text = str(km)",
"new_miles = self.get_valid_miles() + increment\nself.root.ids.miles_input.text = str(new_mile... | <|body_start_0|>
self.title = 'Convert Miles to KM Program'
self.root = Builder.load_file('convert_miles_km.kv')
return self.root
<|end_body_0|>
<|body_start_1|>
miles = self.get_valid_miles()
km = miles * MILES_TO_KM
self.root.ids.km_output.text = str(km)
<|end_body_1|>... | ConvertMilesToKMProgram is a KIVY GUI program for converting miles to km. | ConvertMilesToKMProgram | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvertMilesToKMProgram:
"""ConvertMilesToKMProgram is a KIVY GUI program for converting miles to km."""
def build(self):
"""Build app using Kivy app from kv file"""
<|body_0|>
def calculate_miles_to_km(self):
"""Calculates miles to km and outputs to GUI"""
... | stack_v2_sparse_classes_36k_train_013520 | 1,212 | no_license | [
{
"docstring": "Build app using Kivy app from kv file",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "Calculates miles to km and outputs to GUI",
"name": "calculate_miles_to_km",
"signature": "def calculate_miles_to_km(self)"
},
{
"docstring": "Handle increme... | 4 | stack_v2_sparse_classes_30k_train_015949 | Implement the Python class `ConvertMilesToKMProgram` described below.
Class description:
ConvertMilesToKMProgram is a KIVY GUI program for converting miles to km.
Method signatures and docstrings:
- def build(self): Build app using Kivy app from kv file
- def calculate_miles_to_km(self): Calculates miles to km and ou... | Implement the Python class `ConvertMilesToKMProgram` described below.
Class description:
ConvertMilesToKMProgram is a KIVY GUI program for converting miles to km.
Method signatures and docstrings:
- def build(self): Build app using Kivy app from kv file
- def calculate_miles_to_km(self): Calculates miles to km and ou... | 6c47affda245b594e25accdcd04fbf65facd53da | <|skeleton|>
class ConvertMilesToKMProgram:
"""ConvertMilesToKMProgram is a KIVY GUI program for converting miles to km."""
def build(self):
"""Build app using Kivy app from kv file"""
<|body_0|>
def calculate_miles_to_km(self):
"""Calculates miles to km and outputs to GUI"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvertMilesToKMProgram:
"""ConvertMilesToKMProgram is a KIVY GUI program for converting miles to km."""
def build(self):
"""Build app using Kivy app from kv file"""
self.title = 'Convert Miles to KM Program'
self.root = Builder.load_file('convert_miles_km.kv')
return self... | the_stack_v2_python_sparse | prac_07/convert_miles_km.py | CamA-JCU/cp1404practicals | train | 0 |
ec93a8a3fedc9309a307831ba07e4d7b530d0408 | [
"QtGui.QLabel.__init__(self, parent)\nself.var_name = var_name\nself.setText(var_name)\nself.setAttribute(QtCore.Qt.WA_Hover)\nself.setCursor(QtCore.Qt.PointingHandCursor)\nself.setToolTip('Click to rename')\nself.palette().setColor(QtGui.QPalette.WindowText, CurrentTheme.HOVER_DEFAULT_COLOR)",
"if event.type() =... | <|body_start_0|>
QtGui.QLabel.__init__(self, parent)
self.var_name = var_name
self.setText(var_name)
self.setAttribute(QtCore.Qt.WA_Hover)
self.setCursor(QtCore.Qt.PointingHandCursor)
self.setToolTip('Click to rename')
self.palette().setColor(QtGui.QPalette.Window... | QHoverVariableLabel is a QLabel that supports hover actions similar to a hot link | QHoverVariableLabel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QHoverVariableLabel:
"""QHoverVariableLabel is a QLabel that supports hover actions similar to a hot link"""
def __init__(self, var_name='', parent=None):
"""QHoverVariableLabel(var_name:str, parent: QWidget) -> QHoverVariableLabel Initialize the label with a variable name"""
... | stack_v2_sparse_classes_36k_train_013521 | 22,077 | permissive | [
{
"docstring": "QHoverVariableLabel(var_name:str, parent: QWidget) -> QHoverVariableLabel Initialize the label with a variable name",
"name": "__init__",
"signature": "def __init__(self, var_name='', parent=None)"
},
{
"docstring": "event(event: QEvent) -> Event Result Override to handle hover e... | 3 | null | Implement the Python class `QHoverVariableLabel` described below.
Class description:
QHoverVariableLabel is a QLabel that supports hover actions similar to a hot link
Method signatures and docstrings:
- def __init__(self, var_name='', parent=None): QHoverVariableLabel(var_name:str, parent: QWidget) -> QHoverVariableL... | Implement the Python class `QHoverVariableLabel` described below.
Class description:
QHoverVariableLabel is a QLabel that supports hover actions similar to a hot link
Method signatures and docstrings:
- def __init__(self, var_name='', parent=None): QHoverVariableLabel(var_name:str, parent: QWidget) -> QHoverVariableL... | 23ef56ec24b85c82416e1437a08381635328abe5 | <|skeleton|>
class QHoverVariableLabel:
"""QHoverVariableLabel is a QLabel that supports hover actions similar to a hot link"""
def __init__(self, var_name='', parent=None):
"""QHoverVariableLabel(var_name:str, parent: QWidget) -> QHoverVariableLabel Initialize the label with a variable name"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QHoverVariableLabel:
"""QHoverVariableLabel is a QLabel that supports hover actions similar to a hot link"""
def __init__(self, var_name='', parent=None):
"""QHoverVariableLabel(var_name:str, parent: QWidget) -> QHoverVariableLabel Initialize the label with a variable name"""
QtGui.QLabel... | the_stack_v2_python_sparse | vistrails_current/vistrails/gui/variable_dropbox.py | lumig242/VisTrailsRecommendation | train | 3 |
1d95b2c16f355fcf690685b4112ff05e08d1c2db | [
"self.contents = HashMap()\nfor gdl in description:\n if not self.contents.containsKey(key):\n self.contents.put(key, ArrayList())\n self.contents.get(key).add(rule)",
"key = sentence.__name__\nif self.contents.containsKey(key):\n return self.contents.get(key)\nelse:\n return ArrayList()"
] | <|body_start_0|>
self.contents = HashMap()
for gdl in description:
if not self.contents.containsKey(key):
self.contents.put(key, ArrayList())
self.contents.get(key).add(rule)
<|end_body_0|>
<|body_start_1|>
key = sentence.__name__
if self.contents... | generated source for class KnowledgeBase | KnowledgeBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnowledgeBase:
"""generated source for class KnowledgeBase"""
def __init__(self, description):
"""generated source for method __init__"""
<|body_0|>
def fetch(self, sentence):
"""generated source for method fetch"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_013522 | 1,425 | permissive | [
{
"docstring": "generated source for method __init__",
"name": "__init__",
"signature": "def __init__(self, description)"
},
{
"docstring": "generated source for method fetch",
"name": "fetch",
"signature": "def fetch(self, sentence)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000375 | Implement the Python class `KnowledgeBase` described below.
Class description:
generated source for class KnowledgeBase
Method signatures and docstrings:
- def __init__(self, description): generated source for method __init__
- def fetch(self, sentence): generated source for method fetch | Implement the Python class `KnowledgeBase` described below.
Class description:
generated source for class KnowledgeBase
Method signatures and docstrings:
- def __init__(self, description): generated source for method __init__
- def fetch(self, sentence): generated source for method fetch
<|skeleton|>
class Knowledge... | 4e6e6e876c3a4294cd711647051da2d9c1836b60 | <|skeleton|>
class KnowledgeBase:
"""generated source for class KnowledgeBase"""
def __init__(self, description):
"""generated source for method __init__"""
<|body_0|>
def fetch(self, sentence):
"""generated source for method fetch"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KnowledgeBase:
"""generated source for class KnowledgeBase"""
def __init__(self, description):
"""generated source for method __init__"""
self.contents = HashMap()
for gdl in description:
if not self.contents.containsKey(key):
self.contents.put(key, Arr... | the_stack_v2_python_sparse | ggpy/cruft/autocode/KnowledgeBase.py | hobson/ggpy | train | 1 |
5f06c63b9460448d3503f95ebfe9f62bd59f6710 | [
"request = pecan.request\ncontext = request.environ['context']\nfips = self.central_api.list_floatingips(context)\nLOG.info('Retrieved %(fips)s', {'fips': fips})\nreturn DesignateAdapter.render('API_v2', fips, request=request)",
"request = pecan.request\nresponse = pecan.response\ncontext = request.environ['conte... | <|body_start_0|>
request = pecan.request
context = request.environ['context']
fips = self.central_api.list_floatingips(context)
LOG.info('Retrieved %(fips)s', {'fips': fips})
return DesignateAdapter.render('API_v2', fips, request=request)
<|end_body_0|>
<|body_start_1|>
... | FloatingIPController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloatingIPController:
def get_all(self, **params):
"""List Floating IP PTRs for a Tenant"""
<|body_0|>
def patch_one(self, fip_key):
"""Set or unset a PTR"""
<|body_1|>
def get_one(self, fip_key):
"""Get PTR"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_013523 | 3,119 | permissive | [
{
"docstring": "List Floating IP PTRs for a Tenant",
"name": "get_all",
"signature": "def get_all(self, **params)"
},
{
"docstring": "Set or unset a PTR",
"name": "patch_one",
"signature": "def patch_one(self, fip_key)"
},
{
"docstring": "Get PTR",
"name": "get_one",
"sig... | 3 | null | Implement the Python class `FloatingIPController` described below.
Class description:
Implement the FloatingIPController class.
Method signatures and docstrings:
- def get_all(self, **params): List Floating IP PTRs for a Tenant
- def patch_one(self, fip_key): Set or unset a PTR
- def get_one(self, fip_key): Get PTR | Implement the Python class `FloatingIPController` described below.
Class description:
Implement the FloatingIPController class.
Method signatures and docstrings:
- def get_all(self, **params): List Floating IP PTRs for a Tenant
- def patch_one(self, fip_key): Set or unset a PTR
- def get_one(self, fip_key): Get PTR
... | 360433b38b449d1c53ab1357fdb0c4608c09efa5 | <|skeleton|>
class FloatingIPController:
def get_all(self, **params):
"""List Floating IP PTRs for a Tenant"""
<|body_0|>
def patch_one(self, fip_key):
"""Set or unset a PTR"""
<|body_1|>
def get_one(self, fip_key):
"""Get PTR"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FloatingIPController:
def get_all(self, **params):
"""List Floating IP PTRs for a Tenant"""
request = pecan.request
context = request.environ['context']
fips = self.central_api.list_floatingips(context)
LOG.info('Retrieved %(fips)s', {'fips': fips})
return Desig... | the_stack_v2_python_sparse | designate/api/v2/controllers/floatingips.py | openstack/designate | train | 156 | |
2b96ffcdde22a49e034effed49716f17dc29144a | [
"if hasattr(event_object, u'local_path'):\n return event_object.local_path\nif hasattr(event_object, u'network_path'):\n return event_object.network_path\nif hasattr(event_object, u'relative_path'):\n paths = []\n if hasattr(event_object, u'working_directory'):\n paths.append(event_object.working... | <|body_start_0|>
if hasattr(event_object, u'local_path'):
return event_object.local_path
if hasattr(event_object, u'network_path'):
return event_object.network_path
if hasattr(event_object, u'relative_path'):
paths = []
if hasattr(event_object, u'w... | Formatter for a Windows Shortcut (LNK) link event. | WinLnkLinkFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WinLnkLinkFormatter:
"""Formatter for a Windows Shortcut (LNK) link event."""
def _GetLinkedPath(self, event_object):
"""Determines the linked path. Args: event_object: The event object (EventObject) containing the event specific data. Returns: A string containing the linked path."""... | stack_v2_sparse_classes_36k_train_013524 | 2,856 | permissive | [
{
"docstring": "Determines the linked path. Args: event_object: The event object (EventObject) containing the event specific data. Returns: A string containing the linked path.",
"name": "_GetLinkedPath",
"signature": "def _GetLinkedPath(self, event_object)"
},
{
"docstring": "Determines the for... | 2 | stack_v2_sparse_classes_30k_train_001163 | Implement the Python class `WinLnkLinkFormatter` described below.
Class description:
Formatter for a Windows Shortcut (LNK) link event.
Method signatures and docstrings:
- def _GetLinkedPath(self, event_object): Determines the linked path. Args: event_object: The event object (EventObject) containing the event specif... | Implement the Python class `WinLnkLinkFormatter` described below.
Class description:
Formatter for a Windows Shortcut (LNK) link event.
Method signatures and docstrings:
- def _GetLinkedPath(self, event_object): Determines the linked path. Args: event_object: The event object (EventObject) containing the event specif... | 923797fc00664fa9e3277781b0334d6eed5664fd | <|skeleton|>
class WinLnkLinkFormatter:
"""Formatter for a Windows Shortcut (LNK) link event."""
def _GetLinkedPath(self, event_object):
"""Determines the linked path. Args: event_object: The event object (EventObject) containing the event specific data. Returns: A string containing the linked path."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WinLnkLinkFormatter:
"""Formatter for a Windows Shortcut (LNK) link event."""
def _GetLinkedPath(self, event_object):
"""Determines the linked path. Args: event_object: The event object (EventObject) containing the event specific data. Returns: A string containing the linked path."""
if h... | the_stack_v2_python_sparse | plaso/formatters/winlnk.py | CNR-ITTIG/plasodfaxp | train | 1 |
04f92c146745bce6f8accb8e9c3871aba0d8875a | [
"self._file_cache = injector.file_cache\nself._logger = logging.getLogger()\nself._hook_builder = HookSequenceBuilder()",
"command_type = command['commandType']\nif command_type == AgentCommand.status or not command_name:\n return None\nhook_dir = self._file_cache.get_hook_base_dir(command)\nif not hook_dir:\n... | <|body_start_0|>
self._file_cache = injector.file_cache
self._logger = logging.getLogger()
self._hook_builder = HookSequenceBuilder()
<|end_body_0|>
<|body_start_1|>
command_type = command['commandType']
if command_type == AgentCommand.status or not command_name:
ret... | Resolving hooks according to HookSequenceBuilder definitions | HooksOrchestrator | [
"GPL-1.0-or-later",
"GPL-2.0-or-later",
"OFL-1.1",
"MS-PL",
"AFL-2.1",
"GPL-2.0-only",
"Python-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HooksOrchestrator:
"""Resolving hooks according to HookSequenceBuilder definitions"""
def __init__(self, injector):
""":type injector InitializerModule"""
<|body_0|>
def resolve_hooks(self, command, command_name):
"""Resolving available hooks sequences which shou... | stack_v2_sparse_classes_36k_train_013525 | 5,061 | permissive | [
{
"docstring": ":type injector InitializerModule",
"name": "__init__",
"signature": "def __init__(self, injector)"
},
{
"docstring": "Resolving available hooks sequences which should be appended or prepended to script execution chain :type command dict :type command_name str :rtype ResolvedHooks... | 3 | null | Implement the Python class `HooksOrchestrator` described below.
Class description:
Resolving hooks according to HookSequenceBuilder definitions
Method signatures and docstrings:
- def __init__(self, injector): :type injector InitializerModule
- def resolve_hooks(self, command, command_name): Resolving available hooks... | Implement the Python class `HooksOrchestrator` described below.
Class description:
Resolving hooks according to HookSequenceBuilder definitions
Method signatures and docstrings:
- def __init__(self, injector): :type injector InitializerModule
- def resolve_hooks(self, command, command_name): Resolving available hooks... | 23881f23577a65de396238998e8672d6c4c5a250 | <|skeleton|>
class HooksOrchestrator:
"""Resolving hooks according to HookSequenceBuilder definitions"""
def __init__(self, injector):
""":type injector InitializerModule"""
<|body_0|>
def resolve_hooks(self, command, command_name):
"""Resolving available hooks sequences which shou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HooksOrchestrator:
"""Resolving hooks according to HookSequenceBuilder definitions"""
def __init__(self, injector):
""":type injector InitializerModule"""
self._file_cache = injector.file_cache
self._logger = logging.getLogger()
self._hook_builder = HookSequenceBuilder()
... | the_stack_v2_python_sparse | ambari-agent/src/main/python/ambari_agent/CommandHooksOrchestrator.py | apache/ambari | train | 2,078 |
51a246f9bd53bd6d76b1ac96d06d7acc9cfde8db | [
"session_id = super().create_session(user_id)\nif session_id is None:\n return None\nkwargs = {'user_id': user_id, 'session_id': session_id}\nuser_session = UserSession(**kwargs)\nuser_session.save()\nUserSession.save_to_file()\nreturn session_id",
"if session_id is None:\n return None\nUserSession.load_fro... | <|body_start_0|>
session_id = super().create_session(user_id)
if session_id is None:
return None
kwargs = {'user_id': user_id, 'session_id': session_id}
user_session = UserSession(**kwargs)
user_session.save()
UserSession.save_to_file()
return session_... | Session in database Class | SessionDBAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionDBAuth:
"""Session in database Class"""
def create_session(self, user_id=None):
"""Creation session database"""
<|body_0|>
def user_id_for_session_id(self, session_id=None):
"""User ID for Session ID Database"""
<|body_1|>
def destroy_session(... | stack_v2_sparse_classes_36k_train_013526 | 1,969 | no_license | [
{
"docstring": "Creation session database",
"name": "create_session",
"signature": "def create_session(self, user_id=None)"
},
{
"docstring": "User ID for Session ID Database",
"name": "user_id_for_session_id",
"signature": "def user_id_for_session_id(self, session_id=None)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_016778 | Implement the Python class `SessionDBAuth` described below.
Class description:
Session in database Class
Method signatures and docstrings:
- def create_session(self, user_id=None): Creation session database
- def user_id_for_session_id(self, session_id=None): User ID for Session ID Database
- def destroy_session(self... | Implement the Python class `SessionDBAuth` described below.
Class description:
Session in database Class
Method signatures and docstrings:
- def create_session(self, user_id=None): Creation session database
- def user_id_for_session_id(self, session_id=None): User ID for Session ID Database
- def destroy_session(self... | 609a1679d2c31400979d96523565db8c2d12d794 | <|skeleton|>
class SessionDBAuth:
"""Session in database Class"""
def create_session(self, user_id=None):
"""Creation session database"""
<|body_0|>
def user_id_for_session_id(self, session_id=None):
"""User ID for Session ID Database"""
<|body_1|>
def destroy_session(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionDBAuth:
"""Session in database Class"""
def create_session(self, user_id=None):
"""Creation session database"""
session_id = super().create_session(user_id)
if session_id is None:
return None
kwargs = {'user_id': user_id, 'session_id': session_id}
... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_db_auth.py | agzsoftsi/holbertonschool-web_back_end | train | 2 |
67ad328150f81565eed6168a51112866c3f59d55 | [
"counter = {}\nfor num in nums:\n if num in counter:\n counter[num] += 1\n else:\n counter[num] = 1\nusing = avoid = 0\nprev = None\nfor k in sorted(counter):\n max_value = max(using, avoid)\n if k - 1 != prev:\n using = k * counter[k] + max(using, avoid)\n avoid = max_value\... | <|body_start_0|>
counter = {}
for num in nums:
if num in counter:
counter[num] += 1
else:
counter[num] = 1
using = avoid = 0
prev = None
for k in sorted(counter):
max_value = max(using, avoid)
if k - ... | Array | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array:
def delete_and_earn_(self, nums: List[int]) -> int:
"""Approach: DP (current and previous value) + Sorting Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:"""
<|body_0|>
def delete_and_earn(self, nums: List[int]) -> int:
"""Approach: DP... | stack_v2_sparse_classes_36k_train_013527 | 1,643 | no_license | [
{
"docstring": "Approach: DP (current and previous value) + Sorting Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:",
"name": "delete_and_earn_",
"signature": "def delete_and_earn_(self, nums: List[int]) -> int"
},
{
"docstring": "Approach: DP Time Complexity: O(N) Space... | 2 | stack_v2_sparse_classes_30k_train_003674 | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def delete_and_earn_(self, nums: List[int]) -> int: Approach: DP (current and previous value) + Sorting Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:
- def d... | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def delete_and_earn_(self, nums: List[int]) -> int: Approach: DP (current and previous value) + Sorting Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:
- def d... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Array:
def delete_and_earn_(self, nums: List[int]) -> int:
"""Approach: DP (current and previous value) + Sorting Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:"""
<|body_0|>
def delete_and_earn(self, nums: List[int]) -> int:
"""Approach: DP... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Array:
def delete_and_earn_(self, nums: List[int]) -> int:
"""Approach: DP (current and previous value) + Sorting Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:"""
counter = {}
for num in nums:
if num in counter:
counter[num] += 1
... | the_stack_v2_python_sparse | goldman_sachs/delete_and_earn.py | Shiv2157k/leet_code | train | 1 | |
6e0a7d19dec6a8d1db70c3c15ade1bf770320267 | [
"if request.user.is_authenticated:\n childs = Message.objects.filter(id_parent=id_parent).all()\n message = Message.objects.filter(id=id_parent).get()\n count_childs = int(request.GET.get('count_childs', 0))\n count_childs_form = CountChildsMessageForm(initial={'count_childs': count_childs})\n form_s... | <|body_start_0|>
if request.user.is_authenticated:
childs = Message.objects.filter(id_parent=id_parent).all()
message = Message.objects.filter(id=id_parent).get()
count_childs = int(request.GET.get('count_childs', 0))
count_childs_form = CountChildsMessageForm(ini... | ViewChilds | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewChilds:
def get(self, request, id_parent):
"""Возвращает формы для создания потомков :param id_parent: id родителя :type id_parent: int :return: возвращает формы для создания потомков если пользователь авторизован, иначе ошибка"""
<|body_0|>
def post(self, request, id_pa... | stack_v2_sparse_classes_36k_train_013528 | 6,887 | no_license | [
{
"docstring": "Возвращает формы для создания потомков :param id_parent: id родителя :type id_parent: int :return: возвращает формы для создания потомков если пользователь авторизован, иначе ошибка",
"name": "get",
"signature": "def get(self, request, id_parent)"
},
{
"docstring": "Устанавливает... | 2 | null | Implement the Python class `ViewChilds` described below.
Class description:
Implement the ViewChilds class.
Method signatures and docstrings:
- def get(self, request, id_parent): Возвращает формы для создания потомков :param id_parent: id родителя :type id_parent: int :return: возвращает формы для создания потомков е... | Implement the Python class `ViewChilds` described below.
Class description:
Implement the ViewChilds class.
Method signatures and docstrings:
- def get(self, request, id_parent): Возвращает формы для создания потомков :param id_parent: id родителя :type id_parent: int :return: возвращает формы для создания потомков е... | 5e24e4a677d34f5371ed47d05bbee6f7e24ded09 | <|skeleton|>
class ViewChilds:
def get(self, request, id_parent):
"""Возвращает формы для создания потомков :param id_parent: id родителя :type id_parent: int :return: возвращает формы для создания потомков если пользователь авторизован, иначе ошибка"""
<|body_0|>
def post(self, request, id_pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViewChilds:
def get(self, request, id_parent):
"""Возвращает формы для создания потомков :param id_parent: id родителя :type id_parent: int :return: возвращает формы для создания потомков если пользователь авторизован, иначе ошибка"""
if request.user.is_authenticated:
childs = Mess... | the_stack_v2_python_sparse | appadmin/views/childs_views.py | DanilMazurkin/FogstreamBot | train | 0 | |
7417c1104b717b1feaec7fd9f8949aa71eeda5de | [
"if data is None:\n if lambtha < 1:\n raise ValueError('lambtha must be a positive value')\n self.lambtha = float(lambtha)\nelse:\n if type(data) is not list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple values')\n se... | <|body_start_0|>
if data is None:
if lambtha < 1:
raise ValueError('lambtha must be a positive value')
self.lambtha = float(lambtha)
else:
if type(data) is not list:
raise TypeError('data must be a list')
if len(data) < 2:
... | Class representing a poisson distribution | Poisson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poisson:
"""Class representing a poisson distribution"""
def __init__(self, data=None, lambtha=1):
"""data is a list of the data used to estimate the distribution lambtha is the expected number of occurences in a given time frame"""
<|body_0|>
def pmf(self, k):
"... | stack_v2_sparse_classes_36k_train_013529 | 1,652 | no_license | [
{
"docstring": "data is a list of the data used to estimate the distribution lambtha is the expected number of occurences in a given time frame",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1)"
},
{
"docstring": "Calculates the value of the PMF for a given number of s... | 3 | null | Implement the Python class `Poisson` described below.
Class description:
Class representing a poisson distribution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1): data is a list of the data used to estimate the distribution lambtha is the expected number of occurences in a given time fra... | Implement the Python class `Poisson` described below.
Class description:
Class representing a poisson distribution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1): data is a list of the data used to estimate the distribution lambtha is the expected number of occurences in a given time fra... | 2757c8526290197d45a4de33cda71e686ddcbf1c | <|skeleton|>
class Poisson:
"""Class representing a poisson distribution"""
def __init__(self, data=None, lambtha=1):
"""data is a list of the data used to estimate the distribution lambtha is the expected number of occurences in a given time frame"""
<|body_0|>
def pmf(self, k):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Poisson:
"""Class representing a poisson distribution"""
def __init__(self, data=None, lambtha=1):
"""data is a list of the data used to estimate the distribution lambtha is the expected number of occurences in a given time frame"""
if data is None:
if lambtha < 1:
... | the_stack_v2_python_sparse | math/0x03-probability/poisson.py | 95ktsmith/holbertonschool-machine_learning | train | 0 |
b00baeeea21f8769456e03bacbb89fed027f136c | [
"threading.Thread.__init__(self, name='output')\nself.queues = queue\nself.date_time = date_time\nself.out_func = out_func\nself.out_frequency = out_frequency\nself.nx = nx\nself.ny = ny\nlname = '{}.{}'.format(__name__, 'output')\nself._logger = logging.getLogger(lname)\nself._logger.debug('Initialized output thre... | <|body_start_0|>
threading.Thread.__init__(self, name='output')
self.queues = queue
self.date_time = date_time
self.out_func = out_func
self.out_frequency = out_frequency
self.nx = nx
self.ny = ny
lname = '{}.{}'.format(__name__, 'output')
self._lo... | Takes values from the queue and outputs using 'out_func' | QueueOutput | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueueOutput:
"""Takes values from the queue and outputs using 'out_func'"""
def __init__(self, queue, date_time, out_func, out_frequency, nx, ny):
"""Args: date_time: array of date_time queue: dict of the queue"""
<|body_0|>
def run(self):
"""Output the desired v... | stack_v2_sparse_classes_36k_train_013530 | 9,600 | permissive | [
{
"docstring": "Args: date_time: array of date_time queue: dict of the queue",
"name": "__init__",
"signature": "def __init__(self, queue, date_time, out_func, out_frequency, nx, ny)"
},
{
"docstring": "Output the desired variables to a file. Go through the date times and look for when all the q... | 2 | stack_v2_sparse_classes_30k_train_013633 | Implement the Python class `QueueOutput` described below.
Class description:
Takes values from the queue and outputs using 'out_func'
Method signatures and docstrings:
- def __init__(self, queue, date_time, out_func, out_frequency, nx, ny): Args: date_time: array of date_time queue: dict of the queue
- def run(self):... | Implement the Python class `QueueOutput` described below.
Class description:
Takes values from the queue and outputs using 'out_func'
Method signatures and docstrings:
- def __init__(self, queue, date_time, out_func, out_frequency, nx, ny): Args: date_time: array of date_time queue: dict of the queue
- def run(self):... | 465d42cca85820e76a50bc311d101c7dc506df8c | <|skeleton|>
class QueueOutput:
"""Takes values from the queue and outputs using 'out_func'"""
def __init__(self, queue, date_time, out_func, out_frequency, nx, ny):
"""Args: date_time: array of date_time queue: dict of the queue"""
<|body_0|>
def run(self):
"""Output the desired v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QueueOutput:
"""Takes values from the queue and outputs using 'out_func'"""
def __init__(self, queue, date_time, out_func, out_frequency, nx, ny):
"""Args: date_time: array of date_time queue: dict of the queue"""
threading.Thread.__init__(self, name='output')
self.queues = queue
... | the_stack_v2_python_sparse | smrf/utils/queue.py | USDA-ARS-NWRC/smrf | train | 9 |
d7a48299debfed85d2acbb5960a27728862e8269 | [
"expected = self.forecast.copy()\nwith warnings.catch_warnings():\n warnings.simplefilter('error')\n self.plugin._ensure_monotonicity_across_thresholds(self.forecast)\nassert_array_equal(self.forecast.data, expected.data)",
"expected = self.forecast.copy()\nswitch_val = self.forecast.data[0, 1, 1]\nself.for... | <|body_start_0|>
expected = self.forecast.copy()
with warnings.catch_warnings():
warnings.simplefilter('error')
self.plugin._ensure_monotonicity_across_thresholds(self.forecast)
assert_array_equal(self.forecast.data, expected.data)
<|end_body_0|>
<|body_start_1|>
... | Test the _ensure_monotonicity_across_thresholds method. | Test__ensure_monotonicity_across_thresholds | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__ensure_monotonicity_across_thresholds:
"""Test the _ensure_monotonicity_across_thresholds method."""
def test_monotonic_case(self):
"""Test that a probability cube in which the data is already ordered monotonically is unchanged by this method. Additionally, no warnings or excep... | stack_v2_sparse_classes_36k_train_013531 | 24,150 | permissive | [
{
"docstring": "Test that a probability cube in which the data is already ordered monotonically is unchanged by this method. Additionally, no warnings or exceptions should be raised.",
"name": "test_monotonic_case",
"signature": "def test_monotonic_case(self)"
},
{
"docstring": "Test that if the... | 4 | null | Implement the Python class `Test__ensure_monotonicity_across_thresholds` described below.
Class description:
Test the _ensure_monotonicity_across_thresholds method.
Method signatures and docstrings:
- def test_monotonic_case(self): Test that a probability cube in which the data is already ordered monotonically is unc... | Implement the Python class `Test__ensure_monotonicity_across_thresholds` described below.
Class description:
Test the _ensure_monotonicity_across_thresholds method.
Method signatures and docstrings:
- def test_monotonic_case(self): Test that a probability cube in which the data is already ordered monotonically is unc... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__ensure_monotonicity_across_thresholds:
"""Test the _ensure_monotonicity_across_thresholds method."""
def test_monotonic_case(self):
"""Test that a probability cube in which the data is already ordered monotonically is unchanged by this method. Additionally, no warnings or excep... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__ensure_monotonicity_across_thresholds:
"""Test the _ensure_monotonicity_across_thresholds method."""
def test_monotonic_case(self):
"""Test that a probability cube in which the data is already ordered monotonically is unchanged by this method. Additionally, no warnings or exceptions should ... | the_stack_v2_python_sparse | improver_tests/calibration/reliability_calibration/test_ApplyReliabilityCalibration.py | metoppv/improver | train | 101 |
6f27ec6fdbccd19647f37a3ba4d9f1a36b25c8ac | [
"self.fuzzySetDisplay = fuzzySetDisplay\nself.new_fuzzy_set_root = Toplevel()\nself.new_fuzzy_set_root.title(\"Création d'un nouveau fait\")\nLabel(self.new_fuzzy_set_root, text='Name :').grid(row=0, pady=('0.5c', 0), padx=('0.5c', 0), sticky='E')\nself.name = Entry(self.new_fuzzy_set_root)\nself.name.grid(row=0, c... | <|body_start_0|>
self.fuzzySetDisplay = fuzzySetDisplay
self.new_fuzzy_set_root = Toplevel()
self.new_fuzzy_set_root.title("Création d'un nouveau fait")
Label(self.new_fuzzy_set_root, text='Name :').grid(row=0, pady=('0.5c', 0), padx=('0.5c', 0), sticky='E')
self.name = Entry(sel... | FuzzySetCreation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FuzzySetCreation:
def __init__(self, fuzzySetDisplay):
"""Allows the user to create a new fuzzy set in the knowledge base, giving it a name and a description"""
<|body_0|>
def validate(self):
"""This function is called when the button "creer" is pressed. It adds the ... | stack_v2_sparse_classes_36k_train_013532 | 10,561 | no_license | [
{
"docstring": "Allows the user to create a new fuzzy set in the knowledge base, giving it a name and a description",
"name": "__init__",
"signature": "def __init__(self, fuzzySetDisplay)"
},
{
"docstring": "This function is called when the button \"creer\" is pressed. It adds the new fuzzy set ... | 2 | stack_v2_sparse_classes_30k_train_006518 | Implement the Python class `FuzzySetCreation` described below.
Class description:
Implement the FuzzySetCreation class.
Method signatures and docstrings:
- def __init__(self, fuzzySetDisplay): Allows the user to create a new fuzzy set in the knowledge base, giving it a name and a description
- def validate(self): Thi... | Implement the Python class `FuzzySetCreation` described below.
Class description:
Implement the FuzzySetCreation class.
Method signatures and docstrings:
- def __init__(self, fuzzySetDisplay): Allows the user to create a new fuzzy set in the knowledge base, giving it a name and a description
- def validate(self): Thi... | 989f4050816d1241e41e36e4e6d95784ff4dff1c | <|skeleton|>
class FuzzySetCreation:
def __init__(self, fuzzySetDisplay):
"""Allows the user to create a new fuzzy set in the knowledge base, giving it a name and a description"""
<|body_0|>
def validate(self):
"""This function is called when the button "creer" is pressed. It adds the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FuzzySetCreation:
def __init__(self, fuzzySetDisplay):
"""Allows the user to create a new fuzzy set in the knowledge base, giving it a name and a description"""
self.fuzzySetDisplay = fuzzySetDisplay
self.new_fuzzy_set_root = Toplevel()
self.new_fuzzy_set_root.title("Création d... | the_stack_v2_python_sparse | User_interface/UI_Fuzzy_Sets.py | brieglhostis/ExpertSystems | train | 0 | |
29faa7462cfc0312b083ef67692dc3d721d93d96 | [
"theta, phi = param_util.cart2polar(x - ra_0, y - dec_0)\nf_ = 1.0 / 2 * kappa * theta ** 2\nreturn f_",
"x_ = x - ra_0\ny_ = y - dec_0\nf_x = kappa * x_\nf_y = kappa * y_\nreturn (f_x, f_y)",
"gamma1 = 0\ngamma2 = 0\nkappa = kappa\nf_xx = kappa + gamma1\nf_yy = kappa - gamma1\nf_xy = gamma2\nreturn (f_xx, f_xy... | <|body_start_0|>
theta, phi = param_util.cart2polar(x - ra_0, y - dec_0)
f_ = 1.0 / 2 * kappa * theta ** 2
return f_
<|end_body_0|>
<|body_start_1|>
x_ = x - ra_0
y_ = y - dec_0
f_x = kappa * x_
f_y = kappa * y_
return (f_x, f_y)
<|end_body_1|>
<|body_st... | a single mass sheet (external convergence) | Convergence | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Convergence:
"""a single mass sheet (external convergence)"""
def function(self, x, y, kappa, ra_0=0, dec_0=0):
"""lensing potential :param x: x-coordinate :param y: y-coordinate :param kappa: (external) convergence :return: lensing potential"""
<|body_0|>
def derivative... | stack_v2_sparse_classes_36k_train_013533 | 1,862 | permissive | [
{
"docstring": "lensing potential :param x: x-coordinate :param y: y-coordinate :param kappa: (external) convergence :return: lensing potential",
"name": "function",
"signature": "def function(self, x, y, kappa, ra_0=0, dec_0=0)"
},
{
"docstring": "deflection angle :param x: x-coordinate :param ... | 3 | null | Implement the Python class `Convergence` described below.
Class description:
a single mass sheet (external convergence)
Method signatures and docstrings:
- def function(self, x, y, kappa, ra_0=0, dec_0=0): lensing potential :param x: x-coordinate :param y: y-coordinate :param kappa: (external) convergence :return: le... | Implement the Python class `Convergence` described below.
Class description:
a single mass sheet (external convergence)
Method signatures and docstrings:
- def function(self, x, y, kappa, ra_0=0, dec_0=0): lensing potential :param x: x-coordinate :param y: y-coordinate :param kappa: (external) convergence :return: le... | 73c9645f26f6983fe7961104075ebe8bf7a4b54c | <|skeleton|>
class Convergence:
"""a single mass sheet (external convergence)"""
def function(self, x, y, kappa, ra_0=0, dec_0=0):
"""lensing potential :param x: x-coordinate :param y: y-coordinate :param kappa: (external) convergence :return: lensing potential"""
<|body_0|>
def derivative... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Convergence:
"""a single mass sheet (external convergence)"""
def function(self, x, y, kappa, ra_0=0, dec_0=0):
"""lensing potential :param x: x-coordinate :param y: y-coordinate :param kappa: (external) convergence :return: lensing potential"""
theta, phi = param_util.cart2polar(x - ra_0... | the_stack_v2_python_sparse | lenstronomy/LensModel/Profiles/convergence.py | lenstronomy/lenstronomy | train | 41 |
adfd234506b58be05a053865476d654fe3d3f82d | [
"conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='zhangroot', db='hlrfw_test', unix_socket='/var/run/mysqld/mysqld.sock', cursorclass=pymysql.cursors.DictCursor)\ncur = conn.cursor()\ntry:\n cur.execute(sql)\n conn.commit()\nexcept Exception as e:\n conn.rollback()\nfinally:\n co... | <|body_start_0|>
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='zhangroot', db='hlrfw_test', unix_socket='/var/run/mysqld/mysqld.sock', cursorclass=pymysql.cursors.DictCursor)
cur = conn.cursor()
try:
cur.execute(sql)
conn.commit()
except... | MyDatabase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyDatabase:
def modify_data(self, sql):
"""- 执行sql语句"""
<|body_0|>
def select_last_data(self, sql):
"""- 返回sql的最后一条数据"""
<|body_1|>
def select_all_data(slef, sql):
"""- 返回所有符合sql语句的数据"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_013534 | 2,241 | no_license | [
{
"docstring": "- 执行sql语句",
"name": "modify_data",
"signature": "def modify_data(self, sql)"
},
{
"docstring": "- 返回sql的最后一条数据",
"name": "select_last_data",
"signature": "def select_last_data(self, sql)"
},
{
"docstring": "- 返回所有符合sql语句的数据",
"name": "select_all_data",
"si... | 3 | stack_v2_sparse_classes_30k_train_016786 | Implement the Python class `MyDatabase` described below.
Class description:
Implement the MyDatabase class.
Method signatures and docstrings:
- def modify_data(self, sql): - 执行sql语句
- def select_last_data(self, sql): - 返回sql的最后一条数据
- def select_all_data(slef, sql): - 返回所有符合sql语句的数据 | Implement the Python class `MyDatabase` described below.
Class description:
Implement the MyDatabase class.
Method signatures and docstrings:
- def modify_data(self, sql): - 执行sql语句
- def select_last_data(self, sql): - 返回sql的最后一条数据
- def select_all_data(slef, sql): - 返回所有符合sql语句的数据
<|skeleton|>
class MyDatabase:
... | 61f81163583582c1f5816909f1e3829686c572d7 | <|skeleton|>
class MyDatabase:
def modify_data(self, sql):
"""- 执行sql语句"""
<|body_0|>
def select_last_data(self, sql):
"""- 返回sql的最后一条数据"""
<|body_1|>
def select_all_data(slef, sql):
"""- 返回所有符合sql语句的数据"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyDatabase:
def modify_data(self, sql):
"""- 执行sql语句"""
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='zhangroot', db='hlrfw_test', unix_socket='/var/run/mysqld/mysqld.sock', cursorclass=pymysql.cursors.DictCursor)
cur = conn.cursor()
try:
... | the_stack_v2_python_sparse | hlrfw/database/MyDatabase.py | 253765620/xuzhibo_work | train | 0 | |
5de1527ca426dcf624f23d6cc5abbc0b27f35a71 | [
"if not num:\n return '0'\nhard_code = 4294967295\nif num < 0:\n num = abs(num)\n num = hard_code ^ num\n num += 1\nres = ''\nwhile num:\n res = hex_map[num % 16] + res\n num = num / 16\nreturn res.lstrip('0')",
"flag = False\nif num < 0:\n flag = True\n num = -num\nh = ''\nwhile num:\n ... | <|body_start_0|>
if not num:
return '0'
hard_code = 4294967295
if num < 0:
num = abs(num)
num = hard_code ^ num
num += 1
res = ''
while num:
res = hex_map[num % 16] + res
num = num / 16
return res.lst... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def toHex(self, num):
""":type num: int :rtype: str"""
<|body_0|>
def _toHex(self, num):
""":type num: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not num:
return '0'
hard_code = 4294967295
... | stack_v2_sparse_classes_36k_train_013535 | 2,454 | permissive | [
{
"docstring": ":type num: int :rtype: str",
"name": "toHex",
"signature": "def toHex(self, num)"
},
{
"docstring": ":type num: int :rtype: str",
"name": "_toHex",
"signature": "def _toHex(self, num)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def toHex(self, num): :type num: int :rtype: str
- def _toHex(self, num): :type num: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def toHex(self, num): :type num: int :rtype: str
- def _toHex(self, num): :type num: int :rtype: str
<|skeleton|>
class Solution:
def toHex(self, num):
""":type num... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def toHex(self, num):
""":type num: int :rtype: str"""
<|body_0|>
def _toHex(self, num):
""":type num: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def toHex(self, num):
""":type num: int :rtype: str"""
if not num:
return '0'
hard_code = 4294967295
if num < 0:
num = abs(num)
num = hard_code ^ num
num += 1
res = ''
while num:
res = hex_map... | the_stack_v2_python_sparse | 405.convert-a-number-to-hexadecimal.py | windard/leeeeee | train | 0 | |
720d2a07ca675ad86e8903581955833b08d1330f | [
"edgeList.sort(key=lambda x: x[2])\nself.__uf = VersionedUnionFind(n)\nself.__weights = []\nfor index, (i, j, weight) in enumerate(edgeList):\n if not self.__uf.union_set(i, j):\n continue\n self.__uf.snap()\n self.__weights.append(weight)",
"snap_id = bisect.bisect_left(self.__weights, limit) - 1... | <|body_start_0|>
edgeList.sort(key=lambda x: x[2])
self.__uf = VersionedUnionFind(n)
self.__weights = []
for index, (i, j, weight) in enumerate(edgeList):
if not self.__uf.union_set(i, j):
continue
self.__uf.snap()
self.__weights.append... | DistanceLimitedPathsExist2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistanceLimitedPathsExist2:
def __init__(self, n, edgeList):
""":type n: int :type edgeList: List[List[int]]"""
<|body_0|>
def query(self, p, q, limit):
""":type p: int :type q: int :type limit: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_013536 | 7,205 | permissive | [
{
"docstring": ":type n: int :type edgeList: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, n, edgeList)"
},
{
"docstring": ":type p: int :type q: int :type limit: int :rtype: bool",
"name": "query",
"signature": "def query(self, p, q, limit)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007208 | Implement the Python class `DistanceLimitedPathsExist2` described below.
Class description:
Implement the DistanceLimitedPathsExist2 class.
Method signatures and docstrings:
- def __init__(self, n, edgeList): :type n: int :type edgeList: List[List[int]]
- def query(self, p, q, limit): :type p: int :type q: int :type ... | Implement the Python class `DistanceLimitedPathsExist2` described below.
Class description:
Implement the DistanceLimitedPathsExist2 class.
Method signatures and docstrings:
- def __init__(self, n, edgeList): :type n: int :type edgeList: List[List[int]]
- def query(self, p, q, limit): :type p: int :type q: int :type ... | 4dc4e6642dc92f1983c13564cc0fd99917cab358 | <|skeleton|>
class DistanceLimitedPathsExist2:
def __init__(self, n, edgeList):
""":type n: int :type edgeList: List[List[int]]"""
<|body_0|>
def query(self, p, q, limit):
""":type p: int :type q: int :type limit: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DistanceLimitedPathsExist2:
def __init__(self, n, edgeList):
""":type n: int :type edgeList: List[List[int]]"""
edgeList.sort(key=lambda x: x[2])
self.__uf = VersionedUnionFind(n)
self.__weights = []
for index, (i, j, weight) in enumerate(edgeList):
if not s... | the_stack_v2_python_sparse | Python/checking-existence-of-edge-length-limited-paths-ii.py | kamyu104/LeetCode-Solutions | train | 4,549 | |
d122eb838ece773bd890fd1dff4f1790d379db81 | [
"super().__init__(parent)\nself.printer = printer\nself.setPageList(pageList)",
"self.pageList = []\nfor n, page in enumerate(pageList, 1):\n if isinstance(page, tuple):\n pageNum, page = page\n else:\n pageNum = n\n page = page.copy()\n page.updateSize(page.dpi, page.dpi, 1.0)\n self... | <|body_start_0|>
super().__init__(parent)
self.printer = printer
self.setPageList(pageList)
<|end_body_0|>
<|body_start_1|>
self.pageList = []
for n, page in enumerate(pageList, 1):
if isinstance(page, tuple):
pageNum, page = page
else:
... | Performs a print job in the background. Emits the following signals: ``progress(pageNumber, num, total)`` before each Page ``finished()`` when done | PrintJob | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrintJob:
"""Performs a print job in the background. Emits the following signals: ``progress(pageNumber, num, total)`` before each Page ``finished()`` when done"""
def __init__(self, printer, pageList, parent=None):
"""Initialize with a QPrinter object and a list of pages. pageList m... | stack_v2_sparse_classes_36k_train_013537 | 4,778 | no_license | [
{
"docstring": "Initialize with a QPrinter object and a list of pages. pageList may be a list of two-tuples (num, page). Otherwise, the pages are numbered from 1 in the progress message. The pages are copied.",
"name": "__init__",
"signature": "def __init__(self, printer, pageList, parent=None)"
},
... | 3 | stack_v2_sparse_classes_30k_train_017498 | Implement the Python class `PrintJob` described below.
Class description:
Performs a print job in the background. Emits the following signals: ``progress(pageNumber, num, total)`` before each Page ``finished()`` when done
Method signatures and docstrings:
- def __init__(self, printer, pageList, parent=None): Initiali... | Implement the Python class `PrintJob` described below.
Class description:
Performs a print job in the background. Emits the following signals: ``progress(pageNumber, num, total)`` before each Page ``finished()`` when done
Method signatures and docstrings:
- def __init__(self, printer, pageList, parent=None): Initiali... | 2f870fa69495ffc22913550cbdf3e8c606d3d998 | <|skeleton|>
class PrintJob:
"""Performs a print job in the background. Emits the following signals: ``progress(pageNumber, num, total)`` before each Page ``finished()`` when done"""
def __init__(self, printer, pageList, parent=None):
"""Initialize with a QPrinter object and a list of pages. pageList m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrintJob:
"""Performs a print job in the background. Emits the following signals: ``progress(pageNumber, num, total)`` before each Page ``finished()`` when done"""
def __init__(self, printer, pageList, parent=None):
"""Initialize with a QPrinter object and a list of pages. pageList may be a list ... | the_stack_v2_python_sparse | VenvSocket/Lib/site-packages/qpageview/printing.py | crq-13/PintMegaPapel | train | 0 |
d46dbdc7817e80d9a01d72ded7b4fe60ec4d5ed9 | [
"global _REGISTRY\nregistry_entry = veredi.get().get(_REGISTRY, Null())\nsub_entry = registry_entry.get(key, Null())\nreturn sub_entry",
"context = klass._get(_REGISTRARS)\n_set(context, register, data, ownership)\nregistrees = klass._get(_REGISTREES)\nregistrees[register] = {}",
"all_registries = klass._get(_R... | <|body_start_0|>
global _REGISTRY
registry_entry = veredi.get().get(_REGISTRY, Null())
sub_entry = registry_entry.get(key, Null())
return sub_entry
<|end_body_0|>
<|body_start_1|>
context = klass._get(_REGISTRARS)
_set(context, register, data, ownership)
registre... | registry | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class registry:
def _get(klass: Type['registry'], key: str) -> Nullable[ContextMutableMap]:
"""Get registry's full sub-context from background context."""
<|body_0|>
def registrar(klass: Type['registry'], register: label.DotStr, data: ContextMap, ownership: Ownership) -> None:
... | stack_v2_sparse_classes_36k_train_013538 | 45,187 | no_license | [
{
"docstring": "Get registry's full sub-context from background context.",
"name": "_get",
"signature": "def _get(klass: Type['registry'], key: str) -> Nullable[ContextMutableMap]"
},
{
"docstring": "Adds `register`'s dotted label and background data to the background's registrars.",
"name":... | 3 | null | Implement the Python class `registry` described below.
Class description:
Implement the registry class.
Method signatures and docstrings:
- def _get(klass: Type['registry'], key: str) -> Nullable[ContextMutableMap]: Get registry's full sub-context from background context.
- def registrar(klass: Type['registry'], regi... | Implement the Python class `registry` described below.
Class description:
Implement the registry class.
Method signatures and docstrings:
- def _get(klass: Type['registry'], key: str) -> Nullable[ContextMutableMap]: Get registry's full sub-context from background context.
- def registrar(klass: Type['registry'], regi... | 8c9fc1170ceac335985686571568eebf08b0db7a | <|skeleton|>
class registry:
def _get(klass: Type['registry'], key: str) -> Nullable[ContextMutableMap]:
"""Get registry's full sub-context from background context."""
<|body_0|>
def registrar(klass: Type['registry'], register: label.DotStr, data: ContextMap, ownership: Ownership) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class registry:
def _get(klass: Type['registry'], key: str) -> Nullable[ContextMutableMap]:
"""Get registry's full sub-context from background context."""
global _REGISTRY
registry_entry = veredi.get().get(_REGISTRY, Null())
sub_entry = registry_entry.get(key, Null())
return ... | the_stack_v2_python_sparse | data/background.py | cole-brown/veredi-code | train | 1 | |
1b53647848a52e304893546a831103bd9c221d91 | [
"if LooseVersion(self.version) >= LooseVersion('4.0.1'):\n silent_cfg_names_map = {}\n if LooseVersion(self.version) < LooseVersion('4.1.1'):\n silent_cfg_names_map.update({'activation_name': ACTIVATION_NAME_2012, 'license_file_name': LICENSE_FILE_NAME_2012})\n if LooseVersion(self.version) == Loose... | <|body_start_0|>
if LooseVersion(self.version) >= LooseVersion('4.0.1'):
silent_cfg_names_map = {}
if LooseVersion(self.version) < LooseVersion('4.1.1'):
silent_cfg_names_map.update({'activation_name': ACTIVATION_NAME_2012, 'license_file_name': LICENSE_FILE_NAME_2012})
... | Support for installing Intel MPI library | EB_impi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EB_impi:
"""Support for installing Intel MPI library"""
def install_step(self):
"""Actual installation - create silent cfg file - execute command"""
<|body_0|>
def sanity_check_step(self):
"""Custom sanity check paths for IMPI."""
<|body_1|>
def make... | stack_v2_sparse_classes_36k_train_013539 | 5,780 | no_license | [
{
"docstring": "Actual installation - create silent cfg file - execute command",
"name": "install_step",
"signature": "def install_step(self)"
},
{
"docstring": "Custom sanity check paths for IMPI.",
"name": "sanity_check_step",
"signature": "def sanity_check_step(self)"
},
{
"do... | 4 | stack_v2_sparse_classes_30k_train_014189 | Implement the Python class `EB_impi` described below.
Class description:
Support for installing Intel MPI library
Method signatures and docstrings:
- def install_step(self): Actual installation - create silent cfg file - execute command
- def sanity_check_step(self): Custom sanity check paths for IMPI.
- def make_mod... | Implement the Python class `EB_impi` described below.
Class description:
Support for installing Intel MPI library
Method signatures and docstrings:
- def install_step(self): Actual installation - create silent cfg file - execute command
- def sanity_check_step(self): Custom sanity check paths for IMPI.
- def make_mod... | 3c5434f9a4193fbe4cf8107327faadda83d798ae | <|skeleton|>
class EB_impi:
"""Support for installing Intel MPI library"""
def install_step(self):
"""Actual installation - create silent cfg file - execute command"""
<|body_0|>
def sanity_check_step(self):
"""Custom sanity check paths for IMPI."""
<|body_1|>
def make... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EB_impi:
"""Support for installing Intel MPI library"""
def install_step(self):
"""Actual installation - create silent cfg file - execute command"""
if LooseVersion(self.version) >= LooseVersion('4.0.1'):
silent_cfg_names_map = {}
if LooseVersion(self.version) < Lo... | the_stack_v2_python_sparse | 1.11.1/easyblock/easyblocks/i/impi.py | lsuhpchelp/easybuild_smic | train | 0 |
8f4e820e2ef8e7ea9487dcfe55779e6de9fd418d | [
"testcase = TestCaseTable(**request.json)\ndb.session.add(testcase)\ndb.session.commit()\nreturn 'OK'\nabort(404)",
"if 'name' in request.json:\n testcase = TestCaseTable.query.filter_by(name=request.json.get('name')).first()\n testcase.content = request.json.get('content')\n testcase.description = reque... | <|body_start_0|>
testcase = TestCaseTable(**request.json)
db.session.add(testcase)
db.session.commit()
return 'OK'
abort(404)
<|end_body_0|>
<|body_start_1|>
if 'name' in request.json:
testcase = TestCaseTable.query.filter_by(name=request.json.get('name')).fi... | TestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCase:
def post(self):
"""存储用例 :return:"""
<|body_0|>
def put(self):
"""更新用例 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
testcase = TestCaseTable(**request.json)
db.session.add(testcase)
db.session.commit()
re... | stack_v2_sparse_classes_36k_train_013540 | 6,802 | no_license | [
{
"docstring": "存储用例 :return:",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "更新用例 :return:",
"name": "put",
"signature": "def put(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011718 | Implement the Python class `TestCase` described below.
Class description:
Implement the TestCase class.
Method signatures and docstrings:
- def post(self): 存储用例 :return:
- def put(self): 更新用例 :return: | Implement the Python class `TestCase` described below.
Class description:
Implement the TestCase class.
Method signatures and docstrings:
- def post(self): 存储用例 :return:
- def put(self): 更新用例 :return:
<|skeleton|>
class TestCase:
def post(self):
"""存储用例 :return:"""
<|body_0|>
def put(self):... | 5ff767243f7d7f698997633f39ecd4c4ebcc998a | <|skeleton|>
class TestCase:
def post(self):
"""存储用例 :return:"""
<|body_0|>
def put(self):
"""更新用例 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCase:
def post(self):
"""存储用例 :return:"""
testcase = TestCaseTable(**request.json)
db.session.add(testcase)
db.session.commit()
return 'OK'
abort(404)
def put(self):
"""更新用例 :return:"""
if 'name' in request.json:
testcase = T... | the_stack_v2_python_sparse | backend/server.py | ceshiren/HogwartsSDET16 | train | 16 | |
bf0fcf389638ae57744b106e826e41758ad0b8a9 | [
"argument = lab04.eratosthenes(1)\nexpected = []\nself.assertEqual(expected, argument, 'There are no prime numbers in the list.')",
"argument = lab04.eratosthenes(2)\nexpected = [2]\nself.assertEqual(expected, argument, 'The list contains one prime number.')",
"argument = lab04.eratosthenes(31)\nexpected = [2, ... | <|body_start_0|>
argument = lab04.eratosthenes(1)
expected = []
self.assertEqual(expected, argument, 'There are no prime numbers in the list.')
<|end_body_0|>
<|body_start_1|>
argument = lab04.eratosthenes(2)
expected = [2]
self.assertEqual(expected, argument, 'The list ... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def test_smallest_bound(self):
"""Test the upper bound of one."""
<|body_0|>
def test_list_of_one(self):
"""Test the upper bound of two."""
<|body_1|>
def test_list_of_several(self):
"""Test an upper bound that returns a list of many intege... | stack_v2_sparse_classes_36k_train_013541 | 1,187 | no_license | [
{
"docstring": "Test the upper bound of one.",
"name": "test_smallest_bound",
"signature": "def test_smallest_bound(self)"
},
{
"docstring": "Test the upper bound of two.",
"name": "test_list_of_one",
"signature": "def test_list_of_one(self)"
},
{
"docstring": "Test an upper boun... | 4 | stack_v2_sparse_classes_30k_train_005643 | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_smallest_bound(self): Test the upper bound of one.
- def test_list_of_one(self): Test the upper bound of two.
- def test_list_of_several(self): Test an upper bound that returns ... | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_smallest_bound(self): Test the upper bound of one.
- def test_list_of_one(self): Test the upper bound of two.
- def test_list_of_several(self): Test an upper bound that returns ... | a7014be9881ec4a2d0b332fef353a29f5dbb05de | <|skeleton|>
class Test:
def test_smallest_bound(self):
"""Test the upper bound of one."""
<|body_0|>
def test_list_of_one(self):
"""Test the upper bound of two."""
<|body_1|>
def test_list_of_several(self):
"""Test an upper bound that returns a list of many intege... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
def test_smallest_bound(self):
"""Test the upper bound of one."""
argument = lab04.eratosthenes(1)
expected = []
self.assertEqual(expected, argument, 'There are no prime numbers in the list.')
def test_list_of_one(self):
"""Test the upper bound of two."""
... | the_stack_v2_python_sparse | Lab04/test_eratosthenes.py | ronliang6/A01199458_1510 | train | 0 | |
ac1be2eddb18cbce153bd281adacf490aecebe30 | [
"apps = ('helpers.files', 'helpers.files.settings', 'helpers.files.storage', 'helpers.files.utils')\nfor a in apps:\n self.assertTrue(module_exists(a))",
"from helpers.media.utils import get_test_upload_dir\nself._msg('test', 'test_create_dir', first=True)\npath = os.path.join(get_test_upload_dir(), 'test-dire... | <|body_start_0|>
apps = ('helpers.files', 'helpers.files.settings', 'helpers.files.storage', 'helpers.files.utils')
for a in apps:
self.assertTrue(module_exists(a))
<|end_body_0|>
<|body_start_1|>
from helpers.media.utils import get_test_upload_dir
self._msg('test', 'test_cr... | FilesTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilesTests:
def test_module_imports(self):
"""Ensure modules are importable."""
<|body_0|>
def test_create_dir(self):
"""Ensure create_dir function is working correctly."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
apps = ('helpers.files', 'helpe... | stack_v2_sparse_classes_36k_train_013542 | 1,152 | no_license | [
{
"docstring": "Ensure modules are importable.",
"name": "test_module_imports",
"signature": "def test_module_imports(self)"
},
{
"docstring": "Ensure create_dir function is working correctly.",
"name": "test_create_dir",
"signature": "def test_create_dir(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000941 | Implement the Python class `FilesTests` described below.
Class description:
Implement the FilesTests class.
Method signatures and docstrings:
- def test_module_imports(self): Ensure modules are importable.
- def test_create_dir(self): Ensure create_dir function is working correctly. | Implement the Python class `FilesTests` described below.
Class description:
Implement the FilesTests class.
Method signatures and docstrings:
- def test_module_imports(self): Ensure modules are importable.
- def test_create_dir(self): Ensure create_dir function is working correctly.
<|skeleton|>
class FilesTests:
... | 133d6026f99820d0702f0578b8a3b4574671f888 | <|skeleton|>
class FilesTests:
def test_module_imports(self):
"""Ensure modules are importable."""
<|body_0|>
def test_create_dir(self):
"""Ensure create_dir function is working correctly."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilesTests:
def test_module_imports(self):
"""Ensure modules are importable."""
apps = ('helpers.files', 'helpers.files.settings', 'helpers.files.storage', 'helpers.files.utils')
for a in apps:
self.assertTrue(module_exists(a))
def test_create_dir(self):
"""Ens... | the_stack_v2_python_sparse | helpers/files/tests.py | fogcitymarathoner/rma | train | 0 | |
eebdc26acca3c256d2e89eda60bb90bbf6538125 | [
"super(SimplerAllImageLSTM, self).__init__()\nargs.wrap_model = False\nself.args = args\nself.lstm = nn.LSTM(input_size=args.hidden_dim * 4, hidden_size=args.hidden_dim // 2, num_layers=1, bias=True, batch_first=True, dropout=args.dropout, bidirectional=True)\nself.dropout = nn.Dropout(p=args.dropout)\nself.r_y_fc ... | <|body_start_0|>
super(SimplerAllImageLSTM, self).__init__()
args.wrap_model = False
self.args = args
self.lstm = nn.LSTM(input_size=args.hidden_dim * 4, hidden_size=args.hidden_dim // 2, num_layers=1, bias=True, batch_first=True, dropout=args.dropout, bidirectional=True)
self.dr... | SimplerAllImageLSTM | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimplerAllImageLSTM:
def __init__(self, args):
"""Given some a patch model, add add some FC layers and a shortcut to make whole image prediction"""
<|body_0|>
def forward(self, x):
"""param x: a batch of image tensors, in the order of: [Cu L CC, Cu L MLO, Cu R CC, Cu... | stack_v2_sparse_classes_36k_train_013543 | 5,214 | permissive | [
{
"docstring": "Given some a patch model, add add some FC layers and a shortcut to make whole image prediction",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "param x: a batch of image tensors, in the order of: [Cu L CC, Cu L MLO, Cu R CC, Cu R MLO Pr L CC, Pr L ... | 2 | stack_v2_sparse_classes_30k_train_019149 | Implement the Python class `SimplerAllImageLSTM` described below.
Class description:
Implement the SimplerAllImageLSTM class.
Method signatures and docstrings:
- def __init__(self, args): Given some a patch model, add add some FC layers and a shortcut to make whole image prediction
- def forward(self, x): param x: a ... | Implement the Python class `SimplerAllImageLSTM` described below.
Class description:
Implement the SimplerAllImageLSTM class.
Method signatures and docstrings:
- def __init__(self, args): Given some a patch model, add add some FC layers and a shortcut to make whole image prediction
- def forward(self, x): param x: a ... | 12bace8fd6ce9c5bb129fd0d30a46a00a2f7b054 | <|skeleton|>
class SimplerAllImageLSTM:
def __init__(self, args):
"""Given some a patch model, add add some FC layers and a shortcut to make whole image prediction"""
<|body_0|>
def forward(self, x):
"""param x: a batch of image tensors, in the order of: [Cu L CC, Cu L MLO, Cu R CC, Cu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimplerAllImageLSTM:
def __init__(self, args):
"""Given some a patch model, add add some FC layers and a shortcut to make whole image prediction"""
super(SimplerAllImageLSTM, self).__init__()
args.wrap_model = False
self.args = args
self.lstm = nn.LSTM(input_size=args.h... | the_stack_v2_python_sparse | onconet/models/aggregate_hiddens.py | yala/Mirai | train | 66 | |
78b85435e52e526b872f7558d1de01b7367d8acc | [
"self.project_id = project_id\nself.region = region\nself.subnet = subnet\nself.vpc = vpc",
"if dictionary is None:\n return None\nproject_id = dictionary.get('projectId')\nregion = dictionary.get('region')\nsubnet = dictionary.get('subnet')\nvpc = dictionary.get('vpc')\nreturn cls(project_id, region, subnet, ... | <|body_start_0|>
self.project_id = project_id
self.region = region
self.subnet = subnet
self.vpc = vpc
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
project_id = dictionary.get('projectId')
region = dictionary.get('region')
... | Implementation of the 'FleetNetworkParams' model. Specifies the various network params for the fleet. Attributes: project_id (string): Specifies the project id for the fleet in case of GCP Source. region (string): Specifies the region for the fleet. subnet (string): Specifies the subnet for the fleet. vpc (string): Spe... | FleetNetworkParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FleetNetworkParams:
"""Implementation of the 'FleetNetworkParams' model. Specifies the various network params for the fleet. Attributes: project_id (string): Specifies the project id for the fleet in case of GCP Source. region (string): Specifies the region for the fleet. subnet (string): Specifi... | stack_v2_sparse_classes_36k_train_013544 | 1,986 | permissive | [
{
"docstring": "Constructor for the FleetNetworkParams class",
"name": "__init__",
"signature": "def __init__(self, project_id=None, region=None, subnet=None, vpc=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representat... | 2 | null | Implement the Python class `FleetNetworkParams` described below.
Class description:
Implementation of the 'FleetNetworkParams' model. Specifies the various network params for the fleet. Attributes: project_id (string): Specifies the project id for the fleet in case of GCP Source. region (string): Specifies the region ... | Implement the Python class `FleetNetworkParams` described below.
Class description:
Implementation of the 'FleetNetworkParams' model. Specifies the various network params for the fleet. Attributes: project_id (string): Specifies the project id for the fleet in case of GCP Source. region (string): Specifies the region ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class FleetNetworkParams:
"""Implementation of the 'FleetNetworkParams' model. Specifies the various network params for the fleet. Attributes: project_id (string): Specifies the project id for the fleet in case of GCP Source. region (string): Specifies the region for the fleet. subnet (string): Specifi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FleetNetworkParams:
"""Implementation of the 'FleetNetworkParams' model. Specifies the various network params for the fleet. Attributes: project_id (string): Specifies the project id for the fleet in case of GCP Source. region (string): Specifies the region for the fleet. subnet (string): Specifies the subnet... | the_stack_v2_python_sparse | cohesity_management_sdk/models/fleet_network_params.py | cohesity/management-sdk-python | train | 24 |
a832f33ee1fb45c8a3611846d4e60b8415854120 | [
"if not s:\n return\nc = s.pop()\nself.reverseStringList(s)\ns.insert(0, c)",
"l = 0\nr = len(s) - 1\nss = list(s)\nwhile l <= r:\n if s[l] in string.ascii_letters and s[r] in string.ascii_letters:\n t = ss[l]\n ss[l] = ss[r]\n ss[r] = t\n l += 1\n r -= 1\n elif s[l] in... | <|body_start_0|>
if not s:
return
c = s.pop()
self.reverseStringList(s)
s.insert(0, c)
<|end_body_0|>
<|body_start_1|>
l = 0
r = len(s) - 1
ss = list(s)
while l <= r:
if s[l] in string.ascii_letters and s[r] in string.ascii_letters... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseStringList(self, s):
""":type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""
<|body_0|>
def reverseString(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if ... | stack_v2_sparse_classes_36k_train_013545 | 1,189 | no_license | [
{
"docstring": ":type s: List[str] :rtype: None Do not return anything, modify s in-place instead.",
"name": "reverseStringList",
"signature": "def reverseStringList(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseString",
"signature": "def reverseString(self, s)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseStringList(self, s): :type s: List[str] :rtype: None Do not return anything, modify s in-place instead.
- def reverseString(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseStringList(self, s): :type s: List[str] :rtype: None Do not return anything, modify s in-place instead.
- def reverseString(self, s): :type s: str :rtype: str
<|skele... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def reverseStringList(self, s):
""":type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""
<|body_0|>
def reverseString(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseStringList(self, s):
""":type s: List[str] :rtype: None Do not return anything, modify s in-place instead."""
if not s:
return
c = s.pop()
self.reverseStringList(s)
s.insert(0, c)
def reverseString(self, s):
""":type s: str ... | the_stack_v2_python_sparse | R/ReverseString.py | bssrdf/pyleet | train | 2 | |
2bc327d29910be6f3817dd6587b5d93ebbf9e71c | [
"self.room_size_cap = room_size_cap\nself.z_pad = z_pad\nself.img_size = img_size\nself.x_scale = self.img_size / self.room_size_cap[0]\nself.y_scale = self.img_size / self.room_size_cap[2]\nself.z_scale = 1.0 / (self.room_size_cap[1] + self.z_pad)",
"x_scale, y_scale, z_scale = (self.x_scale, self.y_scale, self.... | <|body_start_0|>
self.room_size_cap = room_size_cap
self.z_pad = z_pad
self.img_size = img_size
self.x_scale = self.img_size / self.room_size_cap[0]
self.y_scale = self.img_size / self.room_size_cap[2]
self.z_scale = 1.0 / (self.room_size_cap[1] + self.z_pad)
<|end_body_0... | ProjectionGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectionGenerator:
def __init__(self, room_size_cap=(6.05, 4.05, 6.05), z_pad=0.5, img_size=512):
""":param room_size_cap: :param z_pad: :param img_size:"""
<|body_0|>
def get_projection(self, room):
"""Generates projection matrices specific to a room, need to be r... | stack_v2_sparse_classes_36k_train_013546 | 17,039 | permissive | [
{
"docstring": ":param room_size_cap: :param z_pad: :param img_size:",
"name": "__init__",
"signature": "def __init__(self, room_size_cap=(6.05, 4.05, 6.05), z_pad=0.5, img_size=512)"
},
{
"docstring": "Generates projection matrices specific to a room, need to be room-specific since every room i... | 2 | stack_v2_sparse_classes_30k_train_003228 | Implement the Python class `ProjectionGenerator` described below.
Class description:
Implement the ProjectionGenerator class.
Method signatures and docstrings:
- def __init__(self, room_size_cap=(6.05, 4.05, 6.05), z_pad=0.5, img_size=512): :param room_size_cap: :param z_pad: :param img_size:
- def get_projection(sel... | Implement the Python class `ProjectionGenerator` described below.
Class description:
Implement the ProjectionGenerator class.
Method signatures and docstrings:
- def __init__(self, room_size_cap=(6.05, 4.05, 6.05), z_pad=0.5, img_size=512): :param room_size_cap: :param z_pad: :param img_size:
- def get_projection(sel... | 8cdf1cc7d30e9425350548cef364fa25a8be19cf | <|skeleton|>
class ProjectionGenerator:
def __init__(self, room_size_cap=(6.05, 4.05, 6.05), z_pad=0.5, img_size=512):
""":param room_size_cap: :param z_pad: :param img_size:"""
<|body_0|>
def get_projection(self, room):
"""Generates projection matrices specific to a room, need to be r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectionGenerator:
def __init__(self, room_size_cap=(6.05, 4.05, 6.05), z_pad=0.5, img_size=512):
""":param room_size_cap: :param z_pad: :param img_size:"""
self.room_size_cap = room_size_cap
self.z_pad = z_pad
self.img_size = img_size
self.x_scale = self.img_size / s... | the_stack_v2_python_sparse | dataset/preprocess/View.py | WillisWong/Deep-sync-front | train | 0 | |
70e66e00d31e3ccba34223d9ffc9c01361c00629 | [
"self._port_range = port_range\nself._expiry_time_secs = expiry_time_secs\nself._ports = {}\nself._port_lock = threading.RLock()",
"with self._port_lock:\n full_key = (key,) + tuple(kwargs.values())\n if not new_port:\n for port, status in self._ports.iteritems():\n if full_key == status['... | <|body_start_0|>
self._port_range = port_range
self._expiry_time_secs = expiry_time_secs
self._ports = {}
self._port_lock = threading.RLock()
<|end_body_0|>
<|body_start_1|>
with self._port_lock:
full_key = (key,) + tuple(kwargs.values())
if not new_port:... | Dynamically allocates/deallocates ports with a given set of constraints. | PortAllocator | [
"BSD-3-Clause",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PortAllocator:
"""Dynamically allocates/deallocates ports with a given set of constraints."""
def __init__(self, port_range, expiry_time_secs=5 * 60):
"""Sets up initial state for the Port Allocator. Args: port_range: Range of ports available for allocation. expiry_time_secs: Amount ... | stack_v2_sparse_classes_36k_train_013547 | 18,107 | permissive | [
{
"docstring": "Sets up initial state for the Port Allocator. Args: port_range: Range of ports available for allocation. expiry_time_secs: Amount of time in seconds before constrained ports are cleaned up.",
"name": "__init__",
"signature": "def __init__(self, port_range, expiry_time_secs=5 * 60)"
},
... | 5 | null | Implement the Python class `PortAllocator` described below.
Class description:
Dynamically allocates/deallocates ports with a given set of constraints.
Method signatures and docstrings:
- def __init__(self, port_range, expiry_time_secs=5 * 60): Sets up initial state for the Port Allocator. Args: port_range: Range of ... | Implement the Python class `PortAllocator` described below.
Class description:
Dynamically allocates/deallocates ports with a given set of constraints.
Method signatures and docstrings:
- def __init__(self, port_range, expiry_time_secs=5 * 60): Sets up initial state for the Port Allocator. Args: port_range: Range of ... | acefdaaadd3ef46f10f63d1acae2259e4024d383 | <|skeleton|>
class PortAllocator:
"""Dynamically allocates/deallocates ports with a given set of constraints."""
def __init__(self, port_range, expiry_time_secs=5 * 60):
"""Sets up initial state for the Port Allocator. Args: port_range: Range of ports available for allocation. expiry_time_secs: Amount ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PortAllocator:
"""Dynamically allocates/deallocates ports with a given set of constraints."""
def __init__(self, port_range, expiry_time_secs=5 * 60):
"""Sets up initial state for the Port Allocator. Args: port_range: Range of ports available for allocation. expiry_time_secs: Amount of time in se... | the_stack_v2_python_sparse | third_party/chromium/media/tools/constrained_network_server/cns.py | youtube/cobalt | train | 169 |
14575d89d064822bbbfca822624e26101a8435a6 | [
"if operations not in ['f', 'b', 'fb', 'bf']:\n raise ValueError(\"'operations' parameter should be one of the following options: f, b, fb, bf.\")\nself.feature = self.parse_feature(feature)\nself.operations = operations\nself.value = value\nself.axis = axis",
"if not isinstance(data, np.ndarray) or data.ndim ... | <|body_start_0|>
if operations not in ['f', 'b', 'fb', 'bf']:
raise ValueError("'operations' parameter should be one of the following options: f, b, fb, bf.")
self.feature = self.parse_feature(feature)
self.operations = operations
self.value = value
self.axis = axis
<... | Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, nan, 8, 5, 5, 1, 0, 0, 0 'b': nan, nan, nan, ... | ValueFilloutTask | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueFilloutTask:
"""Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, n... | stack_v2_sparse_classes_36k_train_013548 | 12,661 | permissive | [
{
"docstring": ":param feature: A feature that must be value-filled. :param operations: Fill directions, which should be one of ['f', 'b', 'fb', 'bf']. :param value: Which value to fill by its neighbors. :param axis: An axis along which to fill values.",
"name": "__init__",
"signature": "def __init__(se... | 3 | null | Implement the Python class `ValueFilloutTask` described below.
Class description:
Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8... | Implement the Python class `ValueFilloutTask` described below.
Class description:
Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8... | a65899e4632b50c9c41a67e1f7698c09b929d840 | <|skeleton|>
class ValueFilloutTask:
"""Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValueFilloutTask:
"""Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, nan, 8, 5, 5, ... | the_stack_v2_python_sparse | features/eolearn/features/feature_manipulation.py | sentinel-hub/eo-learn | train | 1,072 |
0de487015e419e1eae5c0f4aba925b44bcf5b009 | [
"assert len(character) == 1\nself.character = character\nself.bold = bold\nself.italic = italic\nself.underline = underline",
"bold = '*' if self.bold else ''\nitalic = '/' if self.italic else ''\nunderline = '_' if self.underline else ''\nreturn bold + italic + underline + self.character"
] | <|body_start_0|>
assert len(character) == 1
self.character = character
self.bold = bold
self.italic = italic
self.underline = underline
<|end_body_0|>
<|body_start_1|>
bold = '*' if self.bold else ''
italic = '/' if self.italic else ''
underline = '_' if ... | Represents a character with formatting information. | Character | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Character:
"""Represents a character with formatting information."""
def __init__(self, character, bold=False, italic=False, underline=False):
"""Initialise a character with formatting. :param character: The character this class represents. :param bold: True for bold character. :para... | stack_v2_sparse_classes_36k_train_013549 | 4,762 | no_license | [
{
"docstring": "Initialise a character with formatting. :param character: The character this class represents. :param bold: True for bold character. :param italic: True for italic character. :param underline: True for underline character.",
"name": "__init__",
"signature": "def __init__(self, character,... | 2 | stack_v2_sparse_classes_30k_test_000123 | Implement the Python class `Character` described below.
Class description:
Represents a character with formatting information.
Method signatures and docstrings:
- def __init__(self, character, bold=False, italic=False, underline=False): Initialise a character with formatting. :param character: The character this clas... | Implement the Python class `Character` described below.
Class description:
Represents a character with formatting information.
Method signatures and docstrings:
- def __init__(self, character, bold=False, italic=False, underline=False): Initialise a character with formatting. :param character: The character this clas... | de836492ae951ae3d82a55affc824dc2e6ac6b99 | <|skeleton|>
class Character:
"""Represents a character with formatting information."""
def __init__(self, character, bold=False, italic=False, underline=False):
"""Initialise a character with formatting. :param character: The character this class represents. :param bold: True for bold character. :para... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Character:
"""Represents a character with formatting information."""
def __init__(self, character, bold=False, italic=False, underline=False):
"""Initialise a character with formatting. :param character: The character this class represents. :param bold: True for bold character. :param italic: Tru... | the_stack_v2_python_sparse | ch05/document/document.py | DreEleventh/python-3-object-oriented-programming | train | 0 |
ba461497b8e869ea6506b754ac0c7d164d506950 | [
"super().__init__()\nself._units = units\nself._activation = parse_activation(activation)\nself._recurrent_activation = parse_activation(recurrent_activation)\nself._direction = direction\nself._channels = channels\nif self._direction not in ('lt', 'rb'):\n raise ValueError(f'Invalid direction. `{self._direction... | <|body_start_0|>
super().__init__()
self._units = units
self._activation = parse_activation(activation)
self._recurrent_activation = parse_activation(recurrent_activation)
self._direction = direction
self._channels = channels
if self._direction not in ('lt', 'rb')... | Spatial GRU Module. :param channels: Number of word interaction tensor channels. :param units: Number of SpatialGRU units. :param activation: Activation function to use, one of: - String: name of an activation - Torch Modele subclass - Torch Module instance Default: hyperbolic tangent (`tanh`). :param recurrent_activat... | SpatialGRU | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialGRU:
"""Spatial GRU Module. :param channels: Number of word interaction tensor channels. :param units: Number of SpatialGRU units. :param activation: Activation function to use, one of: - String: name of an activation - Torch Modele subclass - Torch Module instance Default: hyperbolic tang... | stack_v2_sparse_classes_36k_train_013550 | 5,452 | permissive | [
{
"docstring": ":class:`SpatialGRU` constructor.",
"name": "__init__",
"signature": "def __init__(self, channels: int=4, units: int=10, activation: typing.Union[str, typing.Type[nn.Module], nn.Module]='tanh', recurrent_activation: typing.Union[str, typing.Type[nn.Module], nn.Module]='sigmoid', direction... | 5 | null | Implement the Python class `SpatialGRU` described below.
Class description:
Spatial GRU Module. :param channels: Number of word interaction tensor channels. :param units: Number of SpatialGRU units. :param activation: Activation function to use, one of: - String: name of an activation - Torch Modele subclass - Torch M... | Implement the Python class `SpatialGRU` described below.
Class description:
Spatial GRU Module. :param channels: Number of word interaction tensor channels. :param units: Number of SpatialGRU units. :param activation: Activation function to use, one of: - String: name of an activation - Torch Modele subclass - Torch M... | 4198ebce942f4afe7ddca6a96ab6f4464ade4518 | <|skeleton|>
class SpatialGRU:
"""Spatial GRU Module. :param channels: Number of word interaction tensor channels. :param units: Number of SpatialGRU units. :param activation: Activation function to use, one of: - String: name of an activation - Torch Modele subclass - Torch Module instance Default: hyperbolic tang... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpatialGRU:
"""Spatial GRU Module. :param channels: Number of word interaction tensor channels. :param units: Number of SpatialGRU units. :param activation: Activation function to use, one of: - String: name of an activation - Torch Modele subclass - Torch Module instance Default: hyperbolic tangent (`tanh`).... | the_stack_v2_python_sparse | poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/modules/spatial_gru.py | microsoft/ContextualSP | train | 332 |
0ec87f2e7cf45cbb4f467d9c7f542a9cb876a11d | [
"vm = Operation.GetVm(host, vm)\nstatus = vm.GetGuestHeartbeatStatus()\nreturn self.FakeHeartbeatTimeFromStatus(vm, status)",
"HEARTBEAT_START = 10\nnow = int(time.time() * 1000000)\nif not hasattr(vm, 'lastGuestStatusChecked') or not vm.lastGuestStatusChecked:\n vm.heartbeat = HEARTBEAT_START + now / 1000000 ... | <|body_start_0|>
vm = Operation.GetVm(host, vm)
status = vm.GetGuestHeartbeatStatus()
return self.FakeHeartbeatTimeFromStatus(vm, status)
<|end_body_0|>
<|body_start_1|>
HEARTBEAT_START = 10
now = int(time.time() * 1000000)
if not hasattr(vm, 'lastGuestStatusChecked') or... | GetHeartbeat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetHeartbeat:
def DoIt(self, host, vm):
"""Example: $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getheartbeat 332"""
<|body_0|>
def FakeHeartbeatTimeFromStatus(self, vm, status):
"""This mapping came from the VMControlSoapVMUpdateHealth function in bora/lib/... | stack_v2_sparse_classes_36k_train_013551 | 1,768 | no_license | [
{
"docstring": "Example: $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getheartbeat 332",
"name": "DoIt",
"signature": "def DoIt(self, host, vm)"
},
{
"docstring": "This mapping came from the VMControlSoapVMUpdateHealth function in bora/lib/vmcontrol/vmcontrolSoapUtil.c: if (vm->lastGues... | 2 | null | Implement the Python class `GetHeartbeat` described below.
Class description:
Implement the GetHeartbeat class.
Method signatures and docstrings:
- def DoIt(self, host, vm): Example: $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getheartbeat 332
- def FakeHeartbeatTimeFromStatus(self, vm, status): This mappin... | Implement the Python class `GetHeartbeat` described below.
Class description:
Implement the GetHeartbeat class.
Method signatures and docstrings:
- def DoIt(self, host, vm): Example: $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getheartbeat 332
- def FakeHeartbeatTimeFromStatus(self, vm, status): This mappin... | 8428a84481be319ae739dfbb87715f31810138d9 | <|skeleton|>
class GetHeartbeat:
def DoIt(self, host, vm):
"""Example: $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getheartbeat 332"""
<|body_0|>
def FakeHeartbeatTimeFromStatus(self, vm, status):
"""This mapping came from the VMControlSoapVMUpdateHealth function in bora/lib/... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetHeartbeat:
def DoIt(self, host, vm):
"""Example: $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getheartbeat 332"""
vm = Operation.GetVm(host, vm)
status = vm.GetGuestHeartbeatStatus()
return self.FakeHeartbeatTimeFromStatus(vm, status)
def FakeHeartbeatTimeFromS... | the_stack_v2_python_sparse | pyVpx/vmware-cmd/operations/GetHeartbeat.py | free-Zen/pvc | train | 0 | |
dd340b5d993d6db71c3367fb32ecc19a7ed223aa | [
"widgets = []\ntextEdit = QLineEdit()\ntextEdit.setText(std_prm['name'])\nwidgets.append(textEdit)\ninputWidget = std_prm['build method'](std_prm['build method prms'], std_prm['slot'])\nwidgets.append(inputWidget)\nstd_prm['name widget'] = textEdit\nstd_prm['widget'] = inputWidget\nreturn widgets",
"if isinstance... | <|body_start_0|>
widgets = []
textEdit = QLineEdit()
textEdit.setText(std_prm['name'])
widgets.append(textEdit)
inputWidget = std_prm['build method'](std_prm['build method prms'], std_prm['slot'])
widgets.append(inputWidget)
std_prm['name widget'] = textEdit
... | This class is used for the methods needed for presenting the StdPrm | StdPrmInput | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StdPrmInput:
"""This class is used for the methods needed for presenting the StdPrm"""
def widgets(std_prm: Parameter) -> List[QWidget]:
"""- This method generates all needed for input to the std_prm - A QLineEdit for the std_prm name - An input widget for the std_prm (by activating ... | stack_v2_sparse_classes_36k_train_013552 | 13,518 | no_license | [
{
"docstring": "- This method generates all needed for input to the std_prm - A QLineEdit for the std_prm name - An input widget for the std_prm (by activating the \"build_method\" attribute of the parameters) Args: std_prm : (Parameter) - The parameter to be presented",
"name": "widgets",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_006847 | Implement the Python class `StdPrmInput` described below.
Class description:
This class is used for the methods needed for presenting the StdPrm
Method signatures and docstrings:
- def widgets(std_prm: Parameter) -> List[QWidget]: - This method generates all needed for input to the std_prm - A QLineEdit for the std_p... | Implement the Python class `StdPrmInput` described below.
Class description:
This class is used for the methods needed for presenting the StdPrm
Method signatures and docstrings:
- def widgets(std_prm: Parameter) -> List[QWidget]: - This method generates all needed for input to the std_prm - A QLineEdit for the std_p... | dfc30621bf330c300bca75103e7f8bca8b7a8d58 | <|skeleton|>
class StdPrmInput:
"""This class is used for the methods needed for presenting the StdPrm"""
def widgets(std_prm: Parameter) -> List[QWidget]:
"""- This method generates all needed for input to the std_prm - A QLineEdit for the std_prm name - An input widget for the std_prm (by activating ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StdPrmInput:
"""This class is used for the methods needed for presenting the StdPrm"""
def widgets(std_prm: Parameter) -> List[QWidget]:
"""- This method generates all needed for input to the std_prm - A QLineEdit for the std_prm name - An input widget for the std_prm (by activating the "build_me... | the_stack_v2_python_sparse | AI Project/Project/UserInterface/Parameter.py | IlanHindy/AI-Learn | train | 0 |
a7b124276b1dc7c6ca5f4e3e3290831a0c33f2bb | [
"self.AddSubDialog(GADGET_ID_SUBDIALOG, c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT, 100, 100)\nself.AttachSubDialog(self.subDialog, GADGET_ID_SUBDIALOG)\nself.AddButton(GADGET_ID_BUTTON_SWITCH_SUBDIALOG, c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT, name='Switch SubDialog')\nreturn True",
"if messageId == GADGET_ID_BUTTON_SWITCH... | <|body_start_0|>
self.AddSubDialog(GADGET_ID_SUBDIALOG, c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT, 100, 100)
self.AttachSubDialog(self.subDialog, GADGET_ID_SUBDIALOG)
self.AddButton(GADGET_ID_BUTTON_SWITCH_SUBDIALOG, c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT, name='Switch SubDialog')
return True
<|e... | ExampleDialog | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog."""
<|body_0|>
def Command(self, messageId, bc):
"""This Method is called automatically when the user clicks on a gadget and/or chan... | stack_v2_sparse_classes_36k_train_013553 | 3,182 | permissive | [
{
"docstring": "This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.",
"name": "CreateLayout",
"signature": "def CreateLayout(self)"
},
{
"docstring": "This Method is called automatically when the user clicks on a gadget and/or changes its value this func... | 2 | stack_v2_sparse_classes_30k_train_001532 | Implement the Python class `ExampleDialog` described below.
Class description:
Implement the ExampleDialog class.
Method signatures and docstrings:
- def CreateLayout(self): This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.
- def Command(self, messageId, bc): This Method is... | Implement the Python class `ExampleDialog` described below.
Class description:
Implement the ExampleDialog class.
Method signatures and docstrings:
- def CreateLayout(self): This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.
- def Command(self, messageId, bc): This Method is... | b1ea3fce533df34094bc3d0bd6460dfb84306e53 | <|skeleton|>
class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog."""
<|body_0|>
def Command(self, messageId, bc):
"""This Method is called automatically when the user clicks on a gadget and/or chan... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog."""
self.AddSubDialog(GADGET_ID_SUBDIALOG, c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT, 100, 100)
self.AttachSubDialog(self.subDialog, GADGET_ID_SUBDIALOG)
... | the_stack_v2_python_sparse | scripts/03_application_development/gui/dialog/gedialog_subdialog_r19.py | PluginCafe/cinema4d_py_sdk_extended | train | 112 | |
a8fa05168a2dd9a4bf20474776096738b0478a97 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('janellc_rstiffel', 'janellc_rstiffel')\nurl = 'http://datamechanics.io/data/DBABoston.csv'\nvalues = csv_to_json(url)\nrepo.dropCollection('fitBusinesses')\nrepo.createCollection('fitBusinesses')\nrepo['... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('janellc_rstiffel', 'janellc_rstiffel')
url = 'http://datamechanics.io/data/DBABoston.csv'
values = csv_to_json(url)
repo.dropCollection('f... | getBusinesses | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getBusinesses:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything... | stack_v2_sparse_classes_36k_train_013554 | 4,340 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `getBusinesses` described below.
Class description:
Implement the getBusinesses class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, e... | Implement the Python class `getBusinesses` described below.
Class description:
Implement the getBusinesses class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, e... | b5ccaad97f6e35f9580e645ca764f36eb3406f43 | <|skeleton|>
class getBusinesses:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class getBusinesses:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('janellc_rstiffel', 'janellc_rstiffel'... | the_stack_v2_python_sparse | janellc_rstiffel/getBusinesses.py | dwang1995/course-2018-spr-proj | train | 1 | |
0bd1808eecfc0c246b65e26d8ac90132f0da6860 | [
"property_id = request.POST['id']\npic_url = request.POST['pic_url']\nname = request.POST['name']\nproperty_value = mall_models.ProductModelPropertyValue.objects.create(property_id=property_id, name=name, pic_url=pic_url)\nresponse = create_response(200)\nresponse.data = property_value.id\nreturn response.get_respo... | <|body_start_0|>
property_id = request.POST['id']
pic_url = request.POST['pic_url']
name = request.POST['name']
property_value = mall_models.ProductModelPropertyValue.objects.create(property_id=property_id, name=name, pic_url=pic_url)
response = create_response(200)
respo... | ModelPropertyValue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelPropertyValue:
def api_put(request):
"""创建规格属性值 Args: id: 规格id name: 规格值的名字 pic_url: 规格值的图片地址"""
<|body_0|>
def api_post(request):
"""修改规格属性值 Args: id: 属性值id name: 规格值的名字 pic_url: 规格值的图片地址"""
<|body_1|>
def api_delete(request):
"""删除规格属性值 Ar... | stack_v2_sparse_classes_36k_train_013555 | 9,873 | no_license | [
{
"docstring": "创建规格属性值 Args: id: 规格id name: 规格值的名字 pic_url: 规格值的图片地址",
"name": "api_put",
"signature": "def api_put(request)"
},
{
"docstring": "修改规格属性值 Args: id: 属性值id name: 规格值的名字 pic_url: 规格值的图片地址",
"name": "api_post",
"signature": "def api_post(request)"
},
{
"docstring": "删... | 3 | null | Implement the Python class `ModelPropertyValue` described below.
Class description:
Implement the ModelPropertyValue class.
Method signatures and docstrings:
- def api_put(request): 创建规格属性值 Args: id: 规格id name: 规格值的名字 pic_url: 规格值的图片地址
- def api_post(request): 修改规格属性值 Args: id: 属性值id name: 规格值的名字 pic_url: 规格值的图片地址
- ... | Implement the Python class `ModelPropertyValue` described below.
Class description:
Implement the ModelPropertyValue class.
Method signatures and docstrings:
- def api_put(request): 创建规格属性值 Args: id: 规格id name: 规格值的名字 pic_url: 规格值的图片地址
- def api_post(request): 修改规格属性值 Args: id: 属性值id name: 规格值的名字 pic_url: 规格值的图片地址
- ... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class ModelPropertyValue:
def api_put(request):
"""创建规格属性值 Args: id: 规格id name: 规格值的名字 pic_url: 规格值的图片地址"""
<|body_0|>
def api_post(request):
"""修改规格属性值 Args: id: 属性值id name: 规格值的名字 pic_url: 规格值的图片地址"""
<|body_1|>
def api_delete(request):
"""删除规格属性值 Ar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelPropertyValue:
def api_put(request):
"""创建规格属性值 Args: id: 规格id name: 规格值的名字 pic_url: 规格值的图片地址"""
property_id = request.POST['id']
pic_url = request.POST['pic_url']
name = request.POST['name']
property_value = mall_models.ProductModelPropertyValue.objects.create(pro... | the_stack_v2_python_sparse | weapp/mall/product/model_property.py | chengdg/weizoom | train | 1 | |
d13f8f8bc0237b3c58757a1716f49f4d7bd34c21 | [
"form = AWSForm(request.POST)\nif not form.is_valid():\n messages.add_message(request, messages.ERROR, 'Failed to create new AWS account')\n return redirect('{}#accounts'.format(reverse('index')))\nelse:\n aws_account = form.save(commit=False)\n aws_account.owner = request.user\n aws_account.save()\n... | <|body_start_0|>
form = AWSForm(request.POST)
if not form.is_valid():
messages.add_message(request, messages.ERROR, 'Failed to create new AWS account')
return redirect('{}#accounts'.format(reverse('index')))
else:
aws_account = form.save(commit=False)
... | AWSAccount | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWSAccount:
def post(request):
"""Create AWS Account"""
<|body_0|>
def get(request, pk):
"""Delete AWS account"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
form = AWSForm(request.POST)
if not form.is_valid():
messages.add_mess... | stack_v2_sparse_classes_36k_train_013556 | 2,209 | permissive | [
{
"docstring": "Create AWS Account",
"name": "post",
"signature": "def post(request)"
},
{
"docstring": "Delete AWS account",
"name": "get",
"signature": "def get(request, pk)"
}
] | 2 | null | Implement the Python class `AWSAccount` described below.
Class description:
Implement the AWSAccount class.
Method signatures and docstrings:
- def post(request): Create AWS Account
- def get(request, pk): Delete AWS account | Implement the Python class `AWSAccount` described below.
Class description:
Implement the AWSAccount class.
Method signatures and docstrings:
- def post(request): Create AWS Account
- def get(request, pk): Delete AWS account
<|skeleton|>
class AWSAccount:
def post(request):
"""Create AWS Account"""
... | 2f0c9f73c9f6aa4d415429c79b58e15baa312f26 | <|skeleton|>
class AWSAccount:
def post(request):
"""Create AWS Account"""
<|body_0|>
def get(request, pk):
"""Delete AWS account"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AWSAccount:
def post(request):
"""Create AWS Account"""
form = AWSForm(request.POST)
if not form.is_valid():
messages.add_message(request, messages.ERROR, 'Failed to create new AWS account')
return redirect('{}#accounts'.format(reverse('index')))
else:
... | the_stack_v2_python_sparse | overwatch/views/accounts.py | inuitwallet/overwatch | train | 2 | |
4f236bcb1c4a1071c549ac271fb7184ebb8bea5a | [
"super().__init__(grad=grad, **kwargs)\nself.keys = keys\nself.prob = prob\nif not isinstance(dims, DiscreteParameter):\n if len(dims) > 2:\n dims = list(combinations(dims, 2))\n else:\n dims = (dims,)\n dims = DiscreteParameter(dims)\nself.register_sampler('dims', dims)\nself.register_sample... | <|body_start_0|>
super().__init__(grad=grad, **kwargs)
self.keys = keys
self.prob = prob
if not isinstance(dims, DiscreteParameter):
if len(dims) > 2:
dims = list(combinations(dims, 2))
else:
dims = (dims,)
dims = Discre... | Rotate 90 degree around dims | Rot90 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rot90:
"""Rotate 90 degree around dims"""
def __init__(self, dims: Union[Sequence[int], DiscreteParameter], keys: Sequence[str]=('data',), num_rots: Sequence[int]=(0, 1, 2, 3), prob: float=0.5, grad: bool=False, **kwargs):
"""Args: dims: dims/axis ro rotate. If more than two dims are... | stack_v2_sparse_classes_36k_train_013557 | 11,105 | permissive | [
{
"docstring": "Args: dims: dims/axis ro rotate. If more than two dims are provided, 2 dimensions are randomly chosen at each call keys: keys which should be rotated num_rots: possible values for number of rotations prob: probability for rotation grad: enable gradient computation inside transformation kwargs: k... | 2 | stack_v2_sparse_classes_30k_train_019262 | Implement the Python class `Rot90` described below.
Class description:
Rotate 90 degree around dims
Method signatures and docstrings:
- def __init__(self, dims: Union[Sequence[int], DiscreteParameter], keys: Sequence[str]=('data',), num_rots: Sequence[int]=(0, 1, 2, 3), prob: float=0.5, grad: bool=False, **kwargs): A... | Implement the Python class `Rot90` described below.
Class description:
Rotate 90 degree around dims
Method signatures and docstrings:
- def __init__(self, dims: Union[Sequence[int], DiscreteParameter], keys: Sequence[str]=('data',), num_rots: Sequence[int]=(0, 1, 2, 3), prob: float=0.5, grad: bool=False, **kwargs): A... | ab6fbcfe7215c2a5b8e401b70909f6a32d0d167b | <|skeleton|>
class Rot90:
"""Rotate 90 degree around dims"""
def __init__(self, dims: Union[Sequence[int], DiscreteParameter], keys: Sequence[str]=('data',), num_rots: Sequence[int]=(0, 1, 2, 3), prob: float=0.5, grad: bool=False, **kwargs):
"""Args: dims: dims/axis ro rotate. If more than two dims are... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rot90:
"""Rotate 90 degree around dims"""
def __init__(self, dims: Union[Sequence[int], DiscreteParameter], keys: Sequence[str]=('data',), num_rots: Sequence[int]=(0, 1, 2, 3), prob: float=0.5, grad: bool=False, **kwargs):
"""Args: dims: dims/axis ro rotate. If more than two dims are provided, 2 ... | the_stack_v2_python_sparse | rising/transforms/spatial.py | PhoenixDL/rising | train | 318 |
e68a064cc0d770a60b519bda6817d7405b32dae5 | [
"graph = {}\nfor flight in flights:\n u, v, w = flight\n if u not in graph:\n graph[u] = {}\n graph[u][v] = w\ndist = [-1] * n\ndist[src] = 0\nqueue = [src]\nstep = 0\nprint(graph)\nwhile len(queue) > 0:\n qlen = len(queue)\n step += 1\n if step > K + 1:\n break\n for i in range(q... | <|body_start_0|>
graph = {}
for flight in flights:
u, v, w = flight
if u not in graph:
graph[u] = {}
graph[u][v] = w
dist = [-1] * n
dist[src] = 0
queue = [src]
step = 0
print(graph)
while len(queue) > 0:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findCheapestPrice_DFS(self, n, flights, src, dst, K):
""":type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int"""
<|body_0|>
def findCheapestPrice(self, n, flights, src, dst, K):
""":type n: int :type flights... | stack_v2_sparse_classes_36k_train_013558 | 2,157 | no_license | [
{
"docstring": ":type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int",
"name": "findCheapestPrice_DFS",
"signature": "def findCheapestPrice_DFS(self, n, flights, src, dst, K)"
},
{
"docstring": ":type n: int :type flights: List[List[int]] :type src: ... | 2 | stack_v2_sparse_classes_30k_train_020549 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findCheapestPrice_DFS(self, n, flights, src, dst, K): :type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int
- def findCheapestPri... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findCheapestPrice_DFS(self, n, flights, src, dst, K): :type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int
- def findCheapestPri... | 176cc1db3291843fb068f06d0180766dd8c3122c | <|skeleton|>
class Solution:
def findCheapestPrice_DFS(self, n, flights, src, dst, K):
""":type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int"""
<|body_0|>
def findCheapestPrice(self, n, flights, src, dst, K):
""":type n: int :type flights... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findCheapestPrice_DFS(self, n, flights, src, dst, K):
""":type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int"""
graph = {}
for flight in flights:
u, v, w = flight
if u not in graph:
gra... | the_stack_v2_python_sparse | 2019/bfs/cheapest_flights_within_k_stops_787.py | yehongyu/acode | train | 0 | |
8449739dd0f1e7fe6916a3dcc5d2939d5042bd6d | [
"Animal.__init__(self, habitat)\nMammal.__init__(self, food, fur)\nself.age = age\nself.sex = sex\nprint('---A Panda---')",
"print(f'\\nAge: {self.age}')\nprint(f'Sex: {self.sex}')\nprint(f'Habitat: {self.habitat}')\nprint(f'Food: {self.food}')\nprint(f'Fur: {self.fur}\\n')"
] | <|body_start_0|>
Animal.__init__(self, habitat)
Mammal.__init__(self, food, fur)
self.age = age
self.sex = sex
print('---A Panda---')
<|end_body_0|>
<|body_start_1|>
print(f'\nAge: {self.age}')
print(f'Sex: {self.sex}')
print(f'Habitat: {self.habitat}')
... | Panda class. Args: age (int): Age of the panda. sex (str): Sex of the panda. | Panda | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Panda:
"""Panda class. Args: age (int): Age of the panda. sex (str): Sex of the panda."""
def __init__(self, age, sex, habitat, food, fur=True):
"""Constructor of Panda class."""
<|body_0|>
def display(self):
"""Display method to print the different characteristi... | stack_v2_sparse_classes_36k_train_013559 | 2,135 | no_license | [
{
"docstring": "Constructor of Panda class.",
"name": "__init__",
"signature": "def __init__(self, age, sex, habitat, food, fur=True)"
},
{
"docstring": "Display method to print the different characteristics.",
"name": "display",
"signature": "def display(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020190 | Implement the Python class `Panda` described below.
Class description:
Panda class. Args: age (int): Age of the panda. sex (str): Sex of the panda.
Method signatures and docstrings:
- def __init__(self, age, sex, habitat, food, fur=True): Constructor of Panda class.
- def display(self): Display method to print the di... | Implement the Python class `Panda` described below.
Class description:
Panda class. Args: age (int): Age of the panda. sex (str): Sex of the panda.
Method signatures and docstrings:
- def __init__(self, age, sex, habitat, food, fur=True): Constructor of Panda class.
- def display(self): Display method to print the di... | 892d9c25b9712bf3bbfd7f29529eca8b47fb8039 | <|skeleton|>
class Panda:
"""Panda class. Args: age (int): Age of the panda. sex (str): Sex of the panda."""
def __init__(self, age, sex, habitat, food, fur=True):
"""Constructor of Panda class."""
<|body_0|>
def display(self):
"""Display method to print the different characteristi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Panda:
"""Panda class. Args: age (int): Age of the panda. sex (str): Sex of the panda."""
def __init__(self, age, sex, habitat, food, fur=True):
"""Constructor of Panda class."""
Animal.__init__(self, habitat)
Mammal.__init__(self, food, fur)
self.age = age
self.se... | the_stack_v2_python_sparse | sem-3/practical_26_Nov.py | B-Tech-AI-Python/Class-assignments | train | 0 |
08919a1fc0f6a949f669c7e21ce0574eedce6e25 | [
"val = 0\nfor i in xrange(x + 1):\n if i * i <= x < (i + 1) * (i + 1):\n val = i\n break\nreturn val",
"l, r, mid = (0, x, 0)\nwhile l <= r:\n mid = l + (r - l) / 2\n square, square_one = (mid * mid, (mid + 1) * (mid + 1))\n if square <= x < square_one:\n break\n elif x < squar... | <|body_start_0|>
val = 0
for i in xrange(x + 1):
if i * i <= x < (i + 1) * (i + 1):
val = i
break
return val
<|end_body_0|>
<|body_start_1|>
l, r, mid = (0, x, 0)
while l <= r:
mid = l + (r - l) / 2
square, squa... | 实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。"""
def mysqrt(self, x):
""":type x: int :rtype: int 遍历法,这里用的是xrange,xrange是个生成器,因此节省空间但效率不如range快;其次需要遍历的元素从0到sq... | stack_v2_sparse_classes_36k_train_013560 | 2,643 | no_license | [
{
"docstring": ":type x: int :rtype: int 遍历法,这里用的是xrange,xrange是个生成器,因此节省空间但效率不如range快;其次需要遍历的元素从0到sqrt(x) 时间复杂度:O(sqrt(x)) 空间复杂度:O(1)",
"name": "mysqrt",
"signature": "def mysqrt(self, x)"
},
{
"docstring": ":type x: int :rtype: int 二分查找法 时间复杂度:O(logx),x的值大小,也即O(logn) 空间复杂度:O(1)",
"name": "... | 3 | null | Implement the Python class `Solution` described below.
Class description:
实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
Method signatures and docstrings:
- def mysqrt(self, x): :type x: int :rtype: int 遍历法... | Implement the Python class `Solution` described below.
Class description:
实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
Method signatures and docstrings:
- def mysqrt(self, x): :type x: int :rtype: int 遍历法... | 2c534185854c1a6f5ffdb2698f9db9989f30a25b | <|skeleton|>
class Solution:
"""实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。"""
def mysqrt(self, x):
""":type x: int :rtype: int 遍历法,这里用的是xrange,xrange是个生成器,因此节省空间但效率不如range快;其次需要遍历的元素从0到sq... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。"""
def mysqrt(self, x):
""":type x: int :rtype: int 遍历法,这里用的是xrange,xrange是个生成器,因此节省空间但效率不如range快;其次需要遍历的元素从0到sqrt(x) 时间复杂度:O... | the_stack_v2_python_sparse | Week 03/id_668/leetcode_69_668.py | Carryours/algorithm004-03 | train | 2 |
c56da1ed3525124305de49a7e445af39cfb7bc8b | [
"data = {'username': '13500001234', 'password': '12574655'}\nresp = self.post(config.Login.api_url, json=data).json()\nif not resp.get('message') == 'success':\n raise AssertionError('用户登陆失败, 请重新配置用户登录数据!!!')",
"resp = self.get(self.api_url, self.data_tmp).json()\nself.assertEqual(resp.get('code'), 200)\nself.... | <|body_start_0|>
data = {'username': '13500001234', 'password': '12574655'}
resp = self.post(config.Login.api_url, json=data).json()
if not resp.get('message') == 'success':
raise AssertionError('用户登陆失败, 请重新配置用户登录数据!!!')
<|end_body_0|>
<|body_start_1|>
resp = self.get(self.a... | Child的项目的查询用户信息接口测试用例 | QueryUserInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueryUserInfo:
"""Child的项目的查询用户信息接口测试用例"""
def setUp(self):
"""pass"""
<|body_0|>
def test_query_userinfo_is_ok(self):
"""[查询用户信息][成功] 正常的get请求可以获取到正确的返回结果"""
<|body_1|>
def test_query_userinfo_method_is_post(self):
"""[查询用户信息][失败] 该接口只支持get方... | stack_v2_sparse_classes_36k_train_013561 | 2,413 | no_license | [
{
"docstring": "pass",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "[查询用户信息][成功] 正常的get请求可以获取到正确的返回结果",
"name": "test_query_userinfo_is_ok",
"signature": "def test_query_userinfo_is_ok(self)"
},
{
"docstring": "[查询用户信息][失败] 该接口只支持get方法请求, post方法返回405",
"... | 5 | stack_v2_sparse_classes_30k_train_006110 | Implement the Python class `QueryUserInfo` described below.
Class description:
Child的项目的查询用户信息接口测试用例
Method signatures and docstrings:
- def setUp(self): pass
- def test_query_userinfo_is_ok(self): [查询用户信息][成功] 正常的get请求可以获取到正确的返回结果
- def test_query_userinfo_method_is_post(self): [查询用户信息][失败] 该接口只支持get方法请求, post方法返回40... | Implement the Python class `QueryUserInfo` described below.
Class description:
Child的项目的查询用户信息接口测试用例
Method signatures and docstrings:
- def setUp(self): pass
- def test_query_userinfo_is_ok(self): [查询用户信息][成功] 正常的get请求可以获取到正确的返回结果
- def test_query_userinfo_method_is_post(self): [查询用户信息][失败] 该接口只支持get方法请求, post方法返回40... | d04fa050cd65d73c9d1207f251d7fe95ec15fa24 | <|skeleton|>
class QueryUserInfo:
"""Child的项目的查询用户信息接口测试用例"""
def setUp(self):
"""pass"""
<|body_0|>
def test_query_userinfo_is_ok(self):
"""[查询用户信息][成功] 正常的get请求可以获取到正确的返回结果"""
<|body_1|>
def test_query_userinfo_method_is_post(self):
"""[查询用户信息][失败] 该接口只支持get方... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QueryUserInfo:
"""Child的项目的查询用户信息接口测试用例"""
def setUp(self):
"""pass"""
data = {'username': '13500001234', 'password': '12574655'}
resp = self.post(config.Login.api_url, json=data).json()
if not resp.get('message') == 'success':
raise AssertionError('用户登陆失败, 请重新... | the_stack_v2_python_sparse | ForthWeek/fifth_day/ChildApi/case/test_get_all_userinfo.py | PeiyaoL/LearnPythonWithWalkers | train | 0 |
b0417402595575e935d41f33c6092bb380993fb5 | [
"super().__init__()\nres_blocks = [ResidualBlock(hidden_size, kernel_size, d, n=2) for d in dilations]\nself.res_blocks = nn.Sequential(*res_blocks)\nself.postnet1 = nn.Sequential(nn.Linear(hidden_size, hidden_size))\nself.postnet2 = ResidualBlock(hidden_size, kernel_size, 1, n=2)\nself.linear = nn.Linear(hidden_si... | <|body_start_0|>
super().__init__()
res_blocks = [ResidualBlock(hidden_size, kernel_size, d, n=2) for d in dilations]
self.res_blocks = nn.Sequential(*res_blocks)
self.postnet1 = nn.Sequential(nn.Linear(hidden_size, hidden_size))
self.postnet2 = ResidualBlock(hidden_size, kernel_... | SpeedySpeechDecoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpeedySpeechDecoder:
def __init__(self, hidden_size: int=128, output_size: int=80, kernel_size: int=3, dilations: List[int]=[1, 3, 9, 27, 1, 3, 9, 27, 1, 3, 9, 27, 1, 3, 9, 27, 1, 1]):
"""SpeedySpeech decoder module. Args: hidden_size (int): Number of decoder hidden units. kernel_size (i... | stack_v2_sparse_classes_36k_train_013562 | 15,439 | permissive | [
{
"docstring": "SpeedySpeech decoder module. Args: hidden_size (int): Number of decoder hidden units. kernel_size (int): Kernel size of decoder. output_size (int): Dimension of the outputs. dilations (List[int]): Dilations of decoder.",
"name": "__init__",
"signature": "def __init__(self, hidden_size: i... | 2 | null | Implement the Python class `SpeedySpeechDecoder` described below.
Class description:
Implement the SpeedySpeechDecoder class.
Method signatures and docstrings:
- def __init__(self, hidden_size: int=128, output_size: int=80, kernel_size: int=3, dilations: List[int]=[1, 3, 9, 27, 1, 3, 9, 27, 1, 3, 9, 27, 1, 3, 9, 27, ... | Implement the Python class `SpeedySpeechDecoder` described below.
Class description:
Implement the SpeedySpeechDecoder class.
Method signatures and docstrings:
- def __init__(self, hidden_size: int=128, output_size: int=80, kernel_size: int=3, dilations: List[int]=[1, 3, 9, 27, 1, 3, 9, 27, 1, 3, 9, 27, 1, 3, 9, 27, ... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class SpeedySpeechDecoder:
def __init__(self, hidden_size: int=128, output_size: int=80, kernel_size: int=3, dilations: List[int]=[1, 3, 9, 27, 1, 3, 9, 27, 1, 3, 9, 27, 1, 3, 9, 27, 1, 1]):
"""SpeedySpeech decoder module. Args: hidden_size (int): Number of decoder hidden units. kernel_size (i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpeedySpeechDecoder:
def __init__(self, hidden_size: int=128, output_size: int=80, kernel_size: int=3, dilations: List[int]=[1, 3, 9, 27, 1, 3, 9, 27, 1, 3, 9, 27, 1, 3, 9, 27, 1, 1]):
"""SpeedySpeech decoder module. Args: hidden_size (int): Number of decoder hidden units. kernel_size (int): Kernel si... | the_stack_v2_python_sparse | paddlespeech/t2s/models/speedyspeech/speedyspeech.py | anniyanvr/DeepSpeech-1 | train | 0 | |
a01c7500b6d35f33d32f399ae27f804f5ecbcf05 | [
"if self.train_verbose >= 2 and self.is_chief and (batch_index % self.train_report_steps == 0):\n try:\n out_buffer = OrderedDict(time=time.strftime('%Y-%m-%d @ %H:%M:%S'), epoch=f'{self.cur_epoch}/{self.epochs}', step=f'{self._format_batch(batch_index, self.train_num_batches)}', lr=f\"{self.trainer.optim... | <|body_start_0|>
if self.train_verbose >= 2 and self.is_chief and (batch_index % self.train_report_steps == 0):
try:
out_buffer = OrderedDict(time=time.strftime('%Y-%m-%d @ %H:%M:%S'), epoch=f'{self.cur_epoch}/{self.epochs}', step=f'{self._format_batch(batch_index, self.train_num_bat... | Callback that shows the progress of evaluating metrics. | DetectionProgressLogger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DetectionProgressLogger:
"""Callback that shows the progress of evaluating metrics."""
def after_train_step(self, batch_index, logs=None):
"""Be called before each batch training."""
<|body_0|>
def after_valid_step(self, batch_index, logs=None):
"""Be called afte... | stack_v2_sparse_classes_36k_train_013563 | 3,359 | permissive | [
{
"docstring": "Be called before each batch training.",
"name": "after_train_step",
"signature": "def after_train_step(self, batch_index, logs=None)"
},
{
"docstring": "Be called after each batch of the validation.",
"name": "after_valid_step",
"signature": "def after_valid_step(self, ba... | 3 | null | Implement the Python class `DetectionProgressLogger` described below.
Class description:
Callback that shows the progress of evaluating metrics.
Method signatures and docstrings:
- def after_train_step(self, batch_index, logs=None): Be called before each batch training.
- def after_valid_step(self, batch_index, logs=... | Implement the Python class `DetectionProgressLogger` described below.
Class description:
Callback that shows the progress of evaluating metrics.
Method signatures and docstrings:
- def after_train_step(self, batch_index, logs=None): Be called before each batch training.
- def after_valid_step(self, batch_index, logs=... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class DetectionProgressLogger:
"""Callback that shows the progress of evaluating metrics."""
def after_train_step(self, batch_index, logs=None):
"""Be called before each batch training."""
<|body_0|>
def after_valid_step(self, batch_index, logs=None):
"""Be called afte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DetectionProgressLogger:
"""Callback that shows the progress of evaluating metrics."""
def after_train_step(self, batch_index, logs=None):
"""Be called before each batch training."""
if self.train_verbose >= 2 and self.is_chief and (batch_index % self.train_report_steps == 0):
... | the_stack_v2_python_sparse | zeus/trainer/callbacks/detection_progress_logger.py | huawei-noah/xingtian | train | 308 |
5f477eaf8233cc0cd2d72366b75ff88c2b2b54f7 | [
"if self.request.path.endswith('.fa'):\n sequence_id = sequence_id.rstrip('.fa')\n try:\n filename, fasta = await get_data_from_req(self.request).otus.get_sequence_fasta(sequence_id)\n except ResourceNotFoundError as err:\n if 'does not exist' in str(err):\n raise NotFound\n ... | <|body_start_0|>
if self.request.path.endswith('.fa'):
sequence_id = sequence_id.rstrip('.fa')
try:
filename, fasta = await get_data_from_req(self.request).otus.get_sequence_fasta(sequence_id)
except ResourceNotFoundError as err:
if 'does not e... | SequenceView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceView:
async def get(self, otu_id: str, isolate_id: str, sequence_id: str, /):
"""Get a sequence. Fetches the details for a sequence. A FASTA file containing the nucelotide sequence can be downloaded by appending `.fa` to the path."""
<|body_0|>
async def patch(self, ... | stack_v2_sparse_classes_36k_train_013564 | 16,946 | permissive | [
{
"docstring": "Get a sequence. Fetches the details for a sequence. A FASTA file containing the nucelotide sequence can be downloaded by appending `.fa` to the path.",
"name": "get",
"signature": "async def get(self, otu_id: str, isolate_id: str, sequence_id: str, /)"
},
{
"docstring": "Update a... | 3 | null | Implement the Python class `SequenceView` described below.
Class description:
Implement the SequenceView class.
Method signatures and docstrings:
- async def get(self, otu_id: str, isolate_id: str, sequence_id: str, /): Get a sequence. Fetches the details for a sequence. A FASTA file containing the nucelotide sequenc... | Implement the Python class `SequenceView` described below.
Class description:
Implement the SequenceView class.
Method signatures and docstrings:
- async def get(self, otu_id: str, isolate_id: str, sequence_id: str, /): Get a sequence. Fetches the details for a sequence. A FASTA file containing the nucelotide sequenc... | 1d17d2ba570cf5487e7514bec29250a5b368bb0a | <|skeleton|>
class SequenceView:
async def get(self, otu_id: str, isolate_id: str, sequence_id: str, /):
"""Get a sequence. Fetches the details for a sequence. A FASTA file containing the nucelotide sequence can be downloaded by appending `.fa` to the path."""
<|body_0|>
async def patch(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceView:
async def get(self, otu_id: str, isolate_id: str, sequence_id: str, /):
"""Get a sequence. Fetches the details for a sequence. A FASTA file containing the nucelotide sequence can be downloaded by appending `.fa` to the path."""
if self.request.path.endswith('.fa'):
se... | the_stack_v2_python_sparse | virtool/otus/api.py | virtool/virtool | train | 45 | |
ca75ef413a95cef2eb35ab516a7f603c7eda3ad1 | [
"\"\"\"Use set\"\"\"\nn = len(nums)\nif n < 3:\n return []\nnums.sort()\n\ndef twoSum(nums, target):\n result = set()\n i, j = (0, len(nums) - 1)\n while i < j:\n if nums[i] + nums[j] == target:\n result.add((nums[i], nums[j]))\n i += 1\n j -= 1\n elif nums... | <|body_start_0|>
"""Use set"""
n = len(nums)
if n < 3:
return []
nums.sort()
def twoSum(nums, target):
result = set()
i, j = (0, len(nums) - 1)
while i < j:
if nums[i] + nums[j] == target:
result... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""2 Pointer of 2Sum, Time: O(n^2)"""
<|body_0|>
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""2 Pointer of 2Sum, Time: O(n^2), Space: O(1)"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_013565 | 2,216 | no_license | [
{
"docstring": "2 Pointer of 2Sum, Time: O(n^2)",
"name": "threeSum",
"signature": "def threeSum(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "2 Pointer of 2Sum, Time: O(n^2), Space: O(1)",
"name": "threeSum",
"signature": "def threeSum(self, nums: List[int]) -> List[List... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums: List[int]) -> List[List[int]]: 2 Pointer of 2Sum, Time: O(n^2)
- def threeSum(self, nums: List[int]) -> List[List[int]]: 2 Pointer of 2Sum, Time: O(n^2),... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums: List[int]) -> List[List[int]]: 2 Pointer of 2Sum, Time: O(n^2)
- def threeSum(self, nums: List[int]) -> List[List[int]]: 2 Pointer of 2Sum, Time: O(n^2),... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""2 Pointer of 2Sum, Time: O(n^2)"""
<|body_0|>
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""2 Pointer of 2Sum, Time: O(n^2), Space: O(1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""2 Pointer of 2Sum, Time: O(n^2)"""
"""Use set"""
n = len(nums)
if n < 3:
return []
nums.sort()
def twoSum(nums, target):
result = set()
i, j = (0, len(nums)... | the_stack_v2_python_sparse | python/15-3Sum.py | cwza/leetcode | train | 0 | |
35baf7a68a7541ba43ee2b6245f45da75c2b73f6 | [
"self._pipe_counter = 0\nself._rule_counter = 0\nself._port_range = port_range\nself._connection_config = connection_config",
"receive_pipe_id = self._CreateDummynetPipe(self._connection_config.receive_bw_kbps, self._connection_config.delay_ms, self._connection_config.packet_loss_percent, self._connection_config.... | <|body_start_0|>
self._pipe_counter = 0
self._rule_counter = 0
self._port_range = port_range
self._connection_config = connection_config
<|end_body_0|>
<|body_start_1|>
receive_pipe_id = self._CreateDummynetPipe(self._connection_config.receive_bw_kbps, self._connection_config.de... | A network emulator that can constrain the network using Dummynet. | NetworkEmulator | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkEmulator:
"""A network emulator that can constrain the network using Dummynet."""
def __init__(self, connection_config, port_range):
"""Constructor. Args: connection_config: A config.ConnectionConfig object containing the characteristics for the connection to be emulation. por... | stack_v2_sparse_classes_36k_train_013566 | 7,158 | permissive | [
{
"docstring": "Constructor. Args: connection_config: A config.ConnectionConfig object containing the characteristics for the connection to be emulation. port_range: Tuple containing two integers defining the port range.",
"name": "__init__",
"signature": "def __init__(self, connection_config, port_rang... | 5 | null | Implement the Python class `NetworkEmulator` described below.
Class description:
A network emulator that can constrain the network using Dummynet.
Method signatures and docstrings:
- def __init__(self, connection_config, port_range): Constructor. Args: connection_config: A config.ConnectionConfig object containing th... | Implement the Python class `NetworkEmulator` described below.
Class description:
A network emulator that can constrain the network using Dummynet.
Method signatures and docstrings:
- def __init__(self, connection_config, port_range): Constructor. Args: connection_config: A config.ConnectionConfig object containing th... | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | <|skeleton|>
class NetworkEmulator:
"""A network emulator that can constrain the network using Dummynet."""
def __init__(self, connection_config, port_range):
"""Constructor. Args: connection_config: A config.ConnectionConfig object containing the characteristics for the connection to be emulation. por... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetworkEmulator:
"""A network emulator that can constrain the network using Dummynet."""
def __init__(self, connection_config, port_range):
"""Constructor. Args: connection_config: A config.ConnectionConfig object containing the characteristics for the connection to be emulation. port_range: Tupl... | the_stack_v2_python_sparse | third_party/webrtc/tools_webrtc/network_emulator/network_emulator.py | iridium-browser/iridium-browser | train | 341 |
7e167a83a753673e77c7d125af15ea7570ac3edb | [
"if not is_exe(exe_path):\n msg = '{0} is not an executable'.format(exe_path)\n raise NotExecutableError(msg)\nself._exe_path = exe_path",
"self.__build_cmd(infname)\npipe = subprocess.run(self._cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)\nresults = Results(self._cmd, self._... | <|body_start_0|>
if not is_exe(exe_path):
msg = '{0} is not an executable'.format(exe_path)
raise NotExecutableError(msg)
self._exe_path = exe_path
<|end_body_0|>
<|body_start_1|>
self.__build_cmd(infname)
pipe = subprocess.run(self._cmd, shell=True, stdout=subpr... | Class for working with Samtools_index | Samtools_Index | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Samtools_Index:
"""Class for working with Samtools_index"""
def __init__(self, exe_path):
"""Instantiate with location of executable"""
<|body_0|>
def run(self, infname):
"""Run Samtools_index on the passed file"""
<|body_1|>
def __build_cmd(self, in... | stack_v2_sparse_classes_36k_train_013567 | 1,843 | permissive | [
{
"docstring": "Instantiate with location of executable",
"name": "__init__",
"signature": "def __init__(self, exe_path)"
},
{
"docstring": "Run Samtools_index on the passed file",
"name": "run",
"signature": "def run(self, infname)"
},
{
"docstring": "Build a command-line for Sa... | 3 | stack_v2_sparse_classes_30k_train_017374 | Implement the Python class `Samtools_Index` described below.
Class description:
Class for working with Samtools_index
Method signatures and docstrings:
- def __init__(self, exe_path): Instantiate with location of executable
- def run(self, infname): Run Samtools_index on the passed file
- def __build_cmd(self, infnam... | Implement the Python class `Samtools_Index` described below.
Class description:
Class for working with Samtools_index
Method signatures and docstrings:
- def __init__(self, exe_path): Instantiate with location of executable
- def run(self, infname): Run Samtools_index on the passed file
- def __build_cmd(self, infnam... | a3c64198aad3709a5c4d969f48ae0af11fdc25db | <|skeleton|>
class Samtools_Index:
"""Class for working with Samtools_index"""
def __init__(self, exe_path):
"""Instantiate with location of executable"""
<|body_0|>
def run(self, infname):
"""Run Samtools_index on the passed file"""
<|body_1|>
def __build_cmd(self, in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Samtools_Index:
"""Class for working with Samtools_index"""
def __init__(self, exe_path):
"""Instantiate with location of executable"""
if not is_exe(exe_path):
msg = '{0} is not an executable'.format(exe_path)
raise NotExecutableError(msg)
self._exe_path =... | the_stack_v2_python_sparse | metapy/pycits/samtools_index.py | peterthorpe5/public_scripts | train | 35 |
0d7435c9c3f78fea8212d02288beb662458c31ff | [
"event = get_object_or_404(Event, pk=event_id)\nserializer = EventSerializer(event)\nreturn Response(serializer.data)",
"event = get_object_or_404(Category, pk=event_id)\nserializer = EventSerializer(event, data=request.data)\nif serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\... | <|body_start_0|>
event = get_object_or_404(Event, pk=event_id)
serializer = EventSerializer(event)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
event = get_object_or_404(Category, pk=event_id)
serializer = EventSerializer(event, data=request.data)
if ... | EventDetail | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventDetail:
def get(self, request, event_id, format=None):
"""Get event details --- serializer: administrator.serializers.EventSerializer"""
<|body_0|>
def put(self, request, event_id, format=None):
"""Edit event --- serializer: administrator.serializers.EventSerial... | stack_v2_sparse_classes_36k_train_013568 | 30,608 | permissive | [
{
"docstring": "Get event details --- serializer: administrator.serializers.EventSerializer",
"name": "get",
"signature": "def get(self, request, event_id, format=None)"
},
{
"docstring": "Edit event --- serializer: administrator.serializers.EventSerializer",
"name": "put",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_007191 | Implement the Python class `EventDetail` described below.
Class description:
Implement the EventDetail class.
Method signatures and docstrings:
- def get(self, request, event_id, format=None): Get event details --- serializer: administrator.serializers.EventSerializer
- def put(self, request, event_id, format=None): ... | Implement the Python class `EventDetail` described below.
Class description:
Implement the EventDetail class.
Method signatures and docstrings:
- def get(self, request, event_id, format=None): Get event details --- serializer: administrator.serializers.EventSerializer
- def put(self, request, event_id, format=None): ... | 73728463badb3bfd4413aa0f7aeb44a9606fdfea | <|skeleton|>
class EventDetail:
def get(self, request, event_id, format=None):
"""Get event details --- serializer: administrator.serializers.EventSerializer"""
<|body_0|>
def put(self, request, event_id, format=None):
"""Edit event --- serializer: administrator.serializers.EventSerial... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventDetail:
def get(self, request, event_id, format=None):
"""Get event details --- serializer: administrator.serializers.EventSerializer"""
event = get_object_or_404(Event, pk=event_id)
serializer = EventSerializer(event)
return Response(serializer.data)
def put(self, re... | the_stack_v2_python_sparse | administrator/views.py | belatrix/BackendAllStars | train | 5 | |
716a49e260e69a61f581213e629fd5c4cc6b6470 | [
"delay = 0\nrow = []\nfor val in prev:\n row.append(val + delay)\n delay = val\nrow.append(delay)\nreturn row",
"self.tri = []\nif numRows >= 1:\n self.tri.append([1])\nif numRows >= 2:\n self.tri.append([1, 1])\ni = 3\nwhile i <= numRows:\n self.tri.append(self.nextRow(self.tri[-1]))\n i = i + ... | <|body_start_0|>
delay = 0
row = []
for val in prev:
row.append(val + delay)
delay = val
row.append(delay)
return row
<|end_body_0|>
<|body_start_1|>
self.tri = []
if numRows >= 1:
self.tri.append([1])
if numRows >= 2:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextRow(self, prev):
""":type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)"""
<|body_0|>
def generate(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_013569 | 1,004 | permissive | [
{
"docstring": ":type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)",
"name": "nextRow",
"signature": "def nextRow(self, prev)"
},
{
"docstring": ":type numRows: int :rtype: List[List[int]]",
"name": "generate",
"signature": "def generate(self, numRows)"
}... | 2 | stack_v2_sparse_classes_30k_train_011746 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextRow(self, prev): :type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)
- def generate(self, numRows): :type numRows: int :rtype: List[List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextRow(self, prev): :type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)
- def generate(self, numRows): :type numRows: int :rtype: List[List[int... | 0521e27097a01a0a2ba2af30f3185d8bb5e3e227 | <|skeleton|>
class Solution:
def nextRow(self, prev):
""":type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)"""
<|body_0|>
def generate(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextRow(self, prev):
""":type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)"""
delay = 0
row = []
for val in prev:
row.append(val + delay)
delay = val
row.append(delay)
return row
def gener... | the_stack_v2_python_sparse | P118-PascalsTriangle/main.py | rlan/LeetCode | train | 0 | |
7def24d98f4b997deb189c2698ed1cd030d796b9 | [
"self.filenames = filenames\nself.cutoff = cutoff\nself.exceptionsToIgnore = exceptionsToIgnore\nself.contactFunction = contactFunction\nself.loadFunction = loadFunction\nself.i = 0",
"if self.i == len(self.filenames):\n raise StopIteration\ntry:\n data = self.loadFunction(self.filenames[self.i])\nexcept tu... | <|body_start_0|>
self.filenames = filenames
self.cutoff = cutoff
self.exceptionsToIgnore = exceptionsToIgnore
self.contactFunction = contactFunction
self.loadFunction = loadFunction
self.i = 0
<|end_body_0|>
<|body_start_1|>
if self.i == len(self.filenames):
... | This is the iterator for the contact map finder | filenameContactMap | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class filenameContactMap:
"""This is the iterator for the contact map finder"""
def __init__(self, filenames, cutoff=1.7, loadFunction=None, exceptionsToIgnore=[], contactFunction=None):
"""Init accepts arguments to initialize the iterator. filenames will be one of the items in the inValue... | stack_v2_sparse_classes_36k_train_013570 | 22,325 | permissive | [
{
"docstring": "Init accepts arguments to initialize the iterator. filenames will be one of the items in the inValues list of the \"averageContacts\" function cutoff and loadFunction should be provided either in classInitArgs or classInitKwargs of averageContacts When initialized, the iterator should store thes... | 2 | stack_v2_sparse_classes_30k_train_017734 | Implement the Python class `filenameContactMap` described below.
Class description:
This is the iterator for the contact map finder
Method signatures and docstrings:
- def __init__(self, filenames, cutoff=1.7, loadFunction=None, exceptionsToIgnore=[], contactFunction=None): Init accepts arguments to initialize the it... | Implement the Python class `filenameContactMap` described below.
Class description:
This is the iterator for the contact map finder
Method signatures and docstrings:
- def __init__(self, filenames, cutoff=1.7, loadFunction=None, exceptionsToIgnore=[], contactFunction=None): Init accepts arguments to initialize the it... | 8052c597b0566f88a7b7ef80658a3f077e474a7e | <|skeleton|>
class filenameContactMap:
"""This is the iterator for the contact map finder"""
def __init__(self, filenames, cutoff=1.7, loadFunction=None, exceptionsToIgnore=[], contactFunction=None):
"""Init accepts arguments to initialize the iterator. filenames will be one of the items in the inValue... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class filenameContactMap:
"""This is the iterator for the contact map finder"""
def __init__(self, filenames, cutoff=1.7, loadFunction=None, exceptionsToIgnore=[], contactFunction=None):
"""Init accepts arguments to initialize the iterator. filenames will be one of the items in the inValues list of the... | the_stack_v2_python_sparse | polychrom/contactmaps.py | open2c/polychrom | train | 24 |
8b822436648f057d0cbec2e6015e4ffdfb4e5fba | [
"super(AdamWeightDecayOptimizer, self).__init__(False, name)\nself.learning_rate = learning_rate\nself.l1_param = l1_weight\nself.l2_param = l2_weight\nself.weight_decay_rate = weight_decay_rate\nself.beta_1 = beta_1\nself.beta_2 = beta_2\nself.epsilon = epsilon\nself.exclude_from_weight_decay = exclude_from_weight... | <|body_start_0|>
super(AdamWeightDecayOptimizer, self).__init__(False, name)
self.learning_rate = learning_rate
self.l1_param = l1_weight
self.l2_param = l2_weight
self.weight_decay_rate = weight_decay_rate
self.beta_1 = beta_1
self.beta_2 = beta_2
self.ep... | A basic Adam optimizer that includes "correct" L2 weight decay. | AdamWeightDecayOptimizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdamWeightDecayOptimizer:
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self, learning_rate, l1_weight=0.0, l2_weight=0.0, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-08, exclude_from_weight_decay=None, exclude_from_l1_reg=None, exclude_fr... | stack_v2_sparse_classes_36k_train_013571 | 18,357 | permissive | [
{
"docstring": "Constructs a AdamWeightDecayOptimizer.",
"name": "__init__",
"signature": "def __init__(self, learning_rate, l1_weight=0.0, l2_weight=0.0, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-08, exclude_from_weight_decay=None, exclude_from_l1_reg=None, exclude_from_l2_reg=None, n... | 6 | stack_v2_sparse_classes_30k_train_002149 | Implement the Python class `AdamWeightDecayOptimizer` described below.
Class description:
A basic Adam optimizer that includes "correct" L2 weight decay.
Method signatures and docstrings:
- def __init__(self, learning_rate, l1_weight=0.0, l2_weight=0.0, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-08, ... | Implement the Python class `AdamWeightDecayOptimizer` described below.
Class description:
A basic Adam optimizer that includes "correct" L2 weight decay.
Method signatures and docstrings:
- def __init__(self, learning_rate, l1_weight=0.0, l2_weight=0.0, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-08, ... | b3c9f0b23713bea88dd2f727e2dac64aeeddaff7 | <|skeleton|>
class AdamWeightDecayOptimizer:
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self, learning_rate, l1_weight=0.0, l2_weight=0.0, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-08, exclude_from_weight_decay=None, exclude_from_l1_reg=None, exclude_fr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdamWeightDecayOptimizer:
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self, learning_rate, l1_weight=0.0, l2_weight=0.0, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-08, exclude_from_weight_decay=None, exclude_from_l1_reg=None, exclude_from_l2_reg=Non... | the_stack_v2_python_sparse | optimization.py | h4ste/cantrip | train | 3 |
d6f54ad509bf7ed2968c828a686f4a77d635f0dd | [
"numTrainDocs = len(trainMatrix)\nnumWords = len(trainMatrix[0])\npAbusive = sum(trainCategory) / float(numTrainDocs)\np0Num = np.ones(numWords)\np1Num = np.ones(numWords)\np0Denom = 2.0\np1Denom = 2.0\nfor i in range(numTrainDocs):\n if trainCategory[i] == 1:\n p1Num += trainMatrix[i]\n p1Denom +=... | <|body_start_0|>
numTrainDocs = len(trainMatrix)
numWords = len(trainMatrix[0])
pAbusive = sum(trainCategory) / float(numTrainDocs)
p0Num = np.ones(numWords)
p1Num = np.ones(numWords)
p0Denom = 2.0
p1Denom = 2.0
for i in range(numTrainDocs):
if... | TrainDoc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainDoc:
def trainNB0(trainMatrix, trainCategory):
"""朴素贝叶斯分类器训练函数 :param trainMatrix: 训练文档矩阵,即setOfWords2Vec返回的returnVec构成的矩阵 :param trainCategory: 训练类标签向量,即create_dataset返回的classVec :return:"""
<|body_0|>
def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
"""朴素贝... | stack_v2_sparse_classes_36k_train_013572 | 4,690 | no_license | [
{
"docstring": "朴素贝叶斯分类器训练函数 :param trainMatrix: 训练文档矩阵,即setOfWords2Vec返回的returnVec构成的矩阵 :param trainCategory: 训练类标签向量,即create_dataset返回的classVec :return:",
"name": "trainNB0",
"signature": "def trainNB0(trainMatrix, trainCategory)"
},
{
"docstring": "朴素贝叶斯分类器分类函数 :param vec2Classify: 待分类的词条数组 :... | 2 | stack_v2_sparse_classes_30k_train_016883 | Implement the Python class `TrainDoc` described below.
Class description:
Implement the TrainDoc class.
Method signatures and docstrings:
- def trainNB0(trainMatrix, trainCategory): 朴素贝叶斯分类器训练函数 :param trainMatrix: 训练文档矩阵,即setOfWords2Vec返回的returnVec构成的矩阵 :param trainCategory: 训练类标签向量,即create_dataset返回的classVec :retur... | Implement the Python class `TrainDoc` described below.
Class description:
Implement the TrainDoc class.
Method signatures and docstrings:
- def trainNB0(trainMatrix, trainCategory): 朴素贝叶斯分类器训练函数 :param trainMatrix: 训练文档矩阵,即setOfWords2Vec返回的returnVec构成的矩阵 :param trainCategory: 训练类标签向量,即create_dataset返回的classVec :retur... | 42b82bab46e00dfbdd6b66a3581f35d62f12d3de | <|skeleton|>
class TrainDoc:
def trainNB0(trainMatrix, trainCategory):
"""朴素贝叶斯分类器训练函数 :param trainMatrix: 训练文档矩阵,即setOfWords2Vec返回的returnVec构成的矩阵 :param trainCategory: 训练类标签向量,即create_dataset返回的classVec :return:"""
<|body_0|>
def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
"""朴素贝... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainDoc:
def trainNB0(trainMatrix, trainCategory):
"""朴素贝叶斯分类器训练函数 :param trainMatrix: 训练文档矩阵,即setOfWords2Vec返回的returnVec构成的矩阵 :param trainCategory: 训练类标签向量,即create_dataset返回的classVec :return:"""
numTrainDocs = len(trainMatrix)
numWords = len(trainMatrix[0])
pAbusive = sum(tra... | the_stack_v2_python_sparse | 朴素贝叶斯/NaiveBayes/BayesSimple.py | LiuX666/Machin_learning | train | 0 | |
4c546a2754add2cc8b169d47b31ab471cd48bd0b | [
"order_warns = []\nnow = datetime.datetime.now()\nnow_5 = now + datetime.timedelta(days=5)\nnow_5.strftime('%Y-%m-%d %H:%M:%S')\nnow.strftime('%Y-%m-%d %H:%M:%S')\npurchase_order = request.env['purchase.order']\nuid = request.env.uid\nuser = request.env.user\nif user.has_group('purchase.group_purchase_manager'):\n ... | <|body_start_0|>
order_warns = []
now = datetime.datetime.now()
now_5 = now + datetime.timedelta(days=5)
now_5.strftime('%Y-%m-%d %H:%M:%S')
now.strftime('%Y-%m-%d %H:%M:%S')
purchase_order = request.env['purchase.order']
uid = request.env.uid
user = reque... | PurchaseController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PurchaseController:
def get_order_planned(self):
"""采购到货情况预测"""
<|body_0|>
def get_product_num_top(self):
"""采购数量TOP5"""
<|body_1|>
def get_product_value_top(self):
"""采购金额TOP5"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
ord... | stack_v2_sparse_classes_36k_train_013573 | 5,330 | no_license | [
{
"docstring": "采购到货情况预测",
"name": "get_order_planned",
"signature": "def get_order_planned(self)"
},
{
"docstring": "采购数量TOP5",
"name": "get_product_num_top",
"signature": "def get_product_num_top(self)"
},
{
"docstring": "采购金额TOP5",
"name": "get_product_value_top",
"sig... | 3 | stack_v2_sparse_classes_30k_train_002445 | Implement the Python class `PurchaseController` described below.
Class description:
Implement the PurchaseController class.
Method signatures and docstrings:
- def get_order_planned(self): 采购到货情况预测
- def get_product_num_top(self): 采购数量TOP5
- def get_product_value_top(self): 采购金额TOP5 | Implement the Python class `PurchaseController` described below.
Class description:
Implement the PurchaseController class.
Method signatures and docstrings:
- def get_order_planned(self): 采购到货情况预测
- def get_product_num_top(self): 采购数量TOP5
- def get_product_value_top(self): 采购金额TOP5
<|skeleton|>
class PurchaseContro... | f45a562b1bd962697f096e7f7bc57b131b3e11f3 | <|skeleton|>
class PurchaseController:
def get_order_planned(self):
"""采购到货情况预测"""
<|body_0|>
def get_product_num_top(self):
"""采购数量TOP5"""
<|body_1|>
def get_product_value_top(self):
"""采购金额TOP5"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PurchaseController:
def get_order_planned(self):
"""采购到货情况预测"""
order_warns = []
now = datetime.datetime.now()
now_5 = now + datetime.timedelta(days=5)
now_5.strftime('%Y-%m-%d %H:%M:%S')
now.strftime('%Y-%m-%d %H:%M:%S')
purchase_order = request.env['pu... | the_stack_v2_python_sparse | edit_being/qyaddons/ct_purchase_home/controllers/main.py | marvin981973/odoo-2 | train | 0 | |
b9b5028ffd889d338bf44ee0a6c9102b632b5fd5 | [
"self.queue = [1]\nself.p1 = 0\nself.past5min = {1: 0}\nself.p2 = 0\nself.numOfHits = {1: 0}",
"if self.p1 >= len(self.queue):\n self.queue.append(timestamp)\n self.past5min[timestamp] = 1\n self.numOfHits[timestamp] = 1\nelif self.queue[self.p2] == timestamp:\n lastTime = self.queue[self.p2]\n sel... | <|body_start_0|>
self.queue = [1]
self.p1 = 0
self.past5min = {1: 0}
self.p2 = 0
self.numOfHits = {1: 0}
<|end_body_0|>
<|body_start_1|>
if self.p1 >= len(self.queue):
self.queue.append(timestamp)
self.past5min[timestamp] = 1
self.numO... | HitCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp):
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity). :type timestamp: int :rtype: void"""
<|body_1|>
def getHit... | stack_v2_sparse_classes_36k_train_013574 | 1,661 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Record a hit. @param timestamp - The current timestamp (in seconds granularity). :type timestamp: int :rtype: void",
"name": "hit",
"signature": "def hit(self, ... | 3 | stack_v2_sparse_classes_30k_train_011401 | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp): Record a hit. @param timestamp - The current timestamp (in seconds granularity). :type ti... | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp): Record a hit. @param timestamp - The current timestamp (in seconds granularity). :type ti... | 15f012927dc34b5d751af6633caa5e8882d26ff7 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp):
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity). :type timestamp: int :rtype: void"""
<|body_1|>
def getHit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
self.queue = [1]
self.p1 = 0
self.past5min = {1: 0}
self.p2 = 0
self.numOfHits = {1: 0}
def hit(self, timestamp):
"""Record a hit. @param timestamp - The current timestamp (i... | the_stack_v2_python_sparse | python/362.DesignHitCounter.py | MaxPoon/Leetcode | train | 15 | |
bf4ca549cec0eefcc8df7d96e98d7a0933000892 | [
"super(DomainAliasAPITestCase, cls).setUpTestData()\nfactories.populate_database()\ncls.dom_alias1 = factories.DomainAliasFactory(name='dalias1.com', target__name='test.com')\ncls.dom_alias2 = factories.DomainAliasFactory(name='dalias2.com', target__name='test2.com')\ncls.da_token = Token.objects.create(user=core_m... | <|body_start_0|>
super(DomainAliasAPITestCase, cls).setUpTestData()
factories.populate_database()
cls.dom_alias1 = factories.DomainAliasFactory(name='dalias1.com', target__name='test.com')
cls.dom_alias2 = factories.DomainAliasFactory(name='dalias2.com', target__name='test2.com')
... | Check DomainAlias API. | DomainAliasAPITestCase | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DomainAliasAPITestCase:
"""Check DomainAlias API."""
def setUpTestData(cls):
"""Create test data."""
<|body_0|>
def test_get(self):
"""Retrieve a list of domain aliases."""
<|body_1|>
def test_post(self):
"""Try to create a new domain alias."... | stack_v2_sparse_classes_36k_train_013575 | 33,144 | permissive | [
{
"docstring": "Create test data.",
"name": "setUpTestData",
"signature": "def setUpTestData(cls)"
},
{
"docstring": "Retrieve a list of domain aliases.",
"name": "test_get",
"signature": "def test_get(self)"
},
{
"docstring": "Try to create a new domain alias.",
"name": "tes... | 5 | stack_v2_sparse_classes_30k_test_000740 | Implement the Python class `DomainAliasAPITestCase` described below.
Class description:
Check DomainAlias API.
Method signatures and docstrings:
- def setUpTestData(cls): Create test data.
- def test_get(self): Retrieve a list of domain aliases.
- def test_post(self): Try to create a new domain alias.
- def test_put(... | Implement the Python class `DomainAliasAPITestCase` described below.
Class description:
Check DomainAlias API.
Method signatures and docstrings:
- def setUpTestData(cls): Create test data.
- def test_get(self): Retrieve a list of domain aliases.
- def test_post(self): Try to create a new domain alias.
- def test_put(... | df699aab0799ec1725b6b89be38e56285821c889 | <|skeleton|>
class DomainAliasAPITestCase:
"""Check DomainAlias API."""
def setUpTestData(cls):
"""Create test data."""
<|body_0|>
def test_get(self):
"""Retrieve a list of domain aliases."""
<|body_1|>
def test_post(self):
"""Try to create a new domain alias."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DomainAliasAPITestCase:
"""Check DomainAlias API."""
def setUpTestData(cls):
"""Create test data."""
super(DomainAliasAPITestCase, cls).setUpTestData()
factories.populate_database()
cls.dom_alias1 = factories.DomainAliasFactory(name='dalias1.com', target__name='test.com')
... | the_stack_v2_python_sparse | modoboa/admin/api/v1/tests.py | modoboa/modoboa | train | 2,201 |
6128271c4a241f3fb72a4b31f44290074421c4df | [
"super(MultiModalClassifier, self).__init__()\nself.nheads = nheads\nself.height = pool_height\nself.width = pool_width\nself.depth = pool_depth\nself.dropout = nn.Dropout(p=0.5)\nself.intermediate = int(intermediate)\nself.FC = nn.Linear(self.height * self.width * self.depth, self.intermediate)\nself.attn_FC = nn.... | <|body_start_0|>
super(MultiModalClassifier, self).__init__()
self.nheads = nheads
self.height = pool_height
self.width = pool_width
self.depth = pool_depth
self.dropout = nn.Dropout(p=0.5)
self.intermediate = int(intermediate)
self.FC = nn.Linear(self.hei... | Head classifier | MultiModalClassifier | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiModalClassifier:
"""Head classifier"""
def __init__(self, pool_height, pool_width, pool_depth, intermediate, nheads, ncls):
"""Initialize a Head object :param pool_height: The height of the output ROI pool :param pool_width: the width of the output ROI pool :param pool_depth: th... | stack_v2_sparse_classes_36k_train_013576 | 2,292 | permissive | [
{
"docstring": "Initialize a Head object :param pool_height: The height of the output ROI pool :param pool_width: the width of the output ROI pool :param pool_depth: the depth of the output ROI pool :param intermediate: the dimensionality of the intermediate FC layer :param ncls: the number of classes",
"na... | 2 | null | Implement the Python class `MultiModalClassifier` described below.
Class description:
Head classifier
Method signatures and docstrings:
- def __init__(self, pool_height, pool_width, pool_depth, intermediate, nheads, ncls): Initialize a Head object :param pool_height: The height of the output ROI pool :param pool_widt... | Implement the Python class `MultiModalClassifier` described below.
Class description:
Head classifier
Method signatures and docstrings:
- def __init__(self, pool_height, pool_width, pool_depth, intermediate, nheads, ncls): Initialize a Head object :param pool_height: The height of the output ROI pool :param pool_widt... | 5ed4a4c149e03773690668437d2f93aa532453c6 | <|skeleton|>
class MultiModalClassifier:
"""Head classifier"""
def __init__(self, pool_height, pool_width, pool_depth, intermediate, nheads, ncls):
"""Initialize a Head object :param pool_height: The height of the output ROI pool :param pool_width: the width of the output ROI pool :param pool_depth: th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiModalClassifier:
"""Head classifier"""
def __init__(self, pool_height, pool_width, pool_depth, intermediate, nheads, ncls):
"""Initialize a Head object :param pool_height: The height of the output ROI pool :param pool_width: the width of the output ROI pool :param pool_depth: the depth of th... | the_stack_v2_python_sparse | cosmos/ingestion/ingest/process/detection/src/torch_model/model/head/object_classifier.py | UW-COSMOS/Cosmos | train | 39 |
26c0e2bfc5816e8dc0bd21e658a6b0adca637d41 | [
"if not isinstance(batch_size, int) or batch_size < 1:\n raise ValueError(f'Batch size must be a positive integer, but got {batch_size}')\nelif batch_size == 1:\n raise ValueError('This is a batch acquisition function. If batch-size is 1, use the single-point acquisition instead')\nself.model = model\nself.ac... | <|body_start_0|>
if not isinstance(batch_size, int) or batch_size < 1:
raise ValueError(f'Batch size must be a positive integer, but got {batch_size}')
elif batch_size == 1:
raise ValueError('This is a batch acquisition function. If batch-size is 1, use the single-point acquisiti... | Batch point calculator. This point calculator calculates the first point in the batch using a single-point acquisition function, and then selects the rest of the points uniformly at random | GreedyRandomBatchPointCalculator | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GreedyRandomBatchPointCalculator:
"""Batch point calculator. This point calculator calculates the first point in the batch using a single-point acquisition function, and then selects the rest of the points uniformly at random"""
def __init__(self, model: IModel, acquisition: Acquisition, acq... | stack_v2_sparse_classes_36k_train_013577 | 9,291 | permissive | [
{
"docstring": ":param model: Model that is used by the acquisition function :param acquisition: Acquisition to be optimized to find each point in batch :param acquisition_optimizer: Acquisition optimizer that optimizes acquisition function to find each point in batch :param batch_size: Number of points to calc... | 2 | null | Implement the Python class `GreedyRandomBatchPointCalculator` described below.
Class description:
Batch point calculator. This point calculator calculates the first point in the batch using a single-point acquisition function, and then selects the rest of the points uniformly at random
Method signatures and docstring... | Implement the Python class `GreedyRandomBatchPointCalculator` described below.
Class description:
Batch point calculator. This point calculator calculates the first point in the batch using a single-point acquisition function, and then selects the rest of the points uniformly at random
Method signatures and docstring... | 40bab526af6562653c42dbb32b174524c44ce2ba | <|skeleton|>
class GreedyRandomBatchPointCalculator:
"""Batch point calculator. This point calculator calculates the first point in the batch using a single-point acquisition function, and then selects the rest of the points uniformly at random"""
def __init__(self, model: IModel, acquisition: Acquisition, acq... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GreedyRandomBatchPointCalculator:
"""Batch point calculator. This point calculator calculates the first point in the batch using a single-point acquisition function, and then selects the rest of the points uniformly at random"""
def __init__(self, model: IModel, acquisition: Acquisition, acquisition_opti... | the_stack_v2_python_sparse | PyStationB/libraries/GlobalPenalisation/gp/calculators.py | mebristo/station-b-libraries | train | 0 |
ead78d6107264d1609a27f38e0a5edb009369176 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SubscribedSku()",
"from .entity import Entity\nfrom .license_units_detail import LicenseUnitsDetail\nfrom .service_plan_info import ServicePlanInfo\nfrom .entity import Entity\nfrom .license_units_detail import LicenseUnitsDetail\nfrom... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SubscribedSku()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .license_units_detail import LicenseUnitsDetail
from .service_plan_info import ServicePlanInfo
... | SubscribedSku | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscribedSku:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SubscribedSku:
"""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... | stack_v2_sparse_classes_36k_train_013578 | 5,146 | 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: SubscribedSku",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | null | Implement the Python class `SubscribedSku` described below.
Class description:
Implement the SubscribedSku class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SubscribedSku: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `SubscribedSku` described below.
Class description:
Implement the SubscribedSku class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SubscribedSku: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SubscribedSku:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SubscribedSku:
"""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... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubscribedSku:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SubscribedSku:
"""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: SubscribedSk... | the_stack_v2_python_sparse | msgraph/generated/models/subscribed_sku.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
eb82dc3a97647cf6c4ca89d86135ce11cc88a391 | [
"slow = fast = head\nwhile fast and fast.next:\n slow, fast = (slow.next, fast.next.next)\npre, length = (None, 0)\nwhile slow:\n slow.next, pre, slow = (pre, slow, slow.next)\nwhile pre:\n if head.val != pre.val:\n return False\n head, pre = (head.next, pre.next)\nreturn True",
"size, node = (... | <|body_start_0|>
slow = fast = head
while fast and fast.next:
slow, fast = (slow.next, fast.next.next)
pre, length = (None, 0)
while slow:
slow.next, pre, slow = (pre, slow, slow.next)
while pre:
if head.val != pre.val:
return F... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""先快慢指针找出中间的(奇数)或中点的下一个(偶数),然后从它开始反序后面一半,最后比较两部分即可"""
<|body_0|>
def isPalindrome2(self, head: ListNode) -> bool:
"""计数法找中间的节点,效率不高"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
slow = fas... | stack_v2_sparse_classes_36k_train_013579 | 1,565 | permissive | [
{
"docstring": "先快慢指针找出中间的(奇数)或中点的下一个(偶数),然后从它开始反序后面一半,最后比较两部分即可",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head: ListNode) -> bool"
},
{
"docstring": "计数法找中间的节点,效率不高",
"name": "isPalindrome2",
"signature": "def isPalindrome2(self, head: ListNode) -> bool"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head: ListNode) -> bool: 先快慢指针找出中间的(奇数)或中点的下一个(偶数),然后从它开始反序后面一半,最后比较两部分即可
- def isPalindrome2(self, head: ListNode) -> bool: 计数法找中间的节点,效率不高 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head: ListNode) -> bool: 先快慢指针找出中间的(奇数)或中点的下一个(偶数),然后从它开始反序后面一半,最后比较两部分即可
- def isPalindrome2(self, head: ListNode) -> bool: 计数法找中间的节点,效率不高
<|skeleton|>
c... | d203aecd1afe1af13a0384a9c657c8424aab322d | <|skeleton|>
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""先快慢指针找出中间的(奇数)或中点的下一个(偶数),然后从它开始反序后面一半,最后比较两部分即可"""
<|body_0|>
def isPalindrome2(self, head: ListNode) -> bool:
"""计数法找中间的节点,效率不高"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""先快慢指针找出中间的(奇数)或中点的下一个(偶数),然后从它开始反序后面一半,最后比较两部分即可"""
slow = fast = head
while fast and fast.next:
slow, fast = (slow.next, fast.next.next)
pre, length = (None, 0)
while slow:
slow.next, ... | the_stack_v2_python_sparse | easy/Q234_PalindromeLinkedList.py | Kaciras/leetcode | train | 0 | |
27795b5319530924f8965bd153da6102a426834e | [
"self.driver.get(login_url)\nlogin_title = self.driver.find_element(Login_Locator.LOGIN_TITLE).text\ntt_check.assertEqual('手机快捷登录', login_title, '登录页面的title,期望是手机快捷登录,实际是%s' % login_title)",
"self.driver.get(login_url)\nself.driver.find_element(Login_Locator.LOGIN_PASSWORD_LOGIN).click()\nsleep(2)\nself.driver.fi... | <|body_start_0|>
self.driver.get(login_url)
login_title = self.driver.find_element(Login_Locator.LOGIN_TITLE).text
tt_check.assertEqual('手机快捷登录', login_title, '登录页面的title,期望是手机快捷登录,实际是%s' % login_title)
<|end_body_0|>
<|body_start_1|>
self.driver.get(login_url)
self.driver.find_... | Login | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login:
def test_login_title(self):
"""测试登录页面的Title显示的是否正确@author:zhangyanli"""
<|body_0|>
def login(self):
"""手机号密码登录M站"""
<|body_1|>
def test_login_passwordlogin(self):
"""测试手机号密码登录@author:zhangyanli"""
<|body_2|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_013580 | 2,174 | no_license | [
{
"docstring": "测试登录页面的Title显示的是否正确@author:zhangyanli",
"name": "test_login_title",
"signature": "def test_login_title(self)"
},
{
"docstring": "手机号密码登录M站",
"name": "login",
"signature": "def login(self)"
},
{
"docstring": "测试手机号密码登录@author:zhangyanli",
"name": "test_login_pa... | 3 | stack_v2_sparse_classes_30k_train_021470 | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- def test_login_title(self): 测试登录页面的Title显示的是否正确@author:zhangyanli
- def login(self): 手机号密码登录M站
- def test_login_passwordlogin(self): 测试手机号密码登录@author:zhangyanli | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- def test_login_title(self): 测试登录页面的Title显示的是否正确@author:zhangyanli
- def login(self): 手机号密码登录M站
- def test_login_passwordlogin(self): 测试手机号密码登录@author:zhangyanli
<|skeleton|>
class Log... | 204856bd33c06d25f2970eba13799db75d4fd4fe | <|skeleton|>
class Login:
def test_login_title(self):
"""测试登录页面的Title显示的是否正确@author:zhangyanli"""
<|body_0|>
def login(self):
"""手机号密码登录M站"""
<|body_1|>
def test_login_passwordlogin(self):
"""测试手机号密码登录@author:zhangyanli"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Login:
def test_login_title(self):
"""测试登录页面的Title显示的是否正确@author:zhangyanli"""
self.driver.get(login_url)
login_title = self.driver.find_element(Login_Locator.LOGIN_TITLE).text
tt_check.assertEqual('手机快捷登录', login_title, '登录页面的title,期望是手机快捷登录,实际是%s' % login_title)
def logi... | the_stack_v2_python_sparse | mc/taocheM/test_login/test_login.py | boeai/mc | train | 0 | |
68edfb9888274b111beb4f45ebc052cbe9332fc0 | [
"factor_dict = get_factor_dict()\n_factor_provider = HDFDataProvider(factor_dict[factor_name]['abs_path'], start_time, end_time)\n_rebcalculator = load_rebcalculator(reb_type, start_time, end_time)\n_quote_provider = HDFDataProvider(factor_dict['ADJ_CLOSE']['abs_path'], start_time, end_time)\nif universe is None:\n... | <|body_start_0|>
factor_dict = get_factor_dict()
_factor_provider = HDFDataProvider(factor_dict[factor_name]['abs_path'], start_time, end_time)
_rebcalculator = load_rebcalculator(reb_type, start_time, end_time)
_quote_provider = HDFDataProvider(factor_dict['ADJ_CLOSE']['abs_path'], star... | 计算因子(rank)IC的衰减情况 具体如下: 假设计算10期IC衰减情况,则分别计算每一个滞后期对应的IC的序列,然后求平均值,返回这10期的 所有的IC平均值 | ICDecay | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ICDecay:
"""计算因子(rank)IC的衰减情况 具体如下: 假设计算10期IC衰减情况,则分别计算每一个滞后期对应的IC的序列,然后求平均值,返回这10期的 所有的IC平均值"""
def __init__(self, factor_name, start_time, end_time, universe=None, period_num=10, reb_type=MONTHLY):
"""Parameter --------- factor_name: str 因子名称,要求能在fmanager.get_factor_dict中找到 start_t... | stack_v2_sparse_classes_36k_train_013581 | 16,864 | no_license | [
{
"docstring": "Parameter --------- factor_name: str 因子名称,要求能在fmanager.get_factor_dict中找到 start_time: datetime like 测试的开始时间 end_time: datetime like 测试的结束时间 universe: str 使用的universe名称,要求能在fmanager.list_allfactor()中找到 period_num: int, default 10 IC衰减的最大期数 reb_type: str, default MONTHLY 换仓日计算的规则,目前只支持月度(MONTHLY)和... | 2 | stack_v2_sparse_classes_30k_train_002090 | Implement the Python class `ICDecay` described below.
Class description:
计算因子(rank)IC的衰减情况 具体如下: 假设计算10期IC衰减情况,则分别计算每一个滞后期对应的IC的序列,然后求平均值,返回这10期的 所有的IC平均值
Method signatures and docstrings:
- def __init__(self, factor_name, start_time, end_time, universe=None, period_num=10, reb_type=MONTHLY): Parameter --------- fact... | Implement the Python class `ICDecay` described below.
Class description:
计算因子(rank)IC的衰减情况 具体如下: 假设计算10期IC衰减情况,则分别计算每一个滞后期对应的IC的序列,然后求平均值,返回这10期的 所有的IC平均值
Method signatures and docstrings:
- def __init__(self, factor_name, start_time, end_time, universe=None, period_num=10, reb_type=MONTHLY): Parameter --------- fact... | 4080154dbf05781f3b48f551ee830d9f66687f87 | <|skeleton|>
class ICDecay:
"""计算因子(rank)IC的衰减情况 具体如下: 假设计算10期IC衰减情况,则分别计算每一个滞后期对应的IC的序列,然后求平均值,返回这10期的 所有的IC平均值"""
def __init__(self, factor_name, start_time, end_time, universe=None, period_num=10, reb_type=MONTHLY):
"""Parameter --------- factor_name: str 因子名称,要求能在fmanager.get_factor_dict中找到 start_t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ICDecay:
"""计算因子(rank)IC的衰减情况 具体如下: 假设计算10期IC衰减情况,则分别计算每一个滞后期对应的IC的序列,然后求平均值,返回这10期的 所有的IC平均值"""
def __init__(self, factor_name, start_time, end_time, universe=None, period_num=10, reb_type=MONTHLY):
"""Parameter --------- factor_name: str 因子名称,要求能在fmanager.get_factor_dict中找到 start_time: datetime... | the_stack_v2_python_sparse | factortest/correlation.py | rlcjj/GeneralLib | train | 0 |
b9b60ae99182eeb485d0d831a8866da4aeda77a3 | [
"self.port = localPort or _getFreePort()\nself.controlSocket = '/tmp/sshtunnel-control-socket-' + str(self.port)\nfwdSpec = [str(self.port), fwdHost, str(fwdPort)]\nif localAddress:\n fwdSpec.insert(0, localAddress)\nargs = ['ssh', '-N', '-T', '-L', ':'.join(fwdSpec), '-x', '-c', cipher, '-f', '-M', '-S', self.c... | <|body_start_0|>
self.port = localPort or _getFreePort()
self.controlSocket = '/tmp/sshtunnel-control-socket-' + str(self.port)
fwdSpec = [str(self.port), fwdHost, str(fwdPort)]
if localAddress:
fwdSpec.insert(0, localAddress)
args = ['ssh', '-N', '-T', '-L', ':'.join... | Class implementing SSH tunneling of TCP port(s). Instance of this class starts separate SSH process configured for TCP forwarding. Instance also controls lifetime of the process, when instance disappears the process is killed. | SSHTunnel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSHTunnel:
"""Class implementing SSH tunneling of TCP port(s). Instance of this class starts separate SSH process configured for TCP forwarding. Instance also controls lifetime of the process, when instance disappears the process is killed."""
def __init__(self, host, localPort, fwdHost, fwd... | stack_v2_sparse_classes_36k_train_013582 | 6,487 | no_license | [
{
"docstring": "Start SSH tunnelling with specified parameters. This can generate same exceptions as subprocess.check_call method. @param host: String, host name or IP address to SSH to. @param localPort: Local port number (or range) that SSH will listen to, pass 0 to try to auto-select port number, use `port` ... | 2 | stack_v2_sparse_classes_30k_val_001054 | Implement the Python class `SSHTunnel` described below.
Class description:
Class implementing SSH tunneling of TCP port(s). Instance of this class starts separate SSH process configured for TCP forwarding. Instance also controls lifetime of the process, when instance disappears the process is killed.
Method signature... | Implement the Python class `SSHTunnel` described below.
Class description:
Class implementing SSH tunneling of TCP port(s). Instance of this class starts separate SSH process configured for TCP forwarding. Instance also controls lifetime of the process, when instance disappears the process is killed.
Method signature... | 97016932a752c0e641571538912d309cd3dd461b | <|skeleton|>
class SSHTunnel:
"""Class implementing SSH tunneling of TCP port(s). Instance of this class starts separate SSH process configured for TCP forwarding. Instance also controls lifetime of the process, when instance disappears the process is killed."""
def __init__(self, host, localPort, fwdHost, fwd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSHTunnel:
"""Class implementing SSH tunneling of TCP port(s). Instance of this class starts separate SSH process configured for TCP forwarding. Instance also controls lifetime of the process, when instance disappears the process is killed."""
def __init__(self, host, localPort, fwdHost, fwdPort, localAd... | the_stack_v2_python_sparse | admin/python/lsst/qserv/admin/ssh.py | provingground-moe/qserv | train | 0 |
90e08401cf50ef80d42fcfa6c388650e5fc09d54 | [
"if not vertex:\n return jsonify_response({'error': 'Vertex not found'}, 404)\ncore_vertices = CoreVertexInheritsFromTemplate.get_all_template_inheritors(template_id)\nschema = CoreVertexListSchema(many=True)\nresponse = json.loads(schema.dumps(core_vertices).data)\nreturn jsonify_response(response, 200)",
"if... | <|body_start_0|>
if not vertex:
return jsonify_response({'error': 'Vertex not found'}, 404)
core_vertices = CoreVertexInheritsFromTemplate.get_all_template_inheritors(template_id)
schema = CoreVertexListSchema(many=True)
response = json.loads(schema.dumps(core_vertices).data)... | Contains the GET and POST views required for listing and creating children CoreVertices in a given Team or CoreVertex | ListCreateCoreVertexView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListCreateCoreVertexView:
"""Contains the GET and POST views required for listing and creating children CoreVertices in a given Team or CoreVertex"""
def get(self, vertex=None, vertex_type=None, vertex_id=None, template_id=None):
"""Returns all corevertices that inherit from the give... | stack_v2_sparse_classes_36k_train_013583 | 44,865 | no_license | [
{
"docstring": "Returns all corevertices that inherit from the given template id",
"name": "get",
"signature": "def get(self, vertex=None, vertex_type=None, vertex_id=None, template_id=None)"
},
{
"docstring": "Creates the core vertex instance of the given type as well as and edge from the paren... | 2 | stack_v2_sparse_classes_30k_train_012038 | Implement the Python class `ListCreateCoreVertexView` described below.
Class description:
Contains the GET and POST views required for listing and creating children CoreVertices in a given Team or CoreVertex
Method signatures and docstrings:
- def get(self, vertex=None, vertex_type=None, vertex_id=None, template_id=N... | Implement the Python class `ListCreateCoreVertexView` described below.
Class description:
Contains the GET and POST views required for listing and creating children CoreVertices in a given Team or CoreVertex
Method signatures and docstrings:
- def get(self, vertex=None, vertex_type=None, vertex_id=None, template_id=N... | 00434985013b65fe45b0a8c8a7f0b50bb727087a | <|skeleton|>
class ListCreateCoreVertexView:
"""Contains the GET and POST views required for listing and creating children CoreVertices in a given Team or CoreVertex"""
def get(self, vertex=None, vertex_type=None, vertex_id=None, template_id=None):
"""Returns all corevertices that inherit from the give... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListCreateCoreVertexView:
"""Contains the GET and POST views required for listing and creating children CoreVertices in a given Team or CoreVertex"""
def get(self, vertex=None, vertex_type=None, vertex_id=None, template_id=None):
"""Returns all corevertices that inherit from the given template id... | the_stack_v2_python_sparse | core/views.py | gingerComms/gingerCommsAPIs | train | 0 |
50953792f24878356effe2ffa9914110391200c4 | [
"self.__zmq_context = None\n'\\n The ZMQ context.\\n\\n :type: Context\\n '\nself.__zmq_controller = None\n'\\n The socket for communicating with the controller.\\n\\n :type: zmq.sugar.socket.Socket\\n '\nself._io = io\n'\\n The output decorator.\\n\\n :type: ... | <|body_start_0|>
self.__zmq_context = None
'\n The ZMQ context.\n\n :type: Context\n '
self.__zmq_controller = None
'\n The socket for communicating with the controller.\n\n :type: zmq.sugar.socket.Socket\n '
self._io = io
'\n ... | A client for requesting the controller to load new schedules. | LoadScheduleClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadScheduleClient:
"""A client for requesting the controller to load new schedules."""
def __init__(self, io):
"""Object constructor. :param enarksh.style.EnarkshStyle.EnarkshStyle io: The output decorator."""
<|body_0|>
def main(self, filenames):
"""The main fu... | stack_v2_sparse_classes_36k_train_013584 | 3,440 | permissive | [
{
"docstring": "Object constructor. :param enarksh.style.EnarkshStyle.EnarkshStyle io: The output decorator.",
"name": "__init__",
"signature": "def __init__(self, io)"
},
{
"docstring": "The main function of load_schedule. :param list[str] filenames: The filenames of the schedules to be loaded.... | 4 | null | Implement the Python class `LoadScheduleClient` described below.
Class description:
A client for requesting the controller to load new schedules.
Method signatures and docstrings:
- def __init__(self, io): Object constructor. :param enarksh.style.EnarkshStyle.EnarkshStyle io: The output decorator.
- def main(self, fi... | Implement the Python class `LoadScheduleClient` described below.
Class description:
A client for requesting the controller to load new schedules.
Method signatures and docstrings:
- def __init__(self, io): Object constructor. :param enarksh.style.EnarkshStyle.EnarkshStyle io: The output decorator.
- def main(self, fi... | ec0c33cdae4a0afeea37928743abd744ef291a9f | <|skeleton|>
class LoadScheduleClient:
"""A client for requesting the controller to load new schedules."""
def __init__(self, io):
"""Object constructor. :param enarksh.style.EnarkshStyle.EnarkshStyle io: The output decorator."""
<|body_0|>
def main(self, filenames):
"""The main fu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadScheduleClient:
"""A client for requesting the controller to load new schedules."""
def __init__(self, io):
"""Object constructor. :param enarksh.style.EnarkshStyle.EnarkshStyle io: The output decorator."""
self.__zmq_context = None
'\n The ZMQ context.\n\n :type... | the_stack_v2_python_sparse | enarksh/controller/client/LoadScheduleClient.py | SetBased/py-enarksh | train | 3 |
ea535a8aa694a7a1cb0be6f8fd329edcb9eb2c1e | [
"self.attempt_number = attempt_number\nself.job_run_id = job_run_id\nself.started_time_usecs = started_time_usecs",
"if dictionary is None:\n return None\nattempt_number = dictionary.get('attemptNumber')\njob_run_id = dictionary.get('jobRunId')\nstarted_time_usecs = dictionary.get('startedTimeUsecs')\nreturn c... | <|body_start_0|>
self.attempt_number = attempt_number
self.job_run_id = job_run_id
self.started_time_usecs = started_time_usecs
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
attempt_number = dictionary.get('attemptNumber')
job_run_id = di... | Implementation of the 'SnapshotAttempt' model. Specifies information about a single snapshot. Attributes: attempt_number (long|int): Specifies the number of the attempts made by the Job Run to capture a snapshot of the object. For example, if an snapshot is successfully captured after three attempts, this field equals ... | SnapshotAttempt | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnapshotAttempt:
"""Implementation of the 'SnapshotAttempt' model. Specifies information about a single snapshot. Attributes: attempt_number (long|int): Specifies the number of the attempts made by the Job Run to capture a snapshot of the object. For example, if an snapshot is successfully captur... | stack_v2_sparse_classes_36k_train_013585 | 2,267 | permissive | [
{
"docstring": "Constructor for the SnapshotAttempt class",
"name": "__init__",
"signature": "def __init__(self, attempt_number=None, job_run_id=None, started_time_usecs=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary repr... | 2 | stack_v2_sparse_classes_30k_train_012054 | Implement the Python class `SnapshotAttempt` described below.
Class description:
Implementation of the 'SnapshotAttempt' model. Specifies information about a single snapshot. Attributes: attempt_number (long|int): Specifies the number of the attempts made by the Job Run to capture a snapshot of the object. For example... | Implement the Python class `SnapshotAttempt` described below.
Class description:
Implementation of the 'SnapshotAttempt' model. Specifies information about a single snapshot. Attributes: attempt_number (long|int): Specifies the number of the attempts made by the Job Run to capture a snapshot of the object. For example... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SnapshotAttempt:
"""Implementation of the 'SnapshotAttempt' model. Specifies information about a single snapshot. Attributes: attempt_number (long|int): Specifies the number of the attempts made by the Job Run to capture a snapshot of the object. For example, if an snapshot is successfully captur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnapshotAttempt:
"""Implementation of the 'SnapshotAttempt' model. Specifies information about a single snapshot. Attributes: attempt_number (long|int): Specifies the number of the attempts made by the Job Run to capture a snapshot of the object. For example, if an snapshot is successfully captured after thre... | the_stack_v2_python_sparse | cohesity_management_sdk/models/snapshot_attempt.py | cohesity/management-sdk-python | train | 24 |
b7829bbc0eb2913ddfca9ea982b775dae01ac4ab | [
"m = [0] * len(nums)\nm[0] = nums[0]\nfor i in range(1, len(nums)):\n m[i] = max(nums[i] + m[i - 1], nums[i])\nreturn max(m)",
"m = nums[0]\nans = nums[0]\nfor i in range(1, len(nums)):\n m = max(nums[i] + m, nums[i])\n if m > ans:\n ans = m\nreturn ans"
] | <|body_start_0|>
m = [0] * len(nums)
m[0] = nums[0]
for i in range(1, len(nums)):
m[i] = max(nums[i] + m[i - 1], nums[i])
return max(m)
<|end_body_0|>
<|body_start_1|>
m = nums[0]
ans = nums[0]
for i in range(1, len(nums)):
m = max(nums[i]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int DP O(n) Space"""
<|body_0|>
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int DP O(1) Space"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = [0] * len(num... | stack_v2_sparse_classes_36k_train_013586 | 1,045 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int DP O(n) Space",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int DP O(1) Space",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int DP O(n) Space
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int DP O(1) Space | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int DP O(n) Space
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int DP O(1) Space
<|skeleton|>
class So... | 9746205998338fb4d7fd51300a21149c4181fc8f | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int DP O(n) Space"""
<|body_0|>
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int DP O(1) Space"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int DP O(n) Space"""
m = [0] * len(nums)
m[0] = nums[0]
for i in range(1, len(nums)):
m[i] = max(nums[i] + m[i - 1], nums[i])
return max(m)
def maxSubArray(self, nums):
""":... | the_stack_v2_python_sparse | leetcode/dp/5_maxsubarray.py | RuizhenMai/academic-blog | train | 0 | |
32842bcf44d2aa299c34f2d5242a343747c26d9e | [
"for attribute_name in attributes:\n if self._unexpected_attribute_handler:\n self._unexpected_attribute_handler(attribute_name)\n else:\n raise UnexpectedAttributeError(attribute_name)\n\ndef wrapper():\n value = (yield)\n setter(value)\niterator = wrapper()\niterator.next()\nreturn VALUE... | <|body_start_0|>
for attribute_name in attributes:
if self._unexpected_attribute_handler:
self._unexpected_attribute_handler(attribute_name)
else:
raise UnexpectedAttributeError(attribute_name)
def wrapper():
value = (yield)
... | LegacyInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LegacyInterface:
def handle_value(self, name, attributes, setter):
"""Parse element value and report about all nested elements :param name: Element name to parse :param attributes: Unhandled attributes to report :param setter: Setter to handle value"""
<|body_0|>
def handle_... | stack_v2_sparse_classes_36k_train_013587 | 3,955 | no_license | [
{
"docstring": "Parse element value and report about all nested elements :param name: Element name to parse :param attributes: Unhandled attributes to report :param setter: Setter to handle value",
"name": "handle_value",
"signature": "def handle_value(self, name, attributes, setter)"
},
{
"docs... | 5 | null | Implement the Python class `LegacyInterface` described below.
Class description:
Implement the LegacyInterface class.
Method signatures and docstrings:
- def handle_value(self, name, attributes, setter): Parse element value and report about all nested elements :param name: Element name to parse :param attributes: Unh... | Implement the Python class `LegacyInterface` described below.
Class description:
Implement the LegacyInterface class.
Method signatures and docstrings:
- def handle_value(self, name, attributes, setter): Parse element value and report about all nested elements :param name: Element name to parse :param attributes: Unh... | cb9932f5f75d5c6d7889f26d58aee079b4127299 | <|skeleton|>
class LegacyInterface:
def handle_value(self, name, attributes, setter):
"""Parse element value and report about all nested elements :param name: Element name to parse :param attributes: Unhandled attributes to report :param setter: Setter to handle value"""
<|body_0|>
def handle_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LegacyInterface:
def handle_value(self, name, attributes, setter):
"""Parse element value and report about all nested elements :param name: Element name to parse :param attributes: Unhandled attributes to report :param setter: Setter to handle value"""
for attribute_name in attributes:
... | the_stack_v2_python_sparse | sources/utils/parsing/legacy.py | VDOMBoxGroup/runtime2.0 | train | 0 | |
cf682bb3dcc17acf7e88597181093f2f790f54e8 | [
"http_client.HTTPConnection.__init__(self, '')\nself.path = path\nself.sock = None",
"sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\nsock.connect(self.path)\nself.sock = sock"
] | <|body_start_0|>
http_client.HTTPConnection.__init__(self, '')
self.path = path
self.sock = None
<|end_body_0|>
<|body_start_1|>
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(self.path)
self.sock = sock
<|end_body_1|>
| Variant of http_client.HTTPConnection that supports HTTP connections over Unix domain sockets. | UnixSocketConnection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnixSocketConnection:
"""Variant of http_client.HTTPConnection that supports HTTP connections over Unix domain sockets."""
def __init__(self, path):
"""Initialize a Unix domain socket HTTP connection The HTTPConnection __init__ method expects a single argument, which it interprets as... | stack_v2_sparse_classes_36k_train_013588 | 10,120 | no_license | [
{
"docstring": "Initialize a Unix domain socket HTTP connection The HTTPConnection __init__ method expects a single argument, which it interprets as the host to connect to. For this class, we instead interpret the parameter as the filesystem path of the Unix domain socket. :type path: :class:`str` :param path: ... | 2 | stack_v2_sparse_classes_30k_train_000167 | Implement the Python class `UnixSocketConnection` described below.
Class description:
Variant of http_client.HTTPConnection that supports HTTP connections over Unix domain sockets.
Method signatures and docstrings:
- def __init__(self, path): Initialize a Unix domain socket HTTP connection The HTTPConnection __init__... | Implement the Python class `UnixSocketConnection` described below.
Class description:
Variant of http_client.HTTPConnection that supports HTTP connections over Unix domain sockets.
Method signatures and docstrings:
- def __init__(self, path): Initialize a Unix domain socket HTTP connection The HTTPConnection __init__... | a3b6d86a802f28c7ee249fc03523d5e5f0a2e3bd | <|skeleton|>
class UnixSocketConnection:
"""Variant of http_client.HTTPConnection that supports HTTP connections over Unix domain sockets."""
def __init__(self, path):
"""Initialize a Unix domain socket HTTP connection The HTTPConnection __init__ method expects a single argument, which it interprets as... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnixSocketConnection:
"""Variant of http_client.HTTPConnection that supports HTTP connections over Unix domain sockets."""
def __init__(self, path):
"""Initialize a Unix domain socket HTTP connection The HTTPConnection __init__ method expects a single argument, which it interprets as the host to ... | the_stack_v2_python_sparse | venv/Lib/site-packages/vmware/vapi/protocol/client/rpc/http_provider.py | dungla2011/python_pyvmomi_working_sample_vmware_easy | train | 1 |
1954606c6ec2884e57be0f4992d490f2853faf06 | [
"rng, inputs, shared_args = test_utils.get_common_model_test_inputs()\nmodel = bigbird.BigBirdEncoder(**shared_args, block_size=2)\nparams = model.init(rng, inputs)\ny = model.apply(params, inputs)\nself.assertEqual(y.shape, inputs.shape + (shared_args['emb_dim'],))",
"rng, inputs, shared_args = test_utils.get_sm... | <|body_start_0|>
rng, inputs, shared_args = test_utils.get_common_model_test_inputs()
model = bigbird.BigBirdEncoder(**shared_args, block_size=2)
params = model.init(rng, inputs)
y = model.apply(params, inputs)
self.assertEqual(y.shape, inputs.shape + (shared_args['emb_dim'],))
<... | Tests for the Big Bird model. | BigBirdTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BigBirdTest:
"""Tests for the Big Bird model."""
def test_bigbird(self):
"""Tests Big Bird model."""
<|body_0|>
def test_jit_bigbird(self):
"""Tests Big Bird model."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rng, inputs, shared_args = test_... | stack_v2_sparse_classes_36k_train_013589 | 1,726 | permissive | [
{
"docstring": "Tests Big Bird model.",
"name": "test_bigbird",
"signature": "def test_bigbird(self)"
},
{
"docstring": "Tests Big Bird model.",
"name": "test_jit_bigbird",
"signature": "def test_jit_bigbird(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001109 | Implement the Python class `BigBirdTest` described below.
Class description:
Tests for the Big Bird model.
Method signatures and docstrings:
- def test_bigbird(self): Tests Big Bird model.
- def test_jit_bigbird(self): Tests Big Bird model. | Implement the Python class `BigBirdTest` described below.
Class description:
Tests for the Big Bird model.
Method signatures and docstrings:
- def test_bigbird(self): Tests Big Bird model.
- def test_jit_bigbird(self): Tests Big Bird model.
<|skeleton|>
class BigBirdTest:
"""Tests for the Big Bird model."""
... | 1b4929016aba883d2f06fa1a51e343ccdbd631ed | <|skeleton|>
class BigBirdTest:
"""Tests for the Big Bird model."""
def test_bigbird(self):
"""Tests Big Bird model."""
<|body_0|>
def test_jit_bigbird(self):
"""Tests Big Bird model."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BigBirdTest:
"""Tests for the Big Bird model."""
def test_bigbird(self):
"""Tests Big Bird model."""
rng, inputs, shared_args = test_utils.get_common_model_test_inputs()
model = bigbird.BigBirdEncoder(**shared_args, block_size=2)
params = model.init(rng, inputs)
y ... | the_stack_v2_python_sparse | pegasus/flax/models/encoders/bigbird/test_bigbird.py | google-research/pegasus | train | 1,543 |
d20ef590a686da8c01f0c01d51b7106b4a0175ee | [
"self.microblaze = Pmod(mb_info, PMOD_DAC_PROGRAM)\nif value:\n self.write(value)",
"if not 0.0 <= value <= 2.5:\n raise ValueError('Requested value not in range [0.00, 2.50].')\nint_val = int(value / 0.0006105)\ncmd = int_val << 20 | FIXEDGEN\nself.microblaze.write_blocking_command(cmd)"
] | <|body_start_0|>
self.microblaze = Pmod(mb_info, PMOD_DAC_PROGRAM)
if value:
self.write(value)
<|end_body_0|>
<|body_start_1|>
if not 0.0 <= value <= 2.5:
raise ValueError('Requested value not in range [0.00, 2.50].')
int_val = int(value / 0.0006105)
cmd ... | This class controls a Digital to Analog Converter Pmod. The Pmod DA4 (PB 200-245) is an 8 channel 12-bit digital-to-analog converter run via AD5628. Attributes ---------- microblaze : Pmod Microblaze processor instance used by this module. | Pmod_DAC | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pmod_DAC:
"""This class controls a Digital to Analog Converter Pmod. The Pmod DA4 (PB 200-245) is an 8 channel 12-bit digital-to-analog converter run via AD5628. Attributes ---------- microblaze : Pmod Microblaze processor instance used by this module."""
def __init__(self, mb_info, value=No... | stack_v2_sparse_classes_36k_train_013590 | 1,668 | permissive | [
{
"docstring": "Return a new instance of a DAC object. Note ---- The floating point number to be written should be in the range of [0.00, 2.50]. Parameters ---------- mb_info : dict A dictionary storing Microblaze information, such as the IP name and the reset name.",
"name": "__init__",
"signature": "d... | 2 | null | Implement the Python class `Pmod_DAC` described below.
Class description:
This class controls a Digital to Analog Converter Pmod. The Pmod DA4 (PB 200-245) is an 8 channel 12-bit digital-to-analog converter run via AD5628. Attributes ---------- microblaze : Pmod Microblaze processor instance used by this module.
Meth... | Implement the Python class `Pmod_DAC` described below.
Class description:
This class controls a Digital to Analog Converter Pmod. The Pmod DA4 (PB 200-245) is an 8 channel 12-bit digital-to-analog converter run via AD5628. Attributes ---------- microblaze : Pmod Microblaze processor instance used by this module.
Meth... | de6b6fc3a803945d59f8f06523addfe0d9b60a1c | <|skeleton|>
class Pmod_DAC:
"""This class controls a Digital to Analog Converter Pmod. The Pmod DA4 (PB 200-245) is an 8 channel 12-bit digital-to-analog converter run via AD5628. Attributes ---------- microblaze : Pmod Microblaze processor instance used by this module."""
def __init__(self, mb_info, value=No... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pmod_DAC:
"""This class controls a Digital to Analog Converter Pmod. The Pmod DA4 (PB 200-245) is an 8 channel 12-bit digital-to-analog converter run via AD5628. Attributes ---------- microblaze : Pmod Microblaze processor instance used by this module."""
def __init__(self, mb_info, value=None):
... | the_stack_v2_python_sparse | pynq/lib/pmod/pmod_dac.py | schelleg/PYNQ | train | 1 |
1552058a422fc9bce65570bbf0469dc7c96cdb92 | [
"queue = ReEngageQueue.get(self.request.get('queue_uuid'))\nif not queue:\n session = get_current_session()\n queues = get_queues()\n queue = get_list_item(queues, 0)\nif not queue:\n logging.error('Could not find queue. Store URL: %s' % session.get('shop'))\n self.error(404)\n return\nresponse = ... | <|body_start_0|>
queue = ReEngageQueue.get(self.request.get('queue_uuid'))
if not queue:
session = get_current_session()
queues = get_queues()
queue = get_list_item(queues, 0)
if not queue:
logging.error('Could not find queue. Store URL: %s' % sess... | A resource for accessing queues using JSON | ReEngageQueueJSONHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReEngageQueueJSONHandler:
"""A resource for accessing queues using JSON"""
def get(self):
"""Get all queued elements for a shop Unless a queue_uuid is found, in which case it will be used. You'll still need to be logged in, though."""
<|body_0|>
def post(self):
"... | stack_v2_sparse_classes_36k_train_013591 | 12,697 | no_license | [
{
"docstring": "Get all queued elements for a shop Unless a queue_uuid is found, in which case it will be used. You'll still need to be logged in, though.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a new post element in the queue",
"name": "post",
"signature"... | 3 | null | Implement the Python class `ReEngageQueueJSONHandler` described below.
Class description:
A resource for accessing queues using JSON
Method signatures and docstrings:
- def get(self): Get all queued elements for a shop Unless a queue_uuid is found, in which case it will be used. You'll still need to be logged in, tho... | Implement the Python class `ReEngageQueueJSONHandler` described below.
Class description:
A resource for accessing queues using JSON
Method signatures and docstrings:
- def get(self): Get all queued elements for a shop Unless a queue_uuid is found, in which case it will be used. You'll still need to be logged in, tho... | d1e046d5b7bf1ba0febb337a31ec04f5888fb341 | <|skeleton|>
class ReEngageQueueJSONHandler:
"""A resource for accessing queues using JSON"""
def get(self):
"""Get all queued elements for a shop Unless a queue_uuid is found, in which case it will be used. You'll still need to be logged in, though."""
<|body_0|>
def post(self):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReEngageQueueJSONHandler:
"""A resource for accessing queues using JSON"""
def get(self):
"""Get all queued elements for a shop Unless a queue_uuid is found, in which case it will be used. You'll still need to be logged in, though."""
queue = ReEngageQueue.get(self.request.get('queue_uuid... | the_stack_v2_python_sparse | apps/reengage/resources.py | bbarclay/Willet-Referrals | train | 0 |
4dc8b4ffd74e7820e31c62b863b4d643876ba8f5 | [
"self.srcLang = NAME_YAPPN_MAPPINGS[sourceLang]\nself.tgtLang = NAME_YAPPN_MAPPINGS[targetLang]\nself._mappings = {srcRegex: tgtRegex for srcLang, tgtLang, srcRegex, tgtRegex in templates if srcLang == self.srcLang and tgtLang == self.tgtLang}",
"res = None\nfor srcRegex in self._mappings:\n sr = re.compile(sr... | <|body_start_0|>
self.srcLang = NAME_YAPPN_MAPPINGS[sourceLang]
self.tgtLang = NAME_YAPPN_MAPPINGS[targetLang]
self._mappings = {srcRegex: tgtRegex for srcLang, tgtLang, srcRegex, tgtRegex in templates if srcLang == self.srcLang and tgtLang == self.tgtLang}
<|end_body_0|>
<|body_start_1|>
... | Template-based translation using regex | TemplateTranslator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateTranslator:
"""Template-based translation using regex"""
def __init__(self, templates, sourceLang, targetLang):
"""Initialize a TemplateTranslator instance Args: templates (list): a list of (source_lang, target_lang, source_regex, target_regex) tuples sourceLang (str): source... | stack_v2_sparse_classes_36k_train_013592 | 21,856 | no_license | [
{
"docstring": "Initialize a TemplateTranslator instance Args: templates (list): a list of (source_lang, target_lang, source_regex, target_regex) tuples sourceLang (str): source language in full spelling, e.g., 'English' targetLang (str): target language in full spelling, e.g., 'French'",
"name": "__init__"... | 2 | stack_v2_sparse_classes_30k_train_009870 | Implement the Python class `TemplateTranslator` described below.
Class description:
Template-based translation using regex
Method signatures and docstrings:
- def __init__(self, templates, sourceLang, targetLang): Initialize a TemplateTranslator instance Args: templates (list): a list of (source_lang, target_lang, so... | Implement the Python class `TemplateTranslator` described below.
Class description:
Template-based translation using regex
Method signatures and docstrings:
- def __init__(self, templates, sourceLang, targetLang): Initialize a TemplateTranslator instance Args: templates (list): a list of (source_lang, target_lang, so... | 3db60d54f076ea26d45cdbbe194d1cd357f8f1a3 | <|skeleton|>
class TemplateTranslator:
"""Template-based translation using regex"""
def __init__(self, templates, sourceLang, targetLang):
"""Initialize a TemplateTranslator instance Args: templates (list): a list of (source_lang, target_lang, source_regex, target_regex) tuples sourceLang (str): source... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemplateTranslator:
"""Template-based translation using regex"""
def __init__(self, templates, sourceLang, targetLang):
"""Initialize a TemplateTranslator instance Args: templates (list): a list of (source_lang, target_lang, source_regex, target_regex) tuples sourceLang (str): source language in ... | the_stack_v2_python_sparse | tb_utils/rules.py | EthannyDing/text_mining | train | 0 |
7852641014676cb0d6ac6444c5f0ae11da7a5b90 | [
"self.tweetId2UserId = {}\nself.followList = {}\nself.tweetList = []",
"self.tweetList.insert(0, tweetId)\nself.tweetId2UserId[tweetId] = userId\nself.follow(userId, userId)",
"Cnt = 0\nresult = []\nif self.followList.has_key(userId):\n fList = self.followList[userId]\nelse:\n return []\nfor tweetId in se... | <|body_start_0|>
self.tweetId2UserId = {}
self.followList = {}
self.tweetList = []
<|end_body_0|>
<|body_start_1|>
self.tweetList.insert(0, tweetId)
self.tweetId2UserId[tweetId] = userId
self.follow(userId, userId)
<|end_body_1|>
<|body_start_2|>
Cnt = 0
... | Twitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
<|body_1|>
def getNewsFeed(self, userId):
"""Ret... | stack_v2_sparse_classes_36k_train_013593 | 2,732 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet. :type userId: int :type tweetId: int :rtype: void",
"name": "postTweet",
"signature": "def postTweet(self, userId, tweetId)"
},
{
"... | 5 | null | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. :type userId: int :type tweetId: int :rtype: void
- def getNew... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. :type userId: int :type tweetId: int :rtype: void
- def getNew... | ca8fac297e4d0bc078d7b56164a6e4b4be6f7908 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
<|body_1|>
def getNewsFeed(self, userId):
"""Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
self.tweetId2UserId = {}
self.followList = {}
self.tweetList = []
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
self... | the_stack_v2_python_sparse | twitter.py | docooler/leetcodePy | train | 0 | |
cd7d417595c69e70822f29b5615508f12f52bd0f | [
"self.kubeconfig = kubeconfig\nself.name = sname\nself.namespace = namespace\nself.access_modes = access_modes\nself.vol_capacity = vol_capacity\nself.data = {}\nself.selector = selector\nself.storage_class_name = storage_class_name\nself.create_dict()",
"self.data['apiVersion'] = 'v1'\nself.data['kind'] = 'Persi... | <|body_start_0|>
self.kubeconfig = kubeconfig
self.name = sname
self.namespace = namespace
self.access_modes = access_modes
self.vol_capacity = vol_capacity
self.data = {}
self.selector = selector
self.storage_class_name = storage_class_name
self.c... | Handle pvc options | PersistentVolumeClaimConfig | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersistentVolumeClaimConfig:
"""Handle pvc options"""
def __init__(self, sname, namespace, kubeconfig, access_modes=None, vol_capacity='1G', selector=None, storage_class_name=None):
"""constructor for handling pvc options"""
<|body_0|>
def create_dict(self):
"""r... | stack_v2_sparse_classes_36k_train_013594 | 6,676 | permissive | [
{
"docstring": "constructor for handling pvc options",
"name": "__init__",
"signature": "def __init__(self, sname, namespace, kubeconfig, access_modes=None, vol_capacity='1G', selector=None, storage_class_name=None)"
},
{
"docstring": "return a service as a dict",
"name": "create_dict",
... | 2 | null | Implement the Python class `PersistentVolumeClaimConfig` described below.
Class description:
Handle pvc options
Method signatures and docstrings:
- def __init__(self, sname, namespace, kubeconfig, access_modes=None, vol_capacity='1G', selector=None, storage_class_name=None): constructor for handling pvc options
- def... | Implement the Python class `PersistentVolumeClaimConfig` described below.
Class description:
Handle pvc options
Method signatures and docstrings:
- def __init__(self, sname, namespace, kubeconfig, access_modes=None, vol_capacity='1G', selector=None, storage_class_name=None): constructor for handling pvc options
- def... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class PersistentVolumeClaimConfig:
"""Handle pvc options"""
def __init__(self, sname, namespace, kubeconfig, access_modes=None, vol_capacity='1G', selector=None, storage_class_name=None):
"""constructor for handling pvc options"""
<|body_0|>
def create_dict(self):
"""r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersistentVolumeClaimConfig:
"""Handle pvc options"""
def __init__(self, sname, namespace, kubeconfig, access_modes=None, vol_capacity='1G', selector=None, storage_class_name=None):
"""constructor for handling pvc options"""
self.kubeconfig = kubeconfig
self.name = sname
s... | the_stack_v2_python_sparse | openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/src/lib/pvc.py | openshift/openshift-tools | train | 170 |
a64d01b85e8e1b6c8dac788147ac3079ebfef658 | [
"self.yaml_dir = yaml_dir\nself.yaml_list = CaseSelect(self.yaml_dir).get_yaml_list(base_path=self.yaml_dir)\nself.testing = testing\nself.py_cmd = py_cmd\nself.report_dir = os.path.join(os.getcwd(), 'report')",
"for yaml in self.yaml_list:\n for case in YamlLoader(yml=yaml).get_all_case_name():\n last_... | <|body_start_0|>
self.yaml_dir = yaml_dir
self.yaml_list = CaseSelect(self.yaml_dir).get_yaml_list(base_path=self.yaml_dir)
self.testing = testing
self.py_cmd = py_cmd
self.report_dir = os.path.join(os.getcwd(), 'report')
<|end_body_0|>
<|body_start_1|>
for yaml in self.... | 最终执行接口 | Run | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Run:
"""最终执行接口"""
def __init__(self, py_cmd, yaml_dir, testing):
""":param yaml_dir: 所有layer.yml文件夹路径 :param testing: 单个testing.yml文件路径"""
<|body_0|>
def _test_run(self):
"""run some test"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.yaml... | stack_v2_sparse_classes_36k_train_013595 | 2,153 | no_license | [
{
"docstring": ":param yaml_dir: 所有layer.yml文件夹路径 :param testing: 单个testing.yml文件路径",
"name": "__init__",
"signature": "def __init__(self, py_cmd, yaml_dir, testing)"
},
{
"docstring": "run some test",
"name": "_test_run",
"signature": "def _test_run(self)"
}
] | 2 | null | Implement the Python class `Run` described below.
Class description:
最终执行接口
Method signatures and docstrings:
- def __init__(self, py_cmd, yaml_dir, testing): :param yaml_dir: 所有layer.yml文件夹路径 :param testing: 单个testing.yml文件路径
- def _test_run(self): run some test | Implement the Python class `Run` described below.
Class description:
最终执行接口
Method signatures and docstrings:
- def __init__(self, py_cmd, yaml_dir, testing): :param yaml_dir: 所有layer.yml文件夹路径 :param testing: 单个testing.yml文件路径
- def _test_run(self): run some test
<|skeleton|>
class Run:
"""最终执行接口"""
def __i... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class Run:
"""最终执行接口"""
def __init__(self, py_cmd, yaml_dir, testing):
""":param yaml_dir: 所有layer.yml文件夹路径 :param testing: 单个testing.yml文件路径"""
<|body_0|>
def _test_run(self):
"""run some test"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Run:
"""最终执行接口"""
def __init__(self, py_cmd, yaml_dir, testing):
""":param yaml_dir: 所有layer.yml文件夹路径 :param testing: 单个testing.yml文件路径"""
self.yaml_dir = yaml_dir
self.yaml_list = CaseSelect(self.yaml_dir).get_yaml_list(base_path=self.yaml_dir)
self.testing = testing
... | the_stack_v2_python_sparse | framework/e2e/paddleLT/run.py | PaddlePaddle/PaddleTest | train | 42 |
0c98c4fe76afed5eb6280a3a1fcd2f59e1f21f31 | [
"if isinstance(ksize, int):\n self.ksize = (ksize,) * 2\nelse:\n self.ksize = ksize\nif isinstance(stride, int):\n self.stride = (stride,) * 2\nelse:\n self.stride = stride\nif isinstance(pad, int):\n self.pad = (0,) + (pad,) * 2 + (0,)\nelse:\n self.pad = (0,) + tuple(pad) + (0,)\nself.istrainabl... | <|body_start_0|>
if isinstance(ksize, int):
self.ksize = (ksize,) * 2
else:
self.ksize = ksize
if isinstance(stride, int):
self.stride = (stride,) * 2
else:
self.stride = stride
if isinstance(pad, int):
self.pad = (0,) +... | MaxPooling2d | MaxPooling2d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxPooling2d:
"""MaxPooling2d"""
def __init__(self, ksize, stride=1, pad=0):
"""construct max pooling layer Parameters ---------- ksize : int window size stride : int stride of window applications pad : int pad width"""
<|body_0|>
def forward(self, x, training=False):
... | stack_v2_sparse_classes_36k_train_013596 | 2,610 | no_license | [
{
"docstring": "construct max pooling layer Parameters ---------- ksize : int window size stride : int stride of window applications pad : int pad width",
"name": "__init__",
"signature": "def __init__(self, ksize, stride=1, pad=0)"
},
{
"docstring": "spatial max pooling Parameters ---------- x ... | 3 | null | Implement the Python class `MaxPooling2d` described below.
Class description:
MaxPooling2d
Method signatures and docstrings:
- def __init__(self, ksize, stride=1, pad=0): construct max pooling layer Parameters ---------- ksize : int window size stride : int stride of window applications pad : int pad width
- def forw... | Implement the Python class `MaxPooling2d` described below.
Class description:
MaxPooling2d
Method signatures and docstrings:
- def __init__(self, ksize, stride=1, pad=0): construct max pooling layer Parameters ---------- ksize : int window size stride : int stride of window applications pad : int pad width
- def forw... | 77056922f23176065b056d5ca136a43971831969 | <|skeleton|>
class MaxPooling2d:
"""MaxPooling2d"""
def __init__(self, ksize, stride=1, pad=0):
"""construct max pooling layer Parameters ---------- ksize : int window size stride : int stride of window applications pad : int pad width"""
<|body_0|>
def forward(self, x, training=False):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaxPooling2d:
"""MaxPooling2d"""
def __init__(self, ksize, stride=1, pad=0):
"""construct max pooling layer Parameters ---------- ksize : int window size stride : int stride of window applications pad : int pad width"""
if isinstance(ksize, int):
self.ksize = (ksize,) * 2
... | the_stack_v2_python_sparse | prml/neural_networks/layers/pooling.py | zgcgreat/PRML-1 | train | 0 |
df9fb87dfb9bc8c49248359e5af6b19efaceb68a | [
"lines = []\nif self.width <= 0:\n raise ValueError('invalid width %r (must be > 0)' % self.width)\nchunks.reverse()\nwhile chunks:\n cur_line = []\n cur_len = 0\n if lines:\n indent = self.subsequent_indent\n else:\n indent = self.initial_indent\n width = self.width - column_width(i... | <|body_start_0|>
lines = []
if self.width <= 0:
raise ValueError('invalid width %r (must be > 0)' % self.width)
chunks.reverse()
while chunks:
cur_line = []
cur_len = 0
if lines:
indent = self.subsequent_indent
e... | Custom subclass that uses a different word splitter. | TextWrapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextWrapper:
"""Custom subclass that uses a different word splitter."""
def _wrap_chunks(self, chunks):
"""_wrap_chunks(chunks : [string]) -> [string] Original _wrap_chunks use len() to calculate width. This method respect to wide/fullwidth characters for width adjustment."""
... | stack_v2_sparse_classes_36k_train_013597 | 4,115 | permissive | [
{
"docstring": "_wrap_chunks(chunks : [string]) -> [string] Original _wrap_chunks use len() to calculate width. This method respect to wide/fullwidth characters for width adjustment.",
"name": "_wrap_chunks",
"signature": "def _wrap_chunks(self, chunks)"
},
{
"docstring": "_break_word(word : str... | 4 | stack_v2_sparse_classes_30k_train_001797 | Implement the Python class `TextWrapper` described below.
Class description:
Custom subclass that uses a different word splitter.
Method signatures and docstrings:
- def _wrap_chunks(self, chunks): _wrap_chunks(chunks : [string]) -> [string] Original _wrap_chunks use len() to calculate width. This method respect to w... | Implement the Python class `TextWrapper` described below.
Class description:
Custom subclass that uses a different word splitter.
Method signatures and docstrings:
- def _wrap_chunks(self, chunks): _wrap_chunks(chunks : [string]) -> [string] Original _wrap_chunks use len() to calculate width. This method respect to w... | 309b0594ce3f995a023111b6e3518e3a2b038575 | <|skeleton|>
class TextWrapper:
"""Custom subclass that uses a different word splitter."""
def _wrap_chunks(self, chunks):
"""_wrap_chunks(chunks : [string]) -> [string] Original _wrap_chunks use len() to calculate width. This method respect to wide/fullwidth characters for width adjustment."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextWrapper:
"""Custom subclass that uses a different word splitter."""
def _wrap_chunks(self, chunks):
"""_wrap_chunks(chunks : [string]) -> [string] Original _wrap_chunks use len() to calculate width. This method respect to wide/fullwidth characters for width adjustment."""
lines = []
... | the_stack_v2_python_sparse | gfzs/utils/text_wrapper.py | yukihirop/gfzs | train | 0 |
34f64ecdb33041369efe579ab880b9d6d4e951e9 | [
"if not isinstance(value, str):\n raise TypeError(f'<value> should be {str}, {type(value)} is given.')\nif not value:\n raise ValueError('<value> should not be empty.')\nsuper(ExpirationDateExtractor, self.__class__).data_to_convert.fset(self, value)",
"for regex in self.PATTERNS:\n expiration_date_line ... | <|body_start_0|>
if not isinstance(value, str):
raise TypeError(f'<value> should be {str}, {type(value)} is given.')
if not value:
raise ValueError('<value> should not be empty.')
super(ExpirationDateExtractor, self.__class__).data_to_convert.fset(self, value)
<|end_body_... | Provides an interface for the extraction of the expiration date. | ExpirationDateExtractor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpirationDateExtractor:
"""Provides an interface for the extraction of the expiration date."""
def data_to_convert(self, value: str) -> None:
"""Sets the data to convert or work with. :param value: The record to work with. :raise TypeError: When the given :code:`value` is not a :py:... | stack_v2_sparse_classes_36k_train_013598 | 13,419 | permissive | [
{
"docstring": "Sets the data to convert or work with. :param value: The record to work with. :raise TypeError: When the given :code:`value` is not a :py:class:`str`. :raise ValueError: When the given :code:`value` is empty.",
"name": "data_to_convert",
"signature": "def data_to_convert(self, value: str... | 4 | stack_v2_sparse_classes_30k_val_000720 | Implement the Python class `ExpirationDateExtractor` described below.
Class description:
Provides an interface for the extraction of the expiration date.
Method signatures and docstrings:
- def data_to_convert(self, value: str) -> None: Sets the data to convert or work with. :param value: The record to work with. :ra... | Implement the Python class `ExpirationDateExtractor` described below.
Class description:
Provides an interface for the extraction of the expiration date.
Method signatures and docstrings:
- def data_to_convert(self, value: str) -> None: Sets the data to convert or work with. :param value: The record to work with. :ra... | 214a57d0eca3df7c4ed3421937aaff9998452ba6 | <|skeleton|>
class ExpirationDateExtractor:
"""Provides an interface for the extraction of the expiration date."""
def data_to_convert(self, value: str) -> None:
"""Sets the data to convert or work with. :param value: The record to work with. :raise TypeError: When the given :code:`value` is not a :py:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExpirationDateExtractor:
"""Provides an interface for the extraction of the expiration date."""
def data_to_convert(self, value: str) -> None:
"""Sets the data to convert or work with. :param value: The record to work with. :raise TypeError: When the given :code:`value` is not a :py:class:`str`. ... | the_stack_v2_python_sparse | PyFunceble/query/whois/converter/expiration_date.py | funilrys/PyFunceble | train | 267 |
a52197b59eda44c3b937a925affb83433f628d98 | [
"super().__init__()\nself.op_space_pd = OperationalSpacePD(Kp, Kd, robot_model)\nself.robot_model = self.op_space_pd.robot_model\n_, self.ee_quat_desired = self.robot_model.forward_kinematics(joint_pos_current)",
"ee_pose_desired = T.from_rot_xyz(rotation=R.from_quat(self.ee_quat_desired), translation=ee_pos_desi... | <|body_start_0|>
super().__init__()
self.op_space_pd = OperationalSpacePD(Kp, Kd, robot_model)
self.robot_model = self.op_space_pd.robot_model
_, self.ee_quat_desired = self.robot_model.forward_kinematics(joint_pos_current)
<|end_body_0|>
<|body_start_1|>
ee_pose_desired = T.fro... | PD feedback control in operational space, but with position only. Feedback forces are computed in Cartesian space, then projected back into joint space. nA is the action dimension and N is the number of degrees of freedom Module parameters: - op_space_pd.Kp: P gain matrix of shape (6, 6) - op_space_pd.Kd: D gain matrix... | OperationalSpacePositionPD | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OperationalSpacePositionPD:
"""PD feedback control in operational space, but with position only. Feedback forces are computed in Cartesian space, then projected back into joint space. nA is the action dimension and N is the number of degrees of freedom Module parameters: - op_space_pd.Kp: P gain ... | stack_v2_sparse_classes_36k_train_013599 | 9,060 | permissive | [
{
"docstring": "Args: Kp: P gain matrix of shape (6, 6) or shape (6,) representing a 6-by-6 diagonal matrix (if nA=6) Kd: D gain matrix of shape (6, 6) or shape (6,) representing a 6-by-6 diagonal matrix (if nA=6) joint_pos_current: Current joint position of shape (N,) robot_model: A valid robot model module fr... | 2 | stack_v2_sparse_classes_30k_train_019570 | Implement the Python class `OperationalSpacePositionPD` described below.
Class description:
PD feedback control in operational space, but with position only. Feedback forces are computed in Cartesian space, then projected back into joint space. nA is the action dimension and N is the number of degrees of freedom Modul... | Implement the Python class `OperationalSpacePositionPD` described below.
Class description:
PD feedback control in operational space, but with position only. Feedback forces are computed in Cartesian space, then projected back into joint space. nA is the action dimension and N is the number of degrees of freedom Modul... | 1b2ea8528d4fb9ad72cec9c766be4cbdbdf76f18 | <|skeleton|>
class OperationalSpacePositionPD:
"""PD feedback control in operational space, but with position only. Feedback forces are computed in Cartesian space, then projected back into joint space. nA is the action dimension and N is the number of degrees of freedom Module parameters: - op_space_pd.Kp: P gain ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OperationalSpacePositionPD:
"""PD feedback control in operational space, but with position only. Feedback forces are computed in Cartesian space, then projected back into joint space. nA is the action dimension and N is the number of degrees of freedom Module parameters: - op_space_pd.Kp: P gain matrix of sha... | the_stack_v2_python_sparse | polymetis/python/torchcontrol/modules/feedback.py | facebookresearch/polymetis | train | 44 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.