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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
31f0bd7136afe448ad779e5e410cbb5770c1711d | [
"user = db.User.find_one(User.user_id == user_id)\nroles = db.Role.all()\nif not user:\n return self.make_response('Unable to find the user requested, might have been removed', HTTP.NOT_FOUND)\nreturn self.make_response({'user': user.to_json(), 'roles': roles}, HTTP.OK)",
"self.reqparse.add_argument('roles', t... | <|body_start_0|>
user = db.User.find_one(User.user_id == user_id)
roles = db.Role.all()
if not user:
return self.make_response('Unable to find the user requested, might have been removed', HTTP.NOT_FOUND)
return self.make_response({'user': user.to_json(), 'roles': roles}, HTT... | UserDetails | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDetails:
def get(self, user_id):
"""Returns a specific user"""
<|body_0|>
def put(self, user_id):
"""Update a user object"""
<|body_1|>
def delete(self, user_id):
"""Delete a user"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_026700 | 8,708 | permissive | [
{
"docstring": "Returns a specific user",
"name": "get",
"signature": "def get(self, user_id)"
},
{
"docstring": "Update a user object",
"name": "put",
"signature": "def put(self, user_id)"
},
{
"docstring": "Delete a user",
"name": "delete",
"signature": "def delete(self... | 3 | null | Implement the Python class `UserDetails` described below.
Class description:
Implement the UserDetails class.
Method signatures and docstrings:
- def get(self, user_id): Returns a specific user
- def put(self, user_id): Update a user object
- def delete(self, user_id): Delete a user | Implement the Python class `UserDetails` described below.
Class description:
Implement the UserDetails class.
Method signatures and docstrings:
- def get(self, user_id): Returns a specific user
- def put(self, user_id): Update a user object
- def delete(self, user_id): Delete a user
<|skeleton|>
class UserDetails:
... | 29a26c705381fdba3538b4efedb25b9e09b387ed | <|skeleton|>
class UserDetails:
def get(self, user_id):
"""Returns a specific user"""
<|body_0|>
def put(self, user_id):
"""Update a user object"""
<|body_1|>
def delete(self, user_id):
"""Delete a user"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserDetails:
def get(self, user_id):
"""Returns a specific user"""
user = db.User.find_one(User.user_id == user_id)
roles = db.Role.all()
if not user:
return self.make_response('Unable to find the user requested, might have been removed', HTTP.NOT_FOUND)
ret... | the_stack_v2_python_sparse | backend/cloud_inquisitor/plugins/views/users.py | RiotGames/cloud-inquisitor | train | 468 | |
6d4484031f7909f4342eaf4f5e4161bef4299fe8 | [
"with file_util.BaseWriteStream(None) as stream:\n stream.write(b'hello\\n')\n stream.write(b'world')\nmock_write_bytes.assert_has_calls([mock.call(offset=0, data=b'hello\\n', finish=False), mock.call(offset=6, data=b'world', finish=False), mock.call(offset=11)])",
"with file_util.BaseWriteStream(None) as s... | <|body_start_0|>
with file_util.BaseWriteStream(None) as stream:
stream.write(b'hello\n')
stream.write(b'world')
mock_write_bytes.assert_has_calls([mock.call(offset=0, data=b'hello\n', finish=False), mock.call(offset=6, data=b'world', finish=False), mock.call(offset=11)])
<|end_b... | Tests BaseWriteStream functionality. | BaseWriteStreamTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseWriteStreamTest:
"""Tests BaseWriteStream functionality."""
def testFileWrite(self, mock_write_bytes):
"""Tests that file.write is implemented."""
<|body_0|>
def testFileWritelines(self, mock_write_bytes):
"""Tests that file.writelines is implemented."""
... | stack_v2_sparse_classes_36k_train_026701 | 25,687 | permissive | [
{
"docstring": "Tests that file.write is implemented.",
"name": "testFileWrite",
"signature": "def testFileWrite(self, mock_write_bytes)"
},
{
"docstring": "Tests that file.writelines is implemented.",
"name": "testFileWritelines",
"signature": "def testFileWritelines(self, mock_write_by... | 2 | stack_v2_sparse_classes_30k_train_015079 | Implement the Python class `BaseWriteStreamTest` described below.
Class description:
Tests BaseWriteStream functionality.
Method signatures and docstrings:
- def testFileWrite(self, mock_write_bytes): Tests that file.write is implemented.
- def testFileWritelines(self, mock_write_bytes): Tests that file.writelines is... | Implement the Python class `BaseWriteStreamTest` described below.
Class description:
Tests BaseWriteStream functionality.
Method signatures and docstrings:
- def testFileWrite(self, mock_write_bytes): Tests that file.write is implemented.
- def testFileWritelines(self, mock_write_bytes): Tests that file.writelines is... | 5e10bed02089e4cf29ae4d9d67e127f77e8fb3c9 | <|skeleton|>
class BaseWriteStreamTest:
"""Tests BaseWriteStream functionality."""
def testFileWrite(self, mock_write_bytes):
"""Tests that file.write is implemented."""
<|body_0|>
def testFileWritelines(self, mock_write_bytes):
"""Tests that file.writelines is implemented."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseWriteStreamTest:
"""Tests BaseWriteStream functionality."""
def testFileWrite(self, mock_write_bytes):
"""Tests that file.write is implemented."""
with file_util.BaseWriteStream(None) as stream:
stream.write(b'hello\n')
stream.write(b'world')
mock_write... | the_stack_v2_python_sparse | multitest_transport/util/file_util_test.py | maksonlee/multitest_transport | train | 0 |
fd0d4b2d7d92219a66df5994d6159e09e8f963e7 | [
"lookupurl = 'https://itunes.apple.com/lookup?id={}'.format(appid)\nresp = requests.get(lookupurl)\ndata = resp.json()\nreturn data",
"os.makedirs(dirr) if not os.path.isdir(dirr) else False\nfn = dirr + '/' + str(f'{indexx}_') + picurl.split('/')[-1]\nr = requests.get(picurl, stream=True)\nf = open(fn, 'wb')\nfo... | <|body_start_0|>
lookupurl = 'https://itunes.apple.com/lookup?id={}'.format(appid)
resp = requests.get(lookupurl)
data = resp.json()
return data
<|end_body_0|>
<|body_start_1|>
os.makedirs(dirr) if not os.path.isdir(dirr) else False
fn = dirr + '/' + str(f'{indexx}_') + ... | Class for extracting data for apps. | StoreAppData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoreAppData:
"""Class for extracting data for apps."""
def get_raw_app_json(self, appid: str):
"""Retrieve app data. :param appid: ID of ios application. :type appid: str"""
<|body_0|>
def get_images(self, picurl: str, dirr: str, indexx: int):
"""Method for down... | stack_v2_sparse_classes_36k_train_026702 | 5,032 | permissive | [
{
"docstring": "Retrieve app data. :param appid: ID of ios application. :type appid: str",
"name": "get_raw_app_json",
"signature": "def get_raw_app_json(self, appid: str)"
},
{
"docstring": "Method for downloading app images. :param picurl: url of image to download. :type picurl: str :param dir... | 6 | stack_v2_sparse_classes_30k_train_016087 | Implement the Python class `StoreAppData` described below.
Class description:
Class for extracting data for apps.
Method signatures and docstrings:
- def get_raw_app_json(self, appid: str): Retrieve app data. :param appid: ID of ios application. :type appid: str
- def get_images(self, picurl: str, dirr: str, indexx: ... | Implement the Python class `StoreAppData` described below.
Class description:
Class for extracting data for apps.
Method signatures and docstrings:
- def get_raw_app_json(self, appid: str): Retrieve app data. :param appid: ID of ios application. :type appid: str
- def get_images(self, picurl: str, dirr: str, indexx: ... | 6f52c3772e810a0794050e22f3c67257b1a0302c | <|skeleton|>
class StoreAppData:
"""Class for extracting data for apps."""
def get_raw_app_json(self, appid: str):
"""Retrieve app data. :param appid: ID of ios application. :type appid: str"""
<|body_0|>
def get_images(self, picurl: str, dirr: str, indexx: int):
"""Method for down... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StoreAppData:
"""Class for extracting data for apps."""
def get_raw_app_json(self, appid: str):
"""Retrieve app data. :param appid: ID of ios application. :type appid: str"""
lookupurl = 'https://itunes.apple.com/lookup?id={}'.format(appid)
resp = requests.get(lookupurl)
d... | the_stack_v2_python_sparse | ios_data_client/store_data.py | samroon2/ios_data_client | train | 0 |
3a1185f7f8ceabef8d0213e0cbaf435e4e212fb0 | [
"ok = [True]\nfor i in range(1, len(s) + 1):\n ok += (any((ok[j] and s[j:i] in wordDict for j in range(i))),)\nreturn ok[-1]",
"queue = [s]\nvisited = set([s])\nwhile queue:\n front = queue.pop(0)\n if front in wordDict:\n return True\n prefix = ''\n for c in front:\n prefix += c\n ... | <|body_start_0|>
ok = [True]
for i in range(1, len(s) + 1):
ok += (any((ok[j] and s[j:i] in wordDict for j in range(i))),)
return ok[-1]
<|end_body_0|>
<|body_start_1|>
queue = [s]
visited = set([s])
while queue:
front = queue.pop(0)
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
"""另附一段简练的代码,参考LeetCode Discuss https://leetcode.com/discuss/41411/4-lines-in-python :type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak_v0(self, s, wordDict):
"""BFS(广度优先搜索):将当前单词拆分为前后两半,若前缀可以在字... | stack_v2_sparse_classes_36k_train_026703 | 2,717 | no_license | [
{
"docstring": "另附一段简练的代码,参考LeetCode Discuss https://leetcode.com/discuss/41411/4-lines-in-python :type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
},
{
"docstring": "BFS(广度优先搜索):将当前单词拆分为前后两半,若前缀可以在字典dict中找到,则将后缀加入队列。 http:... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): 另附一段简练的代码,参考LeetCode Discuss https://leetcode.com/discuss/41411/4-lines-in-python :type s: str :type wordDict: List[str] :rtype: bool
- def word... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): 另附一段简练的代码,参考LeetCode Discuss https://leetcode.com/discuss/41411/4-lines-in-python :type s: str :type wordDict: List[str] :rtype: bool
- def word... | b5e09f24e8e96454dc99e20281e853fb9fcc85ed | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
"""另附一段简练的代码,参考LeetCode Discuss https://leetcode.com/discuss/41411/4-lines-in-python :type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak_v0(self, s, wordDict):
"""BFS(广度优先搜索):将当前单词拆分为前后两半,若前缀可以在字... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak(self, s, wordDict):
"""另附一段简练的代码,参考LeetCode Discuss https://leetcode.com/discuss/41411/4-lines-in-python :type s: str :type wordDict: List[str] :rtype: bool"""
ok = [True]
for i in range(1, len(s) + 1):
ok += (any((ok[j] and s[j:i] in wordDict for j ... | the_stack_v2_python_sparse | python/139_Word_Break.py | Moby5/myleetcode | train | 2 | |
6731457248c27fca7555424c34fc2eb6bf4a94f8 | [
"parser.add_argument('--no-pylint', action='store_false', help='Disable pylint violations check')\nparser.add_argument('--no-flake8', action='store_false', help='Disable flake8 violations check')\nparser.add_argument('--max', type=int, help='Maximum number of acceptable pylint violations')",
"count = 0\nif not os... | <|body_start_0|>
parser.add_argument('--no-pylint', action='store_false', help='Disable pylint violations check')
parser.add_argument('--no-flake8', action='store_false', help='Disable flake8 violations check')
parser.add_argument('--max', type=int, help='Maximum number of acceptable pylint viol... | Checks for violation in code. | Command | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Checks for violation in code."""
def add_arguments(self, parser):
"""Add arguments to violations command. :param parser: Argument parser."""
<|body_0|>
def handle(self, *args, **options):
"""Command execution."""
<|body_1|>
def handle_pyl... | stack_v2_sparse_classes_36k_train_026704 | 4,115 | no_license | [
{
"docstring": "Add arguments to violations command. :param parser: Argument parser.",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Command execution.",
"name": "handle",
"signature": "def handle(self, *args, **options)"
},
{
"docstri... | 4 | stack_v2_sparse_classes_30k_train_010777 | Implement the Python class `Command` described below.
Class description:
Checks for violation in code.
Method signatures and docstrings:
- def add_arguments(self, parser): Add arguments to violations command. :param parser: Argument parser.
- def handle(self, *args, **options): Command execution.
- def handle_pylint(... | Implement the Python class `Command` described below.
Class description:
Checks for violation in code.
Method signatures and docstrings:
- def add_arguments(self, parser): Add arguments to violations command. :param parser: Argument parser.
- def handle(self, *args, **options): Command execution.
- def handle_pylint(... | 85da16ac8f279e4701428d71421b59ef5694a65f | <|skeleton|>
class Command:
"""Checks for violation in code."""
def add_arguments(self, parser):
"""Add arguments to violations command. :param parser: Argument parser."""
<|body_0|>
def handle(self, *args, **options):
"""Command execution."""
<|body_1|>
def handle_pyl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
"""Checks for violation in code."""
def add_arguments(self, parser):
"""Add arguments to violations command. :param parser: Argument parser."""
parser.add_argument('--no-pylint', action='store_false', help='Disable pylint violations check')
parser.add_argument('--no-flake... | the_stack_v2_python_sparse | app/management/commands/violations.py | SauloNascimento/TrocaDoBem | train | 0 |
d91f500f4ddbb2834173b1bf36586e6b3b09f526 | [
"if not isinstance(model, Model):\n wrapper_warning_logits()\n model = CallableModelWrapper(model, 'logits')\nsuper(DeepFool, self).__init__(model, sess, dtypestr, **kwargs)\nself.structural_kwargs = ['overshoot', 'max_iter', 'clip_max', 'clip_min', 'nb_candidate']",
"assert self.sess is not None, 'Cannot u... | <|body_start_0|>
if not isinstance(model, Model):
wrapper_warning_logits()
model = CallableModelWrapper(model, 'logits')
super(DeepFool, self).__init__(model, sess, dtypestr, **kwargs)
self.structural_kwargs = ['overshoot', 'max_iter', 'clip_max', 'clip_min', 'nb_candidat... | DeepFool is an untargeted & iterative attack which is based on an iterative linearization of the classifier. The implementation here is w.r.t. the L2 norm. Paper link: "https://arxiv.org/pdf/1511.04599.pdf" :param model: cleverhans.model.Model :param sess: tf.Session :param dtypestr: dtype of the data :param kwargs: pa... | DeepFool | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepFool:
"""DeepFool is an untargeted & iterative attack which is based on an iterative linearization of the classifier. The implementation here is w.r.t. the L2 norm. Paper link: "https://arxiv.org/pdf/1511.04599.pdf" :param model: cleverhans.model.Model :param sess: tf.Session :param dtypestr:... | stack_v2_sparse_classes_36k_train_026705 | 9,260 | permissive | [
{
"docstring": "Create a DeepFool instance.",
"name": "__init__",
"signature": "def __init__(self, model, sess, dtypestr='float32', **kwargs)"
},
{
"docstring": "Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`"... | 3 | stack_v2_sparse_classes_30k_train_017231 | Implement the Python class `DeepFool` described below.
Class description:
DeepFool is an untargeted & iterative attack which is based on an iterative linearization of the classifier. The implementation here is w.r.t. the L2 norm. Paper link: "https://arxiv.org/pdf/1511.04599.pdf" :param model: cleverhans.model.Model :... | Implement the Python class `DeepFool` described below.
Class description:
DeepFool is an untargeted & iterative attack which is based on an iterative linearization of the classifier. The implementation here is w.r.t. the L2 norm. Paper link: "https://arxiv.org/pdf/1511.04599.pdf" :param model: cleverhans.model.Model :... | bbe96757fa7daded0090b1d9a26b9c90d7d87c61 | <|skeleton|>
class DeepFool:
"""DeepFool is an untargeted & iterative attack which is based on an iterative linearization of the classifier. The implementation here is w.r.t. the L2 norm. Paper link: "https://arxiv.org/pdf/1511.04599.pdf" :param model: cleverhans.model.Model :param sess: tf.Session :param dtypestr:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepFool:
"""DeepFool is an untargeted & iterative attack which is based on an iterative linearization of the classifier. The implementation here is w.r.t. the L2 norm. Paper link: "https://arxiv.org/pdf/1511.04599.pdf" :param model: cleverhans.model.Model :param sess: tf.Session :param dtypestr: dtype of the... | the_stack_v2_python_sparse | cleverhans/attacks/deep_fool.py | yogeshbalaji/InvGAN | train | 17 |
92df8ae692b8404ceb2977192cfffdcfd50e7711 | [
"results = self.results(query)\nif results is None:\n return 'This is an invalid url'\nreturn create_prompt(results)",
"results = {}\nfor imun in self.imuns:\n result = imun.results(query)\n if result is None:\n return None\n for k, v in result.items():\n results[k] = v\nreturn results"
... | <|body_start_0|>
results = self.results(query)
if results is None:
return 'This is an invalid url'
return create_prompt(results)
<|end_body_0|>
<|body_start_1|>
results = {}
for imun in self.imuns:
result = imun.results(query)
if result is Non... | Wrapper for Multi Image Understanding API. | ImunMultiAPIWrapper | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImunMultiAPIWrapper:
"""Wrapper for Multi Image Understanding API."""
def run(self, query: str) -> str:
"""Run query through Multiple Image Understanding and parse the aggregate result."""
<|body_0|>
def results(self, query: str) -> List[Dict]:
"""Run query throu... | stack_v2_sparse_classes_36k_train_026706 | 21,192 | permissive | [
{
"docstring": "Run query through Multiple Image Understanding and parse the aggregate result.",
"name": "run",
"signature": "def run(self, query: str) -> str"
},
{
"docstring": "Run query through All Image Understanding tools and aggregate the metadata. Args: query: The query to search for. Ret... | 2 | stack_v2_sparse_classes_30k_train_008088 | Implement the Python class `ImunMultiAPIWrapper` described below.
Class description:
Wrapper for Multi Image Understanding API.
Method signatures and docstrings:
- def run(self, query: str) -> str: Run query through Multiple Image Understanding and parse the aggregate result.
- def results(self, query: str) -> List[D... | Implement the Python class `ImunMultiAPIWrapper` described below.
Class description:
Wrapper for Multi Image Understanding API.
Method signatures and docstrings:
- def run(self, query: str) -> str: Run query through Multiple Image Understanding and parse the aggregate result.
- def results(self, query: str) -> List[D... | b8f29af7f3c24cf3a4554bebfa2053064467fbdb | <|skeleton|>
class ImunMultiAPIWrapper:
"""Wrapper for Multi Image Understanding API."""
def run(self, query: str) -> str:
"""Run query through Multiple Image Understanding and parse the aggregate result."""
<|body_0|>
def results(self, query: str) -> List[Dict]:
"""Run query throu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImunMultiAPIWrapper:
"""Wrapper for Multi Image Understanding API."""
def run(self, query: str) -> str:
"""Run query through Multiple Image Understanding and parse the aggregate result."""
results = self.results(query)
if results is None:
return 'This is an invalid url... | the_stack_v2_python_sparse | langchain/utilities/imun.py | microsoft/MM-REACT | train | 705 |
ce8ea60cf9e84cb9919fa10693b6db092c37711b | [
"if len(needle) == 0:\n return 0\nif len(needle) > len(haystack):\n return -1\ni = 0\nwhile i < len(haystack):\n if haystack[i:i + len(needle)] == needle:\n return i\n i += 1\nreturn -1",
"if len(needle) == 0:\n return 0\nif len(needle) > len(haystack):\n return -1\nfor i in range(0, len(... | <|body_start_0|>
if len(needle) == 0:
return 0
if len(needle) > len(haystack):
return -1
i = 0
while i < len(haystack):
if haystack[i:i + len(needle)] == needle:
return i
i += 1
return -1
<|end_body_0|>
<|body_start... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def strStr(self, haystack, needle):
"""use python array slicing :type haystack: str :type needle: str :rtype: int"""
<|body_0|>
def strStr2(self, haystack, needle):
"""two pointers :type haystack: str :type needle: str :rtype: int"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_026707 | 1,367 | no_license | [
{
"docstring": "use python array slicing :type haystack: str :type needle: str :rtype: int",
"name": "strStr",
"signature": "def strStr(self, haystack, needle)"
},
{
"docstring": "two pointers :type haystack: str :type needle: str :rtype: int",
"name": "strStr2",
"signature": "def strStr... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def strStr(self, haystack, needle): use python array slicing :type haystack: str :type needle: str :rtype: int
- def strStr2(self, haystack, needle): two pointers :type haystack:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def strStr(self, haystack, needle): use python array slicing :type haystack: str :type needle: str :rtype: int
- def strStr2(self, haystack, needle): two pointers :type haystack:... | 143aa25f92f3827aa379f29c67a9b7ec3757fef9 | <|skeleton|>
class Solution:
def strStr(self, haystack, needle):
"""use python array slicing :type haystack: str :type needle: str :rtype: int"""
<|body_0|>
def strStr2(self, haystack, needle):
"""two pointers :type haystack: str :type needle: str :rtype: int"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def strStr(self, haystack, needle):
"""use python array slicing :type haystack: str :type needle: str :rtype: int"""
if len(needle) == 0:
return 0
if len(needle) > len(haystack):
return -1
i = 0
while i < len(haystack):
if h... | the_stack_v2_python_sparse | py/leetcode_py/28.py | imsure/tech-interview-prep | train | 0 | |
b910462cc1ae7ea7a155099c74c30ed634092451 | [
"self.mac = mac\nself.name = name\nself.device_policy = device_policy\nself.group_policy_id = group_policy_id",
"if dictionary is None:\n return None\nmac = dictionary.get('mac')\ndevice_policy = dictionary.get('devicePolicy')\nname = dictionary.get('name')\ngroup_policy_id = dictionary.get('groupPolicyId')\nr... | <|body_start_0|>
self.mac = mac
self.name = name
self.device_policy = device_policy
self.group_policy_id = group_policy_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
mac = dictionary.get('mac')
device_policy = dictionary.get('d... | Implementation of the 'provisionNetworkClients' model. TODO: type model description here. Attributes: mac (string): The MAC address of the client. Required. name (string): The display name for the client. Optional. Limited to 255 bytes. device_policy (DevicePolicyEnum): The policy to apply to the specified client. Can ... | ProvisionNetworkClientsModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProvisionNetworkClientsModel:
"""Implementation of the 'provisionNetworkClients' model. TODO: type model description here. Attributes: mac (string): The MAC address of the client. Required. name (string): The display name for the client. Optional. Limited to 255 bytes. device_policy (DevicePolicy... | stack_v2_sparse_classes_36k_train_026708 | 2,493 | permissive | [
{
"docstring": "Constructor for the ProvisionNetworkClientsModel class",
"name": "__init__",
"signature": "def __init__(self, mac=None, device_policy=None, name=None, group_policy_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A di... | 2 | stack_v2_sparse_classes_30k_train_019819 | Implement the Python class `ProvisionNetworkClientsModel` described below.
Class description:
Implementation of the 'provisionNetworkClients' model. TODO: type model description here. Attributes: mac (string): The MAC address of the client. Required. name (string): The display name for the client. Optional. Limited to... | Implement the Python class `ProvisionNetworkClientsModel` described below.
Class description:
Implementation of the 'provisionNetworkClients' model. TODO: type model description here. Attributes: mac (string): The MAC address of the client. Required. name (string): The display name for the client. Optional. Limited to... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class ProvisionNetworkClientsModel:
"""Implementation of the 'provisionNetworkClients' model. TODO: type model description here. Attributes: mac (string): The MAC address of the client. Required. name (string): The display name for the client. Optional. Limited to 255 bytes. device_policy (DevicePolicy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProvisionNetworkClientsModel:
"""Implementation of the 'provisionNetworkClients' model. TODO: type model description here. Attributes: mac (string): The MAC address of the client. Required. name (string): The display name for the client. Optional. Limited to 255 bytes. device_policy (DevicePolicyEnum): The po... | the_stack_v2_python_sparse | meraki_sdk/models/provision_network_clients_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
3cafc44d35d98bff56c5d27a71a4cf8497bb5d83 | [
"super(MajorityVote, self).__init__(raise_error=raise_error)\nself.threshold = threshold\nself.normalizer = normalizer",
"if len(values) == 0:\n if not raise_error:\n return default\n raise ValueError('cannot pick from empty set')\nvalue, freq = values.most_common(1)[0]\nif self.threshold is not None... | <|body_start_0|>
super(MajorityVote, self).__init__(raise_error=raise_error)
self.threshold = threshold
self.normalizer = normalizer
<|end_body_0|>
<|body_start_1|>
if len(values) == 0:
if not raise_error:
return default
raise ValueError('cannot p... | Majority picker that select the most frequent value. This picker returns the default value (or raises an error) if the given list of values is empty or there are multiple-most frequent values. THe picker allows to define an additional threshold (min. frequency) that the most-frequent value has to satisfy. | MajorityVote | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MajorityVote:
"""Majority picker that select the most frequent value. This picker returns the default value (or raises an error) if the given list of values is empty or there are multiple-most frequent values. THe picker allows to define an additional threshold (min. frequency) that the most-freq... | stack_v2_sparse_classes_36k_train_026709 | 11,064 | permissive | [
{
"docstring": "Initialize the optional min. frequency thrshold and normalizer that will be applied to frequency values. Parameters ---------- threshold: float, default=None Additional frequency threshold for the selected value. Ignored if None. normalizer: callable, default=None Normalizer that is applied to t... | 2 | stack_v2_sparse_classes_30k_train_013082 | Implement the Python class `MajorityVote` described below.
Class description:
Majority picker that select the most frequent value. This picker returns the default value (or raises an error) if the given list of values is empty or there are multiple-most frequent values. THe picker allows to define an additional thresh... | Implement the Python class `MajorityVote` described below.
Class description:
Majority picker that select the most frequent value. This picker returns the default value (or raises an error) if the given list of values is empty or there are multiple-most frequent values. THe picker allows to define an additional thresh... | e3d0e04f90468c49f29ca53edc2feb12465c24d5 | <|skeleton|>
class MajorityVote:
"""Majority picker that select the most frequent value. This picker returns the default value (or raises an error) if the given list of values is empty or there are multiple-most frequent values. THe picker allows to define an additional threshold (min. frequency) that the most-freq... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MajorityVote:
"""Majority picker that select the most frequent value. This picker returns the default value (or raises an error) if the given list of values is empty or there are multiple-most frequent values. THe picker allows to define an additional threshold (min. frequency) that the most-frequent value ha... | the_stack_v2_python_sparse | openclean/function/value/picker.py | Denisfench/openclean-core | train | 0 |
3ca5ed0df4bcc2d849361d26554e2ea40fbda0d3 | [
"self.init_args = (args, kw)\nsurface = pgzero.ptext.draw(text, (0, 0), *args, get_surface=True, **kw)\nsuper(Text, self).__init__(surface, *args, **kw)\nself.text = text",
"p = self.pos\nsurface = pgzero.ptext.draw(text, (0, 0), *self.init_args[0], get_surface=True, **self.init_args[1])\nsuper(Text, self).__init... | <|body_start_0|>
self.init_args = (args, kw)
surface = pgzero.ptext.draw(text, (0, 0), *args, get_surface=True, **kw)
super(Text, self).__init__(surface, *args, **kw)
self.text = text
<|end_body_0|>
<|body_start_1|>
p = self.pos
surface = pgzero.ptext.draw(text, (0, 0), ... | Class to show text | Text | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Text:
"""Class to show text"""
def __init__(self, text, *args, **kw):
"""Initialise the text"""
<|body_0|>
def set_text(self, text):
"""Set some text"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.init_args = (args, kw)
surface = p... | stack_v2_sparse_classes_36k_train_026710 | 785 | no_license | [
{
"docstring": "Initialise the text",
"name": "__init__",
"signature": "def __init__(self, text, *args, **kw)"
},
{
"docstring": "Set some text",
"name": "set_text",
"signature": "def set_text(self, text)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002096 | Implement the Python class `Text` described below.
Class description:
Class to show text
Method signatures and docstrings:
- def __init__(self, text, *args, **kw): Initialise the text
- def set_text(self, text): Set some text | Implement the Python class `Text` described below.
Class description:
Class to show text
Method signatures and docstrings:
- def __init__(self, text, *args, **kw): Initialise the text
- def set_text(self, text): Set some text
<|skeleton|>
class Text:
"""Class to show text"""
def __init__(self, text, *args, ... | 99228d5c5648ab12c7f26d31048dba8ef583dcea | <|skeleton|>
class Text:
"""Class to show text"""
def __init__(self, text, *args, **kw):
"""Initialise the text"""
<|body_0|>
def set_text(self, text):
"""Set some text"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Text:
"""Class to show text"""
def __init__(self, text, *args, **kw):
"""Initialise the text"""
self.init_args = (args, kw)
surface = pgzero.ptext.draw(text, (0, 0), *args, get_surface=True, **kw)
super(Text, self).__init__(surface, *args, **kw)
self.text = text
... | the_stack_v2_python_sparse | CreateApplications/pyweek/godel/game/text.py | Asher-1/pythonGames | train | 2 |
c1a38c3e9e77c755e3c99ea75d5df8ad334870e8 | [
"res = self.get(self.INDEX_URN)\nself.assert200(res)\nself.assertEqual(len(res.json['data']), 0)\ncontacts = [Contact(userId=self.user.id, **item) for item in datasets.index.CONTACTS]\ndb.session.add_all(contacts)\ndb.session.commit()\nres = self.get(self.INDEX_URN)\nself.assert200(res)\nfor index, item in enumerat... | <|body_start_0|>
res = self.get(self.INDEX_URN)
self.assert200(res)
self.assertEqual(len(res.json['data']), 0)
contacts = [Contact(userId=self.user.id, **item) for item in datasets.index.CONTACTS]
db.session.add_all(contacts)
db.session.commit()
res = self.get(sel... | TemplatesResourceTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplatesResourceTest:
def test_index_endpoint(self):
"""User's contacts GET index endpoint"""
<|body_0|>
def test_get_endpoint(self):
"""User's contact GET get endpoint"""
<|body_1|>
def test_post_endpoint(self):
"""User's contact POST create en... | stack_v2_sparse_classes_36k_train_026711 | 6,915 | permissive | [
{
"docstring": "User's contacts GET index endpoint",
"name": "test_index_endpoint",
"signature": "def test_index_endpoint(self)"
},
{
"docstring": "User's contact GET get endpoint",
"name": "test_get_endpoint",
"signature": "def test_get_endpoint(self)"
},
{
"docstring": "User's ... | 5 | stack_v2_sparse_classes_30k_train_014605 | Implement the Python class `TemplatesResourceTest` described below.
Class description:
Implement the TemplatesResourceTest class.
Method signatures and docstrings:
- def test_index_endpoint(self): User's contacts GET index endpoint
- def test_get_endpoint(self): User's contact GET get endpoint
- def test_post_endpoin... | Implement the Python class `TemplatesResourceTest` described below.
Class description:
Implement the TemplatesResourceTest class.
Method signatures and docstrings:
- def test_index_endpoint(self): User's contacts GET index endpoint
- def test_get_endpoint(self): User's contact GET get endpoint
- def test_post_endpoin... | 37a3be814fc32ad87eb2a0ecfd93aa46ef46e68d | <|skeleton|>
class TemplatesResourceTest:
def test_index_endpoint(self):
"""User's contacts GET index endpoint"""
<|body_0|>
def test_get_endpoint(self):
"""User's contact GET get endpoint"""
<|body_1|>
def test_post_endpoint(self):
"""User's contact POST create en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemplatesResourceTest:
def test_index_endpoint(self):
"""User's contacts GET index endpoint"""
res = self.get(self.INDEX_URN)
self.assert200(res)
self.assertEqual(len(res.json['data']), 0)
contacts = [Contact(userId=self.user.id, **item) for item in datasets.index.CONTA... | the_stack_v2_python_sparse | smsgw/resources/contacts/api_test.py | jajonsraviation/smsgw | train | 0 | |
940b3518c3329403d367492791ceae1c5c85588e | [
"def dfs(node, ans):\n if not node:\n return\n ans.append(str(node.val))\n dfs(node.left, ans)\n dfs(node.right, ans)\nans = []\ndfs(root, ans)\nreturn ' '.join(ans)",
"dataList = data.split(' ')\nif len(dataList[0]) == 0:\n return []\n\ndef helper(dataList, minV, maxV):\n if not dataList... | <|body_start_0|>
def dfs(node, ans):
if not node:
return
ans.append(str(node.val))
dfs(node.left, ans)
dfs(node.right, ans)
ans = []
dfs(root, ans)
return ' '.join(ans)
<|end_body_0|>
<|body_start_1|>
dataList = dat... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(node, ... | stack_v2_sparse_classes_36k_train_026712 | 1,390 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 2ae3529366227efb5f2ad81a8b039ad71e8d1ed5 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def dfs(node, ans):
if not node:
return
ans.append(str(node.val))
dfs(node.left, ans)
dfs(node.right, ans)
ans = []
dfs(ro... | the_stack_v2_python_sparse | tree/树的结构转化/449. Serialize and Deserialize BST.py | LYXalex/Leetcode-PythonSolution | train | 1 | |
bbc5b6ae7a99d4d3bd03ce22141ef1c005de947c | [
"if num == 0:\n return 'Zero'\nmapping = ['', 'Thousand', 'Million', 'Billion']\nresstr = ''\nfor i in range(len(mapping)):\n if num % 1000 != 0:\n resstr = self.helperths(num % 1000) + mapping[i] + ' ' + resstr\n num /= 1000\nreturn resstr.strip()",
"lesstw = ['', 'One', 'Two', 'Three', 'Four', '... | <|body_start_0|>
if num == 0:
return 'Zero'
mapping = ['', 'Thousand', 'Million', 'Billion']
resstr = ''
for i in range(len(mapping)):
if num % 1000 != 0:
resstr = self.helperths(num % 1000) + mapping[i] + ' ' + resstr
num /= 1000
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numberToWords(self, num):
""":type num: int :rtype: str"""
<|body_0|>
def helperths(self, num):
"""deal with the number less than one thousand"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if num == 0:
return 'Zero'
... | stack_v2_sparse_classes_36k_train_026713 | 1,131 | permissive | [
{
"docstring": ":type num: int :rtype: str",
"name": "numberToWords",
"signature": "def numberToWords(self, num)"
},
{
"docstring": "deal with the number less than one thousand",
"name": "helperths",
"signature": "def helperths(self, num)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numberToWords(self, num): :type num: int :rtype: str
- def helperths(self, num): deal with the number less than one thousand | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numberToWords(self, num): :type num: int :rtype: str
- def helperths(self, num): deal with the number less than one thousand
<|skeleton|>
class Solution:
def numberToWo... | 86f1cb98de801f58c39d9a48ce9de12df7303d20 | <|skeleton|>
class Solution:
def numberToWords(self, num):
""":type num: int :rtype: str"""
<|body_0|>
def helperths(self, num):
"""deal with the number less than one thousand"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numberToWords(self, num):
""":type num: int :rtype: str"""
if num == 0:
return 'Zero'
mapping = ['', 'Thousand', 'Million', 'Billion']
resstr = ''
for i in range(len(mapping)):
if num % 1000 != 0:
resstr = self.helpe... | the_stack_v2_python_sparse | 273-Integer-to-English-Words/solution.py | Tanych/CodeTracking | train | 0 | |
cf603d1c032ffc9d726595322cf4115167caa7c5 | [
"if N == 1:\n return 10\ntemp = 10 ** 9 + 7\ndp = [[0] * 10 for _ in range(N)]\nfor i in range(10):\n dp[0][i] = 1\nfor i in range(1, N):\n dp[i][0] = (dp[i - 1][4] + dp[i - 1][6]) % temp\n dp[i][1] = (dp[i - 1][6] + dp[i - 1][8]) % temp\n dp[i][2] = (dp[i - 1][7] + dp[i - 1][9]) % temp\n dp[i][3]... | <|body_start_0|>
if N == 1:
return 10
temp = 10 ** 9 + 7
dp = [[0] * 10 for _ in range(N)]
for i in range(10):
dp[0][i] = 1
for i in range(1, N):
dp[i][0] = (dp[i - 1][4] + dp[i - 1][6]) % temp
dp[i][1] = (dp[i - 1][6] + dp[i - 1][8... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def knightDialer(self, N):
""":type N: int :rtype: int 552 ms"""
<|body_0|>
def knightDialer_1(self, N):
""":type N: int :rtype: int 80ms 矩阵乘法,斐波那契数列的方法!!!!"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if N == 1:
return 10
... | stack_v2_sparse_classes_36k_train_026714 | 2,749 | no_license | [
{
"docstring": ":type N: int :rtype: int 552 ms",
"name": "knightDialer",
"signature": "def knightDialer(self, N)"
},
{
"docstring": ":type N: int :rtype: int 80ms 矩阵乘法,斐波那契数列的方法!!!!",
"name": "knightDialer_1",
"signature": "def knightDialer_1(self, N)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006609 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def knightDialer(self, N): :type N: int :rtype: int 552 ms
- def knightDialer_1(self, N): :type N: int :rtype: int 80ms 矩阵乘法,斐波那契数列的方法!!!! | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def knightDialer(self, N): :type N: int :rtype: int 552 ms
- def knightDialer_1(self, N): :type N: int :rtype: int 80ms 矩阵乘法,斐波那契数列的方法!!!!
<|skeleton|>
class Solution:
def ... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def knightDialer(self, N):
""":type N: int :rtype: int 552 ms"""
<|body_0|>
def knightDialer_1(self, N):
""":type N: int :rtype: int 80ms 矩阵乘法,斐波那契数列的方法!!!!"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def knightDialer(self, N):
""":type N: int :rtype: int 552 ms"""
if N == 1:
return 10
temp = 10 ** 9 + 7
dp = [[0] * 10 for _ in range(N)]
for i in range(10):
dp[0][i] = 1
for i in range(1, N):
dp[i][0] = (dp[i - 1][... | the_stack_v2_python_sparse | KnightDialer_MID_935.py | 953250587/leetcode-python | train | 2 | |
5629ad020469bb4f0749842a5e0a615cc8c15d4c | [
"Frame.__init__(self, master)\nself.pack()\nself.createAlbumWidgets()",
"top_frame = Frame(self)\nself.labelInput = Label(top_frame, text='Album Name')\nself.text_in = Entry(top_frame)\nself.labelResult = Label(top_frame, text='Result')\nself.labelInput.pack()\nself.text_in.pack()\nself.labelResult.pack()\ntop_fr... | <|body_start_0|>
Frame.__init__(self, master)
self.pack()
self.createAlbumWidgets()
<|end_body_0|>
<|body_start_1|>
top_frame = Frame(self)
self.labelInput = Label(top_frame, text='Album Name')
self.text_in = Entry(top_frame)
self.labelResult = Label(top_frame, t... | Application main window class. | getAlbum_UI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getAlbum_UI:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createAlbumWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_36k_train_026715 | 10,077 | no_license | [
{
"docstring": "Main frame initialization (mostly delegated)",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Add all the widgets to the main frame.",
"name": "createAlbumWidgets",
"signature": "def createAlbumWidgets(self)"
},
{
"docstring"... | 3 | stack_v2_sparse_classes_30k_train_009025 | Implement the Python class `getAlbum_UI` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createAlbumWidgets(self): Add all the widgets to the main frame.
- def handle(self): Handl... | Implement the Python class `getAlbum_UI` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createAlbumWidgets(self): Add all the widgets to the main frame.
- def handle(self): Handl... | 2dba11861f91e4bdc1ef28279132a6d8dd4ccf54 | <|skeleton|>
class getAlbum_UI:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createAlbumWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class getAlbum_UI:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
Frame.__init__(self, master)
self.pack()
self.createAlbumWidgets()
def createAlbumWidgets(self):
"""Add all the widgets to the... | the_stack_v2_python_sparse | Mux_src/Fix_All_Music_Guis.py | rduvalwa5/Mux | train | 0 |
3a68ede989a0413fd7be2365a9831c63b347c8ae | [
"a, ans = ({}, 0)\ni, j = (0, 0)\nwhile i < len(s) and j < len(s):\n if s[j] in a:\n del a[s[i]]\n i += 1\n else:\n a[s[j]] = 1\n ans = max(ans, j - i + 1)\n j += 1\nreturn ans",
"used_char, ans = ({}, 0)\nstart, j = (0, 0)\nfor j in range(len(s)):\n if s[j] in used_cha... | <|body_start_0|>
a, ans = ({}, 0)
i, j = (0, 0)
while i < len(s) and j < len(s):
if s[j] in a:
del a[s[i]]
i += 1
else:
a[s[j]] = 1
ans = max(ans, j - i + 1)
j += 1
return ans
<|end_bo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int Accepted solution. In this solution, when s[j] is in the window, move i, but don't move j"""
<|body_0|>
def lengthOfLongestSubstring1(self, s):
""":type s: str :rtype: int In previous soluti... | stack_v2_sparse_classes_36k_train_026716 | 2,637 | no_license | [
{
"docstring": ":type s: str :rtype: int Accepted solution. In this solution, when s[j] is in the window, move i, but don't move j",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int In previous solution, when s[j... | 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 Accepted solution. In this solution, when s[j] is in the window, move i, but don't move j
- def lengthOfLongestSub... | 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 Accepted solution. In this solution, when s[j] is in the window, move i, but don't move j
- def lengthOfLongestSub... | 22794e5e80f534c41ff81eb40072acaa1346a75c | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int Accepted solution. In this solution, when s[j] is in the window, move i, but don't move j"""
<|body_0|>
def lengthOfLongestSubstring1(self, s):
""":type s: str :rtype: int In previous soluti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int Accepted solution. In this solution, when s[j] is in the window, move i, but don't move j"""
a, ans = ({}, 0)
i, j = (0, 0)
while i < len(s) and j < len(s):
if s[j] in a:
de... | the_stack_v2_python_sparse | 003.py | huosan0123/leetcode-py | train | 0 | |
f068238f44d66169f7d98fdbb4afcb52104b6c63 | [
"if 'sep' in kwargs:\n sep = kwargs.pop('sep')\nelse:\n sep = ';'\nself.fill_values = dict() if fill_values is None else fill_values\nself.df = pd.read_csv(station_meta_csv, sep=sep, **kwargs)",
"vars = []\nfor var in varnames:\n if var in self.fill_values.keys() and (not (var.endswith('_depth_from') or ... | <|body_start_0|>
if 'sep' in kwargs:
sep = kwargs.pop('sep')
else:
sep = ';'
self.fill_values = dict() if fill_values is None else fill_values
self.df = pd.read_csv(station_meta_csv, sep=sep, **kwargs)
<|end_body_0|>
<|body_start_1|>
vars = []
for... | Allows passing (static) metadata for ISMN stations as a csv file. E.g. if the station specific variables provided by the ISMN are not enough. In this case that the metadata must be stored in a csv file with the following structure: network;station;<var1>;<var1>_depth_from;<var1>_depth_to;<var2>;... - where network and ... | CustomStationMetadataCsv | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomStationMetadataCsv:
"""Allows passing (static) metadata for ISMN stations as a csv file. E.g. if the station specific variables provided by the ISMN are not enough. In this case that the metadata must be stored in a csv file with the following structure: network;station;<var1>;<var1>_depth_... | stack_v2_sparse_classes_36k_train_026717 | 8,725 | permissive | [
{
"docstring": "Parameters ---------- station_meta_csv: str Path to the csv file with the above described content fill_values: dict, optional (default: None) Values to use for a certain custom metadata variable, if no match is found. kwargs: Additional kwargs as passed to :func:`pandas.read_csv` To use a differ... | 4 | stack_v2_sparse_classes_30k_val_000751 | Implement the Python class `CustomStationMetadataCsv` described below.
Class description:
Allows passing (static) metadata for ISMN stations as a csv file. E.g. if the station specific variables provided by the ISMN are not enough. In this case that the metadata must be stored in a csv file with the following structur... | Implement the Python class `CustomStationMetadataCsv` described below.
Class description:
Allows passing (static) metadata for ISMN stations as a csv file. E.g. if the station specific variables provided by the ISMN are not enough. In this case that the metadata must be stored in a csv file with the following structur... | 66d798089ff5bd97ad9892f24bf903a8e97be620 | <|skeleton|>
class CustomStationMetadataCsv:
"""Allows passing (static) metadata for ISMN stations as a csv file. E.g. if the station specific variables provided by the ISMN are not enough. In this case that the metadata must be stored in a csv file with the following structure: network;station;<var1>;<var1>_depth_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomStationMetadataCsv:
"""Allows passing (static) metadata for ISMN stations as a csv file. E.g. if the station specific variables provided by the ISMN are not enough. In this case that the metadata must be stored in a csv file with the following structure: network;station;<var1>;<var1>_depth_from;<var1>_d... | the_stack_v2_python_sparse | src/ismn/custom.py | TUW-GEO/ismn | train | 20 |
30c1dbeaa8885cb28c3936e8715c8739e5a14698 | [
"if self.context.get('view').action == 'create':\n if not re.match('^1[3-9]\\\\d{9}$', value):\n raise serializers.ValidationError('手机号格式不正确')\n count = User.objects.filter(mobile=value).count()\n if count > 0:\n raise serializers.ValidationError('手机号已经注册,请务重复注册')\nelif self.context.get('view... | <|body_start_0|>
if self.context.get('view').action == 'create':
if not re.match('^1[3-9]\\d{9}$', value):
raise serializers.ValidationError('手机号格式不正确')
count = User.objects.filter(mobile=value).count()
if count > 0:
raise serializers.Validatio... | 管理员用户列表序列化器类 | PermsAdminsSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermsAdminsSerializer:
"""管理员用户列表序列化器类"""
def validate_mobile(self, value):
"""校验手机号格式"""
<|body_0|>
def validate_username(self, value):
"""如果是更新数据, 用户名不用判断重复"""
<|body_1|>
def create(self, validated_data):
"""密码要加密保存"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_026718 | 3,778 | permissive | [
{
"docstring": "校验手机号格式",
"name": "validate_mobile",
"signature": "def validate_mobile(self, value)"
},
{
"docstring": "如果是更新数据, 用户名不用判断重复",
"name": "validate_username",
"signature": "def validate_username(self, value)"
},
{
"docstring": "密码要加密保存",
"name": "create",
"sign... | 4 | stack_v2_sparse_classes_30k_test_000593 | Implement the Python class `PermsAdminsSerializer` described below.
Class description:
管理员用户列表序列化器类
Method signatures and docstrings:
- def validate_mobile(self, value): 校验手机号格式
- def validate_username(self, value): 如果是更新数据, 用户名不用判断重复
- def create(self, validated_data): 密码要加密保存
- def update(self, instance, validated_... | Implement the Python class `PermsAdminsSerializer` described below.
Class description:
管理员用户列表序列化器类
Method signatures and docstrings:
- def validate_mobile(self, value): 校验手机号格式
- def validate_username(self, value): 如果是更新数据, 用户名不用判断重复
- def create(self, validated_data): 密码要加密保存
- def update(self, instance, validated_... | d3ce2185ec3c68325e8becddce07d0a9da144325 | <|skeleton|>
class PermsAdminsSerializer:
"""管理员用户列表序列化器类"""
def validate_mobile(self, value):
"""校验手机号格式"""
<|body_0|>
def validate_username(self, value):
"""如果是更新数据, 用户名不用判断重复"""
<|body_1|>
def create(self, validated_data):
"""密码要加密保存"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PermsAdminsSerializer:
"""管理员用户列表序列化器类"""
def validate_mobile(self, value):
"""校验手机号格式"""
if self.context.get('view').action == 'create':
if not re.match('^1[3-9]\\d{9}$', value):
raise serializers.ValidationError('手机号格式不正确')
count = User.objects.fi... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/meiduo_admin/serializers/permissions.py | qls7/dianshanghoutai | train | 0 |
750a020a73eb0baafc1b8616cfe3e2419869d908 | [
"if method.upper() == 'GET':\n try:\n self.res = requests.get(url, params=param, headers=header, cookies=cookies)\n except Exception as e:\n self.log.error('报错啦:{0}'.format(e))\nelif method.upper() == 'POST':\n try:\n self.res = requests.post(url, json=param, headers=header, cookies=co... | <|body_start_0|>
if method.upper() == 'GET':
try:
self.res = requests.get(url, params=param, headers=header, cookies=cookies)
except Exception as e:
self.log.error('报错啦:{0}'.format(e))
elif method.upper() == 'POST':
try:
... | HttpRquest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpRquest:
def http_request(self, method, url, param, header, cookies):
""":param method: 请求类型 :param url: 请求地址 :param param: 请求参数 :param header: 请求头部 :param cookies: :return: 请求结果"""
<|body_0|>
def __jsonpr(self, url, method, *args, **kwags):
"""测试执行http请求"""
... | stack_v2_sparse_classes_36k_train_026719 | 2,173 | no_license | [
{
"docstring": ":param method: 请求类型 :param url: 请求地址 :param param: 请求参数 :param header: 请求头部 :param cookies: :return: 请求结果",
"name": "http_request",
"signature": "def http_request(self, method, url, param, header, cookies)"
},
{
"docstring": "测试执行http请求",
"name": "__jsonpr",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_016465 | Implement the Python class `HttpRquest` described below.
Class description:
Implement the HttpRquest class.
Method signatures and docstrings:
- def http_request(self, method, url, param, header, cookies): :param method: 请求类型 :param url: 请求地址 :param param: 请求参数 :param header: 请求头部 :param cookies: :return: 请求结果
- def _... | Implement the Python class `HttpRquest` described below.
Class description:
Implement the HttpRquest class.
Method signatures and docstrings:
- def http_request(self, method, url, param, header, cookies): :param method: 请求类型 :param url: 请求地址 :param param: 请求参数 :param header: 请求头部 :param cookies: :return: 请求结果
- def _... | 75cb922b0c6f7581668f08e3752aff021468cb25 | <|skeleton|>
class HttpRquest:
def http_request(self, method, url, param, header, cookies):
""":param method: 请求类型 :param url: 请求地址 :param param: 请求参数 :param header: 请求头部 :param cookies: :return: 请求结果"""
<|body_0|>
def __jsonpr(self, url, method, *args, **kwags):
"""测试执行http请求"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpRquest:
def http_request(self, method, url, param, header, cookies):
""":param method: 请求类型 :param url: 请求地址 :param param: 请求参数 :param header: 请求头部 :param cookies: :return: 请求结果"""
if method.upper() == 'GET':
try:
self.res = requests.get(url, params=param, heade... | the_stack_v2_python_sparse | common/httprequest.py | xjx985426946/test_api | train | 0 | |
19ac5f24344275f82888143e025ca70b180488c5 | [
"self._prog = re.compile(regex)\nself._stop_words = self.get_stop_words(stop_words)\nif use_stemmer:\n self._stemmer = PorterStemmer()\nelse:\n self._stemmer = None\nif ngrams < 1:\n raise ValueError('ngrams should be >= 1.')\nself._ngrams = ngrams\nself._strip_html = strip_html\nif strip_html:\n self._... | <|body_start_0|>
self._prog = re.compile(regex)
self._stop_words = self.get_stop_words(stop_words)
if use_stemmer:
self._stemmer = PorterStemmer()
else:
self._stemmer = None
if ngrams < 1:
raise ValueError('ngrams should be >= 1.')
self... | A tokenizer for plain text. | _TextTokenizer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TextTokenizer:
"""A tokenizer for plain text."""
def __init__(self, regex, stop_words, use_stemmer, ngrams, strip_html, removable_tags):
"""Initializes an instance a PlainTextTokenizer. Args: regex: A regex to group characters. stop_words: the list of stop_words to use use_stemmer: ... | stack_v2_sparse_classes_36k_train_026720 | 6,736 | permissive | [
{
"docstring": "Initializes an instance a PlainTextTokenizer. Args: regex: A regex to group characters. stop_words: the list of stop_words to use use_stemmer: True if the words should be stemmed. ngrams: The maximum length of ngrams. strip_html: Boolean on whether html_markup should be removed before processing... | 3 | null | Implement the Python class `_TextTokenizer` described below.
Class description:
A tokenizer for plain text.
Method signatures and docstrings:
- def __init__(self, regex, stop_words, use_stemmer, ngrams, strip_html, removable_tags): Initializes an instance a PlainTextTokenizer. Args: regex: A regex to group characters... | Implement the Python class `_TextTokenizer` described below.
Class description:
A tokenizer for plain text.
Method signatures and docstrings:
- def __init__(self, regex, stop_words, use_stemmer, ngrams, strip_html, removable_tags): Initializes an instance a PlainTextTokenizer. Args: regex: A regex to group characters... | afdc2805cb1b77bd5ac9fdd1a76217f4841f0ea6 | <|skeleton|>
class _TextTokenizer:
"""A tokenizer for plain text."""
def __init__(self, regex, stop_words, use_stemmer, ngrams, strip_html, removable_tags):
"""Initializes an instance a PlainTextTokenizer. Args: regex: A regex to group characters. stop_words: the list of stop_words to use use_stemmer: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _TextTokenizer:
"""A tokenizer for plain text."""
def __init__(self, regex, stop_words, use_stemmer, ngrams, strip_html, removable_tags):
"""Initializes an instance a PlainTextTokenizer. Args: regex: A regex to group characters. stop_words: the list of stop_words to use use_stemmer: True if the w... | the_stack_v2_python_sparse | google-cloud-sdk/lib/third_party/cloud_ml_engine_sdk/features/_tokenizer.py | bopopescu/searchparty | train | 0 |
8afbcf0cd7c8848a88f3a9e7f9f17a090479c30d | [
"try:\n return Category.objects.get(pk=pk)\nexcept Category.DoesNotExist:\n raise Http404",
"category = self.get_object(pk)\nserializer = CategorySerializer(category)\nreturn Response(serializer.data)",
"category = self.get_object(pk)\nserializer = CategorySerializer(category, data=request.data)\nif seria... | <|body_start_0|>
try:
return Category.objects.get(pk=pk)
except Category.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
category = self.get_object(pk)
serializer = CategorySerializer(category)
return Response(serializer.data)
<|end_body_1|>
... | Retrieve, update or delete a category instance. | CategoryDetails | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryDetails:
"""Retrieve, update or delete a category instance."""
def get_object(self, pk):
"""Get the perticular row from the table."""
<|body_0|>
def get(self, request, pk, format=None):
"""We are going to add the Category content along with this pull requ... | stack_v2_sparse_classes_36k_train_026721 | 4,310 | permissive | [
{
"docstring": "Get the perticular row from the table.",
"name": "get_object",
"signature": "def get_object(self, pk)"
},
{
"docstring": "We are going to add the Category content along with this pull request",
"name": "get",
"signature": "def get(self, request, pk, format=None)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_019250 | Implement the Python class `CategoryDetails` described below.
Class description:
Retrieve, update or delete a category instance.
Method signatures and docstrings:
- def get_object(self, pk): Get the perticular row from the table.
- def get(self, request, pk, format=None): We are going to add the Category content alon... | Implement the Python class `CategoryDetails` described below.
Class description:
Retrieve, update or delete a category instance.
Method signatures and docstrings:
- def get_object(self, pk): Get the perticular row from the table.
- def get(self, request, pk, format=None): We are going to add the Category content alon... | b0635e72338e14dad24f1ee0329212cd60a3e83a | <|skeleton|>
class CategoryDetails:
"""Retrieve, update or delete a category instance."""
def get_object(self, pk):
"""Get the perticular row from the table."""
<|body_0|>
def get(self, request, pk, format=None):
"""We are going to add the Category content along with this pull requ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoryDetails:
"""Retrieve, update or delete a category instance."""
def get_object(self, pk):
"""Get the perticular row from the table."""
try:
return Category.objects.get(pk=pk)
except Category.DoesNotExist:
raise Http404
def get(self, request, pk,... | the_stack_v2_python_sparse | links/views.py | faisaltheparttimecoder/carelogBackend | train | 1 |
29d14a275ea95e7e79ebc728fb49b1780f55b9b8 | [
"print()\nprint('SalesDoctor - init')\nself.management = management\nself.date_begin = date_begin\nself.date_end = date_end\nself.doctor_line = doctor_line\nself.total_amount = total_amount",
"print()\nprint('SalesDoctor - update')\nself.doctor_line.unlink()\ntotal_amount = 0\ntotal_count = 0\ntotal_tickets = 0\n... | <|body_start_0|>
print()
print('SalesDoctor - init')
self.management = management
self.date_begin = date_begin
self.date_end = date_end
self.doctor_line = doctor_line
self.total_amount = total_amount
<|end_body_0|>
<|body_start_1|>
print()
print('... | Sales Doctor | SalesDoctor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SalesDoctor:
"""Sales Doctor"""
def __init__(self, management, date_begin, date_end, doctor_line, total_amount):
"""Init"""
<|body_0|>
def update(self):
"""Update sales by doctor"""
<|body_1|>
def create_doctor_data(self, doctor_name, orders):
... | stack_v2_sparse_classes_36k_train_026722 | 3,809 | no_license | [
{
"docstring": "Init",
"name": "__init__",
"signature": "def __init__(self, management, date_begin, date_end, doctor_line, total_amount)"
},
{
"docstring": "Update sales by doctor",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Create doctor data",
"nam... | 3 | stack_v2_sparse_classes_30k_train_010168 | Implement the Python class `SalesDoctor` described below.
Class description:
Sales Doctor
Method signatures and docstrings:
- def __init__(self, management, date_begin, date_end, doctor_line, total_amount): Init
- def update(self): Update sales by doctor
- def create_doctor_data(self, doctor_name, orders): Create doc... | Implement the Python class `SalesDoctor` described below.
Class description:
Sales Doctor
Method signatures and docstrings:
- def __init__(self, management, date_begin, date_end, doctor_line, total_amount): Init
- def update(self): Update sales by doctor
- def create_doctor_data(self, doctor_name, orders): Create doc... | c15f8b146392d47a9040404a4ac8e45a1b062198 | <|skeleton|>
class SalesDoctor:
"""Sales Doctor"""
def __init__(self, management, date_begin, date_end, doctor_line, total_amount):
"""Init"""
<|body_0|>
def update(self):
"""Update sales by doctor"""
<|body_1|>
def create_doctor_data(self, doctor_name, orders):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SalesDoctor:
"""Sales Doctor"""
def __init__(self, management, date_begin, date_end, doctor_line, total_amount):
"""Init"""
print()
print('SalesDoctor - init')
self.management = management
self.date_begin = date_begin
self.date_end = date_end
self.d... | the_stack_v2_python_sparse | models/management/sales_doctor.py | gibil5/openhealth | train | 1 |
2e65038d81694c6a61657307a59379f1e85bdd91 | [
"required = []\nfor param in required:\n if not param in params:\n messg = \"PilotShutdownHandler object requires params['%s']\" % param\n numb = 0\n raise WMException(messg, numb)\nmyThread = threading.currentThread()\nfactory = WMFactory('default', 'TQComp.Database.' + myThread.dialect)\ns... | <|body_start_0|>
required = []
for param in required:
if not param in params:
messg = "PilotShutdownHandler object requires params['%s']" % param
numb = 0
raise WMException(messg, numb)
myThread = threading.currentThread()
facto... | Handler for pilot's pilotShutdown message. | PilotShutdownHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PilotShutdownHandler:
"""Handler for pilot's pilotShutdown message."""
def __init__(self, params=None):
"""Constructor. The params argument can be used as a dict for any parameter (if needed). Basic things can be obtained from currentThread. The required params are as follow: (none)"... | stack_v2_sparse_classes_36k_train_026723 | 2,303 | no_license | [
{
"docstring": "Constructor. The params argument can be used as a dict for any parameter (if needed). Basic things can be obtained from currentThread. The required params are as follow: (none)",
"name": "__init__",
"signature": "def __init__(self, params=None)"
},
{
"docstring": "Handles the eve... | 2 | stack_v2_sparse_classes_30k_train_018844 | Implement the Python class `PilotShutdownHandler` described below.
Class description:
Handler for pilot's pilotShutdown message.
Method signatures and docstrings:
- def __init__(self, params=None): Constructor. The params argument can be used as a dict for any parameter (if needed). Basic things can be obtained from ... | Implement the Python class `PilotShutdownHandler` described below.
Class description:
Handler for pilot's pilotShutdown message.
Method signatures and docstrings:
- def __init__(self, params=None): Constructor. The params argument can be used as a dict for any parameter (if needed). Basic things can be obtained from ... | 9575691bd7383e4de8bcdf83714ec71b3fec6aa7 | <|skeleton|>
class PilotShutdownHandler:
"""Handler for pilot's pilotShutdown message."""
def __init__(self, params=None):
"""Constructor. The params argument can be used as a dict for any parameter (if needed). Basic things can be obtained from currentThread. The required params are as follow: (none)"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PilotShutdownHandler:
"""Handler for pilot's pilotShutdown message."""
def __init__(self, params=None):
"""Constructor. The params argument can be used as a dict for any parameter (if needed). Basic things can be obtained from currentThread. The required params are as follow: (none)"""
re... | the_stack_v2_python_sparse | src/python/WMCore/TaskQueue/TQComp/ListenerHandler/PilotShutdownHandler.py | sryufnal/WMCore | train | 0 |
8afbcf0cd7c8848a88f3a9e7f9f17a090479c30d | [
"links = Link.objects.all()\nserializer = LinksSerializer(links, many=True)\nreturn Response(serializer.data)",
"serializer = LinksSerializer(data=request.data)\nif serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\nprint(serializer.errors)\nreturn... | <|body_start_0|>
links = Link.objects.all()
serializer = LinksSerializer(links, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
serializer = LinksSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return ... | List all links, or create a new category. | LinksList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinksList:
"""List all links, or create a new category."""
def get(self, request, format=None):
"""The default get method, i.e on page load"""
<|body_0|>
def post(self, request, format=None):
"""The default post method."""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_026724 | 4,310 | permissive | [
{
"docstring": "The default get method, i.e on page load",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "The default post method.",
"name": "post",
"signature": "def post(self, request, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019782 | Implement the Python class `LinksList` described below.
Class description:
List all links, or create a new category.
Method signatures and docstrings:
- def get(self, request, format=None): The default get method, i.e on page load
- def post(self, request, format=None): The default post method. | Implement the Python class `LinksList` described below.
Class description:
List all links, or create a new category.
Method signatures and docstrings:
- def get(self, request, format=None): The default get method, i.e on page load
- def post(self, request, format=None): The default post method.
<|skeleton|>
class Li... | b0635e72338e14dad24f1ee0329212cd60a3e83a | <|skeleton|>
class LinksList:
"""List all links, or create a new category."""
def get(self, request, format=None):
"""The default get method, i.e on page load"""
<|body_0|>
def post(self, request, format=None):
"""The default post method."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinksList:
"""List all links, or create a new category."""
def get(self, request, format=None):
"""The default get method, i.e on page load"""
links = Link.objects.all()
serializer = LinksSerializer(links, many=True)
return Response(serializer.data)
def post(self, req... | the_stack_v2_python_sparse | links/views.py | faisaltheparttimecoder/carelogBackend | train | 1 |
bdbd754c11e37813d85f9f4dddce157baae4c081 | [
"resource = f'/inspection/api/v1/formGroups/{id}'\nresponse = item_fixture.request('post', resource)\nreturn response",
"resource = f'/inspection/api/v1/formInstances/{id}'\nresponse = item_fixture.request('post', resource)\nreturn response",
"resource = f'/inspection/api/v1/formInstances/{id}'\nresponse = item... | <|body_start_0|>
resource = f'/inspection/api/v1/formGroups/{id}'
response = item_fixture.request('post', resource)
return response
<|end_body_0|>
<|body_start_1|>
resource = f'/inspection/api/v1/formInstances/{id}'
response = item_fixture.request('post', resource)
retur... | 排序 | Sort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sort:
"""排序"""
def formGroupsPOST(self, item_fixture, id=None):
"""建管跳转登录接口 :param item_fixture: item fixture, :param jsgl_token: 建管系统token"""
<|body_0|>
def formInstancesPOST(self, item_fixture, id=None):
"""登录信息查询接口 :param item_fixture: item fixture,"""
... | stack_v2_sparse_classes_36k_train_026725 | 1,219 | no_license | [
{
"docstring": "建管跳转登录接口 :param item_fixture: item fixture, :param jsgl_token: 建管系统token",
"name": "formGroupsPOST",
"signature": "def formGroupsPOST(self, item_fixture, id=None)"
},
{
"docstring": "登录信息查询接口 :param item_fixture: item fixture,",
"name": "formInstancesPOST",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_005202 | Implement the Python class `Sort` described below.
Class description:
排序
Method signatures and docstrings:
- def formGroupsPOST(self, item_fixture, id=None): 建管跳转登录接口 :param item_fixture: item fixture, :param jsgl_token: 建管系统token
- def formInstancesPOST(self, item_fixture, id=None): 登录信息查询接口 :param item_fixture: ite... | Implement the Python class `Sort` described below.
Class description:
排序
Method signatures and docstrings:
- def formGroupsPOST(self, item_fixture, id=None): 建管跳转登录接口 :param item_fixture: item fixture, :param jsgl_token: 建管系统token
- def formInstancesPOST(self, item_fixture, id=None): 登录信息查询接口 :param item_fixture: ite... | f875de62f7f505c596ea5567e1fc2c8a64010f87 | <|skeleton|>
class Sort:
"""排序"""
def formGroupsPOST(self, item_fixture, id=None):
"""建管跳转登录接口 :param item_fixture: item fixture, :param jsgl_token: 建管系统token"""
<|body_0|>
def formInstancesPOST(self, item_fixture, id=None):
"""登录信息查询接口 :param item_fixture: item fixture,"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Sort:
"""排序"""
def formGroupsPOST(self, item_fixture, id=None):
"""建管跳转登录接口 :param item_fixture: item fixture, :param jsgl_token: 建管系统token"""
resource = f'/inspection/api/v1/formGroups/{id}'
response = item_fixture.request('post', resource)
return response
def formIn... | the_stack_v2_python_sparse | swagger/api/inspection/sort.py | zhangjingwen198817/pytest-api-allure | train | 1 |
12b346b372625e2892dd5240fc02808a4560ccfe | [
"log_test_case(self.case_config_map[fs_wrapper.CASE_NAME_ATTR], 'ui_phone_case8 : case Start')\nglobal case_flag\ncase_flag = False\nstart_activity('com.android.dialer', 'com.android.dialer.DialtactsActivity')\nphone.go_home()\nclear_flag = phone.clear_call_log()\nsleep(3)\nif clear_flag and (not search_text('10086... | <|body_start_0|>
log_test_case(self.case_config_map[fs_wrapper.CASE_NAME_ATTR], 'ui_phone_case8 : case Start')
global case_flag
case_flag = False
start_activity('com.android.dialer', 'com.android.dialer.DialtactsActivity')
phone.go_home()
clear_flag = phone.clear_call_log... | test_suit_ui_contact_case1 is a class for add a new contact @see: L{TestCaseBase <TestCaseBase>} | test_suit_ui_phone_case8 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_suit_ui_phone_case8:
"""test_suit_ui_contact_case1 is a class for add a new contact @see: L{TestCaseBase <TestCaseBase>}"""
def test_case_main(self, case_results):
"""main entry. @type case_results: tuple @param case_results: record some case result information"""
<|body... | stack_v2_sparse_classes_36k_train_026726 | 1,837 | no_license | [
{
"docstring": "main entry. @type case_results: tuple @param case_results: record some case result information",
"name": "test_case_main",
"signature": "def test_case_main(self, case_results)"
},
{
"docstring": "record the case result",
"name": "test_case_end",
"signature": "def test_cas... | 2 | null | Implement the Python class `test_suit_ui_phone_case8` described below.
Class description:
test_suit_ui_contact_case1 is a class for add a new contact @see: L{TestCaseBase <TestCaseBase>}
Method signatures and docstrings:
- def test_case_main(self, case_results): main entry. @type case_results: tuple @param case_resul... | Implement the Python class `test_suit_ui_phone_case8` described below.
Class description:
test_suit_ui_contact_case1 is a class for add a new contact @see: L{TestCaseBase <TestCaseBase>}
Method signatures and docstrings:
- def test_case_main(self, case_results): main entry. @type case_results: tuple @param case_resul... | a04b717ae437511abae1e7e9e399373c161a7b65 | <|skeleton|>
class test_suit_ui_phone_case8:
"""test_suit_ui_contact_case1 is a class for add a new contact @see: L{TestCaseBase <TestCaseBase>}"""
def test_case_main(self, case_results):
"""main entry. @type case_results: tuple @param case_results: record some case result information"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_suit_ui_phone_case8:
"""test_suit_ui_contact_case1 is a class for add a new contact @see: L{TestCaseBase <TestCaseBase>}"""
def test_case_main(self, case_results):
"""main entry. @type case_results: tuple @param case_results: record some case result information"""
log_test_case(self.... | the_stack_v2_python_sparse | test_env/test_suit_ui_phone/test_suit_ui_phone_case8.py | wwlwwlqaz/Qualcomm | train | 1 |
1d4f4e6f207fad81c4bca588960f3a2c7664535d | [
"if self.request.method in permissions.SAFE_METHODS:\n return (permissions.IsAuthenticated(),)\nreturn (permissions.IsAuthenticated(), IsAdminOfTeam())",
"serializer = self.serializer_class(data=request.data)\nif serializer.is_valid():\n team = get_object_or_404(Team.objects.all(), name=serializer.validated... | <|body_start_0|>
if self.request.method in permissions.SAFE_METHODS:
return (permissions.IsAuthenticated(),)
return (permissions.IsAuthenticated(), IsAdminOfTeam())
<|end_body_0|>
<|body_start_1|>
serializer = self.serializer_class(data=request.data)
if serializer.is_valid()... | MemberInTeamViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemberInTeamViewSet:
def get_permissions(self):
"""If one user wants to add one user to the team it must be a Admin of the team. If one user wants to remove other user from the team it must be a admin of the team. The others methods: retrieve it must be only Authenticated."""
<|b... | stack_v2_sparse_classes_36k_train_026727 | 14,739 | no_license | [
{
"docstring": "If one user wants to add one user to the team it must be a Admin of the team. If one user wants to remove other user from the team it must be a admin of the team. The others methods: retrieve it must be only Authenticated.",
"name": "get_permissions",
"signature": "def get_permissions(se... | 4 | stack_v2_sparse_classes_30k_val_000094 | Implement the Python class `MemberInTeamViewSet` described below.
Class description:
Implement the MemberInTeamViewSet class.
Method signatures and docstrings:
- def get_permissions(self): If one user wants to add one user to the team it must be a Admin of the team. If one user wants to remove other user from the tea... | Implement the Python class `MemberInTeamViewSet` described below.
Class description:
Implement the MemberInTeamViewSet class.
Method signatures and docstrings:
- def get_permissions(self): If one user wants to add one user to the team it must be a Admin of the team. If one user wants to remove other user from the tea... | 8f296850eeab1df4c52bb7b9df0681884449e761 | <|skeleton|>
class MemberInTeamViewSet:
def get_permissions(self):
"""If one user wants to add one user to the team it must be a Admin of the team. If one user wants to remove other user from the team it must be a admin of the team. The others methods: retrieve it must be only Authenticated."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MemberInTeamViewSet:
def get_permissions(self):
"""If one user wants to add one user to the team it must be a Admin of the team. If one user wants to remove other user from the team it must be a admin of the team. The others methods: retrieve it must be only Authenticated."""
if self.request.m... | the_stack_v2_python_sparse | src/web/teams/views.py | CiberRato/pei2015-ciberrato | train | 0 | |
dbb70166fcf33487978eae15b874743eff75c724 | [
"self.trade_days = trade_days\nself.trade_strategy = trade_strategy\nself.profit_array = []",
"for index, day in enumerate(self.trade_days):\n if self.trade_strategy.keep_stock_day > 0:\n self.profit_array.append(day.change)\n if hasattr(self.trade_strategy, 'buy_strategy'):\n self.trade_strat... | <|body_start_0|>
self.trade_days = trade_days
self.trade_strategy = trade_strategy
self.profit_array = []
<|end_body_0|>
<|body_start_1|>
for index, day in enumerate(self.trade_days):
if self.trade_strategy.keep_stock_day > 0:
self.profit_array.append(day.cha... | 交易回测系统 | TradeLoopBack | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TradeLoopBack:
"""交易回测系统"""
def __init__(self, trade_days, trade_strategy):
"""使用前面封装的StockTradeDays类和TradeStrategy1类 :param trade_days: :param trade_strategy:"""
<|body_0|>
def execute_trade(self):
"""执行交易回测 :return:"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_026728 | 1,071 | permissive | [
{
"docstring": "使用前面封装的StockTradeDays类和TradeStrategy1类 :param trade_days: :param trade_strategy:",
"name": "__init__",
"signature": "def __init__(self, trade_days, trade_strategy)"
},
{
"docstring": "执行交易回测 :return:",
"name": "execute_trade",
"signature": "def execute_trade(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000360 | Implement the Python class `TradeLoopBack` described below.
Class description:
交易回测系统
Method signatures and docstrings:
- def __init__(self, trade_days, trade_strategy): 使用前面封装的StockTradeDays类和TradeStrategy1类 :param trade_days: :param trade_strategy:
- def execute_trade(self): 执行交易回测 :return: | Implement the Python class `TradeLoopBack` described below.
Class description:
交易回测系统
Method signatures and docstrings:
- def __init__(self, trade_days, trade_strategy): 使用前面封装的StockTradeDays类和TradeStrategy1类 :param trade_days: :param trade_strategy:
- def execute_trade(self): 执行交易回测 :return:
<|skeleton|>
class Trad... | 32b9b21acdf7746081ff8cb39193afacafdb8fdf | <|skeleton|>
class TradeLoopBack:
"""交易回测系统"""
def __init__(self, trade_days, trade_strategy):
"""使用前面封装的StockTradeDays类和TradeStrategy1类 :param trade_days: :param trade_strategy:"""
<|body_0|>
def execute_trade(self):
"""执行交易回测 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TradeLoopBack:
"""交易回测系统"""
def __init__(self, trade_days, trade_strategy):
"""使用前面封装的StockTradeDays类和TradeStrategy1类 :param trade_days: :param trade_strategy:"""
self.trade_days = trade_days
self.trade_strategy = trade_strategy
self.profit_array = []
def execute_trad... | the_stack_v2_python_sparse | trade1/trade_loop_back.py | Expert68/Expert_quant | train | 2 |
4373af4f7269b4351061ede4540076573c8b5d58 | [
"for key in inmap:\n if not key.startswith('conversion '):\n raise KeyError('Unrecognized object type: %s' % key)\n cnv = key[11:]\n inconv = inmap[key]\n conv = Conversion(schema=schema.name, name=cnv, **inconv)\n if inconv:\n if 'oldname' in inconv:\n conv.oldname = inconv[... | <|body_start_0|>
for key in inmap:
if not key.startswith('conversion '):
raise KeyError('Unrecognized object type: %s' % key)
cnv = key[11:]
inconv = inmap[key]
conv = Conversion(schema=schema.name, name=cnv, **inconv)
if inconv:
... | The collection of conversions in a database. | ConversionDict | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConversionDict:
"""The collection of conversions in a database."""
def from_map(self, schema, inmap):
"""Initialize the dictionary of conversions by examining the input map :param schema: the schema owing the conversions :param inmap: the input YAML map defining the conversions"""
... | stack_v2_sparse_classes_36k_train_026729 | 4,035 | permissive | [
{
"docstring": "Initialize the dictionary of conversions by examining the input map :param schema: the schema owing the conversions :param inmap: the input YAML map defining the conversions",
"name": "from_map",
"signature": "def from_map(self, schema, inmap)"
},
{
"docstring": "Generate SQL to ... | 2 | stack_v2_sparse_classes_30k_train_014162 | Implement the Python class `ConversionDict` described below.
Class description:
The collection of conversions in a database.
Method signatures and docstrings:
- def from_map(self, schema, inmap): Initialize the dictionary of conversions by examining the input map :param schema: the schema owing the conversions :param... | Implement the Python class `ConversionDict` described below.
Class description:
The collection of conversions in a database.
Method signatures and docstrings:
- def from_map(self, schema, inmap): Initialize the dictionary of conversions by examining the input map :param schema: the schema owing the conversions :param... | 0133f3bc522890e0564d27de6791824acb4d2773 | <|skeleton|>
class ConversionDict:
"""The collection of conversions in a database."""
def from_map(self, schema, inmap):
"""Initialize the dictionary of conversions by examining the input map :param schema: the schema owing the conversions :param inmap: the input YAML map defining the conversions"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConversionDict:
"""The collection of conversions in a database."""
def from_map(self, schema, inmap):
"""Initialize the dictionary of conversions by examining the input map :param schema: the schema owing the conversions :param inmap: the input YAML map defining the conversions"""
for key... | the_stack_v2_python_sparse | pyrseas/dbobject/conversion.py | vayerx/Pyrseas | train | 1 |
8490fd537ed5d3c28cd597e45f54b5668d6934b4 | [
"super().__init__()\nif init_method == 'zeros':\n self._learned_defaults = nn.Parameter(torch.zeros(feature_dim), requires_grad=not freeze)\nelif init_method == 'gaussian':\n self._learned_defaults = nn.Parameter(torch.Tensor(feature_dim), requires_grad=not freeze)\n nn.init.normal_(self._learned_defaults)... | <|body_start_0|>
super().__init__()
if init_method == 'zeros':
self._learned_defaults = nn.Parameter(torch.zeros(feature_dim), requires_grad=not freeze)
elif init_method == 'gaussian':
self._learned_defaults = nn.Parameter(torch.Tensor(feature_dim), requires_grad=not free... | Learns default values to fill invalid entries within input tensors. The invalid entries are represented by a mask which is passed into forward alongside the input tensor. Note the default value is only used if all entries in the batch row are invalid rather than just a portion of invalid entries within each batch row. | LearnMaskedDefault | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearnMaskedDefault:
"""Learns default values to fill invalid entries within input tensors. The invalid entries are represented by a mask which is passed into forward alongside the input tensor. Note the default value is only used if all entries in the batch row are invalid rather than just a port... | stack_v2_sparse_classes_36k_train_026730 | 13,032 | permissive | [
{
"docstring": "Args: feature_dim (int): the size of the default value parameter, this must match the input tensor size. init_method (str): the initial default value parameter. Options: 'guassian' 'zeros' freeze (bool): If True, the learned default parameter weights are frozen.",
"name": "__init__",
"si... | 2 | stack_v2_sparse_classes_30k_train_010150 | Implement the Python class `LearnMaskedDefault` described below.
Class description:
Learns default values to fill invalid entries within input tensors. The invalid entries are represented by a mask which is passed into forward alongside the input tensor. Note the default value is only used if all entries in the batch ... | Implement the Python class `LearnMaskedDefault` described below.
Class description:
Learns default values to fill invalid entries within input tensors. The invalid entries are represented by a mask which is passed into forward alongside the input tensor. Note the default value is only used if all entries in the batch ... | 16f2abf2f8aa174915316007622bbb260215dee8 | <|skeleton|>
class LearnMaskedDefault:
"""Learns default values to fill invalid entries within input tensors. The invalid entries are represented by a mask which is passed into forward alongside the input tensor. Note the default value is only used if all entries in the batch row are invalid rather than just a port... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LearnMaskedDefault:
"""Learns default values to fill invalid entries within input tensors. The invalid entries are represented by a mask which is passed into forward alongside the input tensor. Note the default value is only used if all entries in the batch row are invalid rather than just a portion of invali... | the_stack_v2_python_sparse | pytorchvideo/models/masked_multistream.py | xchani/pytorchvideo | train | 0 |
7dec43bdd0c78b382c2badc34c97723acc2771bc | [
"if not root:\n return 0\nfrom collections import deque\nq = deque()\nq.appendleft(root)\nn = 0\nwhile q:\n for _ in range(len(q)):\n cur_node = q.pop()\n n += 1\n if cur_node.left:\n q.appendleft(cur_node.left)\n if cur_node.right:\n q.appendleft(cur_node.rig... | <|body_start_0|>
if not root:
return 0
from collections import deque
q = deque()
q.appendleft(root)
n = 0
while q:
for _ in range(len(q)):
cur_node = q.pop()
n += 1
if cur_node.left:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countNodes(self, root: TreeNode) -> int:
"""爆搜方式,使用层次遍历 :param root: :return:"""
<|body_0|>
def countNodes1(self, root: TreeNode) -> int:
"""使用递归方式 :param root: :return:"""
<|body_1|>
def countNodes2(self, root: TreeNode) -> int:
""... | stack_v2_sparse_classes_36k_train_026731 | 2,999 | no_license | [
{
"docstring": "爆搜方式,使用层次遍历 :param root: :return:",
"name": "countNodes",
"signature": "def countNodes(self, root: TreeNode) -> int"
},
{
"docstring": "使用递归方式 :param root: :return:",
"name": "countNodes1",
"signature": "def countNodes1(self, root: TreeNode) -> int"
},
{
"docstrin... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNodes(self, root: TreeNode) -> int: 爆搜方式,使用层次遍历 :param root: :return:
- def countNodes1(self, root: TreeNode) -> int: 使用递归方式 :param root: :return:
- def countNodes2(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNodes(self, root: TreeNode) -> int: 爆搜方式,使用层次遍历 :param root: :return:
- def countNodes1(self, root: TreeNode) -> int: 使用递归方式 :param root: :return:
- def countNodes2(self... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def countNodes(self, root: TreeNode) -> int:
"""爆搜方式,使用层次遍历 :param root: :return:"""
<|body_0|>
def countNodes1(self, root: TreeNode) -> int:
"""使用递归方式 :param root: :return:"""
<|body_1|>
def countNodes2(self, root: TreeNode) -> int:
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countNodes(self, root: TreeNode) -> int:
"""爆搜方式,使用层次遍历 :param root: :return:"""
if not root:
return 0
from collections import deque
q = deque()
q.appendleft(root)
n = 0
while q:
for _ in range(len(q)):
... | the_stack_v2_python_sparse | datastructure/binary_array/CountNodes.py | yinhuax/leet_code | train | 0 | |
5de4c6c144ed05b31ba1a0991e18e2f3dc3fb7eb | [
"self.classifiers = list()\nfor f in args:\n if not isinstance(f, ValueFunction):\n f = CallableWrapper(func=f)\n self.classifiers.append(f)\nself.none_label = kwargs.get('none_label')\nself.default_label = kwargs.get('default_label')\nself.raise_error = kwargs.get('raise_error', False)",
"for classi... | <|body_start_0|>
self.classifiers = list()
for f in args:
if not isinstance(f, ValueFunction):
f = CallableWrapper(func=f)
self.classifiers.append(f)
self.none_label = kwargs.get('none_label')
self.default_label = kwargs.get('default_label')
... | The value classifier evaluates a list of predicates or conditions on a given value (scalar or tuple). Each predicate is associated with a class label. The corresponding class label for the first predicate that is satisfied by the value is returned as the classification result. If no predicate is satisfied by a given va... | ValueClassifier | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueClassifier:
"""The value classifier evaluates a list of predicates or conditions on a given value (scalar or tuple). Each predicate is associated with a class label. The corresponding class label for the first predicate that is satisfied by the value is returned as the classification result.... | stack_v2_sparse_classes_36k_train_026732 | 7,355 | permissive | [
{
"docstring": "Initialize the individual classifier and object properties. Parameters ---------- args: list of callable or openclean.function.value.base.ValueFunction List of functions that accept a scalar value as input and that return a class label as output. none_label: string, default=None Label that is re... | 4 | stack_v2_sparse_classes_30k_train_004257 | Implement the Python class `ValueClassifier` described below.
Class description:
The value classifier evaluates a list of predicates or conditions on a given value (scalar or tuple). Each predicate is associated with a class label. The corresponding class label for the first predicate that is satisfied by the value is... | Implement the Python class `ValueClassifier` described below.
Class description:
The value classifier evaluates a list of predicates or conditions on a given value (scalar or tuple). Each predicate is associated with a class label. The corresponding class label for the first predicate that is satisfied by the value is... | e3d0e04f90468c49f29ca53edc2feb12465c24d5 | <|skeleton|>
class ValueClassifier:
"""The value classifier evaluates a list of predicates or conditions on a given value (scalar or tuple). Each predicate is associated with a class label. The corresponding class label for the first predicate that is satisfied by the value is returned as the classification result.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValueClassifier:
"""The value classifier evaluates a list of predicates or conditions on a given value (scalar or tuple). Each predicate is associated with a class label. The corresponding class label for the first predicate that is satisfied by the value is returned as the classification result. If no predic... | the_stack_v2_python_sparse | openclean/function/value/classifier.py | Denisfench/openclean-core | train | 0 |
6b7bec2c0f071832bec13b53966b1b33b84e41aa | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = self.__nb_objects",
"if list_dictionaries is None or len(list_dictionaries) == 0:\n return []\nreturn json.dumps(list_dictionaries)",
"l = []\nfn = cls.__name__ + '.json'\nif list_objs:\n for a in list_objs:\n l... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = self.__nb_objects
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None or len(list_dictionaries) == 0:
return []
return json.dumps(list_diction... | A class Base doing base. | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""A class Base doing base."""
def __init__(self, id=None):
"""An init function to start."""
<|body_0|>
def to_json_string(list_dictionaries):
"""Function to json string."""
<|body_1|>
def save_to_file(cls, list_objs):
"""Function save ... | stack_v2_sparse_classes_36k_train_026733 | 1,838 | no_license | [
{
"docstring": "An init function to start.",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "Function to json string.",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docstring": "Function save to file.",
... | 6 | stack_v2_sparse_classes_30k_train_006765 | Implement the Python class `Base` described below.
Class description:
A class Base doing base.
Method signatures and docstrings:
- def __init__(self, id=None): An init function to start.
- def to_json_string(list_dictionaries): Function to json string.
- def save_to_file(cls, list_objs): Function save to file.
- def ... | Implement the Python class `Base` described below.
Class description:
A class Base doing base.
Method signatures and docstrings:
- def __init__(self, id=None): An init function to start.
- def to_json_string(list_dictionaries): Function to json string.
- def save_to_file(cls, list_objs): Function save to file.
- def ... | 32f7396181fac7c7495def24af72346d6ba07249 | <|skeleton|>
class Base:
"""A class Base doing base."""
def __init__(self, id=None):
"""An init function to start."""
<|body_0|>
def to_json_string(list_dictionaries):
"""Function to json string."""
<|body_1|>
def save_to_file(cls, list_objs):
"""Function save ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base:
"""A class Base doing base."""
def __init__(self, id=None):
"""An init function to start."""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = self.__nb_objects
def to_json_string(list_dictionaries):
"""Fu... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | jfangwang/holbertonschool-higher_level_programming | train | 0 |
3cee1ada90cf533f45f9eef7811d9e01bff09a09 | [
"if self._context.get('tracking_disable'):\n return\nreturn super().message_post(*args, **kwargs)",
"if self._context.get('tracking_disable'):\n return\nreturn super().message_post_with_view(*args, **kwargs)",
"if self._context.get('tracking_disable'):\n return\nreturn super().message_post_with_templat... | <|body_start_0|>
if self._context.get('tracking_disable'):
return
return super().message_post(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
if self._context.get('tracking_disable'):
return
return super().message_post_with_view(*args, **kwargs)
<|end_body_1|>
... | Mail threads Disable mail thread posting whenever the context parameter ``tracking_disable`` is set. | MailThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MailThread:
"""Mail threads Disable mail thread posting whenever the context parameter ``tracking_disable`` is set."""
def message_post(self, *args, **kwargs):
"""Post message"""
<|body_0|>
def message_post_with_view(self, *args, **kwargs):
"""Post message using ... | stack_v2_sparse_classes_36k_train_026734 | 966 | no_license | [
{
"docstring": "Post message",
"name": "message_post",
"signature": "def message_post(self, *args, **kwargs)"
},
{
"docstring": "Post message using a view",
"name": "message_post_with_view",
"signature": "def message_post_with_view(self, *args, **kwargs)"
},
{
"docstring": "Post ... | 3 | stack_v2_sparse_classes_30k_train_012746 | Implement the Python class `MailThread` described below.
Class description:
Mail threads Disable mail thread posting whenever the context parameter ``tracking_disable`` is set.
Method signatures and docstrings:
- def message_post(self, *args, **kwargs): Post message
- def message_post_with_view(self, *args, **kwargs)... | Implement the Python class `MailThread` described below.
Class description:
Mail threads Disable mail thread posting whenever the context parameter ``tracking_disable`` is set.
Method signatures and docstrings:
- def message_post(self, *args, **kwargs): Post message
- def message_post_with_view(self, *args, **kwargs)... | d6d55fbf8abecb0b8201384921833868ae849920 | <|skeleton|>
class MailThread:
"""Mail threads Disable mail thread posting whenever the context parameter ``tracking_disable`` is set."""
def message_post(self, *args, **kwargs):
"""Post message"""
<|body_0|>
def message_post_with_view(self, *args, **kwargs):
"""Post message using ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MailThread:
"""Mail threads Disable mail thread posting whenever the context parameter ``tracking_disable`` is set."""
def message_post(self, *args, **kwargs):
"""Post message"""
if self._context.get('tracking_disable'):
return
return super().message_post(*args, **kwar... | the_stack_v2_python_sparse | addons/edi/models/mail_thread.py | unipartdigital/odoo-edi | train | 9 |
f3417ecf525e955648492a7cd858dad1b06f9119 | [
"emb_dim = 4\nnum_units = 64\nhparams = {'type': rnn.LSTMCell(num_units)}\ncell = layers.get_rnn_cell(hparams)\nself.assertTrue(isinstance(cell, rnn.LSTMCell))\nhparams = {'type': rnn.LSTMCell, 'kwargs': {'num_units': 10}}\ncell = layers.get_rnn_cell(hparams)\nself.assertTrue(isinstance(cell, rnn.LSTMCell))\nkeep_p... | <|body_start_0|>
emb_dim = 4
num_units = 64
hparams = {'type': rnn.LSTMCell(num_units)}
cell = layers.get_rnn_cell(hparams)
self.assertTrue(isinstance(cell, rnn.LSTMCell))
hparams = {'type': rnn.LSTMCell, 'kwargs': {'num_units': 10}}
cell = layers.get_rnn_cell(hpa... | Tests RNN cell creator. | GetRNNCellTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetRNNCellTest:
"""Tests RNN cell creator."""
def test_get_rnn_cell(self):
"""Tests :func:`texar.tf.core.layers.get_rnn_cell`."""
<|body_0|>
def test_switch_dropout(self):
"""Tests dropout mode."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
em... | stack_v2_sparse_classes_36k_train_026735 | 11,544 | permissive | [
{
"docstring": "Tests :func:`texar.tf.core.layers.get_rnn_cell`.",
"name": "test_get_rnn_cell",
"signature": "def test_get_rnn_cell(self)"
},
{
"docstring": "Tests dropout mode.",
"name": "test_switch_dropout",
"signature": "def test_switch_dropout(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002253 | Implement the Python class `GetRNNCellTest` described below.
Class description:
Tests RNN cell creator.
Method signatures and docstrings:
- def test_get_rnn_cell(self): Tests :func:`texar.tf.core.layers.get_rnn_cell`.
- def test_switch_dropout(self): Tests dropout mode. | Implement the Python class `GetRNNCellTest` described below.
Class description:
Tests RNN cell creator.
Method signatures and docstrings:
- def test_get_rnn_cell(self): Tests :func:`texar.tf.core.layers.get_rnn_cell`.
- def test_switch_dropout(self): Tests dropout mode.
<|skeleton|>
class GetRNNCellTest:
"""Test... | 0704b3d4c93915b9a6f96b725e49ae20bf5d1e90 | <|skeleton|>
class GetRNNCellTest:
"""Tests RNN cell creator."""
def test_get_rnn_cell(self):
"""Tests :func:`texar.tf.core.layers.get_rnn_cell`."""
<|body_0|>
def test_switch_dropout(self):
"""Tests dropout mode."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetRNNCellTest:
"""Tests RNN cell creator."""
def test_get_rnn_cell(self):
"""Tests :func:`texar.tf.core.layers.get_rnn_cell`."""
emb_dim = 4
num_units = 64
hparams = {'type': rnn.LSTMCell(num_units)}
cell = layers.get_rnn_cell(hparams)
self.assertTrue(isin... | the_stack_v2_python_sparse | texar/tf/core/layers_test.py | arita37/texar | train | 2 |
130ab5b9ff85ee582f3d9a8550b3899219fcf5d0 | [
"def bfs(root, string):\n if root is None:\n string += 'None,'\n else:\n string += str(root.val) + ','\n string = bfs(root.left, string)\n string = bfs(root.right, string)\n return string\nreturn bfs(root, '')",
"def bfs(data):\n if data[0] == 'None':\n data.pop(0)\n... | <|body_start_0|>
def bfs(root, string):
if root is None:
string += 'None,'
else:
string += str(root.val) + ','
string = bfs(root.left, string)
string = bfs(root.right, string)
return string
return bfs(roo... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_026736 | 2,791 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 801beb43235872b2419a92b11c4eb05f7ea2adab | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def bfs(root, string):
if root is None:
string += 'None,'
else:
string += str(root.val) + ','
string = bfs(root.le... | the_stack_v2_python_sparse | Python/297__Serialize_And_Deserializa_Binary_Tree.py | FIRESTROM/Leetcode | train | 2 | |
e6380e103209b26201de874a7b615e7fa1d6ebfd | [
"if not root1 and (not root2):\n return True\nif root1 and root2 and (root1.val == root2.val):\n return self.is_mirror(root1.left, root2.right) and self.is_mirror(root1.right, root2.left)\nreturn False",
"if not root:\n return True\nif self.is_mirror(root.left, root.right):\n return True\nreturn False... | <|body_start_0|>
if not root1 and (not root2):
return True
if root1 and root2 and (root1.val == root2.val):
return self.is_mirror(root1.left, root2.right) and self.is_mirror(root1.right, root2.left)
return False
<|end_body_0|>
<|body_start_1|>
if not root:
... | SolutionLeetCode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionLeetCode:
def is_mirror(self, root1, root2):
"""Returns True if two trees are mirror of one another, False otherwise."""
<|body_0|>
def isSymmetric(self, root):
"""Returns True if binary tree is symmetric, False otherwise. Recursive algorithm. Time complexity... | stack_v2_sparse_classes_36k_train_026737 | 3,032 | no_license | [
{
"docstring": "Returns True if two trees are mirror of one another, False otherwise.",
"name": "is_mirror",
"signature": "def is_mirror(self, root1, root2)"
},
{
"docstring": "Returns True if binary tree is symmetric, False otherwise. Recursive algorithm. Time complexity: O(n). Space complexity... | 3 | stack_v2_sparse_classes_30k_train_015671 | Implement the Python class `SolutionLeetCode` described below.
Class description:
Implement the SolutionLeetCode class.
Method signatures and docstrings:
- def is_mirror(self, root1, root2): Returns True if two trees are mirror of one another, False otherwise.
- def isSymmetric(self, root): Returns True if binary tre... | Implement the Python class `SolutionLeetCode` described below.
Class description:
Implement the SolutionLeetCode class.
Method signatures and docstrings:
- def is_mirror(self, root1, root2): Returns True if two trees are mirror of one another, False otherwise.
- def isSymmetric(self, root): Returns True if binary tre... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class SolutionLeetCode:
def is_mirror(self, root1, root2):
"""Returns True if two trees are mirror of one another, False otherwise."""
<|body_0|>
def isSymmetric(self, root):
"""Returns True if binary tree is symmetric, False otherwise. Recursive algorithm. Time complexity... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolutionLeetCode:
def is_mirror(self, root1, root2):
"""Returns True if two trees are mirror of one another, False otherwise."""
if not root1 and (not root2):
return True
if root1 and root2 and (root1.val == root2.val):
return self.is_mirror(root1.left, root2.ri... | the_stack_v2_python_sparse | Trees/symmetric_binary_tree.py | vladn90/Algorithms | train | 0 | |
feebcb9cfc57c504dbc296f2677cae605537abbc | [
"super().__init__()\nself.label = label\nself.tag_set = tag_set\nself.setText(str(label))\nfont = QFont('SansSerif', 9)\nfont.setBold(False)\nself.setFont(font)\nfont_metric = QFontMetrics(font)\nwidth = font_metric.width(str(label)) + 20\nif tooltip_lbl is not None:\n self.setToolTip(str(tooltip_lbl))\n self... | <|body_start_0|>
super().__init__()
self.label = label
self.tag_set = tag_set
self.setText(str(label))
font = QFont('SansSerif', 9)
font.setBold(False)
self.setFont(font)
font_metric = QFontMetrics(font)
width = font_metric.width(str(label)) + 20
... | QTagButton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QTagButton:
def __init__(self, label: str, tag_set: set, tooltip_lbl: str=None):
"""Formats the tag button :param label: String of tag. :param tag_set: set of tag strings"""
<|body_0|>
def mousePressEvent(self, event):
"""Overides existing mousepressevent. If a right... | stack_v2_sparse_classes_36k_train_026738 | 1,526 | no_license | [
{
"docstring": "Formats the tag button :param label: String of tag. :param tag_set: set of tag strings",
"name": "__init__",
"signature": "def __init__(self, label: str, tag_set: set, tooltip_lbl: str=None)"
},
{
"docstring": "Overides existing mousepressevent. If a right click occurs the tag is... | 2 | stack_v2_sparse_classes_30k_train_013710 | Implement the Python class `QTagButton` described below.
Class description:
Implement the QTagButton class.
Method signatures and docstrings:
- def __init__(self, label: str, tag_set: set, tooltip_lbl: str=None): Formats the tag button :param label: String of tag. :param tag_set: set of tag strings
- def mousePressEv... | Implement the Python class `QTagButton` described below.
Class description:
Implement the QTagButton class.
Method signatures and docstrings:
- def __init__(self, label: str, tag_set: set, tooltip_lbl: str=None): Formats the tag button :param label: String of tag. :param tag_set: set of tag strings
- def mousePressEv... | ab04ca1c67839a8269f5275323907c5bc7f9af46 | <|skeleton|>
class QTagButton:
def __init__(self, label: str, tag_set: set, tooltip_lbl: str=None):
"""Formats the tag button :param label: String of tag. :param tag_set: set of tag strings"""
<|body_0|>
def mousePressEvent(self, event):
"""Overides existing mousepressevent. If a right... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QTagButton:
def __init__(self, label: str, tag_set: set, tooltip_lbl: str=None):
"""Formats the tag button :param label: String of tag. :param tag_set: set of tag strings"""
super().__init__()
self.label = label
self.tag_set = tag_set
self.setText(str(label))
fo... | the_stack_v2_python_sparse | custom_widgets/tag_button.py | tobias-gill/Figshare_desktop | train | 0 | |
8c524a0b4ab14b07d04730b1ee181af5c5ea6459 | [
"UserAuthnMethod.__init__(self, srv)\nself.totp = totp\nself.passwd = pwd\nself.mako_template = tmako\nself.template_lookup = template_lookup",
"resp = Response('OK')\nif UserManager.verify_match(username, password):\n '\\n Update the password\\n '\n try:\n usernm = UserManager.... | <|body_start_0|>
UserAuthnMethod.__init__(self, srv)
self.totp = totp
self.passwd = pwd
self.mako_template = tmako
self.template_lookup = template_lookup
<|end_body_0|>
<|body_start_1|>
resp = Response('OK')
if UserManager.verify_match(username, password):
... | Modifier_module | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Modifier_module:
def __init__(self, srv, tmako, template_lookup, totp, pwd):
""":param srv: The server instance :param tmako: Template mako :param template_lookup: template lookup :param totp: TOTP dictionary like database :param pwd: Username/password dictionary like database :return:""... | stack_v2_sparse_classes_36k_train_026739 | 2,911 | no_license | [
{
"docstring": ":param srv: The server instance :param tmako: Template mako :param template_lookup: template lookup :param totp: TOTP dictionary like database :param pwd: Username/password dictionary like database :return:",
"name": "__init__",
"signature": "def __init__(self, srv, tmako, template_looku... | 3 | stack_v2_sparse_classes_30k_train_017578 | Implement the Python class `Modifier_module` described below.
Class description:
Implement the Modifier_module class.
Method signatures and docstrings:
- def __init__(self, srv, tmako, template_lookup, totp, pwd): :param srv: The server instance :param tmako: Template mako :param template_lookup: template lookup :par... | Implement the Python class `Modifier_module` described below.
Class description:
Implement the Modifier_module class.
Method signatures and docstrings:
- def __init__(self, srv, tmako, template_lookup, totp, pwd): :param srv: The server instance :param tmako: Template mako :param template_lookup: template lookup :par... | 4455de4eb61fb4bddf6cfa8a4ce9e5f9f8e9d812 | <|skeleton|>
class Modifier_module:
def __init__(self, srv, tmako, template_lookup, totp, pwd):
""":param srv: The server instance :param tmako: Template mako :param template_lookup: template lookup :param totp: TOTP dictionary like database :param pwd: Username/password dictionary like database :return:""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Modifier_module:
def __init__(self, srv, tmako, template_lookup, totp, pwd):
""":param srv: The server instance :param tmako: Template mako :param template_lookup: template lookup :param totp: TOTP dictionary like database :param pwd: Username/password dictionary like database :return:"""
User... | the_stack_v2_python_sparse | server/modifydb.py | CarlosGonzalezLuzardo/SECAS | train | 0 | |
a7c17eea41f1bca733144fb1fdbda5d7e988de33 | [
"full_name = self.cleaned_data.get('full_name')\nforbidden_users = ['admin', 'user', 'login', 'authenticate', 'css', 'js', 'logout', 'adminstrator', 'root', 'email', 'join', 'sql', 'static', 'python', 'delete']\nif full_name.lower() in forbidden_users:\n raise forms.ValidationError('This is a reserved word.', co... | <|body_start_0|>
full_name = self.cleaned_data.get('full_name')
forbidden_users = ['admin', 'user', 'login', 'authenticate', 'css', 'js', 'logout', 'adminstrator', 'root', 'email', 'join', 'sql', 'static', 'python', 'delete']
if full_name.lower() in forbidden_users:
raise forms.Valid... | User creation form class. | UserRegisterForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRegisterForm:
"""User creation form class."""
def clean_full_name(self):
"""Validate fullname."""
<|body_0|>
def clean_email2(self):
"""Validate email 2."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
full_name = self.cleaned_data.get('full... | stack_v2_sparse_classes_36k_train_026740 | 6,446 | no_license | [
{
"docstring": "Validate fullname.",
"name": "clean_full_name",
"signature": "def clean_full_name(self)"
},
{
"docstring": "Validate email 2.",
"name": "clean_email2",
"signature": "def clean_email2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004231 | Implement the Python class `UserRegisterForm` described below.
Class description:
User creation form class.
Method signatures and docstrings:
- def clean_full_name(self): Validate fullname.
- def clean_email2(self): Validate email 2. | Implement the Python class `UserRegisterForm` described below.
Class description:
User creation form class.
Method signatures and docstrings:
- def clean_full_name(self): Validate fullname.
- def clean_email2(self): Validate email 2.
<|skeleton|>
class UserRegisterForm:
"""User creation form class."""
def c... | 167ffd3a4183529c0cbc5db4ab232026711ea915 | <|skeleton|>
class UserRegisterForm:
"""User creation form class."""
def clean_full_name(self):
"""Validate fullname."""
<|body_0|>
def clean_email2(self):
"""Validate email 2."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserRegisterForm:
"""User creation form class."""
def clean_full_name(self):
"""Validate fullname."""
full_name = self.cleaned_data.get('full_name')
forbidden_users = ['admin', 'user', 'login', 'authenticate', 'css', 'js', 'logout', 'adminstrator', 'root', 'email', 'join', 'sql', ... | the_stack_v2_python_sparse | accounts/forms.py | OmarFateh/Student-Portal | train | 0 |
9341805455df3fb6100971394d95e09b4c1e1c64 | [
"for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]\nreturn [-1, -1]",
"d = {}\nfor idx, n in enumerate(nums):\n if target - n in d.keys():\n return [d[target - n], idx]\n else:\n d[n] = idx\nreturn [-1, -1]",
... | <|body_start_0|>
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return [-1, -1]
<|end_body_0|>
<|body_start_1|>
d = {}
for idx, n in enumerate(nums):
if target - n in ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twoSum_3(self, nums, t... | stack_v2_sparse_classes_36k_train_026741 | 1,617 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_1",
"signature": "def twoSum_1(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_2",
"signature": "def twoSum_2(self, nums, target... | 3 | stack_v2_sparse_classes_30k_train_003628 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum_2(self, nums, target): :type nums: List[int] :type target: int :rtype: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum_2(self, nums, target): :type nums: List[int] :type target: int :rtype: Li... | 8cdb97bc7588b96b91b1c550afd84e976c1926e0 | <|skeleton|>
class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twoSum_3(self, nums, t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return [-1, -1]
de... | the_stack_v2_python_sparse | Array/2Sum.py | ZhengLiangliang1996/Leetcode_ML_Daily | train | 1 | |
4d8d716543ad5424278ad36f500dad52145d75c1 | [
"res = []\ndq = deque([root])\nwhile dq:\n cur_layer_val = []\n length = len(dq)\n for _ in range(length):\n node = dq.popleft()\n cur_layer_val.append(node.val)\n if node.left:\n dq.append(node.left)\n if node.right:\n dq.append(node.right)\n res.insert... | <|body_start_0|>
res = []
dq = deque([root])
while dq:
cur_layer_val = []
length = len(dq)
for _ in range(length):
node = dq.popleft()
cur_layer_val.append(node.val)
if node.left:
dq.append(no... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrderBottom_iteration(self, root: TreeNode):
"""返回给定二叉树自底向上的层次遍历列表。 :param root: :return: list"""
<|body_0|>
def levelOrderBottom(self, root: TreeNode):
""":param root: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res ... | stack_v2_sparse_classes_36k_train_026742 | 2,648 | no_license | [
{
"docstring": "返回给定二叉树自底向上的层次遍历列表。 :param root: :return: list",
"name": "levelOrderBottom_iteration",
"signature": "def levelOrderBottom_iteration(self, root: TreeNode)"
},
{
"docstring": ":param root: :return:",
"name": "levelOrderBottom",
"signature": "def levelOrderBottom(self, root:... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom_iteration(self, root: TreeNode): 返回给定二叉树自底向上的层次遍历列表。 :param root: :return: list
- def levelOrderBottom(self, root: TreeNode): :param root: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom_iteration(self, root: TreeNode): 返回给定二叉树自底向上的层次遍历列表。 :param root: :return: list
- def levelOrderBottom(self, root: TreeNode): :param root: :return:
<|skelet... | 62ad010a992c031e8c0fe4d1a9b6f9364f96ed4c | <|skeleton|>
class Solution:
def levelOrderBottom_iteration(self, root: TreeNode):
"""返回给定二叉树自底向上的层次遍历列表。 :param root: :return: list"""
<|body_0|>
def levelOrderBottom(self, root: TreeNode):
""":param root: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrderBottom_iteration(self, root: TreeNode):
"""返回给定二叉树自底向上的层次遍历列表。 :param root: :return: list"""
res = []
dq = deque([root])
while dq:
cur_layer_val = []
length = len(dq)
for _ in range(length):
node = dq.p... | the_stack_v2_python_sparse | leetcode/solved/107_.py | usnnu/python_foundation | train | 0 | |
6d6181025affe70786e96cfe13f44c618e7f1338 | [
"super().__init__()\nself.embedding = embedding\nself.dropout = nn.Dropout(embedding_dropout)\nself.encoder = encoder\nself.pooling = pooling\nself.padding_idx = padding_idx",
"embedded = self.embedding(data)\nembedded = self.dropout(embedded)\npadding_mask: Optional[Tensor]\nif self.padding_idx is not None:\n ... | <|body_start_0|>
super().__init__()
self.embedding = embedding
self.dropout = nn.Dropout(embedding_dropout)
self.encoder = encoder
self.pooling = pooling
self.padding_idx = padding_idx
<|end_body_0|>
<|body_start_1|>
embedded = self.embedding(data)
embedd... | Implements an Embedder module. An Embedder takes as input a sequence of index tokens, and computes the corresponding embedded representations, and padding mask. The encoder may be initialized using a pretrained embedding matrix. Attributes ---------- embeddings: Module The embedding module encoder: Module The sub-encod... | Embedder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedder:
"""Implements an Embedder module. An Embedder takes as input a sequence of index tokens, and computes the corresponding embedded representations, and padding mask. The encoder may be initialized using a pretrained embedding matrix. Attributes ---------- embeddings: Module The embedding ... | stack_v2_sparse_classes_36k_train_026743 | 12,470 | permissive | [
{
"docstring": "Initializes the TextEncoder module. Extra arguments are passed to the nn.Embedding module. Parameters ---------- embedding: nn.Embedding The embedding layer encoder: Module The encoder pooling: Module, optional An optioonal pooling module, takes a sequence of Tensor and reduces them to a single ... | 2 | null | Implement the Python class `Embedder` described below.
Class description:
Implements an Embedder module. An Embedder takes as input a sequence of index tokens, and computes the corresponding embedded representations, and padding mask. The encoder may be initialized using a pretrained embedding matrix. Attributes -----... | Implement the Python class `Embedder` described below.
Class description:
Implements an Embedder module. An Embedder takes as input a sequence of index tokens, and computes the corresponding embedded representations, and padding mask. The encoder may be initialized using a pretrained embedding matrix. Attributes -----... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class Embedder:
"""Implements an Embedder module. An Embedder takes as input a sequence of index tokens, and computes the corresponding embedded representations, and padding mask. The encoder may be initialized using a pretrained embedding matrix. Attributes ---------- embeddings: Module The embedding ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Embedder:
"""Implements an Embedder module. An Embedder takes as input a sequence of index tokens, and computes the corresponding embedded representations, and padding mask. The encoder may be initialized using a pretrained embedding matrix. Attributes ---------- embeddings: Module The embedding module encode... | the_stack_v2_python_sparse | flambe/nn/embedding.py | cle-ros/flambe | train | 1 |
bd0d8156285e2d0f305af1f34a88ceea8c976356 | [
"self.poolmanager: Optional[UDSPoolManager] = None\nself._pool_kwargs = {'uds': uds}\nif 'timeout' in kwargs:\n self._pool_kwargs['timeout'] = kwargs.get('timeout')\nsuper().__init__(pool_connections, pool_maxsize, max_retries, pool_block)",
"pool_kwargs = kwargs.copy()\npool_kwargs.update(self._pool_kwargs)\n... | <|body_start_0|>
self.poolmanager: Optional[UDSPoolManager] = None
self._pool_kwargs = {'uds': uds}
if 'timeout' in kwargs:
self._pool_kwargs['timeout'] = kwargs.get('timeout')
super().__init__(pool_connections, pool_maxsize, max_retries, pool_block)
<|end_body_0|>
<|body_st... | Specialization of requests transport adapter for UNIX domain sockets. | UDSAdapter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UDSAdapter:
"""Specialization of requests transport adapter for UNIX domain sockets."""
def __init__(self, uds: str, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOLBLOCK, **kwargs):
"""Initialize UDSAdapter. Args:... | stack_v2_sparse_classes_36k_train_026744 | 5,919 | permissive | [
{
"docstring": "Initialize UDSAdapter. Args: uds: Full address of a Podman service UNIX domain socket. Format, http+unix:///run/podman/podman.sock max_retries: The maximum number of retries each connection should attempt. pool_block: Whether the connection pool should block for connections. pool_connections: Th... | 2 | stack_v2_sparse_classes_30k_train_013463 | Implement the Python class `UDSAdapter` described below.
Class description:
Specialization of requests transport adapter for UNIX domain sockets.
Method signatures and docstrings:
- def __init__(self, uds: str, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=D... | Implement the Python class `UDSAdapter` described below.
Class description:
Specialization of requests transport adapter for UNIX domain sockets.
Method signatures and docstrings:
- def __init__(self, uds: str, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=D... | c7356dcff7d15fd0da61e9ffb226e789c2d7d9c4 | <|skeleton|>
class UDSAdapter:
"""Specialization of requests transport adapter for UNIX domain sockets."""
def __init__(self, uds: str, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOLBLOCK, **kwargs):
"""Initialize UDSAdapter. Args:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UDSAdapter:
"""Specialization of requests transport adapter for UNIX domain sockets."""
def __init__(self, uds: str, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOLBLOCK, **kwargs):
"""Initialize UDSAdapter. Args: uds: Full ad... | the_stack_v2_python_sparse | podman/api/uds.py | containers/podman-py | train | 190 |
d6f140875751151e3bcea25cd8787c79a6cbade3 | [
"super(TransformerEncoder, self).__init__(**kw)\nself.maxlen = maxlen\nself.posemb = posemb\nself.embdrop = q.RecDropout(p=embedding_dropout, shareaxis=1)\nself.layers = nn.ModuleList([TransformerEncoderBlock(dim, kdim=kdim, vdim=vdim, innerdim=innerdim, numheads=numheads, activation=activation, attention_dropout=a... | <|body_start_0|>
super(TransformerEncoder, self).__init__(**kw)
self.maxlen = maxlen
self.posemb = posemb
self.embdrop = q.RecDropout(p=embedding_dropout, shareaxis=1)
self.layers = nn.ModuleList([TransformerEncoderBlock(dim, kdim=kdim, vdim=vdim, innerdim=innerdim, numheads=numh... | TransformerEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoder:
def __init__(self, dim=512, kdim=None, vdim=None, innerdim=None, maxlen=512, numlayers=6, numheads=8, activation=nn.ReLU, embedding_dropout=0.0, attention_dropout=0.0, residual_dropout=0.0, scale=True, relpos=False, posemb=None, **kw):
""":param dim: see MultiHeadAtte... | stack_v2_sparse_classes_36k_train_026745 | 24,989 | permissive | [
{
"docstring": ":param dim: see MultiHeadAttention :param kdim: see MultiHeadAttention :param vdim: see MultiHeadAttention :param maxlen: see MultiHeadAttention :param numlayers: number of TransformerEncoderBlock layers used :param numheads: see MultiHeadAttention :param activation: which activation function to... | 2 | null | Implement the Python class `TransformerEncoder` described below.
Class description:
Implement the TransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, dim=512, kdim=None, vdim=None, innerdim=None, maxlen=512, numlayers=6, numheads=8, activation=nn.ReLU, embedding_dropout=0.0, attention_dro... | Implement the Python class `TransformerEncoder` described below.
Class description:
Implement the TransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, dim=512, kdim=None, vdim=None, innerdim=None, maxlen=512, numlayers=6, numheads=8, activation=nn.ReLU, embedding_dropout=0.0, attention_dro... | 8cf2e697830ef09dca40692e7d254b61f9ffdf8d | <|skeleton|>
class TransformerEncoder:
def __init__(self, dim=512, kdim=None, vdim=None, innerdim=None, maxlen=512, numlayers=6, numheads=8, activation=nn.ReLU, embedding_dropout=0.0, attention_dropout=0.0, residual_dropout=0.0, scale=True, relpos=False, posemb=None, **kw):
""":param dim: see MultiHeadAtte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerEncoder:
def __init__(self, dim=512, kdim=None, vdim=None, innerdim=None, maxlen=512, numlayers=6, numheads=8, activation=nn.ReLU, embedding_dropout=0.0, attention_dropout=0.0, residual_dropout=0.0, scale=True, relpos=False, posemb=None, **kw):
""":param dim: see MultiHeadAttention :param k... | the_stack_v2_python_sparse | kbcqa/method_ir/grounding/semantic_matching/qelos/transformer.py | BayLee001/SkeletonKBQA | train | 0 | |
bef26acaa065fbae9aefd9f0edc2e2fe21d37cbf | [
"tab = []\nfor ey in Y:\n line = []\n for ex in X:\n line.append(f(ey, ex))\n tab.append(line)\nreturn tab",
"result = []\nif isinstance(X[0], list):\n for jx in range(len(X)):\n line = []\n for jy in range(len(Y[0])):\n value = []\n for i in range(len(Y)):\n... | <|body_start_0|>
tab = []
for ey in Y:
line = []
for ex in X:
line.append(f(ey, ex))
tab.append(line)
return tab
<|end_body_0|>
<|body_start_1|>
result = []
if isinstance(X[0], list):
for jx in range(len(X)):
... | FuzzyRelations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FuzzyRelations:
def make_relation(X, Y, f):
""":param X: list with n elements i.e. [a, b, c, d] :param Y: list with n elements i.e. [x, y, z, t] :param f: function :return: list with elements which are products of function on pair of elements [f(a,x), f(b,y), f(c,z), f(d,t)]"""
<... | stack_v2_sparse_classes_36k_train_026746 | 2,985 | no_license | [
{
"docstring": ":param X: list with n elements i.e. [a, b, c, d] :param Y: list with n elements i.e. [x, y, z, t] :param f: function :return: list with elements which are products of function on pair of elements [f(a,x), f(b,y), f(c,z), f(d,t)]",
"name": "make_relation",
"signature": "def make_relation(... | 3 | stack_v2_sparse_classes_30k_train_005630 | Implement the Python class `FuzzyRelations` described below.
Class description:
Implement the FuzzyRelations class.
Method signatures and docstrings:
- def make_relation(X, Y, f): :param X: list with n elements i.e. [a, b, c, d] :param Y: list with n elements i.e. [x, y, z, t] :param f: function :return: list with el... | Implement the Python class `FuzzyRelations` described below.
Class description:
Implement the FuzzyRelations class.
Method signatures and docstrings:
- def make_relation(X, Y, f): :param X: list with n elements i.e. [a, b, c, d] :param Y: list with n elements i.e. [x, y, z, t] :param f: function :return: list with el... | 6c1d58ea4773c633c45f065b7ef52268d3319762 | <|skeleton|>
class FuzzyRelations:
def make_relation(X, Y, f):
""":param X: list with n elements i.e. [a, b, c, d] :param Y: list with n elements i.e. [x, y, z, t] :param f: function :return: list with elements which are products of function on pair of elements [f(a,x), f(b,y), f(c,z), f(d,t)]"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FuzzyRelations:
def make_relation(X, Y, f):
""":param X: list with n elements i.e. [a, b, c, d] :param Y: list with n elements i.e. [x, y, z, t] :param f: function :return: list with elements which are products of function on pair of elements [f(a,x), f(b,y), f(c,z), f(d,t)]"""
tab = []
... | the_stack_v2_python_sparse | fuzzy_relations.py | KatarzynaStudzinska/declib | train | 0 | |
42480c4d93106030127c393894ff33ac1be20346 | [
"super().__init__()\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)\nself.F = tf.keras.layers.Dense(vocab)",
"attention = SelfAttention(s_prev.shape[1])\ncontext, weights = attent... | <|body_start_0|>
super().__init__()
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
self.F = tf.keras.layers.Dense(vocab)
<|end_body_0|>
<|body_start_1|>
... | Decode for machine translation | RNNDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""Decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""vocab is an integer representing the size of the decode_out vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer represent... | stack_v2_sparse_classes_36k_train_026747 | 1,824 | no_license | [
{
"docstring": "vocab is an integer representing the size of the decode_out vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer representing the number of hidden units in the RNN cell batch is an integer representing the batch size",
"name": "__init... | 2 | stack_v2_sparse_classes_30k_train_000361 | Implement the Python class `RNNDecoder` described below.
Class description:
Decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): vocab is an integer representing the size of the decode_out vocabulary embedding is an integer representing the dimensional... | Implement the Python class `RNNDecoder` described below.
Class description:
Decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): vocab is an integer representing the size of the decode_out vocabulary embedding is an integer representing the dimensional... | b0c18df889d8bd0c24d4bdbbd69be06bc5c0a918 | <|skeleton|>
class RNNDecoder:
"""Decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""vocab is an integer representing the size of the decode_out vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer represent... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNDecoder:
"""Decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""vocab is an integer representing the size of the decode_out vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer representing the numbe... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | Gaspela/holbertonschool-machine_learning | train | 0 |
90bc535ade209792455369df93a681d5359c1ade | [
"output_layers = []\nif input_shape:\n input = tf.placeholder(tf.float32, shape=input_shape)\n output_layers.append(input)\nconvolution_layer = tf.layers.conv2d(input, filters, kernel_size, cnn_strides, cnn_padding, activation=cnn_activation)\nmax_pooling_layer = tf.layers.max_pooling2d(convolution_layer, poo... | <|body_start_0|>
output_layers = []
if input_shape:
input = tf.placeholder(tf.float32, shape=input_shape)
output_layers.append(input)
convolution_layer = tf.layers.conv2d(input, filters, kernel_size, cnn_strides, cnn_padding, activation=cnn_activation)
max_pooling... | BSSCS_CNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSSCS_CNN:
def create_cnn_block(self, filters, kernel_size, cnn_strides, pool_size, pooling_strides, cnn_padding='SAME', cnn_activation=tf.nn.relu, pooling_padding='VALID', input_shape=None, input=None):
"""BSSCS create cnn block method Handles creation of a 2D convolutional 'block' A co... | stack_v2_sparse_classes_36k_train_026748 | 6,412 | no_license | [
{
"docstring": "BSSCS create cnn block method Handles creation of a 2D convolutional 'block' A convolutional 'block' consists of both a convolutional layer and a max pooling layer. Input: CNN: - input: accepts a tensorflow placeholder of rank 4 (e.g. [batch_size, im_width, im_height, im_channels]) - filters: de... | 5 | stack_v2_sparse_classes_30k_train_016991 | Implement the Python class `BSSCS_CNN` described below.
Class description:
Implement the BSSCS_CNN class.
Method signatures and docstrings:
- def create_cnn_block(self, filters, kernel_size, cnn_strides, pool_size, pooling_strides, cnn_padding='SAME', cnn_activation=tf.nn.relu, pooling_padding='VALID', input_shape=No... | Implement the Python class `BSSCS_CNN` described below.
Class description:
Implement the BSSCS_CNN class.
Method signatures and docstrings:
- def create_cnn_block(self, filters, kernel_size, cnn_strides, pool_size, pooling_strides, cnn_padding='SAME', cnn_activation=tf.nn.relu, pooling_padding='VALID', input_shape=No... | d665ca405bdf35fdb57f8149a10b90be82d8de22 | <|skeleton|>
class BSSCS_CNN:
def create_cnn_block(self, filters, kernel_size, cnn_strides, pool_size, pooling_strides, cnn_padding='SAME', cnn_activation=tf.nn.relu, pooling_padding='VALID', input_shape=None, input=None):
"""BSSCS create cnn block method Handles creation of a 2D convolutional 'block' A co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BSSCS_CNN:
def create_cnn_block(self, filters, kernel_size, cnn_strides, pool_size, pooling_strides, cnn_padding='SAME', cnn_activation=tf.nn.relu, pooling_padding='VALID', input_shape=None, input=None):
"""BSSCS create cnn block method Handles creation of a 2D convolutional 'block' A convolutional 'b... | the_stack_v2_python_sparse | BSSCSFramework/BSSCS_CNN.py | wezleysherman/TBI-NN-421 | train | 3 | |
139b92db13cb6749d191b625128eaa21ab6ae7fb | [
"self.minimum = minimum\nself.maximum = maximum\nself.right_tail_mass = right_tail_mass\nself._fixed_density = 1.0 / (self.maximum - self.minimum)\nif self.right_tail_mass:\n self._fixed_density *= 1.0 - self.right_tail_mass\n self._right_tail_dist = lambda length: self.right_tail_mass * scipy.stats.expon.pdf... | <|body_start_0|>
self.minimum = minimum
self.maximum = maximum
self.right_tail_mass = right_tail_mass
self._fixed_density = 1.0 / (self.maximum - self.minimum)
if self.right_tail_mass:
self._fixed_density *= 1.0 - self.right_tail_mass
self._right_tail_dist... | Represents a distribution with a fixed value over a window. The window is specified by a mimimum and maximum value. Further, a "right_tail_mass" can be specified. If given, that fraction of the total probability mass is added as an exponential distribution to the right side of the window. The exponential distribution i... | FixedWindowLengthDistribution | [
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixedWindowLengthDistribution:
"""Represents a distribution with a fixed value over a window. The window is specified by a mimimum and maximum value. Further, a "right_tail_mass" can be specified. If given, that fraction of the total probability mass is added as an exponential distribution to the... | stack_v2_sparse_classes_36k_train_026749 | 18,188 | permissive | [
{
"docstring": "Construct a FixedWindowLengthDistribution. Args: minimum: left side of window maximum: right side of window right_tail_mass: probability mass added part the right side of the window (see class documentation)",
"name": "__init__",
"signature": "def __init__(self, minimum, maximum, right_t... | 2 | stack_v2_sparse_classes_30k_train_012079 | Implement the Python class `FixedWindowLengthDistribution` described below.
Class description:
Represents a distribution with a fixed value over a window. The window is specified by a mimimum and maximum value. Further, a "right_tail_mass" can be specified. If given, that fraction of the total probability mass is adde... | Implement the Python class `FixedWindowLengthDistribution` described below.
Class description:
Represents a distribution with a fixed value over a window. The window is specified by a mimimum and maximum value. Further, a "right_tail_mass" can be specified. If given, that fraction of the total probability mass is adde... | 320a49f768cea27200044c0d12f394aa6c795feb | <|skeleton|>
class FixedWindowLengthDistribution:
"""Represents a distribution with a fixed value over a window. The window is specified by a mimimum and maximum value. Further, a "right_tail_mass" can be specified. If given, that fraction of the total probability mass is added as an exponential distribution to the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FixedWindowLengthDistribution:
"""Represents a distribution with a fixed value over a window. The window is specified by a mimimum and maximum value. Further, a "right_tail_mass" can be specified. If given, that fraction of the total probability mass is added as an exponential distribution to the right side o... | the_stack_v2_python_sparse | smu/geometry/bond_length_distribution.py | afcarl/google-research | train | 1 |
e3e1091ecb5601df2e558a4a3a63d50054551116 | [
"store_config = config.online_store\nassert isinstance(store_config, HbaseOnlineStoreConfig)\nif not self._conn:\n self._conn = Connection(host=store_config.host, port=int(store_config.port))\nreturn self._conn",
"hbase = HbaseUtils(self._get_conn(config))\nproject = config.project\ntable_name = _table_id(proj... | <|body_start_0|>
store_config = config.online_store
assert isinstance(store_config, HbaseOnlineStoreConfig)
if not self._conn:
self._conn = Connection(host=store_config.host, port=int(store_config.port))
return self._conn
<|end_body_0|>
<|body_start_1|>
hbase = Hbase... | Online feature store for Hbase. Attributes: _conn: Happybase Connection to connect to hbase thrift server. | HbaseOnlineStore | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HbaseOnlineStore:
"""Online feature store for Hbase. Attributes: _conn: Happybase Connection to connect to hbase thrift server."""
def _get_conn(self, config: RepoConfig):
"""Get or Create Hbase Connection from Repoconfig. Args: config: The RepoConfig for the current FeatureStore."""... | stack_v2_sparse_classes_36k_train_026750 | 8,571 | permissive | [
{
"docstring": "Get or Create Hbase Connection from Repoconfig. Args: config: The RepoConfig for the current FeatureStore.",
"name": "_get_conn",
"signature": "def _get_conn(self, config: RepoConfig)"
},
{
"docstring": "Write a batch of feature rows to Hbase online store. Args: config: The RepoC... | 5 | stack_v2_sparse_classes_30k_train_001882 | Implement the Python class `HbaseOnlineStore` described below.
Class description:
Online feature store for Hbase. Attributes: _conn: Happybase Connection to connect to hbase thrift server.
Method signatures and docstrings:
- def _get_conn(self, config: RepoConfig): Get or Create Hbase Connection from Repoconfig. Args... | Implement the Python class `HbaseOnlineStore` described below.
Class description:
Online feature store for Hbase. Attributes: _conn: Happybase Connection to connect to hbase thrift server.
Method signatures and docstrings:
- def _get_conn(self, config: RepoConfig): Get or Create Hbase Connection from Repoconfig. Args... | 58aff346832ebde1695a47cf724da3d65a4a8c53 | <|skeleton|>
class HbaseOnlineStore:
"""Online feature store for Hbase. Attributes: _conn: Happybase Connection to connect to hbase thrift server."""
def _get_conn(self, config: RepoConfig):
"""Get or Create Hbase Connection from Repoconfig. Args: config: The RepoConfig for the current FeatureStore."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HbaseOnlineStore:
"""Online feature store for Hbase. Attributes: _conn: Happybase Connection to connect to hbase thrift server."""
def _get_conn(self, config: RepoConfig):
"""Get or Create Hbase Connection from Repoconfig. Args: config: The RepoConfig for the current FeatureStore."""
stor... | the_stack_v2_python_sparse | sdk/python/feast/infra/online_stores/contrib/hbase_online_store/hbase.py | feast-dev/feast | train | 3,956 |
c4e6b127330682d4c5d6bf997bf9f0c9ed616928 | [
"super().__init__()\nself.generator = Generator()\nself.master = Master()",
"logger.info('SpNasPipeStep started')\nwhile not self.generator.is_completed:\n id, spnas_sample = self.generator.search_alg.search()\n cls_trainer = ClassFactory.get_cls('trainer')\n trainer = cls_trainer(spnas_sample=spnas_samp... | <|body_start_0|>
super().__init__()
self.generator = Generator()
self.master = Master()
<|end_body_0|>
<|body_start_1|>
logger.info('SpNasPipeStep started')
while not self.generator.is_completed:
id, spnas_sample = self.generator.search_alg.search()
cls_t... | PipeStep is the base components class that can be added in Pipeline. | SpNasPipeStep | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpNasPipeStep:
"""PipeStep is the base components class that can be added in Pipeline."""
def __init__(self):
"""Initialize SpNasPipeStep."""
<|body_0|>
def do(self):
"""Do the main task in this pipe step."""
<|body_1|>
def update_generator(self, gen... | stack_v2_sparse_classes_36k_train_026751 | 3,119 | permissive | [
{
"docstring": "Initialize SpNasPipeStep.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Do the main task in this pipe step.",
"name": "do",
"signature": "def do(self)"
},
{
"docstring": "Get finished worker's info, and use it to update target `generat... | 3 | stack_v2_sparse_classes_30k_train_014898 | Implement the Python class `SpNasPipeStep` described below.
Class description:
PipeStep is the base components class that can be added in Pipeline.
Method signatures and docstrings:
- def __init__(self): Initialize SpNasPipeStep.
- def do(self): Do the main task in this pipe step.
- def update_generator(self, generat... | Implement the Python class `SpNasPipeStep` described below.
Class description:
PipeStep is the base components class that can be added in Pipeline.
Method signatures and docstrings:
- def __init__(self): Initialize SpNasPipeStep.
- def do(self): Do the main task in this pipe step.
- def update_generator(self, generat... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class SpNasPipeStep:
"""PipeStep is the base components class that can be added in Pipeline."""
def __init__(self):
"""Initialize SpNasPipeStep."""
<|body_0|>
def do(self):
"""Do the main task in this pipe step."""
<|body_1|>
def update_generator(self, gen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpNasPipeStep:
"""PipeStep is the base components class that can be added in Pipeline."""
def __init__(self):
"""Initialize SpNasPipeStep."""
super().__init__()
self.generator = Generator()
self.master = Master()
def do(self):
"""Do the main task in this pipe ... | the_stack_v2_python_sparse | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/algorithms/nas/sp_nas/spnas_pipe_step.py | Huawei-Ascend/modelzoo | train | 1 |
4140cd45a8b4a78c04e0c45a079d9561fbf23c41 | [
"def backtrace(n, k, order):\n if k == 0:\n ans.append(order)\n return None\n if order and k + order[-1] > n:\n return None\n s_index = 0 if not order else order[-1]\n for i in range(s_index + 1, n + 1):\n backtrace(n, k - 1, order + [i])\nans = []\nbacktrace(n, k, [])\nretur... | <|body_start_0|>
def backtrace(n, k, order):
if k == 0:
ans.append(order)
return None
if order and k + order[-1] > n:
return None
s_index = 0 if not order else order[-1]
for i in range(s_index + 1, n + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
"""回溯法"""
<|body_0|>
def combine_2(self, n: int, k: int) -> List[List[int]]:
"""广度搜索"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def backtrace(n, k, order):
if k == 0:
... | stack_v2_sparse_classes_36k_train_026752 | 1,146 | no_license | [
{
"docstring": "回溯法",
"name": "combine",
"signature": "def combine(self, n: int, k: int) -> List[List[int]]"
},
{
"docstring": "广度搜索",
"name": "combine_2",
"signature": "def combine_2(self, n: int, k: int) -> List[List[int]]"
}
] | 2 | stack_v2_sparse_classes_30k_train_002293 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combine(self, n: int, k: int) -> List[List[int]]: 回溯法
- def combine_2(self, n: int, k: int) -> List[List[int]]: 广度搜索 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combine(self, n: int, k: int) -> List[List[int]]: 回溯法
- def combine_2(self, n: int, k: int) -> List[List[int]]: 广度搜索
<|skeleton|>
class Solution:
def combine(self, n: i... | f2c162654a83c51495ebd161f42a1d0b69caf72d | <|skeleton|>
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
"""回溯法"""
<|body_0|>
def combine_2(self, n: int, k: int) -> List[List[int]]:
"""广度搜索"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
"""回溯法"""
def backtrace(n, k, order):
if k == 0:
ans.append(order)
return None
if order and k + order[-1] > n:
return None
s_index = 0 if not orde... | the_stack_v2_python_sparse | 77 combine.py | ABenxj/leetcode | train | 1 | |
b6fe29e3d13bf48942a2a364d83e64096e054ec8 | [
"S = set([''])\n\ndef helper(s, i, n, max_len, longest):\n if i >= n:\n return longest\n c = s[i]\n if c in S:\n for j in range(i):\n if s[j] == c:\n inner_str = s[j + 1:i]\n if inner_str in S:\n p = c + inner_str + c\n ... | <|body_start_0|>
S = set([''])
def helper(s, i, n, max_len, longest):
if i >= n:
return longest
c = s[i]
if c in S:
for j in range(i):
if s[j] == c:
inner_str = s[j + 1:i]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome_v1(self, s: str) -> str:
"""Use a set to track known palindromes."""
<|body_0|>
def longestPalindrome_v2(self, s: str) -> str:
"""Based on an implementation found on LeetCode. The core concept is to expand, from 1 char to 2 chars, sinc... | stack_v2_sparse_classes_36k_train_026753 | 3,510 | no_license | [
{
"docstring": "Use a set to track known palindromes.",
"name": "longestPalindrome_v1",
"signature": "def longestPalindrome_v1(self, s: str) -> str"
},
{
"docstring": "Based on an implementation found on LeetCode. The core concept is to expand, from 1 char to 2 chars, since a palindrome can have... | 2 | stack_v2_sparse_classes_30k_train_017183 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome_v1(self, s: str) -> str: Use a set to track known palindromes.
- def longestPalindrome_v2(self, s: str) -> str: Based on an implementation found on LeetCode... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome_v1(self, s: str) -> str: Use a set to track known palindromes.
- def longestPalindrome_v2(self, s: str) -> str: Based on an implementation found on LeetCode... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def longestPalindrome_v1(self, s: str) -> str:
"""Use a set to track known palindromes."""
<|body_0|>
def longestPalindrome_v2(self, s: str) -> str:
"""Based on an implementation found on LeetCode. The core concept is to expand, from 1 char to 2 chars, sinc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome_v1(self, s: str) -> str:
"""Use a set to track known palindromes."""
S = set([''])
def helper(s, i, n, max_len, longest):
if i >= n:
return longest
c = s[i]
if c in S:
for j in range(i)... | the_stack_v2_python_sparse | python3/dynamic_programming/longest_palindromic_substring.py | victorchu/algorithms | train | 0 | |
83ce793ab6370b162367585b8c071081bee388da | [
"self.database_id = database_id\nself.name = name\nself.open_mode = open_mode\nself.size_bytes = size_bytes",
"if dictionary is None:\n return None\ndatabase_id = dictionary.get('databaseId')\nname = dictionary.get('name')\nopen_mode = dictionary.get('openMode')\nsize_bytes = dictionary.get('sizeBytes')\nretur... | <|body_start_0|>
self.database_id = database_id
self.name = name
self.open_mode = open_mode
self.size_bytes = size_bytes
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
database_id = dictionary.get('databaseId')
name = dictionary.ge... | Implementation of the 'OraclePluggableDatabaseInfo' model. Specifies the informatiomn about the pluggable database. A Pluggabele Database(PDB) is a portable collection of schemas, schema objects, and nonschema objects that appears to an Oracle Net client as a non-CDB. Attributes: database_id (string): Specifies the ID ... | OraclePluggableDatabaseInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OraclePluggableDatabaseInfo:
"""Implementation of the 'OraclePluggableDatabaseInfo' model. Specifies the informatiomn about the pluggable database. A Pluggabele Database(PDB) is a portable collection of schemas, schema objects, and nonschema objects that appears to an Oracle Net client as a non-C... | stack_v2_sparse_classes_36k_train_026754 | 2,649 | permissive | [
{
"docstring": "Constructor for the OraclePluggableDatabaseInfo class",
"name": "__init__",
"signature": "def __init__(self, database_id=None, name=None, open_mode=None, size_bytes=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dict... | 2 | stack_v2_sparse_classes_30k_train_021612 | Implement the Python class `OraclePluggableDatabaseInfo` described below.
Class description:
Implementation of the 'OraclePluggableDatabaseInfo' model. Specifies the informatiomn about the pluggable database. A Pluggabele Database(PDB) is a portable collection of schemas, schema objects, and nonschema objects that app... | Implement the Python class `OraclePluggableDatabaseInfo` described below.
Class description:
Implementation of the 'OraclePluggableDatabaseInfo' model. Specifies the informatiomn about the pluggable database. A Pluggabele Database(PDB) is a portable collection of schemas, schema objects, and nonschema objects that app... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class OraclePluggableDatabaseInfo:
"""Implementation of the 'OraclePluggableDatabaseInfo' model. Specifies the informatiomn about the pluggable database. A Pluggabele Database(PDB) is a portable collection of schemas, schema objects, and nonschema objects that appears to an Oracle Net client as a non-C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OraclePluggableDatabaseInfo:
"""Implementation of the 'OraclePluggableDatabaseInfo' model. Specifies the informatiomn about the pluggable database. A Pluggabele Database(PDB) is a portable collection of schemas, schema objects, and nonschema objects that appears to an Oracle Net client as a non-CDB. Attribute... | the_stack_v2_python_sparse | cohesity_management_sdk/models/oracle_pluggable_database_info.py | cohesity/management-sdk-python | train | 24 |
c69eb988ab440c4c62f87e15231cdc9daf2ebc7a | [
"if os.path.exists(KEYS_FILENAME):\n with open(KEYS_FILENAME) as f:\n data = json.load(f)\n self.left_arm = data['left']\n self.right_arm = data['right']\n rospy.logdebug('Loaded: %s', data)\nelse:\n self.left_arm = {}\n self.right_arm = {}",
"if note <= NEUTRAL_KEY:\n self... | <|body_start_0|>
if os.path.exists(KEYS_FILENAME):
with open(KEYS_FILENAME) as f:
data = json.load(f)
self.left_arm = data['left']
self.right_arm = data['right']
rospy.logdebug('Loaded: %s', data)
else:
self.left_arm... | Maintain the dictionary of key mappings | Keys | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Keys:
"""Maintain the dictionary of key mappings"""
def __init__(self):
"""Initialize a keys object"""
<|body_0|>
def save_left(self, note, angles):
"""Save a note with certain joint angles on the left arm. Args: note (int): the note to save angles: the joint pos... | stack_v2_sparse_classes_36k_train_026755 | 6,888 | permissive | [
{
"docstring": "Initialize a keys object",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Save a note with certain joint angles on the left arm. Args: note (int): the note to save angles: the joint position",
"name": "save_left",
"signature": "def save_left(self... | 5 | stack_v2_sparse_classes_30k_train_009538 | Implement the Python class `Keys` described below.
Class description:
Maintain the dictionary of key mappings
Method signatures and docstrings:
- def __init__(self): Initialize a keys object
- def save_left(self, note, angles): Save a note with certain joint angles on the left arm. Args: note (int): the note to save ... | Implement the Python class `Keys` described below.
Class description:
Maintain the dictionary of key mappings
Method signatures and docstrings:
- def __init__(self): Initialize a keys object
- def save_left(self, note, angles): Save a note with certain joint angles on the left arm. Args: note (int): the note to save ... | a4c95faefc964c147807dffccf55e7d7a5c58bb0 | <|skeleton|>
class Keys:
"""Maintain the dictionary of key mappings"""
def __init__(self):
"""Initialize a keys object"""
<|body_0|>
def save_left(self, note, angles):
"""Save a note with certain joint angles on the left arm. Args: note (int): the note to save angles: the joint pos... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Keys:
"""Maintain the dictionary of key mappings"""
def __init__(self):
"""Initialize a keys object"""
if os.path.exists(KEYS_FILENAME):
with open(KEYS_FILENAME) as f:
data = json.load(f)
self.left_arm = data['left']
self.right_a... | the_stack_v2_python_sparse | src/artist_performer/learner.py | jasonsbrooks/ARTIST | train | 0 |
7baf0c12abe3c3ed63810a3bcc3471ae88a46c27 | [
"self.driver.find_element_by_link_text('登录').click()\nself.driver.find_element_by_name('login_info').send_keys('wwww')\nself.driver.find_element_by_name('password').send_keys('111111')\nself.driver.find_element_by_class_name('input_submit').click()\nself.assertIn('账号或密码错误', self.driver.find_element_by_xpath('/html/... | <|body_start_0|>
self.driver.find_element_by_link_text('登录').click()
self.driver.find_element_by_name('login_info').send_keys('wwww')
self.driver.find_element_by_name('password').send_keys('111111')
self.driver.find_element_by_class_name('input_submit').click()
self.assertIn('账号或... | 测试购物商场登录用例 | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
"""测试购物商场登录用例"""
def test_loginf(self):
"""错误的用户名"""
<|body_0|>
def test_loginf1(self):
"""错误的密码"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.driver.find_element_by_link_text('登录').click()
self.driver.find_element_by_n... | stack_v2_sparse_classes_36k_train_026756 | 2,193 | no_license | [
{
"docstring": "错误的用户名",
"name": "test_loginf",
"signature": "def test_loginf(self)"
},
{
"docstring": "错误的密码",
"name": "test_loginf1",
"signature": "def test_loginf1(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007636 | Implement the Python class `TestLogin` described below.
Class description:
测试购物商场登录用例
Method signatures and docstrings:
- def test_loginf(self): 错误的用户名
- def test_loginf1(self): 错误的密码 | Implement the Python class `TestLogin` described below.
Class description:
测试购物商场登录用例
Method signatures and docstrings:
- def test_loginf(self): 错误的用户名
- def test_loginf1(self): 错误的密码
<|skeleton|>
class TestLogin:
"""测试购物商场登录用例"""
def test_loginf(self):
"""错误的用户名"""
<|body_0|>
def test_... | 7b790f675419224bfdbe1542eddc5a638982e68a | <|skeleton|>
class TestLogin:
"""测试购物商场登录用例"""
def test_loginf(self):
"""错误的用户名"""
<|body_0|>
def test_loginf1(self):
"""错误的密码"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLogin:
"""测试购物商场登录用例"""
def test_loginf(self):
"""错误的用户名"""
self.driver.find_element_by_link_text('登录').click()
self.driver.find_element_by_name('login_info').send_keys('wwww')
self.driver.find_element_by_name('password').send_keys('111111')
self.driver.find_el... | the_stack_v2_python_sparse | task/day12/testcases/test_false.py | liousAlready/NewDream_learning | train | 0 |
8c5feb4c6339395b4d32c9bca7881fa1d23db0b6 | [
"try:\n artifact = Artifact.find_by(id_=params.pop('id'))\n builder = ArtifactConnector.for_artifact(artifact)\n existing_tags = artifact.tags or []\n new_list = existing_tags + list(set(params['tags']) - set(existing_tags))\n builder.update_with(tags=new_list)\n return no_content()\nexcept Artifa... | <|body_start_0|>
try:
artifact = Artifact.find_by(id_=params.pop('id'))
builder = ArtifactConnector.for_artifact(artifact)
existing_tags = artifact.tags or []
new_list = existing_tags + list(set(params['tags']) - set(existing_tags))
builder.update_with... | Controller for Artifacts | TagsView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagsView:
"""Controller for Artifacts"""
def add_tags(self, **params):
"""Adds tags to an existing artifact"""
<|body_0|>
def suggested_tags(self, **params):
"""Takes an array of tags and suggests tags based on that"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_026757 | 1,822 | permissive | [
{
"docstring": "Adds tags to an existing artifact",
"name": "add_tags",
"signature": "def add_tags(self, **params)"
},
{
"docstring": "Takes an array of tags and suggests tags based on that",
"name": "suggested_tags",
"signature": "def suggested_tags(self, **params)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006746 | Implement the Python class `TagsView` described below.
Class description:
Controller for Artifacts
Method signatures and docstrings:
- def add_tags(self, **params): Adds tags to an existing artifact
- def suggested_tags(self, **params): Takes an array of tags and suggests tags based on that | Implement the Python class `TagsView` described below.
Class description:
Controller for Artifacts
Method signatures and docstrings:
- def add_tags(self, **params): Adds tags to an existing artifact
- def suggested_tags(self, **params): Takes an array of tags and suggests tags based on that
<|skeleton|>
class TagsVi... | 98173eb380bd6add52b21dc9045893949a8a2d30 | <|skeleton|>
class TagsView:
"""Controller for Artifacts"""
def add_tags(self, **params):
"""Adds tags to an existing artifact"""
<|body_0|>
def suggested_tags(self, **params):
"""Takes an array of tags and suggests tags based on that"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TagsView:
"""Controller for Artifacts"""
def add_tags(self, **params):
"""Adds tags to an existing artifact"""
try:
artifact = Artifact.find_by(id_=params.pop('id'))
builder = ArtifactConnector.for_artifact(artifact)
existing_tags = artifact.tags or []
... | the_stack_v2_python_sparse | application/artifacts/tags/tags_view.py | hpi-sam/ask-your-repository-api | train | 4 |
6cf1f5fa3fe7944642cd85cfa1aa2a5ff1ffcaa5 | [
"self.job_id = uuid.uuid4().hex\nself.job_folder = os.path.join(self.scratch_folder, self.job_id)\nos.mkdir(self.job_folder)",
"self.logger.debug('Creating output geodatabase...')\nout_gdb = os.path.join(self.job_folder, 'scratch.gdb')\nrun_gp_tool(self.logger, arcpy.management.CreateFileGDB, [os.path.dirname(out... | <|body_start_0|>
self.job_id = uuid.uuid4().hex
self.job_folder = os.path.join(self.scratch_folder, self.job_id)
os.mkdir(self.job_folder)
<|end_body_0|>
<|body_start_1|>
self.logger.debug('Creating output geodatabase...')
out_gdb = os.path.join(self.job_folder, 'scratch.gdb')
... | Used to define and create a job folder for a parallel process. | JobFolderMixin | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobFolderMixin:
"""Used to define and create a job folder for a parallel process."""
def _create_job_folder(self):
"""Create a job ID and a folder and scratch gdb for this job."""
<|body_0|>
def _create_output_gdb(self):
"""Create a scratch geodatabase in the job... | stack_v2_sparse_classes_36k_train_026758 | 42,314 | permissive | [
{
"docstring": "Create a job ID and a folder and scratch gdb for this job.",
"name": "_create_job_folder",
"signature": "def _create_job_folder(self)"
},
{
"docstring": "Create a scratch geodatabase in the job folder. Returns: str: Catalog path to output geodatabase",
"name": "_create_output... | 2 | stack_v2_sparse_classes_30k_train_009300 | Implement the Python class `JobFolderMixin` described below.
Class description:
Used to define and create a job folder for a parallel process.
Method signatures and docstrings:
- def _create_job_folder(self): Create a job ID and a folder and scratch gdb for this job.
- def _create_output_gdb(self): Create a scratch g... | Implement the Python class `JobFolderMixin` described below.
Class description:
Used to define and create a job folder for a parallel process.
Method signatures and docstrings:
- def _create_job_folder(self): Create a job ID and a folder and scratch gdb for this job.
- def _create_output_gdb(self): Create a scratch g... | 47cbc3de67a7b1bf9255e07e88cba7b051db0505 | <|skeleton|>
class JobFolderMixin:
"""Used to define and create a job folder for a parallel process."""
def _create_job_folder(self):
"""Create a job ID and a folder and scratch gdb for this job."""
<|body_0|>
def _create_output_gdb(self):
"""Create a scratch geodatabase in the job... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JobFolderMixin:
"""Used to define and create a job folder for a parallel process."""
def _create_job_folder(self):
"""Create a job ID and a folder and scratch gdb for this job."""
self.job_id = uuid.uuid4().hex
self.job_folder = os.path.join(self.scratch_folder, self.job_id)
... | the_stack_v2_python_sparse | transit-network-analysis-tools/AnalysisHelpers.py | Esri/public-transit-tools | train | 155 |
52d5bcbf55130f1cc0b4c5eb2c62768eae307ff6 | [
"ret = list()\nif not root:\n return json.dumps(ret)\nlevel = [root]\nwhile any(level):\n for node in level:\n if node:\n ret.append(node.val)\n else:\n ret.append(None)\n tmp = list()\n for node in level:\n if node:\n tmp.extend([node.left, node.rig... | <|body_start_0|>
ret = list()
if not root:
return json.dumps(ret)
level = [root]
while any(level):
for node in level:
if node:
ret.append(node.val)
else:
ret.append(None)
tmp = lis... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_026759 | 1,940 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_012644 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | aea2630be6ca2c60186593d6e66b0a59e56dc848 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
ret = list()
if not root:
return json.dumps(ret)
level = [root]
while any(level):
for node in level:
if node:
... | the_stack_v2_python_sparse | 十二、剑指offer-Python/面试题37.序列化二叉树.py | Lcoderfit/Introduction-to-algotithms | train | 3 | |
1019f891551b3e0b792f504da109bef002843460 | [
"self.n_states = n_states\nif isinstance(self.n_states, int):\n n_states = (np.arange(self.n_states + 1) // 2)[1:] * (-1) ** np.arange(1, self.n_states + 1)\nif domain is None:\n domain = [0, 2.0 * np.pi]\nsuper(FourierBasis, self).__init__(n_states=n_states, domain=domain)",
"self._select_axes(X)\nX_scaled... | <|body_start_0|>
self.n_states = n_states
if isinstance(self.n_states, int):
n_states = (np.arange(self.n_states + 1) // 2)[1:] * (-1) ** np.arange(1, self.n_states + 1)
if domain is None:
domain = [0, 2.0 * np.pi]
super(FourierBasis, self).__init__(n_states=n_sta... | Discretize a continuous field into `deg` local states using complex exponentials such that, .. math:: \\frac{1}{\\Delta x} \\int_s m(h, x) dx = \\sum_{- L / 2}^{L / 2} m[l, s] exp(l*h*I) and the local state space :math:`H` is mapped into the orthogonal domain .. math:: 0 \\le H \\le 2 \\pi The mapping of :math:`H` into... | FourierBasis | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FourierBasis:
"""Discretize a continuous field into `deg` local states using complex exponentials such that, .. math:: \\frac{1}{\\Delta x} \\int_s m(h, x) dx = \\sum_{- L / 2}^{L / 2} m[l, s] exp(l*h*I) and the local state space :math:`H` is mapped into the orthogonal domain .. math:: 0 \\le H \... | stack_v2_sparse_classes_36k_train_026760 | 3,606 | permissive | [
{
"docstring": "Instantiate a `FourierBasis` Args: n_states (int, list): The number of local states, or list of local states to be used. domain (list, optional): indicate the range of expected values for the microstructure, default is [0, 2\\\\pi].",
"name": "__init__",
"signature": "def __init__(self, ... | 2 | stack_v2_sparse_classes_30k_train_002277 | Implement the Python class `FourierBasis` described below.
Class description:
Discretize a continuous field into `deg` local states using complex exponentials such that, .. math:: \\frac{1}{\\Delta x} \\int_s m(h, x) dx = \\sum_{- L / 2}^{L / 2} m[l, s] exp(l*h*I) and the local state space :math:`H` is mapped into the... | Implement the Python class `FourierBasis` described below.
Class description:
Discretize a continuous field into `deg` local states using complex exponentials such that, .. math:: \\frac{1}{\\Delta x} \\int_s m(h, x) dx = \\sum_{- L / 2}^{L / 2} m[l, s] exp(l*h*I) and the local state space :math:`H` is mapped into the... | 9b582ddd5e120ea50d9023301577797ae5c434c3 | <|skeleton|>
class FourierBasis:
"""Discretize a continuous field into `deg` local states using complex exponentials such that, .. math:: \\frac{1}{\\Delta x} \\int_s m(h, x) dx = \\sum_{- L / 2}^{L / 2} m[l, s] exp(l*h*I) and the local state space :math:`H` is mapped into the orthogonal domain .. math:: 0 \\le H \... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FourierBasis:
"""Discretize a continuous field into `deg` local states using complex exponentials such that, .. math:: \\frac{1}{\\Delta x} \\int_s m(h, x) dx = \\sum_{- L / 2}^{L / 2} m[l, s] exp(l*h*I) and the local state space :math:`H` is mapped into the orthogonal domain .. math:: 0 \\le H \\le 2 \\pi Th... | the_stack_v2_python_sparse | pymks/bases/fourier.py | materialsinnovation/pymks | train | 118 |
93ff17bba11c64f207e49589ece4bb97b3aceef7 | [
"array = list(s)\nbegin = 0\nend = len(s) - 1\nwhile begin < end:\n temp = array[begin]\n array[begin] = array[end]\n array[end] = temp\n begin += 1\n end -= 1\nreturn ''.join(array)",
"arr = self.reverse(s).split()\narray_new = []\nfor item in arr:\n array_new.append(self.reverse(item))\nreturn... | <|body_start_0|>
array = list(s)
begin = 0
end = len(s) - 1
while begin < end:
temp = array[begin]
array[begin] = array[end]
array[end] = temp
begin += 1
end -= 1
return ''.join(array)
<|end_body_0|>
<|body_start_1|>
... | 面试题58 - I. 翻转单词顺序 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 示例 3: 输入: "a good example" 输出: "example good a" 解释: 如果两个单词间有多余的空格,... | ReverseWords | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReverseWords:
"""面试题58 - I. 翻转单词顺序 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 示例 3: 输入: "a good example"... | stack_v2_sparse_classes_36k_train_026761 | 2,527 | no_license | [
{
"docstring": "字符串内容全部翻转",
"name": "reverse",
"signature": "def reverse(self, s: str)"
},
{
"docstring": "只翻转单词顺序,不翻转单词",
"name": "reverse_words",
"signature": "def reverse_words(self, s: str)"
},
{
"docstring": "方法二:使用内置函数",
"name": "reverse_words2",
"signature": "def r... | 3 | stack_v2_sparse_classes_30k_train_006520 | Implement the Python class `ReverseWords` described below.
Class description:
面试题58 - I. 翻转单词顺序 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但... | Implement the Python class `ReverseWords` described below.
Class description:
面试题58 - I. 翻转单词顺序 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但... | 099feb4e4c8dec9e68887cedd95705d831e51b0f | <|skeleton|>
class ReverseWords:
"""面试题58 - I. 翻转单词顺序 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 示例 3: 输入: "a good example"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReverseWords:
"""面试题58 - I. 翻转单词顺序 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 示例 3: 输入: "a good example" 输出: "example... | the_stack_v2_python_sparse | leetcode/reverse_words.py | indeyo/PythonStudy | train | 0 |
58a63bf8cf3844d7d5a6fae45be4fc5e0a2ce0ce | [
"super(RevokeRequestPayload, self).__init__()\nself.unique_identifier = unique_identifier\nself.compromise_occurrence_date = compromise_occurrence_date\nself.revocation_reason = revocation_reason\nif self.revocation_reason is None:\n self.revocation_reason = objects.RevocationReason()\nself.validate()",
"super... | <|body_start_0|>
super(RevokeRequestPayload, self).__init__()
self.unique_identifier = unique_identifier
self.compromise_occurrence_date = compromise_occurrence_date
self.revocation_reason = revocation_reason
if self.revocation_reason is None:
self.revocation_reason =... | A request payload for the Revoke operation. The payload contains a UUID of a cryptographic object that that server should revoke. See Section 4.20 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a managed cryptographic object revocation_reason: The reason why the object wa... | RevokeRequestPayload | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RevokeRequestPayload:
"""A request payload for the Revoke operation. The payload contains a UUID of a cryptographic object that that server should revoke. See Section 4.20 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a managed cryptographic object... | stack_v2_sparse_classes_36k_train_026762 | 8,772 | permissive | [
{
"docstring": "Construct a RevokeRequestPayload object. Args: unique_identifier (UniqueIdentifier): The UUID of a managed cryptographic object. revocation_reason (RevocationReason): The reason why the object was revoked. compromise_occurrence_date (DateTime): the datetime when the object was first believed to ... | 4 | null | Implement the Python class `RevokeRequestPayload` described below.
Class description:
A request payload for the Revoke operation. The payload contains a UUID of a cryptographic object that that server should revoke. See Section 4.20 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The... | Implement the Python class `RevokeRequestPayload` described below.
Class description:
A request payload for the Revoke operation. The payload contains a UUID of a cryptographic object that that server should revoke. See Section 4.20 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The... | f0a44b26ce902d8b9c330634d5b3603959edf1d4 | <|skeleton|>
class RevokeRequestPayload:
"""A request payload for the Revoke operation. The payload contains a UUID of a cryptographic object that that server should revoke. See Section 4.20 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a managed cryptographic object... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RevokeRequestPayload:
"""A request payload for the Revoke operation. The payload contains a UUID of a cryptographic object that that server should revoke. See Section 4.20 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a managed cryptographic object revocation_r... | the_stack_v2_python_sparse | kmip/core/messages/payloads/revoke.py | OpenKMIP/PyKMIP | train | 232 |
611262e53d378c269c596c58a7766c2d8a72b750 | [
"import heapq\nh = []\ngas = startFuel\ni = 0\nans = 0\nwhile gas < target:\n while i < len(stations) and stations[i][0] <= gas:\n heapq.heappush(h, -stations[i][1])\n i += 1\n if h == []:\n return -1\n gas -= heapq.heappop(h)\n ans += 1\nreturn ans if gas >= target else -1",
"dp ... | <|body_start_0|>
import heapq
h = []
gas = startFuel
i = 0
ans = 0
while gas < target:
while i < len(stations) and stations[i][0] <= gas:
heapq.heappush(h, -stations[i][1])
i += 1
if h == []:
return -... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minRefuelStops(self, target, startFuel, stations):
""":type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int 44 ms"""
<|body_0|>
def minRefuelStops_1(self, target, startFuel, stations):
""":type target: int :type startFuel: i... | stack_v2_sparse_classes_36k_train_026763 | 3,498 | no_license | [
{
"docstring": ":type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int 44 ms",
"name": "minRefuelStops",
"signature": "def minRefuelStops(self, target, startFuel, stations)"
},
{
"docstring": ":type target: int :type startFuel: int :type stations: List[List[int]] :rty... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minRefuelStops(self, target, startFuel, stations): :type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int 44 ms
- def minRefuelStops_1(self, targe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minRefuelStops(self, target, startFuel, stations): :type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int 44 ms
- def minRefuelStops_1(self, targe... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def minRefuelStops(self, target, startFuel, stations):
""":type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int 44 ms"""
<|body_0|>
def minRefuelStops_1(self, target, startFuel, stations):
""":type target: int :type startFuel: i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minRefuelStops(self, target, startFuel, stations):
""":type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int 44 ms"""
import heapq
h = []
gas = startFuel
i = 0
ans = 0
while gas < target:
while i < le... | the_stack_v2_python_sparse | MinimumNumberOfRefuelingStops_HARD_871.py | 953250587/leetcode-python | train | 2 | |
ee2163444009e02b30dd264718be56eeedbe166b | [
"self.num_classes = num_classes\nself.num_shots = num_shots\nself.num_queries = num_queries\nself.shape_x = shape_x\nself.dataset = dataset\nself.batch_size = batch_size\nself.rng = np.random.RandomState(706)",
"num_classes = self.num_classes\nnum_shots = self.num_shots\nnum_queries = self.num_queries\nshape_x = ... | <|body_start_0|>
self.num_classes = num_classes
self.num_shots = num_shots
self.num_queries = num_queries
self.shape_x = shape_x
self.dataset = dataset
self.batch_size = batch_size
self.rng = np.random.RandomState(706)
<|end_body_0|>
<|body_start_1|>
num_... | DataGenerator | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0",
"CC-BY-NC-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataGenerator:
def __init__(self, num_classes, num_shots, num_queries, shape_x, dataset, batch_size):
"""Create episode function Args: num_classes (int): number of support classes, generally called n_way in one-shot literatuer num_shots (int): number of shots per class num_queries (int):... | stack_v2_sparse_classes_36k_train_026764 | 3,834 | permissive | [
{
"docstring": "Create episode function Args: num_classes (int): number of support classes, generally called n_way in one-shot literatuer num_shots (int): number of shots per class num_queries (int): numper of queries per class. shape_x (tuple): dimension of the input image. dataset(nd_array): nd_array of (clas... | 2 | stack_v2_sparse_classes_30k_train_016010 | Implement the Python class `DataGenerator` described below.
Class description:
Implement the DataGenerator class.
Method signatures and docstrings:
- def __init__(self, num_classes, num_shots, num_queries, shape_x, dataset, batch_size): Create episode function Args: num_classes (int): number of support classes, gener... | Implement the Python class `DataGenerator` described below.
Class description:
Implement the DataGenerator class.
Method signatures and docstrings:
- def __init__(self, num_classes, num_shots, num_queries, shape_x, dataset, batch_size): Create episode function Args: num_classes (int): number of support classes, gener... | 41f71faa6efff7774a76bbd5af3198322a90a6ab | <|skeleton|>
class DataGenerator:
def __init__(self, num_classes, num_shots, num_queries, shape_x, dataset, batch_size):
"""Create episode function Args: num_classes (int): number of support classes, generally called n_way in one-shot literatuer num_shots (int): number of shots per class num_queries (int):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataGenerator:
def __init__(self, num_classes, num_shots, num_queries, shape_x, dataset, batch_size):
"""Create episode function Args: num_classes (int): number of support classes, generally called n_way in one-shot literatuer num_shots (int): number of shots per class num_queries (int): numper of que... | the_stack_v2_python_sparse | meta-learning/maml/data_generator_maml.py | sony/nnabla-examples | train | 308 | |
3eff43eed38a4e83a1778e2fc80af3adcf78b6bb | [
"if x < 0:\n return None\np = x\nwhile p * p - x >= 1:\n p = 0.5 * (p + x / p)\nreturn int(p)",
"if x < 0:\n return None\nleft = 0\nright = x\nwhile True:\n mid = (left + right) // 2\n if mid * mid > x:\n right = mid - 1\n else:\n if (mid + 1) ** 2 > x:\n return mid\n ... | <|body_start_0|>
if x < 0:
return None
p = x
while p * p - x >= 1:
p = 0.5 * (p + x / p)
return int(p)
<|end_body_0|>
<|body_start_1|>
if x < 0:
return None
left = 0
right = x
while True:
mid = (left + right... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def mySqrt2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x < 0:
return None
p = x
while p * p - x >= 1:
... | stack_v2_sparse_classes_36k_train_026765 | 795 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "mySqrt",
"signature": "def mySqrt(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "mySqrt2",
"signature": "def mySqrt2(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019771 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): :type x: int :rtype: int
- def mySqrt2(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): :type x: int :rtype: int
- def mySqrt2(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rt... | 032016724564d0bee85f9e1b9d9d6c769d0eb667 | <|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def mySqrt2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
if x < 0:
return None
p = x
while p * p - x >= 1:
p = 0.5 * (p + x / p)
return int(p)
def mySqrt2(self, x):
""":type x: int :rtype: int"""
if x < 0:
re... | the_stack_v2_python_sparse | q69.py | maples1993/LeetCode | train | 1 | |
cccf35bb26e3ef4b0b352ac6fbbaf7100b449905 | [
"super(EncoderBlock, self).__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(... | <|body_start_0|>
super(EncoderBlock, self).__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)
... | EncoderBlock class Creates an encoder block for a transformer | EncoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderBlock:
"""EncoderBlock class Creates an encoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1) -> None:
"""Initializer Arguments: dm {int} -- Is a represention of the dimensionality of the model h {int} -- Is a represention of the number of head hi... | stack_v2_sparse_classes_36k_train_026766 | 2,001 | no_license | [
{
"docstring": "Initializer Arguments: dm {int} -- Is a represention of the dimensionality of the model h {int} -- Is a represention of the number of head hidden {int} -- Is a representation of hidden fully connected layer Keyword Arguments: drop_rate {float} -- The drop rate (default: {0.1})",
"name": "__i... | 2 | null | Implement the Python class `EncoderBlock` described below.
Class description:
EncoderBlock class Creates an encoder block for a transformer
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1) -> None: Initializer Arguments: dm {int} -- Is a represention of the dimensionality of the mo... | Implement the Python class `EncoderBlock` described below.
Class description:
EncoderBlock class Creates an encoder block for a transformer
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1) -> None: Initializer Arguments: dm {int} -- Is a represention of the dimensionality of the mo... | 2ddae38cc25d914488451b8c30e1234f1fa55ebe | <|skeleton|>
class EncoderBlock:
"""EncoderBlock class Creates an encoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1) -> None:
"""Initializer Arguments: dm {int} -- Is a represention of the dimensionality of the model h {int} -- Is a represention of the number of head hi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderBlock:
"""EncoderBlock class Creates an encoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1) -> None:
"""Initializer Arguments: dm {int} -- Is a represention of the dimensionality of the model h {int} -- Is a represention of the number of head hidden {int} --... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/7-transformer_encoder_block.py | KoeusIss/holbertonschool-machine_learning | train | 0 |
2bb638688a19e7fdc653d5893a0107752902edf5 | [
"self.dnn_cfg = dnn_cfg\ncfg = self.dnn_cfg\nproviders_list = ort.get_available_providers()\nif dnn_cfg.device < 0:\n providers = [('CPUExecutionProvider', {})]\nelse:\n providers = [('CUDAExecutionProvider', {'device_id': cfg.device})]\nself.model = ort.InferenceSession(cfg.fp_model, providers=providers)\nse... | <|body_start_0|>
self.dnn_cfg = dnn_cfg
cfg = self.dnn_cfg
providers_list = ort.get_available_providers()
if dnn_cfg.device < 0:
providers = [('CPUExecutionProvider', {})]
else:
providers = [('CUDAExecutionProvider', {'device_id': cfg.device})]
sel... | YOLOV5ONNX | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YOLOV5ONNX:
def __init__(self, dnn_cfg):
"""Instantiate an ONNX DNN network model"""
<|body_0|>
def _pre_process(self, im):
"""Pre-process image :param im: (numpy.ndarray) in BGR"""
<|body_1|>
def _post_process(self, outputs, ppimd):
"""Post proc... | stack_v2_sparse_classes_36k_train_026767 | 4,741 | permissive | [
{
"docstring": "Instantiate an ONNX DNN network model",
"name": "__init__",
"signature": "def __init__(self, dnn_cfg)"
},
{
"docstring": "Pre-process image :param im: (numpy.ndarray) in BGR",
"name": "_pre_process",
"signature": "def _pre_process(self, im)"
},
{
"docstring": "Pos... | 4 | stack_v2_sparse_classes_30k_train_001050 | Implement the Python class `YOLOV5ONNX` described below.
Class description:
Implement the YOLOV5ONNX class.
Method signatures and docstrings:
- def __init__(self, dnn_cfg): Instantiate an ONNX DNN network model
- def _pre_process(self, im): Pre-process image :param im: (numpy.ndarray) in BGR
- def _post_process(self,... | Implement the Python class `YOLOV5ONNX` described below.
Class description:
Implement the YOLOV5ONNX class.
Method signatures and docstrings:
- def __init__(self, dnn_cfg): Instantiate an ONNX DNN network model
- def _pre_process(self, im): Pre-process image :param im: (numpy.ndarray) in BGR
- def _post_process(self,... | 5c490cb72607f60e33467a9a0f412d23024e5963 | <|skeleton|>
class YOLOV5ONNX:
def __init__(self, dnn_cfg):
"""Instantiate an ONNX DNN network model"""
<|body_0|>
def _pre_process(self, im):
"""Pre-process image :param im: (numpy.ndarray) in BGR"""
<|body_1|>
def _post_process(self, outputs, ppimd):
"""Post proc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YOLOV5ONNX:
def __init__(self, dnn_cfg):
"""Instantiate an ONNX DNN network model"""
self.dnn_cfg = dnn_cfg
cfg = self.dnn_cfg
providers_list = ort.get_available_providers()
if dnn_cfg.device < 0:
providers = [('CPUExecutionProvider', {})]
else:
... | the_stack_v2_python_sparse | src/vframe/image/processors/yolov5_onnx.py | vframeio/vframe | train | 50 | |
7c815950d8dd0fe1981d91a520d9bd82790bd33f | [
"self.function = evaluate.Function(evaluate.getEvaluatorSplitWords(xmlElement.attributeDictionary[key]), xmlElement)\nself.points = []\nself.revolutions = revolutions",
"if self.function == None:\n return point\nself.function.localDictionary['azimuth'] = math.degrees(math.atan2(point.y, point.x))\nself.functio... | <|body_start_0|>
self.function = evaluate.Function(evaluate.getEvaluatorSplitWords(xmlElement.attributeDictionary[key]), xmlElement)
self.points = []
self.revolutions = revolutions
<|end_body_0|>
<|body_start_1|>
if self.function == None:
return point
self.function.l... | Class to get equation results. | EquationResult | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EquationResult:
"""Class to get equation results."""
def __init__(self, key, revolutions, xmlElement):
"""Initialize."""
<|body_0|>
def getReturnValue(self, point):
"""Get return value."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.functi... | stack_v2_sparse_classes_36k_train_026768 | 7,713 | no_license | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, key, revolutions, xmlElement)"
},
{
"docstring": "Get return value.",
"name": "getReturnValue",
"signature": "def getReturnValue(self, point)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005820 | Implement the Python class `EquationResult` described below.
Class description:
Class to get equation results.
Method signatures and docstrings:
- def __init__(self, key, revolutions, xmlElement): Initialize.
- def getReturnValue(self, point): Get return value. | Implement the Python class `EquationResult` described below.
Class description:
Class to get equation results.
Method signatures and docstrings:
- def __init__(self, key, revolutions, xmlElement): Initialize.
- def getReturnValue(self, point): Get return value.
<|skeleton|>
class EquationResult:
"""Class to get ... | ca68e7e3279680a105f6f907508b891c18d5a171 | <|skeleton|>
class EquationResult:
"""Class to get equation results."""
def __init__(self, key, revolutions, xmlElement):
"""Initialize."""
<|body_0|>
def getReturnValue(self, point):
"""Get return value."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EquationResult:
"""Class to get equation results."""
def __init__(self, key, revolutions, xmlElement):
"""Initialize."""
self.function = evaluate.Function(evaluate.getEvaluatorSplitWords(xmlElement.attributeDictionary[key]), xmlElement)
self.points = []
self.revolutions = ... | the_stack_v2_python_sparse | skeinforge/fabmetheus_utilities/geometry/manipulation_shapes/equation.py | mccoyn/SkeinFactory | train | 3 |
5f157086b85fdb60032052f9e228609e8335e690 | [
"if a > b:\n return self.getOrderSum(b, a)\nelse:\n return self.getOrderSum(a, b)",
"bs = bin(short)[2:][::-1]\nbl = bin(long)[2:][::-1]\nlshort = len(bs)\nllong = len(bl)\ncarry = 0\nrevStr = ''\nfor i in range(lshort):\n s = int(bs[i]) ^ int(bl[i]) ^ carry\n revStr += str(s)\n if [int(bs[i]), int... | <|body_start_0|>
if a > b:
return self.getOrderSum(b, a)
else:
return self.getOrderSum(a, b)
<|end_body_0|>
<|body_start_1|>
bs = bin(short)[2:][::-1]
bl = bin(long)[2:][::-1]
lshort = len(bs)
llong = len(bl)
carry = 0
revStr = ''
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getSum(self, a, b):
""":type a: int :type b: int :rtype: int"""
<|body_0|>
def getOrderSum(self, short, long):
""":type short: int :type long : int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if a > b:
retur... | stack_v2_sparse_classes_36k_train_026769 | 1,711 | no_license | [
{
"docstring": ":type a: int :type b: int :rtype: int",
"name": "getSum",
"signature": "def getSum(self, a, b)"
},
{
"docstring": ":type short: int :type long : int :rtype: int",
"name": "getOrderSum",
"signature": "def getOrderSum(self, short, long)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018117 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getSum(self, a, b): :type a: int :type b: int :rtype: int
- def getOrderSum(self, short, long): :type short: int :type long : int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getSum(self, a, b): :type a: int :type b: int :rtype: int
- def getOrderSum(self, short, long): :type short: int :type long : int :rtype: int
<|skeleton|>
class Solution:
... | f8b35179b980e55f61bbcd2631fa3a9bf30c40ec | <|skeleton|>
class Solution:
def getSum(self, a, b):
""":type a: int :type b: int :rtype: int"""
<|body_0|>
def getOrderSum(self, short, long):
""":type short: int :type long : int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getSum(self, a, b):
""":type a: int :type b: int :rtype: int"""
if a > b:
return self.getOrderSum(b, a)
else:
return self.getOrderSum(a, b)
def getOrderSum(self, short, long):
""":type short: int :type long : int :rtype: int"""
... | the_stack_v2_python_sparse | Python Solutions/371 Sum of Two Integers.py | Sue9/Leetcode | train | 0 | |
6ced3c0472633753126be4992303a1f4c315f026 | [
"self.directory = None\nself.testloader = None\nself.attack = None\nself.objective = None\nself.attempts = None\nself.snapshot = None\nself.get_writer = None",
"assert self.directory is not None\nassert len(self.directory) > 0\nassert isinstance(self.testloader, torch.utils.data.DataLoader)\nassert len(self.testl... | <|body_start_0|>
self.directory = None
self.testloader = None
self.attack = None
self.objective = None
self.attempts = None
self.snapshot = None
self.get_writer = None
<|end_body_0|>
<|body_start_1|>
assert self.directory is not None
assert len(se... | Configuration for attacks. | AttackConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttackConfig:
"""Configuration for attacks."""
def __init__(self):
"""Constructor."""
<|body_0|>
def validate(self):
"""Check validity."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.directory = None
self.testloader = None
... | stack_v2_sparse_classes_36k_train_026770 | 16,771 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Check validity.",
"name": "validate",
"signature": "def validate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000425 | Implement the Python class `AttackConfig` described below.
Class description:
Configuration for attacks.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def validate(self): Check validity. | Implement the Python class `AttackConfig` described below.
Class description:
Configuration for attacks.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def validate(self): Check validity.
<|skeleton|>
class AttackConfig:
"""Configuration for attacks."""
def __init__(self):
""... | 736c99b55a77d0c650eae5ced2d8312d13af0baf | <|skeleton|>
class AttackConfig:
"""Configuration for attacks."""
def __init__(self):
"""Constructor."""
<|body_0|>
def validate(self):
"""Check validity."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttackConfig:
"""Configuration for attacks."""
def __init__(self):
"""Constructor."""
self.directory = None
self.testloader = None
self.attack = None
self.objective = None
self.attempts = None
self.snapshot = None
self.get_writer = None
... | the_stack_v2_python_sparse | common/experiments.py | Adversarial-Intelligence-Group/color-adversarial-training | train | 0 |
5055468924fa40be02902451f8716c95c3eca4ae | [
"self.max_cols = max_cols\nself.max_h_space = max_h_space\nself.max_fontsize = max_fontsize\nself.min_fontsize = min_fontsize\nself.total_fontsize = total_fontsize\nself.rows_per_col = rows_per_col\nself.space_scale = space_scale",
"if self.max_cols is not None:\n return int(max(min(ceil(num_plots / self.rows_... | <|body_start_0|>
self.max_cols = max_cols
self.max_h_space = max_h_space
self.max_fontsize = max_fontsize
self.min_fontsize = min_fontsize
self.total_fontsize = total_fontsize
self.rows_per_col = rows_per_col
self.space_scale = space_scale
<|end_body_0|>
<|body_s... | A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib) | LegendSize | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LegendSize:
"""A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib)"""
def __init__(self, max_cols, max_h_space, max_fontsize, min_fontsize, total_fontsize, rows_per_col, space_scale):
"""Initialize a LegendSize instance :param... | stack_v2_sparse_classes_36k_train_026771 | 2,909 | permissive | [
{
"docstring": "Initialize a LegendSize instance :param max_cols: maximum allowed number of columns for the legend :param max_h_space: maximum proportion of horizontal space to be apportioned to the legend :param max_fontsize: maximum font size for legend labels :param min_fontsize: minimum font size for legend... | 4 | stack_v2_sparse_classes_30k_train_003418 | Implement the Python class `LegendSize` described below.
Class description:
A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib)
Method signatures and docstrings:
- def __init__(self, max_cols, max_h_space, max_fontsize, min_fontsize, total_fontsize, rows_per_c... | Implement the Python class `LegendSize` described below.
Class description:
A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib)
Method signatures and docstrings:
- def __init__(self, max_cols, max_h_space, max_fontsize, min_fontsize, total_fontsize, rows_per_c... | 4a03664f1cc9552787bd9cb39d1409b507f10777 | <|skeleton|>
class LegendSize:
"""A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib)"""
def __init__(self, max_cols, max_h_space, max_fontsize, min_fontsize, total_fontsize, rows_per_col, space_scale):
"""Initialize a LegendSize instance :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LegendSize:
"""A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib)"""
def __init__(self, max_cols, max_h_space, max_fontsize, min_fontsize, total_fontsize, rows_per_col, space_scale):
"""Initialize a LegendSize instance :param max_cols: ma... | the_stack_v2_python_sparse | src/LegendSize.py | dilynfullerton/tr-A_dependence_plots | train | 1 |
26f3ca31f80758b28c40e90aef460f44ed4796d2 | [
"check_convert_file_exits(file_tags='user')\nfile_names = os.listdir(base_dir)\nif len(file_names) != 1:\n raise Exception('当前user文件不止一个,请检查问题')\nreturn os.path.join(base_dir, file_names[0])",
"with open(user_file, encoding='utf-8') as f:\n for line in f:\n uid_match = re.search('\"uid\":\"(\\\\d+)\"... | <|body_start_0|>
check_convert_file_exits(file_tags='user')
file_names = os.listdir(base_dir)
if len(file_names) != 1:
raise Exception('当前user文件不止一个,请检查问题')
return os.path.join(base_dir, file_names[0])
<|end_body_0|>
<|body_start_1|>
with open(user_file, encoding='ut... | 消息中的用户列表 | UserListInMessages | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserListInMessages:
"""消息中的用户列表"""
def get_user_file_name():
"""获取用户列表所在文件"""
<|body_0|>
def extract_user_from_file(user_file):
"""从文件中获取用户"""
<|body_1|>
def get_user_in_db_by_uid(uid):
"""根据 uid 获取用户信息"""
<|body_2|>
def generate... | stack_v2_sparse_classes_36k_train_026772 | 36,284 | no_license | [
{
"docstring": "获取用户列表所在文件",
"name": "get_user_file_name",
"signature": "def get_user_file_name()"
},
{
"docstring": "从文件中获取用户",
"name": "extract_user_from_file",
"signature": "def extract_user_from_file(user_file)"
},
{
"docstring": "根据 uid 获取用户信息",
"name": "get_user_in_db_b... | 5 | stack_v2_sparse_classes_30k_train_005617 | Implement the Python class `UserListInMessages` described below.
Class description:
消息中的用户列表
Method signatures and docstrings:
- def get_user_file_name(): 获取用户列表所在文件
- def extract_user_from_file(user_file): 从文件中获取用户
- def get_user_in_db_by_uid(uid): 根据 uid 获取用户信息
- def generate_query_result(self, user_list): 生成查询的结果
... | Implement the Python class `UserListInMessages` described below.
Class description:
消息中的用户列表
Method signatures and docstrings:
- def get_user_file_name(): 获取用户列表所在文件
- def extract_user_from_file(user_file): 从文件中获取用户
- def get_user_in_db_by_uid(uid): 根据 uid 获取用户信息
- def generate_query_result(self, user_list): 生成查询的结果
... | d04cf523ef71b08fe43ed0ddf6ba194f1715fd79 | <|skeleton|>
class UserListInMessages:
"""消息中的用户列表"""
def get_user_file_name():
"""获取用户列表所在文件"""
<|body_0|>
def extract_user_from_file(user_file):
"""从文件中获取用户"""
<|body_1|>
def get_user_in_db_by_uid(uid):
"""根据 uid 获取用户信息"""
<|body_2|>
def generate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserListInMessages:
"""消息中的用户列表"""
def get_user_file_name():
"""获取用户列表所在文件"""
check_convert_file_exits(file_tags='user')
file_names = os.listdir(base_dir)
if len(file_names) != 1:
raise Exception('当前user文件不止一个,请检查问题')
return os.path.join(base_dir, file_... | the_stack_v2_python_sparse | douyin/drag_mouse.py | leizhen10000/learnPython | train | 0 |
84ae46d51a4f49aef9c34b60b4fc4206fb1a16a5 | [
"self._hardware_api = hardware_api\nself._state_store = state_store\nself._thermocycler_plate_lifter = thermocycler_plate_lifter or ThermocyclerPlateLifter(state_store=self._state_store, equipment=equipment, movement=movement)\nself._tc_movement_flagger = thermocycler_movement_flagger or ThermocyclerMovementFlagger... | <|body_start_0|>
self._hardware_api = hardware_api
self._state_store = state_store
self._thermocycler_plate_lifter = thermocycler_plate_lifter or ThermocyclerPlateLifter(state_store=self._state_store, equipment=equipment, movement=movement)
self._tc_movement_flagger = thermocycler_moveme... | Implementation logic for labware movement. | LabwareMovementHandler | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabwareMovementHandler:
"""Implementation logic for labware movement."""
def __init__(self, hardware_api: HardwareControlAPI, state_store: StateStore, equipment: EquipmentHandler, movement: MovementHandler, thermocycler_plate_lifter: Optional[ThermocyclerPlateLifter]=None, thermocycler_movem... | stack_v2_sparse_classes_36k_train_026773 | 7,087 | permissive | [
{
"docstring": "Initialize a LabwareMovementHandler instance.",
"name": "__init__",
"signature": "def __init__(self, hardware_api: HardwareControlAPI, state_store: StateStore, equipment: EquipmentHandler, movement: MovementHandler, thermocycler_plate_lifter: Optional[ThermocyclerPlateLifter]=None, therm... | 3 | stack_v2_sparse_classes_30k_train_003055 | Implement the Python class `LabwareMovementHandler` described below.
Class description:
Implementation logic for labware movement.
Method signatures and docstrings:
- def __init__(self, hardware_api: HardwareControlAPI, state_store: StateStore, equipment: EquipmentHandler, movement: MovementHandler, thermocycler_plat... | Implement the Python class `LabwareMovementHandler` described below.
Class description:
Implementation logic for labware movement.
Method signatures and docstrings:
- def __init__(self, hardware_api: HardwareControlAPI, state_store: StateStore, equipment: EquipmentHandler, movement: MovementHandler, thermocycler_plat... | 026b523c8c9e5d45910c490efb89194d72595be9 | <|skeleton|>
class LabwareMovementHandler:
"""Implementation logic for labware movement."""
def __init__(self, hardware_api: HardwareControlAPI, state_store: StateStore, equipment: EquipmentHandler, movement: MovementHandler, thermocycler_plate_lifter: Optional[ThermocyclerPlateLifter]=None, thermocycler_movem... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabwareMovementHandler:
"""Implementation logic for labware movement."""
def __init__(self, hardware_api: HardwareControlAPI, state_store: StateStore, equipment: EquipmentHandler, movement: MovementHandler, thermocycler_plate_lifter: Optional[ThermocyclerPlateLifter]=None, thermocycler_movement_flagger: ... | the_stack_v2_python_sparse | api/src/opentrons/protocol_engine/execution/labware_movement.py | Opentrons/opentrons | train | 326 |
b59c3ecadbce6c42e2171100fff4fc97271f77f3 | [
"ui.info(ui.green, '::', ui.reset, ui.bold, 'Reading', mpml_path, '\\n')\nself.worktree = worktree\nself.mpml_path = mpml_path\nself.meta_package = qipkg.metapackage.MetaPackage(self.worktree, self.mpml_path)\nself.pml_builders = list()\npml_paths = self.meta_package.pml_paths\nfor pml_path in pml_paths:\n pml_b... | <|body_start_0|>
ui.info(ui.green, '::', ui.reset, ui.bold, 'Reading', mpml_path, '\n')
self.worktree = worktree
self.mpml_path = mpml_path
self.meta_package = qipkg.metapackage.MetaPackage(self.worktree, self.mpml_path)
self.pml_builders = list()
pml_paths = self.meta_pa... | Build a meta package from a mpml file | MetaPMLBuilder | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetaPMLBuilder:
"""Build a meta package from a mpml file"""
def __init__(self, mpml_path, worktree=None):
"""MetaPMLBuilder Init"""
<|body_0|>
def configure(self):
"""Configure every project"""
<|body_1|>
def build(self):
"""Build every proje... | stack_v2_sparse_classes_36k_train_026774 | 3,314 | permissive | [
{
"docstring": "MetaPMLBuilder Init",
"name": "__init__",
"signature": "def __init__(self, mpml_path, worktree=None)"
},
{
"docstring": "Configure every project",
"name": "configure",
"signature": "def configure(self)"
},
{
"docstring": "Build every project",
"name": "build",... | 6 | stack_v2_sparse_classes_30k_train_009982 | Implement the Python class `MetaPMLBuilder` described below.
Class description:
Build a meta package from a mpml file
Method signatures and docstrings:
- def __init__(self, mpml_path, worktree=None): MetaPMLBuilder Init
- def configure(self): Configure every project
- def build(self): Build every project
- def instal... | Implement the Python class `MetaPMLBuilder` described below.
Class description:
Build a meta package from a mpml file
Method signatures and docstrings:
- def __init__(self, mpml_path, worktree=None): MetaPMLBuilder Init
- def configure(self): Configure every project
- def build(self): Build every project
- def instal... | efea6fa3744664348717fe5e8df708a3cf392072 | <|skeleton|>
class MetaPMLBuilder:
"""Build a meta package from a mpml file"""
def __init__(self, mpml_path, worktree=None):
"""MetaPMLBuilder Init"""
<|body_0|>
def configure(self):
"""Configure every project"""
<|body_1|>
def build(self):
"""Build every proje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetaPMLBuilder:
"""Build a meta package from a mpml file"""
def __init__(self, mpml_path, worktree=None):
"""MetaPMLBuilder Init"""
ui.info(ui.green, '::', ui.reset, ui.bold, 'Reading', mpml_path, '\n')
self.worktree = worktree
self.mpml_path = mpml_path
self.meta_... | the_stack_v2_python_sparse | python/qipkg/metabuilder.py | aldebaran/qibuild | train | 60 |
bae9d598f6eef893e3b2a64a75527ff65c8217eb | [
"if self.request.params.get('all', ''):\n collection_data = [i.serialize('view') for i in self.context.documents]\nelse:\n collection_data = sorted(dict([(i.id, i.serialize('view')) for i in self.context.documents]).values(), key=lambda i: i['dateModified'])\nreturn {'data': collection_data}",
"document = u... | <|body_start_0|>
if self.request.params.get('all', ''):
collection_data = [i.serialize('view') for i in self.context.documents]
else:
collection_data = sorted(dict([(i.id, i.serialize('view')) for i in self.context.documents]).values(), key=lambda i: i['dateModified'])
re... | TenderQualificationDocumentResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenderQualificationDocumentResource:
def collection_get(self):
"""Tender Qualification Documents List"""
<|body_0|>
def collection_post(self):
"""Tender Qualification Document Upload"""
<|body_1|>
def get(self):
"""Tender Qualification Document R... | stack_v2_sparse_classes_36k_train_026775 | 5,238 | permissive | [
{
"docstring": "Tender Qualification Documents List",
"name": "collection_get",
"signature": "def collection_get(self)"
},
{
"docstring": "Tender Qualification Document Upload",
"name": "collection_post",
"signature": "def collection_post(self)"
},
{
"docstring": "Tender Qualific... | 5 | stack_v2_sparse_classes_30k_train_020938 | Implement the Python class `TenderQualificationDocumentResource` described below.
Class description:
Implement the TenderQualificationDocumentResource class.
Method signatures and docstrings:
- def collection_get(self): Tender Qualification Documents List
- def collection_post(self): Tender Qualification Document Upl... | Implement the Python class `TenderQualificationDocumentResource` described below.
Class description:
Implement the TenderQualificationDocumentResource class.
Method signatures and docstrings:
- def collection_get(self): Tender Qualification Documents List
- def collection_post(self): Tender Qualification Document Upl... | 5afdd3a62a8e562cf77e2d963d88f1a26613d16a | <|skeleton|>
class TenderQualificationDocumentResource:
def collection_get(self):
"""Tender Qualification Documents List"""
<|body_0|>
def collection_post(self):
"""Tender Qualification Document Upload"""
<|body_1|>
def get(self):
"""Tender Qualification Document R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenderQualificationDocumentResource:
def collection_get(self):
"""Tender Qualification Documents List"""
if self.request.params.get('all', ''):
collection_data = [i.serialize('view') for i in self.context.documents]
else:
collection_data = sorted(dict([(i.id, i.... | the_stack_v2_python_sparse | src/openprocurement/tender/openeu/views/qualification_document.py | pontostroy/api | train | 0 | |
c29fc0c8b35cdaf1c5cb90ab8cd95eacab858509 | [
"super(ColumnDataChangedEvent, self).__init__(document, setter, callback_invoker)\nself.column_source = column_source\nself.cols = cols",
"super(ColumnDataChangedEvent, self).dispatch(receiver)\nif hasattr(receiver, '_column_data_changed'):\n receiver._column_data_changed(self)",
"from ..util.serialization i... | <|body_start_0|>
super(ColumnDataChangedEvent, self).__init__(document, setter, callback_invoker)
self.column_source = column_source
self.cols = cols
<|end_body_0|>
<|body_start_1|>
super(ColumnDataChangedEvent, self).dispatch(receiver)
if hasattr(receiver, '_column_data_changed... | A concrete event representing efficiently replacing *all* existing data for a :class:`~bokeh.models.sources.ColumnDataSource` | ColumnDataChangedEvent | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColumnDataChangedEvent:
"""A concrete event representing efficiently replacing *all* existing data for a :class:`~bokeh.models.sources.ColumnDataSource`"""
def __init__(self, document, column_source, cols=None, setter=None, callback_invoker=None):
"""Args: document (Document) : A Bok... | stack_v2_sparse_classes_36k_train_026776 | 28,443 | permissive | [
{
"docstring": "Args: document (Document) : A Bokeh document that is to be updated. column_source (ColumnDataSource) : cols (list[str]) : optional explicit list of column names to update. If None, all columns will be updated (default: None) setter (ClientSession or ServerSession or None, optional) : This is use... | 3 | stack_v2_sparse_classes_30k_train_014795 | Implement the Python class `ColumnDataChangedEvent` described below.
Class description:
A concrete event representing efficiently replacing *all* existing data for a :class:`~bokeh.models.sources.ColumnDataSource`
Method signatures and docstrings:
- def __init__(self, document, column_source, cols=None, setter=None, ... | Implement the Python class `ColumnDataChangedEvent` described below.
Class description:
A concrete event representing efficiently replacing *all* existing data for a :class:`~bokeh.models.sources.ColumnDataSource`
Method signatures and docstrings:
- def __init__(self, document, column_source, cols=None, setter=None, ... | 1ad7ec05fb1e3676ac879585296c513c3ee50ef9 | <|skeleton|>
class ColumnDataChangedEvent:
"""A concrete event representing efficiently replacing *all* existing data for a :class:`~bokeh.models.sources.ColumnDataSource`"""
def __init__(self, document, column_source, cols=None, setter=None, callback_invoker=None):
"""Args: document (Document) : A Bok... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColumnDataChangedEvent:
"""A concrete event representing efficiently replacing *all* existing data for a :class:`~bokeh.models.sources.ColumnDataSource`"""
def __init__(self, document, column_source, cols=None, setter=None, callback_invoker=None):
"""Args: document (Document) : A Bokeh document t... | the_stack_v2_python_sparse | Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/document/events.py | holzschu/Carnets | train | 541 |
415374d0cdf745a0774554af3f2a53b3363202a0 | [
"super(Generator, self).__init__()\nassert image_size % 16 == 0, 'image size must be a multiple of 16!'\nself.num_gpu = num_gpu\nself.layer = nn.Sequential()\nconv_depth = conv_dim // 2\nconv_size = 4\nwhile conv_size != image_size:\n conv_depth = conv_depth * 2\n conv_size *= 2\nself.layer.add_module('init.{... | <|body_start_0|>
super(Generator, self).__init__()
assert image_size % 16 == 0, 'image size must be a multiple of 16!'
self.num_gpu = num_gpu
self.layer = nn.Sequential()
conv_depth = conv_dim // 2
conv_size = 4
while conv_size != image_size:
conv_dept... | Model for Generator. | Generator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""Model for Generator."""
def __init__(self, num_channels, z_dim, conv_dim, image_size, num_gpu, num_extra_layers, use_BN):
"""Init for Generator model."""
<|body_0|>
def forward(self, input):
"""Forward step for Generator model."""
<|body_1|>... | stack_v2_sparse_classes_36k_train_026777 | 7,633 | permissive | [
{
"docstring": "Init for Generator model.",
"name": "__init__",
"signature": "def __init__(self, num_channels, z_dim, conv_dim, image_size, num_gpu, num_extra_layers, use_BN)"
},
{
"docstring": "Forward step for Generator model.",
"name": "forward",
"signature": "def forward(self, input)... | 2 | stack_v2_sparse_classes_30k_train_018661 | Implement the Python class `Generator` described below.
Class description:
Model for Generator.
Method signatures and docstrings:
- def __init__(self, num_channels, z_dim, conv_dim, image_size, num_gpu, num_extra_layers, use_BN): Init for Generator model.
- def forward(self, input): Forward step for Generator model. | Implement the Python class `Generator` described below.
Class description:
Model for Generator.
Method signatures and docstrings:
- def __init__(self, num_channels, z_dim, conv_dim, image_size, num_gpu, num_extra_layers, use_BN): Init for Generator model.
- def forward(self, input): Forward step for Generator model.
... | fd4498da35ace5a3d1696ff4fbec3568eddbe6a1 | <|skeleton|>
class Generator:
"""Model for Generator."""
def __init__(self, num_channels, z_dim, conv_dim, image_size, num_gpu, num_extra_layers, use_BN):
"""Init for Generator model."""
<|body_0|>
def forward(self, input):
"""Forward step for Generator model."""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
"""Model for Generator."""
def __init__(self, num_channels, z_dim, conv_dim, image_size, num_gpu, num_extra_layers, use_BN):
"""Init for Generator model."""
super(Generator, self).__init__()
assert image_size % 16 == 0, 'image size must be a multiple of 16!'
sel... | the_stack_v2_python_sparse | WGAN-GP/models.py | corenel/GAN-Zoo | train | 10 |
5c1d653df2380e03c42735136d5d98ac4410a5c3 | [
"if operation == 'update' and self.request.authenticated_role != self.context.author:\n self.request.errors.add('url', 'role', 'Can update document only author')\n self.request.errors.status = 403\n raise error_handler(self.request)\nif self.request.validated['tender_status'] not in ['active.qualification'... | <|body_start_0|>
if operation == 'update' and self.request.authenticated_role != self.context.author:
self.request.errors.add('url', 'role', 'Can update document only author')
self.request.errors.status = 403
raise error_handler(self.request)
if self.request.validated... | TenderUaAwardComplaintDocumentResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenderUaAwardComplaintDocumentResource:
def validate_complaint_document(self, operation):
"""TODO move validators This class is inherited in limited and openeu (qualification complaint) package, but validate_complaint_document function has different validators. For now, we have no way to... | stack_v2_sparse_classes_36k_train_026778 | 3,624 | permissive | [
{
"docstring": "TODO move validators This class is inherited in limited and openeu (qualification complaint) package, but validate_complaint_document function has different validators. For now, we have no way to use different validators on methods according to procedure type.",
"name": "validate_complaint_d... | 4 | stack_v2_sparse_classes_30k_train_010775 | Implement the Python class `TenderUaAwardComplaintDocumentResource` described below.
Class description:
Implement the TenderUaAwardComplaintDocumentResource class.
Method signatures and docstrings:
- def validate_complaint_document(self, operation): TODO move validators This class is inherited in limited and openeu (... | Implement the Python class `TenderUaAwardComplaintDocumentResource` described below.
Class description:
Implement the TenderUaAwardComplaintDocumentResource class.
Method signatures and docstrings:
- def validate_complaint_document(self, operation): TODO move validators This class is inherited in limited and openeu (... | f901e1d8913cb10fee044dc267ef7c0f42c6a947 | <|skeleton|>
class TenderUaAwardComplaintDocumentResource:
def validate_complaint_document(self, operation):
"""TODO move validators This class is inherited in limited and openeu (qualification complaint) package, but validate_complaint_document function has different validators. For now, we have no way to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenderUaAwardComplaintDocumentResource:
def validate_complaint_document(self, operation):
"""TODO move validators This class is inherited in limited and openeu (qualification complaint) package, but validate_complaint_document function has different validators. For now, we have no way to use different... | the_stack_v2_python_sparse | src/openprocurement/tender/openua/views/award_complaint_document.py | ProzorroUKR/openprocurement.api | train | 14 | |
a435e7f9e41df576c7d3988c7958dc4c57f699dc | [
"self.logger = logging.getLogger(__name__ + '.TokenizedSentences')\nself.logger.addHandler(logging.NullHandler())\nself.filename = self.full_filename(filename)",
"words = []\nwith codecs.open(self.filename, encoding='utf-8') as fid:\n for line in fid:\n words.extend(line.split())\nword_counts = Counter(... | <|body_start_0|>
self.logger = logging.getLogger(__name__ + '.TokenizedSentences')
self.logger.addHandler(logging.NullHandler())
self.filename = self.full_filename(filename)
<|end_body_0|>
<|body_start_1|>
words = []
with codecs.open(self.filename, encoding='utf-8') as fid:
... | Interface to tokenized sentences. | TokenizedSentences | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenizedSentences:
"""Interface to tokenized sentences."""
def __init__(self, filename=TOKENIZED_SENTENCES_FILENAME):
"""Initialize logger and filename. Parameters ---------- filename : str filename with tokenized sentences."""
<|body_0|>
def count_words(self):
... | stack_v2_sparse_classes_36k_train_026779 | 14,008 | permissive | [
{
"docstring": "Initialize logger and filename. Parameters ---------- filename : str filename with tokenized sentences.",
"name": "__init__",
"signature": "def __init__(self, filename=TOKENIZED_SENTENCES_FILENAME)"
},
{
"docstring": "Count words. Returns ------- word_counts : dict Counts for ind... | 2 | stack_v2_sparse_classes_30k_train_003559 | Implement the Python class `TokenizedSentences` described below.
Class description:
Interface to tokenized sentences.
Method signatures and docstrings:
- def __init__(self, filename=TOKENIZED_SENTENCES_FILENAME): Initialize logger and filename. Parameters ---------- filename : str filename with tokenized sentences.
-... | Implement the Python class `TokenizedSentences` described below.
Class description:
Interface to tokenized sentences.
Method signatures and docstrings:
- def __init__(self, filename=TOKENIZED_SENTENCES_FILENAME): Initialize logger and filename. Parameters ---------- filename : str filename with tokenized sentences.
-... | d8d1c5e68aedf758aee1ba83da063f1e0952c21d | <|skeleton|>
class TokenizedSentences:
"""Interface to tokenized sentences."""
def __init__(self, filename=TOKENIZED_SENTENCES_FILENAME):
"""Initialize logger and filename. Parameters ---------- filename : str filename with tokenized sentences."""
<|body_0|>
def count_words(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenizedSentences:
"""Interface to tokenized sentences."""
def __init__(self, filename=TOKENIZED_SENTENCES_FILENAME):
"""Initialize logger and filename. Parameters ---------- filename : str filename with tokenized sentences."""
self.logger = logging.getLogger(__name__ + '.TokenizedSenten... | the_stack_v2_python_sparse | dasem/fullmonty.py | eaksnes/dasem | train | 0 |
834e0340fe4bbc309ebdde876e9586e9614058f6 | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = MacOSLSQuarantineEventData()\nevent_data.agent = self._GetRowValue(query_hash, row, 'Agent')\nevent_data.data =... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event_data = MacOSLSQuarantineEventData(... | SQLite parser plugin for MacOS LS quarantine events database files. The MacOS launch services (LS) quarantine database file is typically stored in: /Users/<username>/Library/Preferences/ QuarantineEvents.com.apple.LaunchServices | MacOSLSQuarantinePlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MacOSLSQuarantinePlugin:
"""SQLite parser plugin for MacOS LS quarantine events database files. The MacOS launch services (LS) quarantine database file is typically stored in: /Users/<username>/Library/Preferences/ QuarantineEvents.com.apple.LaunchServices"""
def _GetDateTimeRowValue(self, q... | stack_v2_sparse_classes_36k_train_026780 | 3,932 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.CocoaTime: date and time value or None if not available.",
"name... | 2 | stack_v2_sparse_classes_30k_train_015557 | Implement the Python class `MacOSLSQuarantinePlugin` described below.
Class description:
SQLite parser plugin for MacOS LS quarantine events database files. The MacOS launch services (LS) quarantine database file is typically stored in: /Users/<username>/Library/Preferences/ QuarantineEvents.com.apple.LaunchServices
... | Implement the Python class `MacOSLSQuarantinePlugin` described below.
Class description:
SQLite parser plugin for MacOS LS quarantine events database files. The MacOS launch services (LS) quarantine database file is typically stored in: /Users/<username>/Library/Preferences/ QuarantineEvents.com.apple.LaunchServices
... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class MacOSLSQuarantinePlugin:
"""SQLite parser plugin for MacOS LS quarantine events database files. The MacOS launch services (LS) quarantine database file is typically stored in: /Users/<username>/Library/Preferences/ QuarantineEvents.com.apple.LaunchServices"""
def _GetDateTimeRowValue(self, q... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MacOSLSQuarantinePlugin:
"""SQLite parser plugin for MacOS LS quarantine events database files. The MacOS launch services (LS) quarantine database file is typically stored in: /Users/<username>/Library/Preferences/ QuarantineEvents.com.apple.LaunchServices"""
def _GetDateTimeRowValue(self, query_hash, ro... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/ls_quarantine.py | log2timeline/plaso | train | 1,506 |
c210f473ad5dddc28ca0da6b1a2f6081b007deb3 | [
"jobs = sorted(zip(startTime, endTime, profit), key=lambda x: x[1])\ndp = [0] * (len(jobs) + 1)\nfor i in range(1, len(jobs) + 1):\n pos = bisect.bisect(jobs, jobs[i - 1][0], hi=i, key=lambda x: x[1])\n dp[i] = max(dp[pos] + jobs[i - 1][2], dp[i - 1])\nreturn dp[-1]",
"jobs = []\nfor s, e, p in sorted(zip(s... | <|body_start_0|>
jobs = sorted(zip(startTime, endTime, profit), key=lambda x: x[1])
dp = [0] * (len(jobs) + 1)
for i in range(1, len(jobs) + 1):
pos = bisect.bisect(jobs, jobs[i - 1][0], hi=i, key=lambda x: x[1])
dp[i] = max(dp[pos] + jobs[i - 1][2], dp[i - 1])
re... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
"""https://leetcode.cn/problems/maximum-profit-in-job-scheduling/solution/gui-hua-jian-zhi-gong-zuo-by-leetcode-so-gu0e/ Runtime: 1436 ms, faster than 39.93% Memory Usage: 26.4 MB, less... | stack_v2_sparse_classes_36k_train_026781 | 2,339 | permissive | [
{
"docstring": "https://leetcode.cn/problems/maximum-profit-in-job-scheduling/solution/gui-hua-jian-zhi-gong-zuo-by-leetcode-so-gu0e/ Runtime: 1436 ms, faster than 39.93% Memory Usage: 26.4 MB, less than 78.04%",
"name": "jobScheduling",
"signature": "def jobScheduling(self, startTime: List[int], endTim... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: https://leetcode.cn/problems/maximum-profit-in-job-scheduling/solution/gui-hua-jian-z... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: https://leetcode.cn/problems/maximum-profit-in-job-scheduling/solution/gui-hua-jian-z... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
"""https://leetcode.cn/problems/maximum-profit-in-job-scheduling/solution/gui-hua-jian-zhi-gong-zuo-by-leetcode-so-gu0e/ Runtime: 1436 ms, faster than 39.93% Memory Usage: 26.4 MB, less... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
"""https://leetcode.cn/problems/maximum-profit-in-job-scheduling/solution/gui-hua-jian-zhi-gong-zuo-by-leetcode-so-gu0e/ Runtime: 1436 ms, faster than 39.93% Memory Usage: 26.4 MB, less than 78.04%""... | the_stack_v2_python_sparse | src/1235-MaximumProfitInJobScheduling.py | Jiezhi/myleetcode | train | 1 | |
624ab166f79ebe69454a10e5cfb45de3f12f815c | [
"if not lists:\n return None\nif len(lists) == 1:\n return lists[0]\nif len(lists) == 2:\n return self.mergeTwoLists(lists[0], lists[1])\nreturn self.mergeTwoLists(self.mergeKLists(lists[:len(lists) / 2]), self.mergeKLists(lists[len(lists) / 2:]))",
"res = ListNode(0)\nlast = res\nwhile l1 or l2:\n if... | <|body_start_0|>
if not lists:
return None
if len(lists) == 1:
return lists[0]
if len(lists) == 2:
return self.mergeTwoLists(lists[0], lists[1])
return self.mergeTwoLists(self.mergeKLists(lists[:len(lists) / 2]), self.mergeKLists(lists[len(lists) / 2:]... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not l... | stack_v2_sparse_classes_36k_train_026782 | 1,455 | permissive | [
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012662 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
<|skeleton|>... | 64747eb172c2ecb3c889830246f3282669516e10 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
if not lists:
return None
if len(lists) == 1:
return lists[0]
if len(lists) == 2:
return self.mergeTwoLists(lists[0], lists[1])
return self.mer... | the_stack_v2_python_sparse | LC/23.py | szhu3210/LeetCode_Solutions | train | 2 | |
09ceeff88db61da4ecf6a84878bedc5302bdf39a | [
"if self.request.version == 'v6':\n return ScanSerializerV6\nelif self.request.version == 'v7':\n return ScanSerializerV6",
"if request.version == 'v6':\n return self._list_v6(request)\nelif request.version == 'v7':\n return self._list_v6(request)\nraise Http404()",
"started = rest_util.parse_timest... | <|body_start_0|>
if self.request.version == 'v6':
return ScanSerializerV6
elif self.request.version == 'v7':
return ScanSerializerV6
<|end_body_0|>
<|body_start_1|>
if request.version == 'v6':
return self._list_v6(request)
elif request.version == 'v7'... | This view is the endpoint for retrieving the list of all Scan process. | ScansView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScansView:
"""This view is the endpoint for retrieving the list of all Scan process."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API."""
<|body_0|>
def list(self, request):
"""Retrieves the l... | stack_v2_sparse_classes_36k_train_026783 | 30,689 | permissive | [
{
"docstring": "Returns the appropriate serializer based off the requests version of the REST API.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Retrieves the list of all Scan process and returns it in JSON form :param request: the HTTP GET re... | 5 | stack_v2_sparse_classes_30k_train_017514 | Implement the Python class `ScansView` described below.
Class description:
This view is the endpoint for retrieving the list of all Scan process.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API.
- def list(self, requ... | Implement the Python class `ScansView` described below.
Class description:
This view is the endpoint for retrieving the list of all Scan process.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API.
- def list(self, requ... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class ScansView:
"""This view is the endpoint for retrieving the list of all Scan process."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API."""
<|body_0|>
def list(self, request):
"""Retrieves the l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScansView:
"""This view is the endpoint for retrieving the list of all Scan process."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API."""
if self.request.version == 'v6':
return ScanSerializerV6
eli... | the_stack_v2_python_sparse | scale/ingest/views.py | kfconsultant/scale | train | 0 |
151525e898ec500441bfc8112922cff8c6b1d582 | [
"self.position = [(0, 0)]\nself.food = food\nself.width, self.height = (width, height)\nself.moves = {'U': (0, -1), 'L': (-1, 0), 'R': (1, 0), 'D': (0, 1)}\nself.score = 0",
"x = self.position[0][0] + self.moves[direction][0]\ny = self.position[0][1] + self.moves[direction][1]\nif not self.width > x >= 0 or not s... | <|body_start_0|>
self.position = [(0, 0)]
self.food = food
self.width, self.height = (width, height)
self.moves = {'U': (0, -1), 'L': (-1, 0), 'R': (1, 0), 'D': (0, 1)}
self.score = 0
<|end_body_0|>
<|body_start_1|>
x = self.position[0][0] + self.moves[direction][0]
... | https://www.cnblogs.com/grandyang/p/5558033.html everytime when the snakes eats, length += 1 | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
"""https://www.cnblogs.com/grandyang/p/5558033.html everytime when the snakes eats, length += 1"""
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param f... | stack_v2_sparse_classes_36k_train_026784 | 1,779 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_002087 | Implement the Python class `SnakeGame` described below.
Class description:
https://www.cnblogs.com/grandyang/p/5558033.html everytime when the snakes eats, length += 1
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param wi... | Implement the Python class `SnakeGame` described below.
Class description:
https://www.cnblogs.com/grandyang/p/5558033.html everytime when the snakes eats, length += 1
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param wi... | 54d777e11b91c5debe49c1aef723234c66a5d2cc | <|skeleton|>
class SnakeGame:
"""https://www.cnblogs.com/grandyang/p/5558033.html everytime when the snakes eats, length += 1"""
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
"""https://www.cnblogs.com/grandyang/p/5558033.html everytime when the snakes eats, length += 1"""
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list ... | the_stack_v2_python_sparse | leetcode_solution/design/#353.Design_Snake_Game.py | HsiangHung/Code-Challenges | train | 0 |
49a56d1af660c07dae8fbedcbca98615c35e1d64 | [
"s = len(matrix)\nfor i in range(s):\n for j in range(s - i):\n matrix[i][j], matrix[s - j - 1][s - i - 1] = (matrix[s - j - 1][s - i - 1], matrix[i][j])\nfor i in range(s / 2):\n for j in range(s):\n matrix[i][j], matrix[s - 1 - i][j] = (matrix[s - 1 - i][j], matrix[i][j])",
"lo = 0\nhi = len... | <|body_start_0|>
s = len(matrix)
for i in range(s):
for j in range(s - i):
matrix[i][j], matrix[s - j - 1][s - i - 1] = (matrix[s - j - 1][s - i - 1], matrix[i][j])
for i in range(s / 2):
for j in range(s):
matrix[i][j], matrix[s - 1 - i][j... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate_2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-... | stack_v2_sparse_classes_36k_train_026785 | 1,160 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "rotate",
"signature": "def rotate(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
... | 2 | stack_v2_sparse_classes_30k_train_012800 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate_2(self, matrix): :type matrix: List[List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate_2(self, matrix): :type matrix: List[List... | bd8df12c0d4afd048cf1b58b04c27fa1f3622769 | <|skeleton|>
class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate_2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
s = len(matrix)
for i in range(s):
for j in range(s - i):
matrix[i][j], matrix[s - j - 1][s - i - 1] = (matrix[s - j ... | the_stack_v2_python_sparse | 48_rotate_image.py | aojugg/leetcode | train | 0 | |
13cba4b5ea1f788566ccf02592fc13fd3f7ae042 | [
"super().__init__(name, level=level)\nself.Deque = collections.deque([], 50)\nself._metrics_counter = metrics_counter",
"if record.levelno == logging.WARNING:\n self._metrics_counter.add('warning', 1)\nelif record.levelno >= logging.ERROR:\n self._metrics_counter.add('error', 1)\nrecord.timestamp = self._fo... | <|body_start_0|>
super().__init__(name, level=level)
self.Deque = collections.deque([], 50)
self._metrics_counter = metrics_counter
<|end_body_0|>
<|body_start_1|>
if record.levelno == logging.WARNING:
self._metrics_counter.add('warning', 1)
elif record.levelno >= lo... | PipelineLogger is a feature of BSPump which enables direct monitoring of a specific :meth:`Pipeline <bspump.Pipeline()>`. It offers an overview of errors, error handling, data in a given time with its timestamp. | PipelineLogger | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelineLogger:
"""PipelineLogger is a feature of BSPump which enables direct monitoring of a specific :meth:`Pipeline <bspump.Pipeline()>`. It offers an overview of errors, error handling, data in a given time with its timestamp."""
def __init__(self, name, metrics_counter, level=logging.NO... | stack_v2_sparse_classes_36k_train_026786 | 24,170 | permissive | [
{
"docstring": "Itialize a metrics counter.",
"name": "__init__",
"signature": "def __init__(self, name, metrics_counter, level=logging.NOTSET)"
},
{
"docstring": "Counts and add errors to the error counter. **Parameters** record : Record that is evaluated.",
"name": "handle",
"signature... | 3 | stack_v2_sparse_classes_30k_train_006691 | Implement the Python class `PipelineLogger` described below.
Class description:
PipelineLogger is a feature of BSPump which enables direct monitoring of a specific :meth:`Pipeline <bspump.Pipeline()>`. It offers an overview of errors, error handling, data in a given time with its timestamp.
Method signatures and docs... | Implement the Python class `PipelineLogger` described below.
Class description:
PipelineLogger is a feature of BSPump which enables direct monitoring of a specific :meth:`Pipeline <bspump.Pipeline()>`. It offers an overview of errors, error handling, data in a given time with its timestamp.
Method signatures and docs... | 11ee3689d0ff6e9b662deeb3fc5e18bb0aabc8f2 | <|skeleton|>
class PipelineLogger:
"""PipelineLogger is a feature of BSPump which enables direct monitoring of a specific :meth:`Pipeline <bspump.Pipeline()>`. It offers an overview of errors, error handling, data in a given time with its timestamp."""
def __init__(self, name, metrics_counter, level=logging.NO... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PipelineLogger:
"""PipelineLogger is a feature of BSPump which enables direct monitoring of a specific :meth:`Pipeline <bspump.Pipeline()>`. It offers an overview of errors, error handling, data in a given time with its timestamp."""
def __init__(self, name, metrics_counter, level=logging.NOTSET):
... | the_stack_v2_python_sparse | bspump/pipeline.py | LibertyAces/BitSwanPump | train | 24 |
2144e368dedf96f67f29546dc369bfa62b96a157 | [
"self.op = op\nself.e = e\nself.n = 1\nwhile self.n < length:\n self.n *= 2\nself.dat = [e()] * (2 * self.n - 1)",
"assert len(x_list) <= self.n\nfor i, x in enumerate(x_list):\n self.dat[self.n - 1 + i] = x\nfor i in range(self.n - 2, -1, -1):\n self.dat[i] = self.op(self.dat[2 * i + 1], self.dat[2 * i ... | <|body_start_0|>
self.op = op
self.e = e
self.n = 1
while self.n < length:
self.n *= 2
self.dat = [e()] * (2 * self.n - 1)
<|end_body_0|>
<|body_start_1|>
assert len(x_list) <= self.n
for i, x in enumerate(x_list):
self.dat[self.n - 1 + i]... | SegmentTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentTree:
def __init__(self, length, op=min, e=lambda: 0):
""":param length: length of initial values :param op: operator, op(x, y) -> z :param e: function that return identity element for op"""
<|body_0|>
def initialize(self, x_list):
"""initialize data :param x_... | stack_v2_sparse_classes_36k_train_026787 | 3,410 | no_license | [
{
"docstring": ":param length: length of initial values :param op: operator, op(x, y) -> z :param e: function that return identity element for op",
"name": "__init__",
"signature": "def __init__(self, length, op=min, e=lambda: 0)"
},
{
"docstring": "initialize data :param x_list: initial values ... | 6 | stack_v2_sparse_classes_30k_train_012495 | Implement the Python class `SegmentTree` described below.
Class description:
Implement the SegmentTree class.
Method signatures and docstrings:
- def __init__(self, length, op=min, e=lambda: 0): :param length: length of initial values :param op: operator, op(x, y) -> z :param e: function that return identity element ... | Implement the Python class `SegmentTree` described below.
Class description:
Implement the SegmentTree class.
Method signatures and docstrings:
- def __init__(self, length, op=min, e=lambda: 0): :param length: length of initial values :param op: operator, op(x, y) -> z :param e: function that return identity element ... | 02b0a6c92a05c6858b87cb22623ce877c1039f8f | <|skeleton|>
class SegmentTree:
def __init__(self, length, op=min, e=lambda: 0):
""":param length: length of initial values :param op: operator, op(x, y) -> z :param e: function that return identity element for op"""
<|body_0|>
def initialize(self, x_list):
"""initialize data :param x_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SegmentTree:
def __init__(self, length, op=min, e=lambda: 0):
""":param length: length of initial values :param op: operator, op(x, y) -> z :param e: function that return identity element for op"""
self.op = op
self.e = e
self.n = 1
while self.n < length:
se... | the_stack_v2_python_sparse | other_contests/abl001/D.py | k-harada/AtCoder | train | 9 | |
e93f026c815325355f7d160afc9d1fd9205d285f | [
"if id is None:\n Base.__nb_objects += 1\n id = self.__nb_objects\nself.id = id",
"if not list_dictionaries or len(list_dictionaries) is 0:\n return '[]'\nreturn json.dumps(list_dictionaries)",
"content = []\nif list_objs is not None:\n for i in list_objs:\n content.append(cls.to_dictionary(i... | <|body_start_0|>
if id is None:
Base.__nb_objects += 1
id = self.__nb_objects
self.id = id
<|end_body_0|>
<|body_start_1|>
if not list_dictionaries or len(list_dictionaries) is 0:
return '[]'
return json.dumps(list_dictionaries)
<|end_body_1|>
<|body... | The `Base` class | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""The `Base` class"""
def __init__(self, id=None):
"""Constructor of the `Base` class Args: id: the uniqe id"""
<|body_0|>
def to_json_string(list_dictionaries):
"""Returns the JSON string representation of the instance Args: list_dictionaries: the list of... | stack_v2_sparse_classes_36k_train_026788 | 2,621 | no_license | [
{
"docstring": "Constructor of the `Base` class Args: id: the uniqe id",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "Returns the JSON string representation of the instance Args: list_dictionaries: the list of dictionaries",
"name": "to_json_string",
... | 6 | stack_v2_sparse_classes_30k_train_012808 | Implement the Python class `Base` described below.
Class description:
The `Base` class
Method signatures and docstrings:
- def __init__(self, id=None): Constructor of the `Base` class Args: id: the uniqe id
- def to_json_string(list_dictionaries): Returns the JSON string representation of the instance Args: list_dict... | Implement the Python class `Base` described below.
Class description:
The `Base` class
Method signatures and docstrings:
- def __init__(self, id=None): Constructor of the `Base` class Args: id: the uniqe id
- def to_json_string(list_dictionaries): Returns the JSON string representation of the instance Args: list_dict... | b86439b7c2e4b3d199dbd638888524579aa69de9 | <|skeleton|>
class Base:
"""The `Base` class"""
def __init__(self, id=None):
"""Constructor of the `Base` class Args: id: the uniqe id"""
<|body_0|>
def to_json_string(list_dictionaries):
"""Returns the JSON string representation of the instance Args: list_dictionaries: the list of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base:
"""The `Base` class"""
def __init__(self, id=None):
"""Constructor of the `Base` class Args: id: the uniqe id"""
if id is None:
Base.__nb_objects += 1
id = self.__nb_objects
self.id = id
def to_json_string(list_dictionaries):
"""Returns t... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | Cu7ious/holbertonschool-higher_level_programming | train | 0 |
b04126b5be53634a8a34ec381c081c2c19b171f0 | [
"actions = super().get_actions(request)\nactions['delete_selected'] = (delete_selected, 'delete_selected', delete_selected.short_description)\nreturn actions",
"for obj in queryset:\n obj_display = force_text(obj)\n modeladmin.log_deletion(request, obj, obj_display)\nqueryset.delete()"
] | <|body_start_0|>
actions = super().get_actions(request)
actions['delete_selected'] = (delete_selected, 'delete_selected', delete_selected.short_description)
return actions
<|end_body_0|>
<|body_start_1|>
for obj in queryset:
obj_display = force_text(obj)
modeladm... | DeleteSelectedMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteSelectedMixin:
def get_actions(self, request):
"""Customize delete action"""
<|body_0|>
def perform_delete_selected(modeladmin, request, queryset):
"""Perform delete many records"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
actions = super(... | stack_v2_sparse_classes_36k_train_026789 | 720 | permissive | [
{
"docstring": "Customize delete action",
"name": "get_actions",
"signature": "def get_actions(self, request)"
},
{
"docstring": "Perform delete many records",
"name": "perform_delete_selected",
"signature": "def perform_delete_selected(modeladmin, request, queryset)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018804 | Implement the Python class `DeleteSelectedMixin` described below.
Class description:
Implement the DeleteSelectedMixin class.
Method signatures and docstrings:
- def get_actions(self, request): Customize delete action
- def perform_delete_selected(modeladmin, request, queryset): Perform delete many records | Implement the Python class `DeleteSelectedMixin` described below.
Class description:
Implement the DeleteSelectedMixin class.
Method signatures and docstrings:
- def get_actions(self, request): Customize delete action
- def perform_delete_selected(modeladmin, request, queryset): Perform delete many records
<|skeleto... | 9375593778f335ed237957ec589aea9d9aca5792 | <|skeleton|>
class DeleteSelectedMixin:
def get_actions(self, request):
"""Customize delete action"""
<|body_0|>
def perform_delete_selected(modeladmin, request, queryset):
"""Perform delete many records"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteSelectedMixin:
def get_actions(self, request):
"""Customize delete action"""
actions = super().get_actions(request)
actions['delete_selected'] = (delete_selected, 'delete_selected', delete_selected.short_description)
return actions
def perform_delete_selected(modelad... | the_stack_v2_python_sparse | src/app/common/admin/mixins.py | z-station/cappa | train | 13 | |
eac81484174d4413508eb46c751fcbbdf228176a | [
"self.dice = Dice()\nself.money = 100\nself.interface = interface\nself.hi_scores = hi_scores\nself.played_once = False",
"while self.money >= 10 and self.interface.wantToPlay():\n self.playRound()\nif self.played_once and self.hi_scores.is_top_ten(self.money):\n self.interface.enter_score(self.money)\nself... | <|body_start_0|>
self.dice = Dice()
self.money = 100
self.interface = interface
self.hi_scores = hi_scores
self.played_once = False
<|end_body_0|>
<|body_start_1|>
while self.money >= 10 and self.interface.wantToPlay():
self.playRound()
if self.played... | Play dice poker | PokerApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PokerApp:
"""Play dice poker"""
def __init__(self, interface, hi_scores):
"""Initialize dice, money, and interface (could be text or GUI) :param interface: obj -> interface object :param hi_scores: obj -> high scores object"""
<|body_0|>
def run(self):
"""Runs ga... | stack_v2_sparse_classes_36k_train_026790 | 1,931 | no_license | [
{
"docstring": "Initialize dice, money, and interface (could be text or GUI) :param interface: obj -> interface object :param hi_scores: obj -> high scores object",
"name": "__init__",
"signature": "def __init__(self, interface, hi_scores)"
},
{
"docstring": "Runs game continuously until quit or... | 4 | null | Implement the Python class `PokerApp` described below.
Class description:
Play dice poker
Method signatures and docstrings:
- def __init__(self, interface, hi_scores): Initialize dice, money, and interface (could be text or GUI) :param interface: obj -> interface object :param hi_scores: obj -> high scores object
- d... | Implement the Python class `PokerApp` described below.
Class description:
Play dice poker
Method signatures and docstrings:
- def __init__(self, interface, hi_scores): Initialize dice, money, and interface (could be text or GUI) :param interface: obj -> interface object :param hi_scores: obj -> high scores object
- d... | 6588c0ebfa932fbae7eec11c20270e4a8e969377 | <|skeleton|>
class PokerApp:
"""Play dice poker"""
def __init__(self, interface, hi_scores):
"""Initialize dice, money, and interface (could be text or GUI) :param interface: obj -> interface object :param hi_scores: obj -> high scores object"""
<|body_0|>
def run(self):
"""Runs ga... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PokerApp:
"""Play dice poker"""
def __init__(self, interface, hi_scores):
"""Initialize dice, money, and interface (could be text or GUI) :param interface: obj -> interface object :param hi_scores: obj -> high scores object"""
self.dice = Dice()
self.money = 100
self.inter... | the_stack_v2_python_sparse | Chapter12/U12_Ex01_DicePoker/pokerapp.py | billm79/COOP2018 | train | 3 |
58cdc23a91cca2939a9a8d095fe8a8da9dbb2fb1 | [
"if id is None:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\nelse:\n self.id = id",
"if list_dictionaries is None or list_dictionaries == []:\n return '[]'\nif not isinstance(list_dictionaries, list):\n raise TypeError('argument must be a list of dictionaries')\nelse:\n return json.du... | <|body_start_0|>
if id is None:
Base.__nb_objects += 1
self.id = Base.__nb_objects
else:
self.id = id
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None or list_dictionaries == []:
return '[]'
if not isinstance(list_dictionaries,... | base class | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""base class"""
def __init__(self, id=None):
"""initialize"""
<|body_0|>
def to_json_string(list_dictionaries):
"""from list of dict to json string"""
<|body_1|>
def save_to_file(cls, list_objs):
"""save list of instances to file"""
... | stack_v2_sparse_classes_36k_train_026791 | 2,782 | no_license | [
{
"docstring": "initialize",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "from list of dict to json string",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docstring": "save list of instances to file",
... | 6 | stack_v2_sparse_classes_30k_train_019759 | Implement the Python class `Base` described below.
Class description:
base class
Method signatures and docstrings:
- def __init__(self, id=None): initialize
- def to_json_string(list_dictionaries): from list of dict to json string
- def save_to_file(cls, list_objs): save list of instances to file
- def from_json_stri... | Implement the Python class `Base` described below.
Class description:
base class
Method signatures and docstrings:
- def __init__(self, id=None): initialize
- def to_json_string(list_dictionaries): from list of dict to json string
- def save_to_file(cls, list_objs): save list of instances to file
- def from_json_stri... | b7abad365d4ff193c56cd82a236e826394ca031b | <|skeleton|>
class Base:
"""base class"""
def __init__(self, id=None):
"""initialize"""
<|body_0|>
def to_json_string(list_dictionaries):
"""from list of dict to json string"""
<|body_1|>
def save_to_file(cls, list_objs):
"""save list of instances to file"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base:
"""base class"""
def __init__(self, id=None):
"""initialize"""
if id is None:
Base.__nb_objects += 1
self.id = Base.__nb_objects
else:
self.id = id
def to_json_string(list_dictionaries):
"""from list of dict to json string"""
... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | lei-diva/holbertonschool-higher_level_programming | train | 0 |
77fd3491e20cae336f0701f632002e31e4ea4faf | [
"if 1 not in directed_graph[i] and temp not in res:\n inner_res = temp[:]\n res.append(inner_res)\n return\nfor j in range(n):\n if directed_graph[i][j] == 1:\n temp.append(j)\n self.print_path(j, temp, res, n, directed_graph)\n temp.pop()",
"directed_graph = DirectedGraph(len(gra... | <|body_start_0|>
if 1 not in directed_graph[i] and temp not in res:
inner_res = temp[:]
res.append(inner_res)
return
for j in range(n):
if directed_graph[i][j] == 1:
temp.append(j)
self.print_path(j, temp, res, n, directed_g... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def print_path(self, i, temp, res, n, directed_graph):
"""i是第i个点"""
<|body_0|>
def allPathsSourceTarget(self, graph):
""":type graph: [[1,2], [3], [3], []] :rtype: [[0,1,3],[0,2,3]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if 1 not ... | stack_v2_sparse_classes_36k_train_026792 | 1,612 | no_license | [
{
"docstring": "i是第i个点",
"name": "print_path",
"signature": "def print_path(self, i, temp, res, n, directed_graph)"
},
{
"docstring": ":type graph: [[1,2], [3], [3], []] :rtype: [[0,1,3],[0,2,3]]",
"name": "allPathsSourceTarget",
"signature": "def allPathsSourceTarget(self, graph)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def print_path(self, i, temp, res, n, directed_graph): i是第i个点
- def allPathsSourceTarget(self, graph): :type graph: [[1,2], [3], [3], []] :rtype: [[0,1,3],[0,2,3]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def print_path(self, i, temp, res, n, directed_graph): i是第i个点
- def allPathsSourceTarget(self, graph): :type graph: [[1,2], [3], [3], []] :rtype: [[0,1,3],[0,2,3]]
<|skeleton|>
... | 18c06a96bb14688e4a1d5fb6baf235a6b53bd3ae | <|skeleton|>
class Solution:
def print_path(self, i, temp, res, n, directed_graph):
"""i是第i个点"""
<|body_0|>
def allPathsSourceTarget(self, graph):
""":type graph: [[1,2], [3], [3], []] :rtype: [[0,1,3],[0,2,3]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def print_path(self, i, temp, res, n, directed_graph):
"""i是第i个点"""
if 1 not in directed_graph[i] and temp not in res:
inner_res = temp[:]
res.append(inner_res)
return
for j in range(n):
if directed_graph[i][j] == 1:
... | the_stack_v2_python_sparse | medium/others/all-paths-from-source-to-target.py | congyingTech/Basic-Algorithm | train | 10 | |
712d0fca96e172d2e310644e49925035d3cfb08b | [
"H, edges = np.histogramdd(data, bins=bins, normed=True)\nHmasked = np.ma.masked_where(H == 0, H)\nxedges, yedges = edges[:2]\nif 'levels' not in kwargs:\n kwargs['levels'] = np.linspace(0, 10)\nax.contourf(xedges[1:], yedges[1:], Hmasked.T[where], **kwargs)\nax.set_xlabel('time after front passage')\nax.set_yla... | <|body_start_0|>
H, edges = np.histogramdd(data, bins=bins, normed=True)
Hmasked = np.ma.masked_where(H == 0, H)
xedges, yedges = edges[:2]
if 'levels' not in kwargs:
kwargs['levels'] = np.linspace(0, 10)
ax.contourf(xedges[1:], yedges[1:], Hmasked.T[where], **kwargs)... | Histograms | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Histograms:
def plot_time_histogram(ax, data, bins, where=np.s_[:], **kwargs):
"""Plot a histogram of a quantity through time. bins - edges of the histogram bins where - z index or slice object to use"""
<|body_0|>
def vertical_histogram(self, ax, quantity, bins, levels):
... | stack_v2_sparse_classes_36k_train_026793 | 7,603 | no_license | [
{
"docstring": "Plot a histogram of a quantity through time. bins - edges of the histogram bins where - z index or slice object to use",
"name": "plot_time_histogram",
"signature": "def plot_time_histogram(ax, data, bins, where=np.s_[:], **kwargs)"
},
{
"docstring": "Make a contour plot of the v... | 2 | stack_v2_sparse_classes_30k_train_020638 | Implement the Python class `Histograms` described below.
Class description:
Implement the Histograms class.
Method signatures and docstrings:
- def plot_time_histogram(ax, data, bins, where=np.s_[:], **kwargs): Plot a histogram of a quantity through time. bins - edges of the histogram bins where - z index or slice ob... | Implement the Python class `Histograms` described below.
Class description:
Implement the Histograms class.
Method signatures and docstrings:
- def plot_time_histogram(ax, data, bins, where=np.s_[:], **kwargs): Plot a histogram of a quantity through time. bins - edges of the histogram bins where - z index or slice ob... | 4e1f20ecd979810a2f9f744e51b1eaf304b64bb6 | <|skeleton|>
class Histograms:
def plot_time_histogram(ax, data, bins, where=np.s_[:], **kwargs):
"""Plot a histogram of a quantity through time. bins - edges of the histogram bins where - z index or slice object to use"""
<|body_0|>
def vertical_histogram(self, ax, quantity, bins, levels):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Histograms:
def plot_time_histogram(ax, data, bins, where=np.s_[:], **kwargs):
"""Plot a histogram of a quantity through time. bins - edges of the histogram bins where - z index or slice object to use"""
H, edges = np.histogramdd(data, bins=bins, normed=True)
Hmasked = np.ma.masked_whe... | the_stack_v2_python_sparse | gc_turbulence/analysis.py | aaren/lab_turbulence | train | 0 | |
593b7db55df061629bbdd0642dfa5c5ab2e093da | [
"md5 = hashlib.md5()\nwith open(self.file_name, 'rb') as in_file:\n for data_chunk in iter(lambda: in_file.read(4096), b''):\n md5.update(data_chunk)\nif self.digest != md5.hexdigest():\n raise MD5MismatchException(self, md5.hexdigest())\nreturn True",
"if self.data_size != os.stat(self.file_name).st... | <|body_start_0|>
md5 = hashlib.md5()
with open(self.file_name, 'rb') as in_file:
for data_chunk in iter(lambda: in_file.read(4096), b''):
md5.update(data_chunk)
if self.digest != md5.hexdigest():
raise MD5MismatchException(self, md5.hexdigest())
re... | Represents a PartFile including methods for validation. | PartFile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartFile:
"""Represents a PartFile including methods for validation."""
def is_correct_md5_sum(self):
"""Is the md5 sum correct? :return boolean: When True :raises MD5MismatchException:"""
<|body_0|>
def is_correct_size(self):
"""Is the data_size what is expected... | stack_v2_sparse_classes_36k_train_026794 | 2,200 | no_license | [
{
"docstring": "Is the md5 sum correct? :return boolean: When True :raises MD5MismatchException:",
"name": "is_correct_md5_sum",
"signature": "def is_correct_md5_sum(self)"
},
{
"docstring": "Is the data_size what is expected? :return boolean: When True :raises DataSizeMismatchException:",
"... | 3 | stack_v2_sparse_classes_30k_train_018618 | Implement the Python class `PartFile` described below.
Class description:
Represents a PartFile including methods for validation.
Method signatures and docstrings:
- def is_correct_md5_sum(self): Is the md5 sum correct? :return boolean: When True :raises MD5MismatchException:
- def is_correct_size(self): Is the data_... | Implement the Python class `PartFile` described below.
Class description:
Represents a PartFile including methods for validation.
Method signatures and docstrings:
- def is_correct_md5_sum(self): Is the md5 sum correct? :return boolean: When True :raises MD5MismatchException:
- def is_correct_size(self): Is the data_... | d2d0e15aca6a868a0887594ac63252cadb447b0c | <|skeleton|>
class PartFile:
"""Represents a PartFile including methods for validation."""
def is_correct_md5_sum(self):
"""Is the md5 sum correct? :return boolean: When True :raises MD5MismatchException:"""
<|body_0|>
def is_correct_size(self):
"""Is the data_size what is expected... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PartFile:
"""Represents a PartFile including methods for validation."""
def is_correct_md5_sum(self):
"""Is the md5 sum correct? :return boolean: When True :raises MD5MismatchException:"""
md5 = hashlib.md5()
with open(self.file_name, 'rb') as in_file:
for data_chunk i... | the_stack_v2_python_sparse | py-odfi-client/ox_dw_odfi_client/files.py | atuldata/snowflake-wheels | train | 0 |
77d008532919efcc6c3abc352c4d3b9d5e1c210e | [
"result = []\nif not root:\n return result\nstackOfNode = [root]\nstackOfString = [str(root.val)]\nwhile stackOfNode:\n currNode = stackOfNode.pop()\n currString = stackOfString.pop()\n if currNode.left:\n stackOfNode.append(currNode.left)\n stackOfString.append(currString + '->' + str(cur... | <|body_start_0|>
result = []
if not root:
return result
stackOfNode = [root]
stackOfString = [str(root.val)]
while stackOfNode:
currNode = stackOfNode.pop()
currString = stackOfString.pop()
if currNode.left:
stackOfN... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str]"""
<|body_0|>
def binaryTreePaths_self(self, root):
""":type root: TreeNode :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
if... | stack_v2_sparse_classes_36k_train_026795 | 1,739 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[str]",
"name": "binaryTreePaths",
"signature": "def binaryTreePaths(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[str]",
"name": "binaryTreePaths_self",
"signature": "def binaryTreePaths_self(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binaryTreePaths(self, root): :type root: TreeNode :rtype: List[str]
- def binaryTreePaths_self(self, root): :type root: TreeNode :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binaryTreePaths(self, root): :type root: TreeNode :rtype: List[str]
- def binaryTreePaths_self(self, root): :type root: TreeNode :rtype: List[str]
<|skeleton|>
class Solutio... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str]"""
<|body_0|>
def binaryTreePaths_self(self, root):
""":type root: TreeNode :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str]"""
result = []
if not root:
return result
stackOfNode = [root]
stackOfString = [str(root.val)]
while stackOfNode:
currNode = stackOfNode.pop()
... | the_stack_v2_python_sparse | 257_binary_tree_paths/sol.py | lianke123321/leetcode_sol | train | 0 | |
03928cd54a36b58b6cf48f056501d67f7d187655 | [
"for line in tokens_by_line:\n if not line:\n continue\n ix = 0\n ll = len(line)\n while ll > ix and line[ix].type in {tokenize.INDENT, tokenize.DEDENT}:\n ix += 1\n if ix >= ll:\n continue\n if line[ix].string in ESCAPE_SINGLES:\n return cls(line[ix].start)",
"start_... | <|body_start_0|>
for line in tokens_by_line:
if not line:
continue
ix = 0
ll = len(line)
while ll > ix and line[ix].type in {tokenize.INDENT, tokenize.DEDENT}:
ix += 1
if ix >= ll:
continue
if... | Transformer for escaped commands like %foo, !foo, or /foo | EscapedCommand | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EscapedCommand:
"""Transformer for escaped commands like %foo, !foo, or /foo"""
def find(cls, tokens_by_line):
"""Find the first escaped command (%foo, !foo, etc.) in the cell."""
<|body_0|>
def transform(self, lines):
"""Transform an escaped line found by the ``... | stack_v2_sparse_classes_36k_train_026796 | 29,393 | permissive | [
{
"docstring": "Find the first escaped command (%foo, !foo, etc.) in the cell.",
"name": "find",
"signature": "def find(cls, tokens_by_line)"
},
{
"docstring": "Transform an escaped line found by the ``find()`` classmethod.",
"name": "transform",
"signature": "def transform(self, lines)"... | 2 | stack_v2_sparse_classes_30k_train_005036 | Implement the Python class `EscapedCommand` described below.
Class description:
Transformer for escaped commands like %foo, !foo, or /foo
Method signatures and docstrings:
- def find(cls, tokens_by_line): Find the first escaped command (%foo, !foo, etc.) in the cell.
- def transform(self, lines): Transform an escaped... | Implement the Python class `EscapedCommand` described below.
Class description:
Transformer for escaped commands like %foo, !foo, or /foo
Method signatures and docstrings:
- def find(cls, tokens_by_line): Find the first escaped command (%foo, !foo, etc.) in the cell.
- def transform(self, lines): Transform an escaped... | e5103f971233fd66b558585cce7a4f52a716cd56 | <|skeleton|>
class EscapedCommand:
"""Transformer for escaped commands like %foo, !foo, or /foo"""
def find(cls, tokens_by_line):
"""Find the first escaped command (%foo, !foo, etc.) in the cell."""
<|body_0|>
def transform(self, lines):
"""Transform an escaped line found by the ``... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EscapedCommand:
"""Transformer for escaped commands like %foo, !foo, or /foo"""
def find(cls, tokens_by_line):
"""Find the first escaped command (%foo, !foo, etc.) in the cell."""
for line in tokens_by_line:
if not line:
continue
ix = 0
... | the_stack_v2_python_sparse | IPython/core/inputtransformer2.py | ipython/ipython | train | 13,673 |
7ee0ae9a7718c6c8578d7213c6ccdfe53bd75317 | [
"filters1, filters2, filters3 = filters\nkernel_size1, kernel_size2, kernel_size3 = kernel_sizes\nstrides1, strides2, strides3 = strides\npadding1, padding2, padding3 = padding\nx = Conv2D(filters=filters1, kernel_size=kernel_size1, strides=strides1, padding=padding1)(input_tensor)\nx = BatchNormalization()(x)\nx =... | <|body_start_0|>
filters1, filters2, filters3 = filters
kernel_size1, kernel_size2, kernel_size3 = kernel_sizes
strides1, strides2, strides3 = strides
padding1, padding2, padding3 = padding
x = Conv2D(filters=filters1, kernel_size=kernel_size1, strides=strides1, padding=padding1)... | ResNet50_BASE | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNet50_BASE:
def _identity_block(self, input_tensor, filters, kernel_sizes=DEFAULT_ID_KERNELS, strides=DEFAULT_ID_STRIDES, padding=DEFAULT_ID_PADDING):
"""The identity block has a shortcut which is just the identity"""
<|body_0|>
def _conv_block(self, input_tensor, filters... | stack_v2_sparse_classes_36k_train_026797 | 5,478 | no_license | [
{
"docstring": "The identity block has a shortcut which is just the identity",
"name": "_identity_block",
"signature": "def _identity_block(self, input_tensor, filters, kernel_sizes=DEFAULT_ID_KERNELS, strides=DEFAULT_ID_STRIDES, padding=DEFAULT_ID_PADDING)"
},
{
"docstring": "The conv_block blo... | 2 | stack_v2_sparse_classes_30k_train_004559 | Implement the Python class `ResNet50_BASE` described below.
Class description:
Implement the ResNet50_BASE class.
Method signatures and docstrings:
- def _identity_block(self, input_tensor, filters, kernel_sizes=DEFAULT_ID_KERNELS, strides=DEFAULT_ID_STRIDES, padding=DEFAULT_ID_PADDING): The identity block has a shor... | Implement the Python class `ResNet50_BASE` described below.
Class description:
Implement the ResNet50_BASE class.
Method signatures and docstrings:
- def _identity_block(self, input_tensor, filters, kernel_sizes=DEFAULT_ID_KERNELS, strides=DEFAULT_ID_STRIDES, padding=DEFAULT_ID_PADDING): The identity block has a shor... | 9e45ab002eb6f1ff1399d37ce92c66f4310911f3 | <|skeleton|>
class ResNet50_BASE:
def _identity_block(self, input_tensor, filters, kernel_sizes=DEFAULT_ID_KERNELS, strides=DEFAULT_ID_STRIDES, padding=DEFAULT_ID_PADDING):
"""The identity block has a shortcut which is just the identity"""
<|body_0|>
def _conv_block(self, input_tensor, filters... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResNet50_BASE:
def _identity_block(self, input_tensor, filters, kernel_sizes=DEFAULT_ID_KERNELS, strides=DEFAULT_ID_STRIDES, padding=DEFAULT_ID_PADDING):
"""The identity block has a shortcut which is just the identity"""
filters1, filters2, filters3 = filters
kernel_size1, kernel_size2... | the_stack_v2_python_sparse | models/resnet.py | brookisme/planet-kaggle | train | 0 | |
7cfba947868653330f2e61f87cf51d2af0a14f7e | [
"super(RandomForest, self).setUp()\nschema = [('feat1', float), ('feat2', float), ('class', int)]\nfilename = self.get_file('rand_forest_class.csv')\nself.frame = self.context.frame.import_csv(filename, schema=schema)",
"rfmodel = self.context.models.classification.random_forest_classifier.train(self.frame, ['fea... | <|body_start_0|>
super(RandomForest, self).setUp()
schema = [('feat1', float), ('feat2', float), ('class', int)]
filename = self.get_file('rand_forest_class.csv')
self.frame = self.context.frame.import_csv(filename, schema=schema)
<|end_body_0|>
<|body_start_1|>
rfmodel = self.c... | RandomForest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomForest:
def setUp(self):
"""Build the required frame"""
<|body_0|>
def test_class_scoring(self):
"""Test random forest classifier scoring model"""
<|body_1|>
def test_reg_scoring(self):
"""Test random forest regressor scoring model"""
... | stack_v2_sparse_classes_36k_train_026798 | 3,004 | permissive | [
{
"docstring": "Build the required frame",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test random forest classifier scoring model",
"name": "test_class_scoring",
"signature": "def test_class_scoring(self)"
},
{
"docstring": "Test random forest regressor sc... | 3 | stack_v2_sparse_classes_30k_train_001055 | Implement the Python class `RandomForest` described below.
Class description:
Implement the RandomForest class.
Method signatures and docstrings:
- def setUp(self): Build the required frame
- def test_class_scoring(self): Test random forest classifier scoring model
- def test_reg_scoring(self): Test random forest reg... | Implement the Python class `RandomForest` described below.
Class description:
Implement the RandomForest class.
Method signatures and docstrings:
- def setUp(self): Build the required frame
- def test_class_scoring(self): Test random forest classifier scoring model
- def test_reg_scoring(self): Test random forest reg... | 5548fc925b5c278263cbdebbd9e8c7593320c2f4 | <|skeleton|>
class RandomForest:
def setUp(self):
"""Build the required frame"""
<|body_0|>
def test_class_scoring(self):
"""Test random forest classifier scoring model"""
<|body_1|>
def test_reg_scoring(self):
"""Test random forest regressor scoring model"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomForest:
def setUp(self):
"""Build the required frame"""
super(RandomForest, self).setUp()
schema = [('feat1', float), ('feat2', float), ('class', int)]
filename = self.get_file('rand_forest_class.csv')
self.frame = self.context.frame.import_csv(filename, schema=sc... | the_stack_v2_python_sparse | regression-tests/sparktkregtests/testcases/scoretests/random_forest_test.py | trustedanalytics/spark-tk | train | 35 | |
f1abbeeb3a3bd721b7244555e560f6f2e3da510e | [
"dp = [0 for i in range(n + 1)]\nif n == 2:\n return 1\ndp[1] = 1\ndp[2] = 1\nfor i in range(3, n + 1):\n for j in range(1, i // 2 + 1):\n dp[i] = max(dp[i], max(dp[j], j) * max(dp[i - j], i - j))\nreturn dp[-1]",
"res = 0\nfor i in range(2, n + 1):\n a1 = n // i\n if n % i == 0:\n res =... | <|body_start_0|>
dp = [0 for i in range(n + 1)]
if n == 2:
return 1
dp[1] = 1
dp[2] = 1
for i in range(3, n + 1):
for j in range(1, i // 2 + 1):
dp[i] = max(dp[i], max(dp[j], j) * max(dp[i - j], i - j))
return dp[-1]
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def integerBreak(self, n):
""":type n: int :rtype: int 32ms"""
<|body_0|>
def integerBreak(self, n):
""":type n: int :rtype: int 28ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [0 for i in range(n + 1)]
if n == 2:
... | stack_v2_sparse_classes_36k_train_026799 | 1,193 | no_license | [
{
"docstring": ":type n: int :rtype: int 32ms",
"name": "integerBreak",
"signature": "def integerBreak(self, n)"
},
{
"docstring": ":type n: int :rtype: int 28ms",
"name": "integerBreak",
"signature": "def integerBreak(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerBreak(self, n): :type n: int :rtype: int 32ms
- def integerBreak(self, n): :type n: int :rtype: int 28ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerBreak(self, n): :type n: int :rtype: int 32ms
- def integerBreak(self, n): :type n: int :rtype: int 28ms
<|skeleton|>
class Solution:
def integerBreak(self, n):
... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def integerBreak(self, n):
""":type n: int :rtype: int 32ms"""
<|body_0|>
def integerBreak(self, n):
""":type n: int :rtype: int 28ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def integerBreak(self, n):
""":type n: int :rtype: int 32ms"""
dp = [0 for i in range(n + 1)]
if n == 2:
return 1
dp[1] = 1
dp[2] = 1
for i in range(3, n + 1):
for j in range(1, i // 2 + 1):
dp[i] = max(dp[i], ma... | the_stack_v2_python_sparse | IntegerBreak_MID_343.py | 953250587/leetcode-python | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.