blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
444e3caa509117de0416db2e7eddae8940caac82 | [
"super().__init__(target)\nif wrap:\n if wrap < 1:\n raise ValueError\nself.wrap = wrap\nself.record2title = record2title",
"if self.record2title:\n title = self.clean(self.record2title(record))\nelse:\n id = self.clean(record.id)\n description = self.clean(record.description)\n if descripti... | <|body_start_0|>
super().__init__(target)
if wrap:
if wrap < 1:
raise ValueError
self.wrap = wrap
self.record2title = record2title
<|end_body_0|>
<|body_start_1|>
if self.record2title:
title = self.clean(self.record2title(record))
... | Class to write Fasta format files (OBSOLETE). Please use the ``as_fasta`` function instead, or the top level ``Bio.SeqIO.write()`` function instead using ``format="fasta"``. | FastaWriter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastaWriter:
"""Class to write Fasta format files (OBSOLETE). Please use the ``as_fasta`` function instead, or the top level ``Bio.SeqIO.write()`` function instead using ``format="fasta"``."""
def __init__(self, target, wrap=60, record2title=None):
"""Create a Fasta writer (OBSOLETE)... | stack_v2_sparse_classes_75kplus_train_002200 | 14,957 | permissive | [
{
"docstring": "Create a Fasta writer (OBSOLETE). Arguments: - target - Output stream opened in text mode, or a path to a file. - wrap - Optional line length used to wrap sequence lines. Defaults to wrapping the sequence at 60 characters Use zero (or None) for no wrapping, giving a single long line for the sequ... | 2 | stack_v2_sparse_classes_30k_train_043670 | Implement the Python class `FastaWriter` described below.
Class description:
Class to write Fasta format files (OBSOLETE). Please use the ``as_fasta`` function instead, or the top level ``Bio.SeqIO.write()`` function instead using ``format="fasta"``.
Method signatures and docstrings:
- def __init__(self, target, wrap... | Implement the Python class `FastaWriter` described below.
Class description:
Class to write Fasta format files (OBSOLETE). Please use the ``as_fasta`` function instead, or the top level ``Bio.SeqIO.write()`` function instead using ``format="fasta"``.
Method signatures and docstrings:
- def __init__(self, target, wrap... | 595c5c46794ae08a1f19716636eac7430cededa1 | <|skeleton|>
class FastaWriter:
"""Class to write Fasta format files (OBSOLETE). Please use the ``as_fasta`` function instead, or the top level ``Bio.SeqIO.write()`` function instead using ``format="fasta"``."""
def __init__(self, target, wrap=60, record2title=None):
"""Create a Fasta writer (OBSOLETE)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FastaWriter:
"""Class to write Fasta format files (OBSOLETE). Please use the ``as_fasta`` function instead, or the top level ``Bio.SeqIO.write()`` function instead using ``format="fasta"``."""
def __init__(self, target, wrap=60, record2title=None):
"""Create a Fasta writer (OBSOLETE). Arguments: ... | the_stack_v2_python_sparse | .venv/Lib/site-packages/Bio/SeqIO/FastaIO.py | abner-lucas/tp-cruzi-db | train | 2 |
a62370ed1742386283b1b2b264209c3fad4e54df | [
"for num in nums:\n idx = abs(num) - 1\n nums[idx] = -abs(nums[idx])\nreturn [i + 1 for i, num in enumerate(nums) if num > 0]",
"if len(nums) == 0:\n return []\nresult = []\nn = len(nums)\nfor i in range(1, n + 1):\n if i not in nums:\n result.append(i)\nreturn result"
] | <|body_start_0|>
for num in nums:
idx = abs(num) - 1
nums[idx] = -abs(nums[idx])
return [i + 1 for i, num in enumerate(nums) if num > 0]
<|end_body_0|>
<|body_start_1|>
if len(nums) == 0:
return []
result = []
n = len(nums)
for i in ra... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDisappearedNumbers(self, nums):
"""该方法不会超时"""
<|body_0|>
def findDisappearedNumbers1(self, nums):
"""下面的方法会超时,所以不能这么做"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for num in nums:
idx = abs(num) - 1
nums[... | stack_v2_sparse_classes_75kplus_train_002201 | 770 | no_license | [
{
"docstring": "该方法不会超时",
"name": "findDisappearedNumbers",
"signature": "def findDisappearedNumbers(self, nums)"
},
{
"docstring": "下面的方法会超时,所以不能这么做",
"name": "findDisappearedNumbers1",
"signature": "def findDisappearedNumbers1(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDisappearedNumbers(self, nums): 该方法不会超时
- def findDisappearedNumbers1(self, nums): 下面的方法会超时,所以不能这么做 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDisappearedNumbers(self, nums): 该方法不会超时
- def findDisappearedNumbers1(self, nums): 下面的方法会超时,所以不能这么做
<|skeleton|>
class Solution:
def findDisappearedNumbers(self, nu... | 9dccbdea918cc0531f7cbe60677a197a60ac61b7 | <|skeleton|>
class Solution:
def findDisappearedNumbers(self, nums):
"""该方法不会超时"""
<|body_0|>
def findDisappearedNumbers1(self, nums):
"""下面的方法会超时,所以不能这么做"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findDisappearedNumbers(self, nums):
"""该方法不会超时"""
for num in nums:
idx = abs(num) - 1
nums[idx] = -abs(nums[idx])
return [i + 1 for i, num in enumerate(nums) if num > 0]
def findDisappearedNumbers1(self, nums):
"""下面的方法会超时,所以不能这么做"""
... | the_stack_v2_python_sparse | leetcode/List/FindAllNumbersDisappearedinanArray.py | chuanfanyoudong/algorithm | train | 0 | |
2913b9ed2bca56a394f18b8968109f36e377563c | [
"img = _getimg(img)\nif not no_conversion:\n img = cvt(img, from_=eColorSpace.BGR, to=color_space)\nself._color_space = color_space\nself._ColInt = ColInt\nself._img = img\nself.img_detected = None",
"if isinstance(self._ColInt, ColorInterval):\n intervals = [self._ColInt]\nelse:\n intervals = self._ColI... | <|body_start_0|>
img = _getimg(img)
if not no_conversion:
img = cvt(img, from_=eColorSpace.BGR, to=color_space)
self._color_space = color_space
self._ColInt = ColInt
self._img = img
self.img_detected = None
<|end_body_0|>
<|body_start_1|>
if isinstanc... | color detection stuff Simple example: #define a colorinterval in the imagej HSV color space ciH = color.ColorInterval(color.eColorSpace.HSV255255255, (33, 0, 0), (255, 255, 102)) #Create class instance with image and the color interval. img_in is in BGR, we tell opencv to convert to HSV CD = color.ColorDetection(img_in... | ColorDetection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorDetection:
"""color detection stuff Simple example: #define a colorinterval in the imagej HSV color space ciH = color.ColorInterval(color.eColorSpace.HSV255255255, (33, 0, 0), (255, 255, 102)) #Create class instance with image and the color interval. img_in is in BGR, we tell opencv to conve... | stack_v2_sparse_classes_75kplus_train_002202 | 15,509 | no_license | [
{
"docstring": "(ndarray|str, class:ColorInterval|list:class:ColorInterval, Enum:eColorSpace) -> void img: Will load img if a path is passed. color_space: Convert to this colorspace, assumes OpenCV format (BGR) of img ColInt: Class ColorInterval or list like of ColorInterval instances. Colorinterval class speci... | 4 | null | Implement the Python class `ColorDetection` described below.
Class description:
color detection stuff Simple example: #define a colorinterval in the imagej HSV color space ciH = color.ColorInterval(color.eColorSpace.HSV255255255, (33, 0, 0), (255, 255, 102)) #Create class instance with image and the color interval. im... | Implement the Python class `ColorDetection` described below.
Class description:
color detection stuff Simple example: #define a colorinterval in the imagej HSV color space ciH = color.ColorInterval(color.eColorSpace.HSV255255255, (33, 0, 0), (255, 255, 102)) #Create class instance with image and the color interval. im... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class ColorDetection:
"""color detection stuff Simple example: #define a colorinterval in the imagej HSV color space ciH = color.ColorInterval(color.eColorSpace.HSV255255255, (33, 0, 0), (255, 255, 102)) #Create class instance with image and the color interval. img_in is in BGR, we tell opencv to conve... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ColorDetection:
"""color detection stuff Simple example: #define a colorinterval in the imagej HSV color space ciH = color.ColorInterval(color.eColorSpace.HSV255255255, (33, 0, 0), (255, 255, 102)) #Create class instance with image and the color interval. img_in is in BGR, we tell opencv to convert to HSV CD ... | the_stack_v2_python_sparse | opencvlib/color.py | gmonkman/python | train | 0 |
64c8e3ccc97975251c9ac96fd7180357b341575e | [
"nums.sort()\nlength = len(nums)\nif length == 0:\n return False\nif length == 2 and nums[0] == nums[1]:\n return True\nfor i in range(1, length):\n if nums[i - 1] == nums[i]:\n return True\nreturn False",
"nums.sort()\nlength = len(nums) - 1\nwhile length > 0:\n if nums[length] == nums[length ... | <|body_start_0|>
nums.sort()
length = len(nums)
if length == 0:
return False
if length == 2 and nums[0] == nums[1]:
return True
for i in range(1, length):
if nums[i - 1] == nums[i]:
return True
return False
<|end_body_0|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsDuplicate(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def containsDuplicate2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.sort()
length = l... | stack_v2_sparse_classes_75kplus_train_002203 | 956 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "containsDuplicate",
"signature": "def containsDuplicate(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "containsDuplicate2",
"signature": "def containsDuplicate2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsDuplicate(self, nums): :type nums: List[int] :rtype: bool
- def containsDuplicate2(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsDuplicate(self, nums): :type nums: List[int] :rtype: bool
- def containsDuplicate2(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
... | cd746c37e0a44dc80c5c5177450769908a38fee5 | <|skeleton|>
class Solution:
def containsDuplicate(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def containsDuplicate2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def containsDuplicate(self, nums):
""":type nums: List[int] :rtype: bool"""
nums.sort()
length = len(nums)
if length == 0:
return False
if length == 2 and nums[0] == nums[1]:
return True
for i in range(1, length):
if... | the_stack_v2_python_sparse | leetcode/ContainsDuplicate.py | Sparkoor/learning | train | 0 | |
862980c746946faf69f81e043c15a90cc130fa88 | [
"from Akamai_SIEM import fetch_incidents_command\nrequests_mock.get(f'{BASE_URL}/50170?limit=5&from=1575966002', text=SEC_EVENTS_TXT)\ntested_incidents, tested_last_run = fetch_incidents_command(client=client, fetch_time='12 hours', fetch_limit=5, config_ids='50170', last_run={})\nexpected_incidents = load_params_f... | <|body_start_0|>
from Akamai_SIEM import fetch_incidents_command
requests_mock.get(f'{BASE_URL}/50170?limit=5&from=1575966002', text=SEC_EVENTS_TXT)
tested_incidents, tested_last_run = fetch_incidents_command(client=client, fetch_time='12 hours', fetch_limit=5, config_ids='50170', last_run={})
... | TestCommandsFunctions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCommandsFunctions:
def test_fetch_incidents_command_1(self, client, datadir, requests_mock):
"""Test - No last time exsits and event available"""
<|body_0|>
def test_fetch_incidents_command_2(self, client, datadir, requests_mock):
"""Test - Last time exsits and e... | stack_v2_sparse_classes_75kplus_train_002204 | 7,487 | permissive | [
{
"docstring": "Test - No last time exsits and event available",
"name": "test_fetch_incidents_command_1",
"signature": "def test_fetch_incidents_command_1(self, client, datadir, requests_mock)"
},
{
"docstring": "Test - Last time exsits and events available",
"name": "test_fetch_incidents_c... | 6 | stack_v2_sparse_classes_30k_train_041594 | Implement the Python class `TestCommandsFunctions` described below.
Class description:
Implement the TestCommandsFunctions class.
Method signatures and docstrings:
- def test_fetch_incidents_command_1(self, client, datadir, requests_mock): Test - No last time exsits and event available
- def test_fetch_incidents_comm... | Implement the Python class `TestCommandsFunctions` described below.
Class description:
Implement the TestCommandsFunctions class.
Method signatures and docstrings:
- def test_fetch_incidents_command_1(self, client, datadir, requests_mock): Test - No last time exsits and event available
- def test_fetch_incidents_comm... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestCommandsFunctions:
def test_fetch_incidents_command_1(self, client, datadir, requests_mock):
"""Test - No last time exsits and event available"""
<|body_0|>
def test_fetch_incidents_command_2(self, client, datadir, requests_mock):
"""Test - Last time exsits and e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCommandsFunctions:
def test_fetch_incidents_command_1(self, client, datadir, requests_mock):
"""Test - No last time exsits and event available"""
from Akamai_SIEM import fetch_incidents_command
requests_mock.get(f'{BASE_URL}/50170?limit=5&from=1575966002', text=SEC_EVENTS_TXT)
... | the_stack_v2_python_sparse | Packs/Akamai_SIEM/Integrations/Akamai_SIEM/Akamai_SIEM_test.py | demisto/content | train | 1,023 | |
16d58db564e6e61be73c631255c4aeb09dc878f1 | [
"Log(f'GET Request Received: Searching {phone}', req=req)\nresp.status = falcon.HTTP_204\nresp.content_type = 'application/json'\nperson = PersonOperator.searchBy(key='phone', value=str(phone))\nif len(person) < 1:\n resp.body = json.dumps({'msg': f\"The person with the phone {phone} wasn't found\"})\nelse:\n ... | <|body_start_0|>
Log(f'GET Request Received: Searching {phone}', req=req)
resp.status = falcon.HTTP_204
resp.content_type = 'application/json'
person = PersonOperator.searchBy(key='phone', value=str(phone))
if len(person) < 1:
resp.body = json.dumps({'msg': f"The pers... | It handles the request to a single phone person Args: object (object): No info | PersonDetailHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonDetailHandler:
"""It handles the request to a single phone person Args: object (object): No info"""
def on_get(self, req, resp, phone):
"""Handles the GET request searching an specific phone number Args: req (Falcon HTTP Request): Request received by the server resp (Falcon HTT... | stack_v2_sparse_classes_75kplus_train_002205 | 4,618 | permissive | [
{
"docstring": "Handles the GET request searching an specific phone number Args: req (Falcon HTTP Request): Request received by the server resp (Falcon HTTP Response): Response constructed by the server phone (str): Phone number to be search in the database Returns: None",
"name": "on_get",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_000969 | Implement the Python class `PersonDetailHandler` described below.
Class description:
It handles the request to a single phone person Args: object (object): No info
Method signatures and docstrings:
- def on_get(self, req, resp, phone): Handles the GET request searching an specific phone number Args: req (Falcon HTTP ... | Implement the Python class `PersonDetailHandler` described below.
Class description:
It handles the request to a single phone person Args: object (object): No info
Method signatures and docstrings:
- def on_get(self, req, resp, phone): Handles the GET request searching an specific phone number Args: req (Falcon HTTP ... | 6dad5b1a19156125ae917a28bb78439894e66d9e | <|skeleton|>
class PersonDetailHandler:
"""It handles the request to a single phone person Args: object (object): No info"""
def on_get(self, req, resp, phone):
"""Handles the GET request searching an specific phone number Args: req (Falcon HTTP Request): Request received by the server resp (Falcon HTT... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PersonDetailHandler:
"""It handles the request to a single phone person Args: object (object): No info"""
def on_get(self, req, resp, phone):
"""Handles the GET request searching an specific phone number Args: req (Falcon HTTP Request): Request received by the server resp (Falcon HTTP Response): ... | the_stack_v2_python_sparse | app/api/handler/PersonDetail.py | jormanfernandez/crud | train | 0 |
6e1e87e03aa91dfc55f36b678765a646806b27b1 | [
"m, n = (len(A), len(A[0]))\nB = [[0] * m for _ in range(n)]\nfor i in range(n):\n for j in range(m):\n B[i][j] = A[j][i]\nreturn B",
"m, n = (len(A), len(A[0]))\nfor i in range(m):\n for j in range(i, n):\n x = min(m - 1, j)\n y = i + j - x\n A[i][j], A[x][y] = (A[x][y], A[i][j]... | <|body_start_0|>
m, n = (len(A), len(A[0]))
B = [[0] * m for _ in range(n)]
for i in range(n):
for j in range(m):
B[i][j] = A[j][i]
return B
<|end_body_0|>
<|body_start_1|>
m, n = (len(A), len(A[0]))
for i in range(m):
for j in ran... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def transpose(self, A):
""":type A: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def transpose_Wrong(self, A):
""":type A: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m, n = (len(A), len... | stack_v2_sparse_classes_75kplus_train_002206 | 1,225 | no_license | [
{
"docstring": ":type A: List[List[int]] :rtype: List[List[int]]",
"name": "transpose",
"signature": "def transpose(self, A)"
},
{
"docstring": ":type A: List[List[int]] :rtype: List[List[int]]",
"name": "transpose_Wrong",
"signature": "def transpose_Wrong(self, A)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def transpose(self, A): :type A: List[List[int]] :rtype: List[List[int]]
- def transpose_Wrong(self, A): :type A: List[List[int]] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def transpose(self, A): :type A: List[List[int]] :rtype: List[List[int]]
- def transpose_Wrong(self, A): :type A: List[List[int]] :rtype: List[List[int]]
<|skeleton|>
class Solu... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def transpose(self, A):
""":type A: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def transpose_Wrong(self, A):
""":type A: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def transpose(self, A):
""":type A: List[List[int]] :rtype: List[List[int]]"""
m, n = (len(A), len(A[0]))
B = [[0] * m for _ in range(n)]
for i in range(n):
for j in range(m):
B[i][j] = A[j][i]
return B
def transpose_Wrong(self... | the_stack_v2_python_sparse | code867TransposeMatrix.py | cybelewang/leetcode-python | train | 0 | |
bfd9d4af41d419f1974c340b7228fcfdd39ade23 | [
"self._input_df = pd.read_csv(input_file)\nself._data_path = data_path\ninput_dir = os.path.dirname(input_file)\nmain_log = os.path.join(input_dir, 'getCDS.log')\nlog_obj = logthis.logit(log_f=main_log, log_level=loglevel)\nself._logger = log_obj.get_logger('main')",
"server = 'https://rest.ensembl.org'\nmissing ... | <|body_start_0|>
self._input_df = pd.read_csv(input_file)
self._data_path = data_path
input_dir = os.path.dirname(input_file)
main_log = os.path.join(input_dir, 'getCDS.log')
log_obj = logthis.logit(log_f=main_log, log_level=loglevel)
self._logger = log_obj.get_logger('ma... | getCDS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getCDS:
def __init__(self, input_file, data_path, loglevel='DEBUG'):
""":param input_file: contains all targeted genes and ensembl ID :param data_path: path contains ccds data downloaded from ncbi db :param loglevel"""
<|body_0|>
def _get_ensembl_dna_38(self):
"""go ... | stack_v2_sparse_classes_75kplus_train_002207 | 4,855 | no_license | [
{
"docstring": ":param input_file: contains all targeted genes and ensembl ID :param data_path: path contains ccds data downloaded from ncbi db :param loglevel",
"name": "__init__",
"signature": "def __init__(self, input_file, data_path, loglevel='DEBUG')"
},
{
"docstring": "go through the input... | 4 | stack_v2_sparse_classes_30k_train_027133 | Implement the Python class `getCDS` described below.
Class description:
Implement the getCDS class.
Method signatures and docstrings:
- def __init__(self, input_file, data_path, loglevel='DEBUG'): :param input_file: contains all targeted genes and ensembl ID :param data_path: path contains ccds data downloaded from n... | Implement the Python class `getCDS` described below.
Class description:
Implement the getCDS class.
Method signatures and docstrings:
- def __init__(self, input_file, data_path, loglevel='DEBUG'): :param input_file: contains all targeted genes and ensembl ID :param data_path: path contains ccds data downloaded from n... | 7d80671129fd6c4dc78af58b2f0331b9838c5c4a | <|skeleton|>
class getCDS:
def __init__(self, input_file, data_path, loglevel='DEBUG'):
""":param input_file: contains all targeted genes and ensembl ID :param data_path: path contains ccds data downloaded from ncbi db :param loglevel"""
<|body_0|>
def _get_ensembl_dna_38(self):
"""go ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class getCDS:
def __init__(self, input_file, data_path, loglevel='DEBUG'):
""":param input_file: contains all targeted genes and ensembl ID :param data_path: path contains ccds data downloaded from ncbi db :param loglevel"""
self._input_df = pd.read_csv(input_file)
self._data_path = data_pat... | the_stack_v2_python_sparse | ppsAnalysis/get_humangeneCDS.py | RyogaLi/PPS | train | 0 | |
e2a4357915b8bebcf84c1db3eba9eeb984bec43d | [
"url = 'https://api.kkbox.com/v1.1/mood-stations'\nurl += '?' + url_parse.urlencode({'territory': terr})\nreturn self.http._post_data(url, None, self.http._headers_with_access_token())",
"url = 'https://api.kkbox.com/v1.1/mood-stations/%s' % station_id\nurl += '?' + url_parse.urlencode({'territory': terr})\nretur... | <|body_start_0|>
url = 'https://api.kkbox.com/v1.1/mood-stations'
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
<|end_body_0|>
<|body_start_1|>
url = 'https://api.kkbox.com/v1.1/mood-stations/%s' % st... | Fetch mood stations and get tracks for a specific mood station. See `https://docs-en.kkbox.codes/v1.1/reference#mood-stations`. | KKBOXMoodStationFetcher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KKBOXMoodStationFetcher:
"""Fetch mood stations and get tracks for a specific mood station. See `https://docs-en.kkbox.codes/v1.1/reference#mood-stations`."""
def fetch_all_mood_stations(self, terr=KKBOXTerritory.TAIWAN):
"""Fetches all mood stations. :param terr: the current territo... | stack_v2_sparse_classes_75kplus_train_002208 | 1,420 | permissive | [
{
"docstring": "Fetches all mood stations. :param terr: the current territory. :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#moodstations`.",
"name": "fetch_all_mood_stations",
"signature": "def fetch_all_mood_stations(self, terr=KKBOXTerritory.TAIWAN)"
},
{
... | 2 | null | Implement the Python class `KKBOXMoodStationFetcher` described below.
Class description:
Fetch mood stations and get tracks for a specific mood station. See `https://docs-en.kkbox.codes/v1.1/reference#mood-stations`.
Method signatures and docstrings:
- def fetch_all_mood_stations(self, terr=KKBOXTerritory.TAIWAN): Fe... | Implement the Python class `KKBOXMoodStationFetcher` described below.
Class description:
Fetch mood stations and get tracks for a specific mood station. See `https://docs-en.kkbox.codes/v1.1/reference#mood-stations`.
Method signatures and docstrings:
- def fetch_all_mood_stations(self, terr=KKBOXTerritory.TAIWAN): Fe... | df5906511b3d37d0e2e221f67a34fcbd31a85b59 | <|skeleton|>
class KKBOXMoodStationFetcher:
"""Fetch mood stations and get tracks for a specific mood station. See `https://docs-en.kkbox.codes/v1.1/reference#mood-stations`."""
def fetch_all_mood_stations(self, terr=KKBOXTerritory.TAIWAN):
"""Fetches all mood stations. :param terr: the current territo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KKBOXMoodStationFetcher:
"""Fetch mood stations and get tracks for a specific mood station. See `https://docs-en.kkbox.codes/v1.1/reference#mood-stations`."""
def fetch_all_mood_stations(self, terr=KKBOXTerritory.TAIWAN):
"""Fetches all mood stations. :param terr: the current territory. :return: ... | the_stack_v2_python_sparse | kkbox_developer_sdk/mood_station_fetcher.py | YeiSimon/OpenAPI-Python | train | 0 |
33e7cac3c176df3dbfce6cb8ed9b4140694b1fcb | [
"if not grid:\n return 0\nm = len(grid)\nn = len(grid[0])\npath = [[0] * n for i in range(m)]\npath[0][0] = grid[0][0]\nfor i in range(1, n):\n path[0][i] = path[0][i - 1] + grid[0][i]\nfor i in range(1, m):\n path[i][0] = path[i - 1][0] + grid[i][0]\nfor i in range(1, m):\n for j in range(1, n):\n ... | <|body_start_0|>
if not grid:
return 0
m = len(grid)
n = len(grid[0])
path = [[0] * n for i in range(m)]
path[0][0] = grid[0][0]
for i in range(1, n):
path[0][i] = path[0][i - 1] + grid[0][i]
for i in range(1, m):
path[i][0] = p... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum1(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
def minPathSum2(self, grid):
""":type grid: List[List[int]] :rtyp... | stack_v2_sparse_classes_75kplus_train_002209 | 2,229 | no_license | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum",
"signature": "def minPathSum(self, grid)"
},
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum1",
"signature": "def minPathSum1(self, grid)"
},
{
"docstring": ":type grid: ... | 3 | stack_v2_sparse_classes_30k_train_025059 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum1(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum2(self, grid): :type gr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum1(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum2(self, grid): :type gr... | eedf73b5f167025a97f0905d3718b6eab2ee3e09 | <|skeleton|>
class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum1(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
def minPathSum2(self, grid):
""":type grid: List[List[int]] :rtyp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
if not grid:
return 0
m = len(grid)
n = len(grid[0])
path = [[0] * n for i in range(m)]
path[0][0] = grid[0][0]
for i in range(1, n):
path[0][i] =... | the_stack_v2_python_sparse | Array/64_Minimum_Path_Sum.py | xiaomojie/LeetCode | train | 0 | |
2d69ce70673b8e5fd64a3d066ce07c20d23d3d08 | [
"if not s:\n res.append(path)\n return\nfor word in wordDict:\n k = len(word)\n if s[:k] == word:\n self.dfs(s[k:], wordDict, path + [word], res)",
"if not self.check(s, wordDict):\n return []\nres = []\nself.dfs(s, wordDict, [], res)\nreturn [' '.join(x) for x in res]",
"if not self.check... | <|body_start_0|>
if not s:
res.append(path)
return
for word in wordDict:
k = len(word)
if s[:k] == word:
self.dfs(s[k:], wordDict, path + [word], res)
<|end_body_0|>
<|body_start_1|>
if not self.check(s, wordDict):
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dfs(self, s, wordDict, path, res):
"""超时 :param s: :param wordDict: :param path: :param res: :return:"""
<|body_0|>
def wordBreak(self, s, wordDict):
"""dfs 超时 加个139题的判断就不会超时了。。。mdzz :type s: str :type wordDict: List[str] :rtype: List[str]"""
<|... | stack_v2_sparse_classes_75kplus_train_002210 | 3,438 | no_license | [
{
"docstring": "超时 :param s: :param wordDict: :param path: :param res: :return:",
"name": "dfs",
"signature": "def dfs(self, s, wordDict, path, res)"
},
{
"docstring": "dfs 超时 加个139题的判断就不会超时了。。。mdzz :type s: str :type wordDict: List[str] :rtype: List[str]",
"name": "wordBreak",
"signatur... | 4 | stack_v2_sparse_classes_30k_train_023124 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, s, wordDict, path, res): 超时 :param s: :param wordDict: :param path: :param res: :return:
- def wordBreak(self, s, wordDict): dfs 超时 加个139题的判断就不会超时了。。。mdzz :type s: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, s, wordDict, path, res): 超时 :param s: :param wordDict: :param path: :param res: :return:
- def wordBreak(self, s, wordDict): dfs 超时 加个139题的判断就不会超时了。。。mdzz :type s: ... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def dfs(self, s, wordDict, path, res):
"""超时 :param s: :param wordDict: :param path: :param res: :return:"""
<|body_0|>
def wordBreak(self, s, wordDict):
"""dfs 超时 加个139题的判断就不会超时了。。。mdzz :type s: str :type wordDict: List[str] :rtype: List[str]"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def dfs(self, s, wordDict, path, res):
"""超时 :param s: :param wordDict: :param path: :param res: :return:"""
if not s:
res.append(path)
return
for word in wordDict:
k = len(word)
if s[:k] == word:
self.dfs(s[k:],... | the_stack_v2_python_sparse | 140_单词拆分 II.py | lovehhf/LeetCode | train | 0 | |
93583167fdea3c7155e6c18cf54a098d6e2b3518 | [
"a = self.to_bin(a)\nb = self.to_bin(b)\ndiff = len(a) - len(b)\nret = 0\nif diff < 0:\n a, b = (b, a)\n diff *= -1\nb = '0' * diff + b\nfor i in xrange(len(b)):\n if a[i] != b[i]:\n ret += 1\nreturn ret",
"\"\"\"\n :param n:\n :return:\n \"\"\"\na = abs(n)\nlst = []\nwhile a ... | <|body_start_0|>
a = self.to_bin(a)
b = self.to_bin(b)
diff = len(a) - len(b)
ret = 0
if diff < 0:
a, b = (b, a)
diff *= -1
b = '0' * diff + b
for i in xrange(len(b)):
if a[i] != b[i]:
ret += 1
return ret... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def bitSwapRequired(self, a, b):
""":param a: :param b: :return: int"""
<|body_0|>
def to_bin(self, n):
"""2's complement 32-bit :param n: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
a = self.to_bin(a)
b = self.to_bin(... | stack_v2_sparse_classes_75kplus_train_002211 | 1,433 | permissive | [
{
"docstring": ":param a: :param b: :return: int",
"name": "bitSwapRequired",
"signature": "def bitSwapRequired(self, a, b)"
},
{
"docstring": "2's complement 32-bit :param n: :return:",
"name": "to_bin",
"signature": "def to_bin(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051579 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bitSwapRequired(self, a, b): :param a: :param b: :return: int
- def to_bin(self, n): 2's complement 32-bit :param n: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bitSwapRequired(self, a, b): :param a: :param b: :return: int
- def to_bin(self, n): 2's complement 32-bit :param n: :return:
<|skeleton|>
class Solution:
def bitSwapRe... | 4629a3857b2c57418b86a3b3a7180ecb15e763e3 | <|skeleton|>
class Solution:
def bitSwapRequired(self, a, b):
""":param a: :param b: :return: int"""
<|body_0|>
def to_bin(self, n):
"""2's complement 32-bit :param n: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def bitSwapRequired(self, a, b):
""":param a: :param b: :return: int"""
a = self.to_bin(a)
b = self.to_bin(b)
diff = len(a) - len(b)
ret = 0
if diff < 0:
a, b = (b, a)
diff *= -1
b = '0' * diff + b
for i in xrang... | the_stack_v2_python_sparse | Convert Integer A to Integer B.py | RijuDasgupta9116/LintCode | train | 0 | |
5e01cbb925cdcc5aeec7a01cbc1afadff696d863 | [
"jobs = len(job_difficulty)\nif jobs < days:\n return -1\ndp = [[float('inf')] * jobs + [0] for _ in range(days + 1)]\nfor day in range(1, days + 1):\n right = jobs - day + 1\n for cut in range(right):\n max_so_far, ans = (0, float('inf'))\n for job_rate in range(cut, right):\n max... | <|body_start_0|>
jobs = len(job_difficulty)
if jobs < days:
return -1
dp = [[float('inf')] * jobs + [0] for _ in range(days + 1)]
for day in range(1, days + 1):
right = jobs - day + 1
for cut in range(right):
max_so_far, ans = (0, float... | JobSchedule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobSchedule:
def minimum_difficulty_bottom_up(self, job_difficulty: List[int], days: int) -> int:
"""Approach: DP Table (bottom up) Time Complexity: O(N^2 * D) Space Complexity: O(ND) :param job_difficulty: :param days: :return:"""
<|body_0|>
def minimum_difficulty_top_down(... | stack_v2_sparse_classes_75kplus_train_002212 | 2,851 | no_license | [
{
"docstring": "Approach: DP Table (bottom up) Time Complexity: O(N^2 * D) Space Complexity: O(ND) :param job_difficulty: :param days: :return:",
"name": "minimum_difficulty_bottom_up",
"signature": "def minimum_difficulty_bottom_up(self, job_difficulty: List[int], days: int) -> int"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_020687 | Implement the Python class `JobSchedule` described below.
Class description:
Implement the JobSchedule class.
Method signatures and docstrings:
- def minimum_difficulty_bottom_up(self, job_difficulty: List[int], days: int) -> int: Approach: DP Table (bottom up) Time Complexity: O(N^2 * D) Space Complexity: O(ND) :par... | Implement the Python class `JobSchedule` described below.
Class description:
Implement the JobSchedule class.
Method signatures and docstrings:
- def minimum_difficulty_bottom_up(self, job_difficulty: List[int], days: int) -> int: Approach: DP Table (bottom up) Time Complexity: O(N^2 * D) Space Complexity: O(ND) :par... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class JobSchedule:
def minimum_difficulty_bottom_up(self, job_difficulty: List[int], days: int) -> int:
"""Approach: DP Table (bottom up) Time Complexity: O(N^2 * D) Space Complexity: O(ND) :param job_difficulty: :param days: :return:"""
<|body_0|>
def minimum_difficulty_top_down(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobSchedule:
def minimum_difficulty_bottom_up(self, job_difficulty: List[int], days: int) -> int:
"""Approach: DP Table (bottom up) Time Complexity: O(N^2 * D) Space Complexity: O(ND) :param job_difficulty: :param days: :return:"""
jobs = len(job_difficulty)
if jobs < days:
... | the_stack_v2_python_sparse | revisited_2021/dp/minimum_difficulty_of_job_schedule.py | Shiv2157k/leet_code | train | 1 | |
259eb3ad5497a300701b7b84f5c372a9ce61641f | [
"super().__init__()\nself._logger = logging.getLogger('ConnectionDialog')\nself._logger.setLevel(LOG_LEVEL_PRINT)\nself._logger.info('Connection dialog initializing …')\nself.setWindowTitle('Connection Settings')\nself.resize(360, 240)\nself.setModal(True)\nself.initUI()\nself._logger.info('Connection dialog initia... | <|body_start_0|>
super().__init__()
self._logger = logging.getLogger('ConnectionDialog')
self._logger.setLevel(LOG_LEVEL_PRINT)
self._logger.info('Connection dialog initializing …')
self.setWindowTitle('Connection Settings')
self.resize(360, 240)
self.setModal(Tru... | Connection Dialog. A dialog to enter the IP of the board | ConnectionDialog | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectionDialog:
"""Connection Dialog. A dialog to enter the IP of the board"""
def __init__(self):
"""Initialize the connection dialog."""
<|body_0|>
def initUI(self):
"""Initialize the ui of the connection dialog."""
<|body_1|>
def setValues(self,... | stack_v2_sparse_classes_75kplus_train_002213 | 3,950 | permissive | [
{
"docstring": "Initialize the connection dialog.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Initialize the ui of the connection dialog.",
"name": "initUI",
"signature": "def initUI(self)"
},
{
"docstring": "Set the values. Values: ip, port, …",
... | 4 | stack_v2_sparse_classes_30k_train_009427 | Implement the Python class `ConnectionDialog` described below.
Class description:
Connection Dialog. A dialog to enter the IP of the board
Method signatures and docstrings:
- def __init__(self): Initialize the connection dialog.
- def initUI(self): Initialize the ui of the connection dialog.
- def setValues(self, ip,... | Implement the Python class `ConnectionDialog` described below.
Class description:
Connection Dialog. A dialog to enter the IP of the board
Method signatures and docstrings:
- def __init__(self): Initialize the connection dialog.
- def initUI(self): Initialize the ui of the connection dialog.
- def setValues(self, ip,... | e69f0c48f32ea122dec3a84db058a33786c666c5 | <|skeleton|>
class ConnectionDialog:
"""Connection Dialog. A dialog to enter the IP of the board"""
def __init__(self):
"""Initialize the connection dialog."""
<|body_0|>
def initUI(self):
"""Initialize the ui of the connection dialog."""
<|body_1|>
def setValues(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConnectionDialog:
"""Connection Dialog. A dialog to enter the IP of the board"""
def __init__(self):
"""Initialize the connection dialog."""
super().__init__()
self._logger = logging.getLogger('ConnectionDialog')
self._logger.setLevel(LOG_LEVEL_PRINT)
self._logger.... | the_stack_v2_python_sparse | Bidirectional_interface/Haptics/Interface/src/connectionDialog.py | medioman22/Bidirectional_Interface | train | 0 |
30bd1d1296bad3941e7174f1fc07a2e29b80ab5e | [
"self.num_points = num_points\nself.x_values = [init_coords[0]]\nself.y_values = [init_coords[1]]\nself.z_values = [init_coords[2]]\nself.theta_ = []\nself.phi_ = []\nself.theta = 0\nself.theta_.append(self.theta)\nself.phi = init_phi\nself.phi_.append(self.phi)\nself.deltaTheta = 0\nself.deltaPhi = 0",
"while le... | <|body_start_0|>
self.num_points = num_points
self.x_values = [init_coords[0]]
self.y_values = [init_coords[1]]
self.z_values = [init_coords[2]]
self.theta_ = []
self.phi_ = []
self.theta = 0
self.theta_.append(self.theta)
self.phi = init_phi
... | A class to generate random datas. | GenerateLine3D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenerateLine3D:
"""A class to generate random datas."""
def __init__(self, init_coords=[], init_theta=0, init_phi=0, num_points=5000):
"""Initialize attributes of a data."""
<|body_0|>
def fill_points(self):
"""Calculate all the points in the data."""
<|b... | stack_v2_sparse_classes_75kplus_train_002214 | 20,287 | no_license | [
{
"docstring": "Initialize attributes of a data.",
"name": "__init__",
"signature": "def __init__(self, init_coords=[], init_theta=0, init_phi=0, num_points=5000)"
},
{
"docstring": "Calculate all the points in the data.",
"name": "fill_points",
"signature": "def fill_points(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019413 | Implement the Python class `GenerateLine3D` described below.
Class description:
A class to generate random datas.
Method signatures and docstrings:
- def __init__(self, init_coords=[], init_theta=0, init_phi=0, num_points=5000): Initialize attributes of a data.
- def fill_points(self): Calculate all the points in the... | Implement the Python class `GenerateLine3D` described below.
Class description:
A class to generate random datas.
Method signatures and docstrings:
- def __init__(self, init_coords=[], init_theta=0, init_phi=0, num_points=5000): Initialize attributes of a data.
- def fill_points(self): Calculate all the points in the... | 6e7a278031ff0a1eb51e7810b326d66524d4aef3 | <|skeleton|>
class GenerateLine3D:
"""A class to generate random datas."""
def __init__(self, init_coords=[], init_theta=0, init_phi=0, num_points=5000):
"""Initialize attributes of a data."""
<|body_0|>
def fill_points(self):
"""Calculate all the points in the data."""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenerateLine3D:
"""A class to generate random datas."""
def __init__(self, init_coords=[], init_theta=0, init_phi=0, num_points=5000):
"""Initialize attributes of a data."""
self.num_points = num_points
self.x_values = [init_coords[0]]
self.y_values = [init_coords[1]]
... | the_stack_v2_python_sparse | check_data/generate_data/generate_data.py | c-feng/Neuron-Tracking | train | 1 |
b6ecf8f74225d412486fc6c00e49d29f5249d161 | [
"assert all((stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types))\nis_reverse = 45 <= rup.rake <= 135\nstddevs = [numpy.zeros_like(sites.vs30) for _ in stddev_types]\nmeans = numpy.zeros_like(sites.vs30)\n[rocks_i] = (sites.vs30 > self.ROCK_VS30).nonzero()\nif len(rocks_i):\n ... | <|body_start_0|>
assert all((stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types))
is_reverse = 45 <= rup.rake <= 135
stddevs = [numpy.zeros_like(sites.vs30) for _ in stddev_types]
means = numpy.zeros_like(sites.vs30)
[rocks_i] = (sites.vs30 >... | Implements GMPE developed by Sadigh, K., C. -Y. Chang, J. A. Egan, F. Makdisi, and R. R. Youngs (1997) and published as "Attenuation relationships for shallow crustal earthquakes based on California strong motion data", Seismological Research Letters, 68(1), 180-189. | SadighEtAl1997 | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SadighEtAl1997:
"""Implements GMPE developed by Sadigh, K., C. -Y. Chang, J. A. Egan, F. Makdisi, and R. R. Youngs (1997) and published as "Attenuation relationships for shallow crustal earthquakes based on California strong motion data", Seismological Research Letters, 68(1), 180-189."""
de... | stack_v2_sparse_classes_75kplus_train_002215 | 11,377 | permissive | [
{
"docstring": "See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
},
{
"docstring": "Calculate and retur... | 5 | stack_v2_sparse_classes_30k_test_001488 | Implement the Python class `SadighEtAl1997` described below.
Class description:
Implements GMPE developed by Sadigh, K., C. -Y. Chang, J. A. Egan, F. Makdisi, and R. R. Youngs (1997) and published as "Attenuation relationships for shallow crustal earthquakes based on California strong motion data", Seismological Resea... | Implement the Python class `SadighEtAl1997` described below.
Class description:
Implements GMPE developed by Sadigh, K., C. -Y. Chang, J. A. Egan, F. Makdisi, and R. R. Youngs (1997) and published as "Attenuation relationships for shallow crustal earthquakes based on California strong motion data", Seismological Resea... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class SadighEtAl1997:
"""Implements GMPE developed by Sadigh, K., C. -Y. Chang, J. A. Egan, F. Makdisi, and R. R. Youngs (1997) and published as "Attenuation relationships for shallow crustal earthquakes based on California strong motion data", Seismological Research Letters, 68(1), 180-189."""
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SadighEtAl1997:
"""Implements GMPE developed by Sadigh, K., C. -Y. Chang, J. A. Egan, F. Makdisi, and R. R. Youngs (1997) and published as "Attenuation relationships for shallow crustal earthquakes based on California strong motion data", Seismological Research Letters, 68(1), 180-189."""
def get_mean_an... | the_stack_v2_python_sparse | openquake/hazardlib/gsim/sadigh_1997.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
4dd71521fc9f541fa996d6d0e45f2b1f4d3ca673 | [
"if not root:\n return ''\nreturn str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)",
"def dfs(data):\n if not data:\n return\n val = data.popleft()\n if not val:\n return\n root = TreeNode(int(val))\n root.left = dfs(data)\n root.right = dfs(dat... | <|body_start_0|>
if not root:
return ''
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)
<|end_body_0|>
<|body_start_1|>
def dfs(data):
if not data:
return
val = data.popleft()
if not val:
... | 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_75kplus_train_002216 | 6,040 | 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 | stack_v2_sparse_classes_30k_train_023161 | 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:... | 0324d247a5567745cc1a48b215066d4aa796abd8 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)
def deserialize(self, data):
"""Decodes ... | the_stack_v2_python_sparse | Tree/Codec.py | BruceHi/leetcode | train | 1 | |
556851fcadf63d6e856fc7fc6ff0f5576f1b4768 | [
"self.max = 0\n\ndef get_depth(root):\n if not root:\n return 0\n ld = get_depth(root.left)\n rd = get_depth(root.right)\n new_max = ld + rd\n self.max = new_max if self.max < new_max else self.max\n return (ld if ld > rd else rd) + 1\nget_depth(root)\nreturn self.max",
"pmax = 0\n\ndef g... | <|body_start_0|>
self.max = 0
def get_depth(root):
if not root:
return 0
ld = get_depth(root.left)
rd = get_depth(root.right)
new_max = ld + rd
self.max = new_max if self.max < new_max else self.max
return (ld if ld... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def diameterOfBinaryTreeNonLocal(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.max = 0
... | stack_v2_sparse_classes_75kplus_train_002217 | 1,332 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "diameterOfBinaryTree",
"signature": "def diameterOfBinaryTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "diameterOfBinaryTreeNonLocal",
"signature": "def diameterOfBinaryTreeNonLocal(self, root)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int
- def diameterOfBinaryTreeNonLocal(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int
- def diameterOfBinaryTreeNonLocal(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Soluti... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def diameterOfBinaryTreeNonLocal(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int"""
self.max = 0
def get_depth(root):
if not root:
return 0
ld = get_depth(root.left)
rd = get_depth(root.right)
new_max = ld + rd
... | the_stack_v2_python_sparse | cs_notes/tree/recursive/diameter_of_binary_tree.py | hwc1824/LeetCodeSolution | train | 0 | |
bc17a503755569341f0d1b8d0a28d97c6e2116d9 | [
"def _isSymmetric(left, right):\n if left is None or right is None:\n return left == right\n if not left.val == right.val:\n return False\n return _isSymmetric(left.left, right.right) and _isSymmetric(left.right, right.left)\nif root is None:\n return True\nreturn _isSymmetric(root.left, r... | <|body_start_0|>
def _isSymmetric(left, right):
if left is None or right is None:
return left == right
if not left.val == right.val:
return False
return _isSymmetric(left.left, right.right) and _isSymmetric(left.right, right.left)
if ro... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def _isSymmetric(left, right):
if... | stack_v2_sparse_classes_75kplus_train_002218 | 2,144 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_val_002092 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
<|skeleton|>
class Solution:
def isSymmetric... | 18ed31a3edf20a3e5a0b7a0b56acca5b98939693 | <|skeleton|>
class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
def _isSymmetric(left, right):
if left is None or right is None:
return left == right
if not left.val == right.val:
return False
return _isSymmetri... | the_stack_v2_python_sparse | exercises/binary-tree/symmetric_tree.py | nahgnaw/data-structure | train | 0 | |
dc30df42e6ec220b20dc1c68c555d1d252300836 | [
"vals = []\n\ndef build_res(root, res):\n if not root:\n res.append('#')\n return\n res.append(str(root.val))\n build_res(root.left, res)\n build_res(root.right, res)\nbuild_res(root, vals)\nprint(vals)\nreturn ','.join(vals)",
"vals = iter(data.split(','))\n\ndef build_tree(vals):\n ... | <|body_start_0|>
vals = []
def build_res(root, res):
if not root:
res.append('#')
return
res.append(str(root.val))
build_res(root.left, res)
build_res(root.right, res)
build_res(root, vals)
print(vals)
... | 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 12##34##5##"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_002219 | 1,630 | 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 12##34##5##",
"name": "deserialize",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_012285 | 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:... | 523c11e8a5728168c4978c5a332e7e9bc4533ef7 | <|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 12##34##5##"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
vals = []
def build_res(root, res):
if not root:
res.append('#')
return
res.append(str(root.val))
build_res(r... | the_stack_v2_python_sparse | 297. Serialize and Deserialize Binary Tree/answer.py | LennyDuan/AlgorithmPython | train | 0 | |
f971f5fe79d150e03ecff1af845cbf26124763ab | [
"assert type(n) == int\nself.HAND_SIZE = n\nself.VOWELS = 'aeiou'\nself.CONSONANTS = 'bcdfghjklmnpqrstvwxyz'\nself.dealNewHand()",
"self.hand = {}\nnumVowels = self.HAND_SIZE // 3\nfor i in range(numVowels):\n x = self.VOWELS[random.randrange(0, len(self.VOWELS))]\n self.hand[x] = self.hand.get(x, 0) + 1\nf... | <|body_start_0|>
assert type(n) == int
self.HAND_SIZE = n
self.VOWELS = 'aeiou'
self.CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
self.dealNewHand()
<|end_body_0|>
<|body_start_1|>
self.hand = {}
numVowels = self.HAND_SIZE // 3
for i in range(numVowels):
... | Hand | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hand:
def __init__(self, n):
"""Initialize a Hand. n: integer, the size of the hand."""
<|body_0|>
def dealNewHand(self):
"""Deals a new hand, and sets the hand attribute to the new hand."""
<|body_1|>
def setDummyHand(self, handString):
"""Allow... | stack_v2_sparse_classes_75kplus_train_002220 | 3,675 | no_license | [
{
"docstring": "Initialize a Hand. n: integer, the size of the hand.",
"name": "__init__",
"signature": "def __init__(self, n)"
},
{
"docstring": "Deals a new hand, and sets the hand attribute to the new hand.",
"name": "dealNewHand",
"signature": "def dealNewHand(self)"
},
{
"do... | 6 | stack_v2_sparse_classes_30k_train_010751 | Implement the Python class `Hand` described below.
Class description:
Implement the Hand class.
Method signatures and docstrings:
- def __init__(self, n): Initialize a Hand. n: integer, the size of the hand.
- def dealNewHand(self): Deals a new hand, and sets the hand attribute to the new hand.
- def setDummyHand(sel... | Implement the Python class `Hand` described below.
Class description:
Implement the Hand class.
Method signatures and docstrings:
- def __init__(self, n): Initialize a Hand. n: integer, the size of the hand.
- def dealNewHand(self): Deals a new hand, and sets the hand attribute to the new hand.
- def setDummyHand(sel... | 4e8727154a24c7a1d05361a559a997c8d076480d | <|skeleton|>
class Hand:
def __init__(self, n):
"""Initialize a Hand. n: integer, the size of the hand."""
<|body_0|>
def dealNewHand(self):
"""Deals a new hand, and sets the hand attribute to the new hand."""
<|body_1|>
def setDummyHand(self, handString):
"""Allow... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Hand:
def __init__(self, n):
"""Initialize a Hand. n: integer, the size of the hand."""
assert type(n) == int
self.HAND_SIZE = n
self.VOWELS = 'aeiou'
self.CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
self.dealNewHand()
def dealNewHand(self):
"""Deals a new... | the_stack_v2_python_sparse | 01_MIT_Learning/week_5/lectures_and_examples/Section 2/exercises/hand.py | daftstar/learn_python | train | 0 | |
36e7c510bc6ce0e1ab65bd3280ac811c71c64acd | [
"pseudo = str(pseudo)\nmdp = str(mdp)\nconnexion = PoolConnection.getConnexion()\ncurseur = connexion.cursor()\ntry:\n curseur.execute('INSERT INTO Joueur (id_joueur, pseudo, mdp) VALUES (%(id)s, %(pseudo)s, %(h)s)RETURNING pseudo;', {'id': id_joueur, 'pseudo': pseudo, 'h': h(mdp, pseudo)})\n res = curseur.fe... | <|body_start_0|>
pseudo = str(pseudo)
mdp = str(mdp)
connexion = PoolConnection.getConnexion()
curseur = connexion.cursor()
try:
curseur.execute('INSERT INTO Joueur (id_joueur, pseudo, mdp) VALUES (%(id)s, %(pseudo)s, %(h)s)RETURNING pseudo;', {'id': id_joueur, 'pseud... | JoueurDao | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JoueurDao:
def create(id_joueur, pseudo, mdp):
"""Ajouter un joueur dans la base de données. :param joueur: joueur à ajouter :type joueur: Joueur :return: pseudo :rtype: Joueur"""
<|body_0|>
def read(pseudo, mdp):
"""Vérifier les informations sur un joueur. :param ps... | stack_v2_sparse_classes_75kplus_train_002221 | 4,458 | no_license | [
{
"docstring": "Ajouter un joueur dans la base de données. :param joueur: joueur à ajouter :type joueur: Joueur :return: pseudo :rtype: Joueur",
"name": "create",
"signature": "def create(id_joueur, pseudo, mdp)"
},
{
"docstring": "Vérifier les informations sur un joueur. :param pseudo: pseudo d... | 4 | stack_v2_sparse_classes_30k_train_049862 | Implement the Python class `JoueurDao` described below.
Class description:
Implement the JoueurDao class.
Method signatures and docstrings:
- def create(id_joueur, pseudo, mdp): Ajouter un joueur dans la base de données. :param joueur: joueur à ajouter :type joueur: Joueur :return: pseudo :rtype: Joueur
- def read(ps... | Implement the Python class `JoueurDao` described below.
Class description:
Implement the JoueurDao class.
Method signatures and docstrings:
- def create(id_joueur, pseudo, mdp): Ajouter un joueur dans la base de données. :param joueur: joueur à ajouter :type joueur: Joueur :return: pseudo :rtype: Joueur
- def read(ps... | 17aaf28b7c51dadb1f184c700343400f778fc61d | <|skeleton|>
class JoueurDao:
def create(id_joueur, pseudo, mdp):
"""Ajouter un joueur dans la base de données. :param joueur: joueur à ajouter :type joueur: Joueur :return: pseudo :rtype: Joueur"""
<|body_0|>
def read(pseudo, mdp):
"""Vérifier les informations sur un joueur. :param ps... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JoueurDao:
def create(id_joueur, pseudo, mdp):
"""Ajouter un joueur dans la base de données. :param joueur: joueur à ajouter :type joueur: Joueur :return: pseudo :rtype: Joueur"""
pseudo = str(pseudo)
mdp = str(mdp)
connexion = PoolConnection.getConnexion()
curseur = co... | the_stack_v2_python_sparse | serveur/dao/classe_joueur_dao.py | walid-creator/api_touratour | train | 0 | |
6e1ceab64abf567fa9b29a342a1871e146bba6b1 | [
"list_topimage = []\nfor article_candidate in list_article_candidate:\n if article_candidate.topimage is not None:\n article_candidate.topimage = self.image_absoulte_path(item['url'], article_candidate.topimage)\n list_topimage.append((article_candidate.topimage, article_candidate.extractor))\nif l... | <|body_start_0|>
list_topimage = []
for article_candidate in list_article_candidate:
if article_candidate.topimage is not None:
article_candidate.topimage = self.image_absoulte_path(item['url'], article_candidate.topimage)
list_topimage.append((article_candida... | This class compares the topimages of the list of ArticleCandidates and sends the result back to the Comparer. | ComparerTopimage | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComparerTopimage:
"""This class compares the topimages of the list of ArticleCandidates and sends the result back to the Comparer."""
def extract(self, item, list_article_candidate):
"""Compares the extracted top images. :param item: The corresponding NewscrawlerItem :param list_arti... | stack_v2_sparse_classes_75kplus_train_002222 | 1,973 | permissive | [
{
"docstring": "Compares the extracted top images. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string (url), the most likely top image",
"name": "extract",
"signature": "def extract(self, ... | 2 | stack_v2_sparse_classes_30k_train_047040 | Implement the Python class `ComparerTopimage` described below.
Class description:
This class compares the topimages of the list of ArticleCandidates and sends the result back to the Comparer.
Method signatures and docstrings:
- def extract(self, item, list_article_candidate): Compares the extracted top images. :param... | Implement the Python class `ComparerTopimage` described below.
Class description:
This class compares the topimages of the list of ArticleCandidates and sends the result back to the Comparer.
Method signatures and docstrings:
- def extract(self, item, list_article_candidate): Compares the extracted top images. :param... | aac84065a1eea3cccd8859b9ba0915615a196c54 | <|skeleton|>
class ComparerTopimage:
"""This class compares the topimages of the list of ArticleCandidates and sends the result back to the Comparer."""
def extract(self, item, list_article_candidate):
"""Compares the extracted top images. :param item: The corresponding NewscrawlerItem :param list_arti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComparerTopimage:
"""This class compares the topimages of the list of ArticleCandidates and sends the result back to the Comparer."""
def extract(self, item, list_article_candidate):
"""Compares the extracted top images. :param item: The corresponding NewscrawlerItem :param list_article_candidate... | the_stack_v2_python_sparse | newsplease/pipeline/extractor/comparer/comparer_topimage.py | fhamborg/news-please | train | 1,785 |
1f3cd4090654583356b6b7a5d3469d4985147e11 | [
"super(CnnPolicy, self).__init__(placeholders=placeholders)\nself.reuse = reuse\nself.name = name\nself._init(ob_space, ac_space, architecture_size)\nself.scope = tf.get_variable_scope().name\nself.sess = sess",
"obs, pdtype = self.get_obs_and_pdtype(ob_space, ac_space)\nwith tf.variable_scope(self.name, reuse=se... | <|body_start_0|>
super(CnnPolicy, self).__init__(placeholders=placeholders)
self.reuse = reuse
self.name = name
self._init(ob_space, ac_space, architecture_size)
self.scope = tf.get_variable_scope().name
self.sess = sess
<|end_body_0|>
<|body_start_1|>
obs, pdtyp... | CnnPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CnnPolicy:
def __init__(self, name, ob_space, ac_space, architecture_size='large', sess=None, reuse=False, placeholders=None):
"""A CNN policy object for PPO1 :param name: (str) type of the policy (lin, logits, value) :param ob_space: (Gym Space) The observation space of the environment ... | stack_v2_sparse_classes_75kplus_train_002223 | 3,714 | permissive | [
{
"docstring": "A CNN policy object for PPO1 :param name: (str) type of the policy (lin, logits, value) :param ob_space: (Gym Space) The observation space of the environment :param ac_space: (Gym Space) The action space of the environment :param architecture_size: (str) size of the policy's architecture (small ... | 2 | stack_v2_sparse_classes_30k_train_008760 | Implement the Python class `CnnPolicy` described below.
Class description:
Implement the CnnPolicy class.
Method signatures and docstrings:
- def __init__(self, name, ob_space, ac_space, architecture_size='large', sess=None, reuse=False, placeholders=None): A CNN policy object for PPO1 :param name: (str) type of the ... | Implement the Python class `CnnPolicy` described below.
Class description:
Implement the CnnPolicy class.
Method signatures and docstrings:
- def __init__(self, name, ob_space, ac_space, architecture_size='large', sess=None, reuse=False, placeholders=None): A CNN policy object for PPO1 :param name: (str) type of the ... | 5f11927a4420b46bed873c4a8477a55153d37bcd | <|skeleton|>
class CnnPolicy:
def __init__(self, name, ob_space, ac_space, architecture_size='large', sess=None, reuse=False, placeholders=None):
"""A CNN policy object for PPO1 :param name: (str) type of the policy (lin, logits, value) :param ob_space: (Gym Space) The observation space of the environment ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CnnPolicy:
def __init__(self, name, ob_space, ac_space, architecture_size='large', sess=None, reuse=False, placeholders=None):
"""A CNN policy object for PPO1 :param name: (str) type of the policy (lin, logits, value) :param ob_space: (Gym Space) The observation space of the environment :param ac_spac... | the_stack_v2_python_sparse | baselines/ppo1/cnn_policy.py | northtiger/stable-baselines | train | 0 | |
54b21101f7314c6440704b44f765871b9ca6f459 | [
"self.desired_caps = {'platformName': PLATFORM, 'deviceName': DEVICE_NAME, 'appPackage': APP_PACKAGE, 'appActivity': APP_ACTIVITY}\nself.driver = webdriver.Remote(DRIVER_SERVER, self.desired_caps)\nself.wait = WebDriverWait(self.driver, TIMEOUT)\nself.client = MongoClient(MONGO_URL)\nself.db = self.client[MONGO_DB]... | <|body_start_0|>
self.desired_caps = {'platformName': PLATFORM, 'deviceName': DEVICE_NAME, 'appPackage': APP_PACKAGE, 'appActivity': APP_ACTIVITY}
self.driver = webdriver.Remote(DRIVER_SERVER, self.desired_caps)
self.wait = WebDriverWait(self.driver, TIMEOUT)
self.client = MongoClient(MO... | Moments | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Moments:
def __init__(self):
"""初始化"""
<|body_0|>
def login(self):
"""登录微信 :return:"""
<|body_1|>
def enter(self):
"""进入朋友圈 :return:"""
<|body_2|>
def crawl(self):
"""爬取 :return:"""
<|body_3|>
def main(self):
... | stack_v2_sparse_classes_75kplus_train_002224 | 6,811 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "登录微信 :return:",
"name": "login",
"signature": "def login(self)"
},
{
"docstring": "进入朋友圈 :return:",
"name": "enter",
"signature": "def enter(self)"
},
{
"docstring": "爬取... | 5 | stack_v2_sparse_classes_30k_train_047758 | Implement the Python class `Moments` described below.
Class description:
Implement the Moments class.
Method signatures and docstrings:
- def __init__(self): 初始化
- def login(self): 登录微信 :return:
- def enter(self): 进入朋友圈 :return:
- def crawl(self): 爬取 :return:
- def main(self): 入口 :return: | Implement the Python class `Moments` described below.
Class description:
Implement the Moments class.
Method signatures and docstrings:
- def __init__(self): 初始化
- def login(self): 登录微信 :return:
- def enter(self): 进入朋友圈 :return:
- def crawl(self): 爬取 :return:
- def main(self): 入口 :return:
<|skeleton|>
class Moments:... | 9147c8ea56f241e192110ce57d29946c0ca69868 | <|skeleton|>
class Moments:
def __init__(self):
"""初始化"""
<|body_0|>
def login(self):
"""登录微信 :return:"""
<|body_1|>
def enter(self):
"""进入朋友圈 :return:"""
<|body_2|>
def crawl(self):
"""爬取 :return:"""
<|body_3|>
def main(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Moments:
def __init__(self):
"""初始化"""
self.desired_caps = {'platformName': PLATFORM, 'deviceName': DEVICE_NAME, 'appPackage': APP_PACKAGE, 'appActivity': APP_ACTIVITY}
self.driver = webdriver.Remote(DRIVER_SERVER, self.desired_caps)
self.wait = WebDriverWait(self.driver, TIMEO... | the_stack_v2_python_sparse | AppSpider/moments.py | hcxgit/PycharmProjects | train | 0 | |
afcebd7a832f476f04360ee1b761baf0593c5d8e | [
"x = apm.x\nR = flex.pow2(self.error_model.sortedy - x[1] * self.error_model.sortedx - x[0])\nreturn R",
"x = apm.x\nR = self.error_model.sortedy - x[1] * self.error_model.sortedx - x[0]\ngradient = flex.double([-2.0 * flex.sum(R), -2.0 * flex.sum(R * self.error_model.sortedx)])\nreturn gradient"
] | <|body_start_0|>
x = apm.x
R = flex.pow2(self.error_model.sortedy - x[1] * self.error_model.sortedx - x[0])
return R
<|end_body_0|>
<|body_start_1|>
x = apm.x
R = self.error_model.sortedy - x[1] * self.error_model.sortedx - x[0]
gradient = flex.double([-2.0 * flex.sum(R)... | Target to minimise the 'a' component of the basic error model. | ErrorModelTargetA | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ErrorModelTargetA:
"""Target to minimise the 'a' component of the basic error model."""
def calculate_residuals(self, apm):
"""Return the residual vector"""
<|body_0|>
def calculate_gradients(self, apm):
"""calculate the gradient vector"""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_002225 | 6,995 | permissive | [
{
"docstring": "Return the residual vector",
"name": "calculate_residuals",
"signature": "def calculate_residuals(self, apm)"
},
{
"docstring": "calculate the gradient vector",
"name": "calculate_gradients",
"signature": "def calculate_gradients(self, apm)"
}
] | 2 | null | Implement the Python class `ErrorModelTargetA` described below.
Class description:
Target to minimise the 'a' component of the basic error model.
Method signatures and docstrings:
- def calculate_residuals(self, apm): Return the residual vector
- def calculate_gradients(self, apm): calculate the gradient vector | Implement the Python class `ErrorModelTargetA` described below.
Class description:
Target to minimise the 'a' component of the basic error model.
Method signatures and docstrings:
- def calculate_residuals(self, apm): Return the residual vector
- def calculate_gradients(self, apm): calculate the gradient vector
<|sk... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class ErrorModelTargetA:
"""Target to minimise the 'a' component of the basic error model."""
def calculate_residuals(self, apm):
"""Return the residual vector"""
<|body_0|>
def calculate_gradients(self, apm):
"""calculate the gradient vector"""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ErrorModelTargetA:
"""Target to minimise the 'a' component of the basic error model."""
def calculate_residuals(self, apm):
"""Return the residual vector"""
x = apm.x
R = flex.pow2(self.error_model.sortedy - x[1] * self.error_model.sortedx - x[0])
return R
def calcula... | the_stack_v2_python_sparse | src/dials/algorithms/scaling/error_model/error_model_target.py | dials/dials | train | 71 |
1e99306d2916f977f93567f6069f0638d0fdee8f | [
"if pos_label not in (0, 1):\n raise ValueError('only {0, 1} are accepted for `pos_label`')\ny_true = convert_binary_labels(y_true).ravel()\nscore = _check_binary_score(score, pos_label)\nh = 1.0 - y_true * score\nh[h < 0] = 0.0\nreturn h ** 2",
"if pos_label not in (0, 1):\n raise ValueError('only {0, 1} a... | <|body_start_0|>
if pos_label not in (0, 1):
raise ValueError('only {0, 1} are accepted for `pos_label`')
y_true = convert_binary_labels(y_true).ravel()
score = _check_binary_score(score, pos_label)
h = 1.0 - y_true * score
h[h < 0] = 0.0
return h ** 2
<|end_b... | Squared Hinge Loss Function. The function computes the average distance between the model and the data using hinge loss, a one-sided metric that considers only prediction errors. After converting the labels to {-1, +1}, then the hinge loss is defined as: .. math:: L^2_\\text{Hinge} (y, s) = {\\left( \\max \\left\\{ 1 -... | CLossHingeSquared | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CLossHingeSquared:
"""Squared Hinge Loss Function. The function computes the average distance between the model and the data using hinge loss, a one-sided metric that considers only prediction errors. After converting the labels to {-1, +1}, then the hinge loss is defined as: .. math:: L^2_\\text... | stack_v2_sparse_classes_75kplus_train_002226 | 6,353 | permissive | [
{
"docstring": "Computes the value of the squared hinge loss function. Parameters ---------- y_true : CArray Ground truth (correct), targets. Vector-like array. score : CArray Outputs (predicted), targets. 2-D array of shape (n_samples, n_classes) or 1-D flat array of shape (n_samples,). If 1-D array, the proba... | 2 | stack_v2_sparse_classes_30k_train_018183 | Implement the Python class `CLossHingeSquared` described below.
Class description:
Squared Hinge Loss Function. The function computes the average distance between the model and the data using hinge loss, a one-sided metric that considers only prediction errors. After converting the labels to {-1, +1}, then the hinge l... | Implement the Python class `CLossHingeSquared` described below.
Class description:
Squared Hinge Loss Function. The function computes the average distance between the model and the data using hinge loss, a one-sided metric that considers only prediction errors. After converting the labels to {-1, +1}, then the hinge l... | 431373e65d8cfe2cb7cf042ce1a6c9519ea5a14a | <|skeleton|>
class CLossHingeSquared:
"""Squared Hinge Loss Function. The function computes the average distance between the model and the data using hinge loss, a one-sided metric that considers only prediction errors. After converting the labels to {-1, +1}, then the hinge loss is defined as: .. math:: L^2_\\text... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CLossHingeSquared:
"""Squared Hinge Loss Function. The function computes the average distance between the model and the data using hinge loss, a one-sided metric that considers only prediction errors. After converting the labels to {-1, +1}, then the hinge loss is defined as: .. math:: L^2_\\text{Hinge} (y, s... | the_stack_v2_python_sparse | src/secml/ml/classifiers/loss/c_loss_hinge.py | Cinofix/secml | train | 0 |
98542d94b42bc11777afa1260d55fd8eac38bfb5 | [
"self.framework = framework\nself.default_model_uri = default_model_uri\nself.canary_model_uri = canary_model_uri\nself.canary_traffic_percent = canary_traffic_percent\nself.annotations = annotations\nself.set_labels(labels)\nself.cleanup = cleanup\nself.custom_default_spec = custom_default_spec\nself.custom_canary... | <|body_start_0|>
self.framework = framework
self.default_model_uri = default_model_uri
self.canary_model_uri = canary_model_uri
self.canary_traffic_percent = canary_traffic_percent
self.annotations = annotations
self.set_labels(labels)
self.cleanup = cleanup
... | Serves a prediction endpoint using Kubeflow KFServing. | KFServing | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KFServing:
"""Serves a prediction endpoint using Kubeflow KFServing."""
def __init__(self, framework, default_model_uri=None, canary_model_uri=None, canary_traffic_percent=0, namespace=None, labels=None, annotations=None, custom_default_spec=None, custom_canary_spec=None, stream_log=True, cl... | stack_v2_sparse_classes_75kplus_train_002227 | 5,969 | permissive | [
{
"docstring": ":param framework: The framework for the kfservice, such as Tensorflow, XGBoost and ScikitLearn etc. :param default_model_uri: URI pointing to Saved Model assets for default service. :param canary_model_uri: URI pointing to Saved Model assets for canary service. :param canary_traffic_percent: The... | 5 | stack_v2_sparse_classes_30k_train_052385 | Implement the Python class `KFServing` described below.
Class description:
Serves a prediction endpoint using Kubeflow KFServing.
Method signatures and docstrings:
- def __init__(self, framework, default_model_uri=None, canary_model_uri=None, canary_traffic_percent=0, namespace=None, labels=None, annotations=None, cu... | Implement the Python class `KFServing` described below.
Class description:
Serves a prediction endpoint using Kubeflow KFServing.
Method signatures and docstrings:
- def __init__(self, framework, default_model_uri=None, canary_model_uri=None, canary_traffic_percent=0, namespace=None, labels=None, annotations=None, cu... | 0cc639870ea3f773c5ae8a53c0ab16d4cda2ea6c | <|skeleton|>
class KFServing:
"""Serves a prediction endpoint using Kubeflow KFServing."""
def __init__(self, framework, default_model_uri=None, canary_model_uri=None, canary_traffic_percent=0, namespace=None, labels=None, annotations=None, custom_default_spec=None, custom_canary_spec=None, stream_log=True, cl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KFServing:
"""Serves a prediction endpoint using Kubeflow KFServing."""
def __init__(self, framework, default_model_uri=None, canary_model_uri=None, canary_traffic_percent=0, namespace=None, labels=None, annotations=None, custom_default_spec=None, custom_canary_spec=None, stream_log=True, cleanup=False):... | the_stack_v2_python_sparse | kubeflow/fairing/deployers/kfserving/kfserving.py | wyw64962771/fairing | train | 1 |
916dc450a8f6722fc55b4e3363c6d4f198a55796 | [
"def leaves(node):\n if not node:\n return\n if not node.left and (not node.right):\n yield node.val\n if node.left:\n yield from leaves(node.left)\n if node.right:\n yield from leaves(node.right)\nreturn all((x == y for x, y in itertools.zip_longest(leaves(root1), leaves(roo... | <|body_start_0|>
def leaves(node):
if not node:
return
if not node.left and (not node.right):
yield node.val
if node.left:
yield from leaves(node.left)
if node.right:
yield from leaves(node.right)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
"""Dec 11, 2022 16:24"""
<|body_0|>
def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
"""Feb 18, 2023 19:41"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_002228 | 2,638 | no_license | [
{
"docstring": "Dec 11, 2022 16:24",
"name": "leafSimilar",
"signature": "def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool"
},
{
"docstring": "Feb 18, 2023 19:41",
"name": "leafSimilar",
"signature": "def leafSimilar(self, root1: Optional[TreeNode], roo... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: Dec 11, 2022 16:24
- def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: Dec 11, 2022 16:24
- def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNod... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
"""Dec 11, 2022 16:24"""
<|body_0|>
def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
"""Feb 18, 2023 19:41"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
"""Dec 11, 2022 16:24"""
def leaves(node):
if not node:
return
if not node.left and (not node.right):
yield node.val
if node.left:
... | the_stack_v2_python_sparse | leetcode/solved/904_Leaf-Similar_Trees/solution.py | sungminoh/algorithms | train | 0 | |
661ef93ab5d89d74b9428ea2840a4849108ccc77 | [
"if origin is None:\n origin = ((shape[0] - 1) / 2.0, (shape[1] - 1) / 2.0)\nif r_map is None:\n r_map = radial_grid(origin, shape)\nphi_map = angle_grid(origin, shape)\nself.expected_shape = tuple(shape)\nif mask is not None:\n if mask.shape != self.expected_shape:\n raise ValueError('\"mask\" has ... | <|body_start_0|>
if origin is None:
origin = ((shape[0] - 1) / 2.0, (shape[1] - 1) / 2.0)
if r_map is None:
r_map = radial_grid(origin, shape)
phi_map = angle_grid(origin, shape)
self.expected_shape = tuple(shape)
if mask is not None:
if mask.s... | Create a 2-dimensional histogram by binning a 2-dimensional image in both radius and phi. | RPhiBinnedStatistic | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RPhiBinnedStatistic:
"""Create a 2-dimensional histogram by binning a 2-dimensional image in both radius and phi."""
def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'):
"""Parameters: ----------- shape : tuple of ints of length 2. sha... | stack_v2_sparse_classes_75kplus_train_002229 | 33,902 | permissive | [
{
"docstring": "Parameters: ----------- shape : tuple of ints of length 2. shape of image. bins : int or [int, int] or array_like or [array, array], optional The bin specification: * number of bins for the two dimensions (nr=nphi=bins), * number of bins in each dimension (nr, nphi = bins), * bin edges for the t... | 2 | stack_v2_sparse_classes_30k_train_027069 | Implement the Python class `RPhiBinnedStatistic` described below.
Class description:
Create a 2-dimensional histogram by binning a 2-dimensional image in both radius and phi.
Method signatures and docstrings:
- def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'): Param... | Implement the Python class `RPhiBinnedStatistic` described below.
Class description:
Create a 2-dimensional histogram by binning a 2-dimensional image in both radius and phi.
Method signatures and docstrings:
- def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'): Param... | 0e54357c360b0784b8ee279a8ebf7f9fe011a3d6 | <|skeleton|>
class RPhiBinnedStatistic:
"""Create a 2-dimensional histogram by binning a 2-dimensional image in both radius and phi."""
def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'):
"""Parameters: ----------- shape : tuple of ints of length 2. sha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RPhiBinnedStatistic:
"""Create a 2-dimensional histogram by binning a 2-dimensional image in both radius and phi."""
def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'):
"""Parameters: ----------- shape : tuple of ints of length 2. shape of image. ... | the_stack_v2_python_sparse | skbeam/core/accumulators/binned_statistic.py | scikit-beam/scikit-beam | train | 77 |
1f4a4fb53435f590495f5e796d5d600d949bef95 | [
"self.lowerBound = lower\nself.upperBound = upper\nself.delta = [(upper[i] - lower[i]) / 2.0 for i in range(len(upper))]\nself.child = {}\nself.bloatedTube = []",
"idx = self.delta.index(max(self.delta))\ninitSetOneUB = list(self.upperBound)\ninitSetOneLB = list(self.lowerBound)\ninitSetOneLB[idx] += self.delta[i... | <|body_start_0|>
self.lowerBound = lower
self.upperBound = upper
self.delta = [(upper[i] - lower[i]) / 2.0 for i in range(len(upper))]
self.child = {}
self.bloatedTube = []
<|end_body_0|>
<|body_start_1|>
idx = self.delta.index(max(self.delta))
initSetOneUB = lis... | This is class to represent the initial set | InitialSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InitialSet:
"""This is class to represent the initial set"""
def __init__(self, lower, upper):
"""Initial set class initialization function. Args: lower (list): lowerbound of the initial set upper (list): upperbound of the initial set"""
<|body_0|>
def refine(self):
... | stack_v2_sparse_classes_75kplus_train_002230 | 2,173 | no_license | [
{
"docstring": "Initial set class initialization function. Args: lower (list): lowerbound of the initial set upper (list): upperbound of the initial set",
"name": "__init__",
"signature": "def __init__(self, lower, upper)"
},
{
"docstring": "This function refine the current initial set into two ... | 3 | stack_v2_sparse_classes_30k_train_015064 | Implement the Python class `InitialSet` described below.
Class description:
This is class to represent the initial set
Method signatures and docstrings:
- def __init__(self, lower, upper): Initial set class initialization function. Args: lower (list): lowerbound of the initial set upper (list): upperbound of the init... | Implement the Python class `InitialSet` described below.
Class description:
This is class to represent the initial set
Method signatures and docstrings:
- def __init__(self, lower, upper): Initial set class initialization function. Args: lower (list): lowerbound of the initial set upper (list): upperbound of the init... | 4ee2bbc736d382043be585906704bcc4dc115d3d | <|skeleton|>
class InitialSet:
"""This is class to represent the initial set"""
def __init__(self, lower, upper):
"""Initial set class initialization function. Args: lower (list): lowerbound of the initial set upper (list): upperbound of the initial set"""
<|body_0|>
def refine(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InitialSet:
"""This is class to represent the initial set"""
def __init__(self, lower, upper):
"""Initial set class initialization function. Args: lower (list): lowerbound of the initial set upper (list): upperbound of the initial set"""
self.lowerBound = lower
self.upperBound = u... | the_stack_v2_python_sparse | src/core/initialset.py | qibolun/DryVR_0.2 | train | 7 |
9948a0726f7a8ac952d193426f00b0befa4c3166 | [
"self.nx = config['nx']\ndx = config['dx']\nxbgn, xend = config['x_limits']\nxpos = position - xbgn\nixs = max(1, int(np.ceil(xpos / dx)))\nfrac = ixs - xpos / dx\nfrac = 0.0 if ixs == 1 else frac\nfrac = 1.0 if ixs == self.nx - 1 else frac\nself.ixs = ixs\nself.frac = frac",
"f = torch.zeros([self.nx]).to(device... | <|body_start_0|>
self.nx = config['nx']
dx = config['dx']
xbgn, xend = config['x_limits']
xpos = position - xbgn
ixs = max(1, int(np.ceil(xpos / dx)))
frac = ixs - xpos / dx
frac = 0.0 if ixs == 1 else frac
frac = 1.0 if ixs == self.nx - 1 else frac
... | Point_Source | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Point_Source:
def __init__(self, position, config):
"""Configures interpolation of source in sampling grid"""
<|body_0|>
def set(self, value):
"""Sets amplitude at source point for current time"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.nx... | stack_v2_sparse_classes_75kplus_train_002231 | 20,893 | no_license | [
{
"docstring": "Configures interpolation of source in sampling grid",
"name": "__init__",
"signature": "def __init__(self, position, config)"
},
{
"docstring": "Sets amplitude at source point for current time",
"name": "set",
"signature": "def set(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016227 | Implement the Python class `Point_Source` described below.
Class description:
Implement the Point_Source class.
Method signatures and docstrings:
- def __init__(self, position, config): Configures interpolation of source in sampling grid
- def set(self, value): Sets amplitude at source point for current time | Implement the Python class `Point_Source` described below.
Class description:
Implement the Point_Source class.
Method signatures and docstrings:
- def __init__(self, position, config): Configures interpolation of source in sampling grid
- def set(self, value): Sets amplitude at source point for current time
<|skele... | b7477f7659126da69b9a1bab0377f12c595ffbfb | <|skeleton|>
class Point_Source:
def __init__(self, position, config):
"""Configures interpolation of source in sampling grid"""
<|body_0|>
def set(self, value):
"""Sets amplitude at source point for current time"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Point_Source:
def __init__(self, position, config):
"""Configures interpolation of source in sampling grid"""
self.nx = config['nx']
dx = config['dx']
xbgn, xend = config['x_limits']
xpos = position - xbgn
ixs = max(1, int(np.ceil(xpos / dx)))
frac = ixs... | the_stack_v2_python_sparse | fwi-dl/Wave1D_AGfunc.py | lhuang-pvamu/pytorch-examples | train | 1 | |
c18034298c67deb90f41f3adcfdced1a4851f8d1 | [
"user = g.user\nsubscriptionsList = user.subscriptions.order_by(journals.__model__.id)\nreturn map(lambda j: marshal(j, essential_journal_fields), subscriptionsList)",
"journal_id = request.json['journalId']\njournal = journals.get_or_404(journal_id)\nuser = g.user\nusers.subscribe(user, journal)\nuser_papers.use... | <|body_start_0|>
user = g.user
subscriptionsList = user.subscriptions.order_by(journals.__model__.id)
return map(lambda j: marshal(j, essential_journal_fields), subscriptionsList)
<|end_body_0|>
<|body_start_1|>
journal_id = request.json['journalId']
journal = journals.get_or_40... | API :class:`Resource` for a the user subscriptions. | SubscriptionListAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscriptionListAPI:
"""API :class:`Resource` for a the user subscriptions."""
def get(self):
"""Returns the list of journals the user is subscribed to."""
<|body_0|>
def post(self):
"""Post request with the journal id the user wants to subscribe to."""
<... | stack_v2_sparse_classes_75kplus_train_002232 | 1,634 | permissive | [
{
"docstring": "Returns the list of journals the user is subscribed to.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Post request with the journal id the user wants to subscribe to.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046082 | Implement the Python class `SubscriptionListAPI` described below.
Class description:
API :class:`Resource` for a the user subscriptions.
Method signatures and docstrings:
- def get(self): Returns the list of journals the user is subscribed to.
- def post(self): Post request with the journal id the user wants to subsc... | Implement the Python class `SubscriptionListAPI` described below.
Class description:
API :class:`Resource` for a the user subscriptions.
Method signatures and docstrings:
- def get(self): Returns the list of journals the user is subscribed to.
- def post(self): Post request with the journal id the user wants to subsc... | 728cd2f742275b12223d91613275358fb4a92feb | <|skeleton|>
class SubscriptionListAPI:
"""API :class:`Resource` for a the user subscriptions."""
def get(self):
"""Returns the list of journals the user is subscribed to."""
<|body_0|>
def post(self):
"""Post request with the journal id the user wants to subscribe to."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubscriptionListAPI:
"""API :class:`Resource` for a the user subscriptions."""
def get(self):
"""Returns the list of journals the user is subscribed to."""
user = g.user
subscriptionsList = user.subscriptions.order_by(journals.__model__.id)
return map(lambda j: marshal(j, ... | the_stack_v2_python_sparse | backend/paperchase/api/subscriptions.py | dedalusj/PaperChase | train | 3 |
3e9ec4b03d342eeccacfef72c5a9b35ab1b56fe5 | [
"for member in [self.team1_admin, self.team1_member, self.common_member]:\n self.client.force_login(member)\n response = self.client.get(self.list_url)\n self.assertContains(response, 'Categories for %s' % self.team1.name, status_code=200)\n for category in self.team1.categories.all():\n self.ass... | <|body_start_0|>
for member in [self.team1_admin, self.team1_member, self.common_member]:
self.client.force_login(member)
response = self.client.get(self.list_url)
self.assertContains(response, 'Categories for %s' % self.team1.name, status_code=200)
for category i... | Test CategoryListView | CategoryListViewTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryListViewTest:
"""Test CategoryListView"""
def test_category_list_member(self):
"""Assert that all the right categories are listed for the team admin and regular members"""
<|body_0|>
def test_category_list_nonmember(self):
"""Assert that non-members can n... | stack_v2_sparse_classes_75kplus_train_002233 | 9,408 | permissive | [
{
"docstring": "Assert that all the right categories are listed for the team admin and regular members",
"name": "test_category_list_member",
"signature": "def test_category_list_member(self)"
},
{
"docstring": "Assert that non-members can not list categories",
"name": "test_category_list_no... | 2 | stack_v2_sparse_classes_30k_train_028002 | Implement the Python class `CategoryListViewTest` described below.
Class description:
Test CategoryListView
Method signatures and docstrings:
- def test_category_list_member(self): Assert that all the right categories are listed for the team admin and regular members
- def test_category_list_nonmember(self): Assert t... | Implement the Python class `CategoryListViewTest` described below.
Class description:
Test CategoryListView
Method signatures and docstrings:
- def test_category_list_member(self): Assert that all the right categories are listed for the team admin and regular members
- def test_category_list_nonmember(self): Assert t... | b3a61462d46d33de25fb96c029b2bd822001b669 | <|skeleton|>
class CategoryListViewTest:
"""Test CategoryListView"""
def test_category_list_member(self):
"""Assert that all the right categories are listed for the team admin and regular members"""
<|body_0|>
def test_category_list_nonmember(self):
"""Assert that non-members can n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CategoryListViewTest:
"""Test CategoryListView"""
def test_category_list_member(self):
"""Assert that all the right categories are listed for the team admin and regular members"""
for member in [self.team1_admin, self.team1_member, self.common_member]:
self.client.force_login(... | the_stack_v2_python_sparse | src/category/tests.py | tykling/socialrating | train | 3 |
749182e6a01abbe286f28282afd0c28b1ab3fd64 | [
"test_integers = []\nwhile len(test_integers) < 50:\n random_integer = random.randint(-1000000, 1000000)\n test_integers.append(random_integer)\nfor item in test_integers:\n result = rosevomit.core.utilities.angle_sanity_check(item)\n self.assertTrue(0 <= result < 360)",
"test_floats = []\nwhile len(t... | <|body_start_0|>
test_integers = []
while len(test_integers) < 50:
random_integer = random.randint(-1000000, 1000000)
test_integers.append(random_integer)
for item in test_integers:
result = rosevomit.core.utilities.angle_sanity_check(item)
self.as... | Testing various functions from the utilities module. | UtilityTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilityTests:
"""Testing various functions from the utilities module."""
def test_angle_sanity_check_int(self):
"""Do we ever get angles larger than 360 degrees? (integer version)"""
<|body_0|>
def test_angle_sanity_check_float(self):
"""Do we ever get angles lar... | stack_v2_sparse_classes_75kplus_train_002234 | 5,695 | permissive | [
{
"docstring": "Do we ever get angles larger than 360 degrees? (integer version)",
"name": "test_angle_sanity_check_int",
"signature": "def test_angle_sanity_check_int(self)"
},
{
"docstring": "Do we ever get angles larger than 360 degrees? (float version)",
"name": "test_angle_sanity_check_... | 2 | stack_v2_sparse_classes_30k_train_054105 | Implement the Python class `UtilityTests` described below.
Class description:
Testing various functions from the utilities module.
Method signatures and docstrings:
- def test_angle_sanity_check_int(self): Do we ever get angles larger than 360 degrees? (integer version)
- def test_angle_sanity_check_float(self): Do w... | Implement the Python class `UtilityTests` described below.
Class description:
Testing various functions from the utilities module.
Method signatures and docstrings:
- def test_angle_sanity_check_int(self): Do we ever get angles larger than 360 degrees? (integer version)
- def test_angle_sanity_check_float(self): Do w... | 20de7c330fc44ddc8702aced2c5d0c126707896b | <|skeleton|>
class UtilityTests:
"""Testing various functions from the utilities module."""
def test_angle_sanity_check_int(self):
"""Do we ever get angles larger than 360 degrees? (integer version)"""
<|body_0|>
def test_angle_sanity_check_float(self):
"""Do we ever get angles lar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UtilityTests:
"""Testing various functions from the utilities module."""
def test_angle_sanity_check_int(self):
"""Do we ever get angles larger than 360 degrees? (integer version)"""
test_integers = []
while len(test_integers) < 50:
random_integer = random.randint(-100... | the_stack_v2_python_sparse | devtests/sanitytests.py | AlexLemna/rosevomit | train | 0 |
488c9b33e2a4599bc6435a8972781a565688292d | [
"super(PersonalizedPageRank, self).__init__(self.name)\nself.alpha = alpha\nself.log = log\nself.threshold = threshold",
"A = adjacency_matrix\nif len(A.shape) == 2:\n A = A.unsqueeze(0)\nN = A.shape[1]\ndegs_inv = A.sum(-1) ** (-1)\ndegs_inv[A.sum(-1) == 0] = 0\nD_inv = torch.diag_embed(degs_inv)\nA_rw = A.tr... | <|body_start_0|>
super(PersonalizedPageRank, self).__init__(self.name)
self.alpha = alpha
self.log = log
self.threshold = threshold
<|end_body_0|>
<|body_start_1|>
A = adjacency_matrix
if len(A.shape) == 2:
A = A.unsqueeze(0)
N = A.shape[1]
de... | PersonalizedPageRank | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonalizedPageRank:
def __init__(self, log=True, alpha=0.15, threshold=None):
""":param log: whether to return the log of the ppr values :param alpha: teleport probability :param threshold: Any ppr score below this threshold will be regarded as 0"""
<|body_0|>
def __call__... | stack_v2_sparse_classes_75kplus_train_002235 | 11,329 | permissive | [
{
"docstring": ":param log: whether to return the log of the ppr values :param alpha: teleport probability :param threshold: Any ppr score below this threshold will be regarded as 0",
"name": "__init__",
"signature": "def __init__(self, log=True, alpha=0.15, threshold=None)"
},
{
"docstring": ":... | 2 | stack_v2_sparse_classes_30k_train_020881 | Implement the Python class `PersonalizedPageRank` described below.
Class description:
Implement the PersonalizedPageRank class.
Method signatures and docstrings:
- def __init__(self, log=True, alpha=0.15, threshold=None): :param log: whether to return the log of the ppr values :param alpha: teleport probability :para... | Implement the Python class `PersonalizedPageRank` described below.
Class description:
Implement the PersonalizedPageRank class.
Method signatures and docstrings:
- def __init__(self, log=True, alpha=0.15, threshold=None): :param log: whether to return the log of the ppr values :param alpha: teleport probability :para... | 52600ab17d05a238f35c39a78b22c5c706fbb13c | <|skeleton|>
class PersonalizedPageRank:
def __init__(self, log=True, alpha=0.15, threshold=None):
""":param log: whether to return the log of the ppr values :param alpha: teleport probability :param threshold: Any ppr score below this threshold will be regarded as 0"""
<|body_0|>
def __call__... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PersonalizedPageRank:
def __init__(self, log=True, alpha=0.15, threshold=None):
""":param log: whether to return the log of the ppr values :param alpha: teleport probability :param threshold: Any ppr score below this threshold will be regarded as 0"""
super(PersonalizedPageRank, self).__init__... | the_stack_v2_python_sparse | code_transformer/preprocessing/graph/distances.py | maximzubkov/code-transformer | train | 0 | |
479a26a092f77a856b804a38331a6b8d2440cfc6 | [
"self._given_py_version_info = py_version_info\nif py_version_info is None:\n py_version_info = sys.version_info[:3]\nelse:\n py_version_info = normalize_version_info(py_version_info)\npy_version = '.'.join(map(str, py_version_info[:2]))\nself.abis = abis\nself.implementation = implementation\nself.platforms ... | <|body_start_0|>
self._given_py_version_info = py_version_info
if py_version_info is None:
py_version_info = sys.version_info[:3]
else:
py_version_info = normalize_version_info(py_version_info)
py_version = '.'.join(map(str, py_version_info[:2]))
self.abis... | Encapsulates the properties of a Python interpreter one is targeting for a package install, download, etc. | TargetPython | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TargetPython:
"""Encapsulates the properties of a Python interpreter one is targeting for a package install, download, etc."""
def __init__(self, platforms: Optional[List[str]]=None, py_version_info: Optional[Tuple[int, ...]]=None, abis: Optional[List[str]]=None, implementation: Optional[str... | stack_v2_sparse_classes_75kplus_train_002236 | 4,272 | permissive | [
{
"docstring": ":param platforms: A list of strings or None. If None, searches for packages that are supported by the current system. Otherwise, will find packages that can be built on the platforms passed in. These packages will only be downloaded for distribution: they will not be built locally. :param py_ver... | 4 | stack_v2_sparse_classes_30k_train_026749 | Implement the Python class `TargetPython` described below.
Class description:
Encapsulates the properties of a Python interpreter one is targeting for a package install, download, etc.
Method signatures and docstrings:
- def __init__(self, platforms: Optional[List[str]]=None, py_version_info: Optional[Tuple[int, ...]... | Implement the Python class `TargetPython` described below.
Class description:
Encapsulates the properties of a Python interpreter one is targeting for a package install, download, etc.
Method signatures and docstrings:
- def __init__(self, platforms: Optional[List[str]]=None, py_version_info: Optional[Tuple[int, ...]... | 0778c1c153da7da457b56df55fb77cbba08dfb0c | <|skeleton|>
class TargetPython:
"""Encapsulates the properties of a Python interpreter one is targeting for a package install, download, etc."""
def __init__(self, platforms: Optional[List[str]]=None, py_version_info: Optional[Tuple[int, ...]]=None, abis: Optional[List[str]]=None, implementation: Optional[str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TargetPython:
"""Encapsulates the properties of a Python interpreter one is targeting for a package install, download, etc."""
def __init__(self, platforms: Optional[List[str]]=None, py_version_info: Optional[Tuple[int, ...]]=None, abis: Optional[List[str]]=None, implementation: Optional[str]=None) -> No... | the_stack_v2_python_sparse | src/pip/_internal/models/target_python.py | pypa/pip | train | 8,612 |
cabc1ded6accc5b6360ff2b10def6e2d30ac7e4d | [
"super(PixelSelector, self).__init__()\nassert momentManager.kernelWidth == calMomentManager.kernelWidth\nself.keys = copy.copy(MomentManager.keys)\nself.momentManager = momentManager\nself.calMomentManager = calMomentManager",
"if limit.name not in self.keys:\n raise ValueError('Limit name must be in:' + str(... | <|body_start_0|>
super(PixelSelector, self).__init__()
assert momentManager.kernelWidth == calMomentManager.kernelWidth
self.keys = copy.copy(MomentManager.keys)
self.momentManager = momentManager
self.calMomentManager = calMomentManager
<|end_body_0|>
<|body_start_1|>
i... | A simple pixel selector. Inherit from a list, and we'll contain a list of our MomentLimit objects. We'll go through our list, and any pixels which are numerically within the limits for all MomentLimit objects "pass" and are kept. In the end, we return a boolean image with True set for accepted pixels. | PixelSelector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PixelSelector:
"""A simple pixel selector. Inherit from a list, and we'll contain a list of our MomentLimit objects. We'll go through our list, and any pixels which are numerically within the limits for all MomentLimit objects "pass" and are kept. In the end, we return a boolean image with True s... | stack_v2_sparse_classes_75kplus_train_002237 | 11,918 | no_license | [
{
"docstring": "Construct @param momentManager MomentManager for the image we're selecting from @param calMomentManager The MomentManager for the calibration image.",
"name": "__init__",
"signature": "def __init__(self, momentManager, calMomentManager)"
},
{
"docstring": "Overload our parent lis... | 4 | stack_v2_sparse_classes_30k_train_049315 | Implement the Python class `PixelSelector` described below.
Class description:
A simple pixel selector. Inherit from a list, and we'll contain a list of our MomentLimit objects. We'll go through our list, and any pixels which are numerically within the limits for all MomentLimit objects "pass" and are kept. In the end... | Implement the Python class `PixelSelector` described below.
Class description:
A simple pixel selector. Inherit from a list, and we'll contain a list of our MomentLimit objects. We'll go through our list, and any pixels which are numerically within the limits for all MomentLimit objects "pass" and are kept. In the end... | f826f98369125b9aa0aa6f7228913a503cea80a4 | <|skeleton|>
class PixelSelector:
"""A simple pixel selector. Inherit from a list, and we'll contain a list of our MomentLimit objects. We'll go through our list, and any pixels which are numerically within the limits for all MomentLimit objects "pass" and are kept. In the end, we return a boolean image with True s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PixelSelector:
"""A simple pixel selector. Inherit from a list, and we'll contain a list of our MomentLimit objects. We'll go through our list, and any pixels which are numerically within the limits for all MomentLimit objects "pass" and are kept. In the end, we return a boolean image with True set for accept... | the_stack_v2_python_sparse | python/lsst/meas/artifact/momentCalculator.py | lsst-dm/meas_artifact | train | 3 |
c658f939293fd0572f917083841dc6384a5fb20e | [
"data = ImgShard(index=index, uuid=uuid, imgString=imgString)\ndbSession.add(data)\nreturn dbSession.commit()",
"obj = dbSession.query(ImgShard).filter_by(uuid=uuid).order_by('index').all()\ndata = Utils.db_to_d(obj)\nreturn data"
] | <|body_start_0|>
data = ImgShard(index=index, uuid=uuid, imgString=imgString)
dbSession.add(data)
return dbSession.commit()
<|end_body_0|>
<|body_start_1|>
obj = dbSession.query(ImgShard).filter_by(uuid=uuid).order_by('index').all()
data = Utils.db_to_d(obj)
return data
... | ImgShard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImgShard:
def add(index, uuid, imgString):
"""增加分片数据 :param index: :param uuid: :param imgString: :return:"""
<|body_0|>
def get_data(uuid):
"""根据uuid获取分片数据 :param uuid: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = ImgShard(index=... | stack_v2_sparse_classes_75kplus_train_002238 | 949 | no_license | [
{
"docstring": "增加分片数据 :param index: :param uuid: :param imgString: :return:",
"name": "add",
"signature": "def add(index, uuid, imgString)"
},
{
"docstring": "根据uuid获取分片数据 :param uuid: :return:",
"name": "get_data",
"signature": "def get_data(uuid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045835 | Implement the Python class `ImgShard` described below.
Class description:
Implement the ImgShard class.
Method signatures and docstrings:
- def add(index, uuid, imgString): 增加分片数据 :param index: :param uuid: :param imgString: :return:
- def get_data(uuid): 根据uuid获取分片数据 :param uuid: :return: | Implement the Python class `ImgShard` described below.
Class description:
Implement the ImgShard class.
Method signatures and docstrings:
- def add(index, uuid, imgString): 增加分片数据 :param index: :param uuid: :param imgString: :return:
- def get_data(uuid): 根据uuid获取分片数据 :param uuid: :return:
<|skeleton|>
class ImgShar... | 59c61f94c469038f641b451cb3f5d1adabdfe6a9 | <|skeleton|>
class ImgShard:
def add(index, uuid, imgString):
"""增加分片数据 :param index: :param uuid: :param imgString: :return:"""
<|body_0|>
def get_data(uuid):
"""根据uuid获取分片数据 :param uuid: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImgShard:
def add(index, uuid, imgString):
"""增加分片数据 :param index: :param uuid: :param imgString: :return:"""
data = ImgShard(index=index, uuid=uuid, imgString=imgString)
dbSession.add(data)
return dbSession.commit()
def get_data(uuid):
"""根据uuid获取分片数据 :param uuid:... | the_stack_v2_python_sparse | app/Models/ImgShard.py | FreeGodCode/flask-restful-api | train | 0 | |
e7e64d8af725c369436c3ec542866aa0afef0485 | [
"ctx.input = tensor\ngathered_tensor = [torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())]\ntorch.distributed.all_gather(gathered_tensor, tensor)\ngathered_tensor = torch.cat(gathered_tensor, 0)\nreturn gathered_tensor",
"grad_input = torch.zeros_like(ctx.input)\nper_gpu_batch_size = gra... | <|body_start_0|>
ctx.input = tensor
gathered_tensor = [torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())]
torch.distributed.all_gather(gathered_tensor, tensor)
gathered_tensor = torch.cat(gathered_tensor, 0)
return gathered_tensor
<|end_body_0|>
<|body_... | DifferentiableDistGather | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DifferentiableDistGather:
def forward(ctx, tensor: torch.Tensor):
"""Forward function will be the distributed.all_gather :param tensor: batch_size, hid_dim"""
<|body_0|>
def backward(ctx, grad_output: torch.Tensor):
"""backward function will be the distributed.reduce... | stack_v2_sparse_classes_75kplus_train_002239 | 4,033 | no_license | [
{
"docstring": "Forward function will be the distributed.all_gather :param tensor: batch_size, hid_dim",
"name": "forward",
"signature": "def forward(ctx, tensor: torch.Tensor)"
},
{
"docstring": "backward function will be the distributed.reduce_scatter (with sum as reduce OP) :param grad_output... | 2 | stack_v2_sparse_classes_30k_train_020912 | Implement the Python class `DifferentiableDistGather` described below.
Class description:
Implement the DifferentiableDistGather class.
Method signatures and docstrings:
- def forward(ctx, tensor: torch.Tensor): Forward function will be the distributed.all_gather :param tensor: batch_size, hid_dim
- def backward(ctx,... | Implement the Python class `DifferentiableDistGather` described below.
Class description:
Implement the DifferentiableDistGather class.
Method signatures and docstrings:
- def forward(ctx, tensor: torch.Tensor): Forward function will be the distributed.all_gather :param tensor: batch_size, hid_dim
- def backward(ctx,... | a9afd79e92aa544efdc995c9e40a3d313fdea430 | <|skeleton|>
class DifferentiableDistGather:
def forward(ctx, tensor: torch.Tensor):
"""Forward function will be the distributed.all_gather :param tensor: batch_size, hid_dim"""
<|body_0|>
def backward(ctx, grad_output: torch.Tensor):
"""backward function will be the distributed.reduce... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DifferentiableDistGather:
def forward(ctx, tensor: torch.Tensor):
"""Forward function will be the distributed.all_gather :param tensor: batch_size, hid_dim"""
ctx.input = tensor
gathered_tensor = [torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())]
torc... | the_stack_v2_python_sparse | vimpac/nce_support.py | PkuRainBow/vimpac | train | 0 | |
1726098070ee974cf2eed92807f8c43476f44d65 | [
"name_to_features = mention_encoder_task.MentionEncoderTask.get_name_to_features(config)\nif config.apply_answer_mask:\n name_to_features['dense_answer_mask'] = tf.io.FixedLenFeature(config.model_config.encoder_config.max_length, tf.int64)\nreturn name_to_features",
"max_length = config.model_config.encoder_co... | <|body_start_0|>
name_to_features = mention_encoder_task.MentionEncoderTask.get_name_to_features(config)
if config.apply_answer_mask:
name_to_features['dense_answer_mask'] = tf.io.FixedLenFeature(config.model_config.encoder_config.max_length, tf.int64)
return name_to_features
<|end_b... | Abstract class for all entity-answer question answering tasks. | EntityQATask | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityQATask:
"""Abstract class for all entity-answer question answering tasks."""
def get_name_to_features(config: ml_collections.ConfigDict) -> Dict[str, Any]:
"""Return feature dict for decoding purposes. See BaseTask."""
<|body_0|>
def make_preprocess_fn(config: ml_c... | stack_v2_sparse_classes_75kplus_train_002240 | 5,499 | permissive | [
{
"docstring": "Return feature dict for decoding purposes. See BaseTask.",
"name": "get_name_to_features",
"signature": "def get_name_to_features(config: ml_collections.ConfigDict) -> Dict[str, Any]"
},
{
"docstring": "Produces function to preprocess samples. See BaseTask. During preprocessing w... | 3 | stack_v2_sparse_classes_30k_train_026937 | Implement the Python class `EntityQATask` described below.
Class description:
Abstract class for all entity-answer question answering tasks.
Method signatures and docstrings:
- def get_name_to_features(config: ml_collections.ConfigDict) -> Dict[str, Any]: Return feature dict for decoding purposes. See BaseTask.
- def... | Implement the Python class `EntityQATask` described below.
Class description:
Abstract class for all entity-answer question answering tasks.
Method signatures and docstrings:
- def get_name_to_features(config: ml_collections.ConfigDict) -> Dict[str, Any]: Return feature dict for decoding purposes. See BaseTask.
- def... | ac9447064195e06de48cc91ff642f7fffa28ffe8 | <|skeleton|>
class EntityQATask:
"""Abstract class for all entity-answer question answering tasks."""
def get_name_to_features(config: ml_collections.ConfigDict) -> Dict[str, Any]:
"""Return feature dict for decoding purposes. See BaseTask."""
<|body_0|>
def make_preprocess_fn(config: ml_c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EntityQATask:
"""Abstract class for all entity-answer question answering tasks."""
def get_name_to_features(config: ml_collections.ConfigDict) -> Dict[str, Any]:
"""Return feature dict for decoding purposes. See BaseTask."""
name_to_features = mention_encoder_task.MentionEncoderTask.get_n... | the_stack_v2_python_sparse | language/mentionmemory/tasks/entity_qa_task.py | google-research/language | train | 1,567 |
8b9dec243778e9ddb755b983bd518a3f9c168178 | [
"DBFormatter.__init__(self, logger, dbinterface)\nself.create = {}\nself.constraints = {}\nself.inserts = {}\nself.indexes = {}",
"for i in sorted(self.create.keys()):\n try:\n self.dbi.processData(self.create[i], conn=conn, transaction=transaction)\n except Exception as e:\n msg = WMEXCEPTION... | <|body_start_0|>
DBFormatter.__init__(self, logger, dbinterface)
self.create = {}
self.constraints = {}
self.inserts = {}
self.indexes = {}
<|end_body_0|>
<|body_start_1|>
for i in sorted(self.create.keys()):
try:
self.dbi.processData(self.cre... | _DBCreator_ Generic class for creating database tables. | DBCreator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBCreator:
"""_DBCreator_ Generic class for creating database tables."""
def __init__(self, logger, dbinterface):
"""_init_ Call the constructor of the parent class and create empty dictionaries to hold table create statements, constraint statements and insert statements."""
... | stack_v2_sparse_classes_75kplus_train_002241 | 3,666 | permissive | [
{
"docstring": "_init_ Call the constructor of the parent class and create empty dictionaries to hold table create statements, constraint statements and insert statements.",
"name": "__init__",
"signature": "def __init__(self, logger, dbinterface)"
},
{
"docstring": "_execute_ Generic method to ... | 3 | stack_v2_sparse_classes_30k_train_011453 | Implement the Python class `DBCreator` described below.
Class description:
_DBCreator_ Generic class for creating database tables.
Method signatures and docstrings:
- def __init__(self, logger, dbinterface): _init_ Call the constructor of the parent class and create empty dictionaries to hold table create statements,... | Implement the Python class `DBCreator` described below.
Class description:
_DBCreator_ Generic class for creating database tables.
Method signatures and docstrings:
- def __init__(self, logger, dbinterface): _init_ Call the constructor of the parent class and create empty dictionaries to hold table create statements,... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class DBCreator:
"""_DBCreator_ Generic class for creating database tables."""
def __init__(self, logger, dbinterface):
"""_init_ Call the constructor of the parent class and create empty dictionaries to hold table create statements, constraint statements and insert statements."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DBCreator:
"""_DBCreator_ Generic class for creating database tables."""
def __init__(self, logger, dbinterface):
"""_init_ Call the constructor of the parent class and create empty dictionaries to hold table create statements, constraint statements and insert statements."""
DBFormatter._... | the_stack_v2_python_sparse | src/python/WMCore/Database/DBCreator.py | vkuznet/WMCore | train | 0 |
f51a5b840773d07f4548dc2e7a52e2ad51ff18b7 | [
"super().__init__(**kwargs)\nself.conv1d_1 = tf.keras.layers.Conv1D(config.intermediate_size, kernel_size=config.intermediate_kernel_size, kernel_initializer=get_initializer(config.initializer_range), padding='same', name='conv1d_1')\nself.conv1d_2 = tf.keras.layers.Conv1D(config.hidden_size, kernel_size=config.int... | <|body_start_0|>
super().__init__(**kwargs)
self.conv1d_1 = tf.keras.layers.Conv1D(config.intermediate_size, kernel_size=config.intermediate_kernel_size, kernel_initializer=get_initializer(config.initializer_range), padding='same', name='conv1d_1')
self.conv1d_2 = tf.keras.layers.Conv1D(config.h... | Two_Layers_Conv1d | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Two_Layers_Conv1d:
def __init__(self, config, **kwargs):
"""Init variables."""
<|body_0|>
def call(self, inputs):
"""Call logic."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__(**kwargs)
self.conv1d_1 = tf.keras.layers.Conv1... | stack_v2_sparse_classes_75kplus_train_002242 | 3,355 | permissive | [
{
"docstring": "Init variables.",
"name": "__init__",
"signature": "def __init__(self, config, **kwargs)"
},
{
"docstring": "Call logic.",
"name": "call",
"signature": "def call(self, inputs)"
}
] | 2 | null | Implement the Python class `Two_Layers_Conv1d` described below.
Class description:
Implement the Two_Layers_Conv1d class.
Method signatures and docstrings:
- def __init__(self, config, **kwargs): Init variables.
- def call(self, inputs): Call logic. | Implement the Python class `Two_Layers_Conv1d` described below.
Class description:
Implement the Two_Layers_Conv1d class.
Method signatures and docstrings:
- def __init__(self, config, **kwargs): Init variables.
- def call(self, inputs): Call logic.
<|skeleton|>
class Two_Layers_Conv1d:
def __init__(self, confi... | 59b523e4b11c827e38cc37817da145af15713bcd | <|skeleton|>
class Two_Layers_Conv1d:
def __init__(self, config, **kwargs):
"""Init variables."""
<|body_0|>
def call(self, inputs):
"""Call logic."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Two_Layers_Conv1d:
def __init__(self, config, **kwargs):
"""Init variables."""
super().__init__(**kwargs)
self.conv1d_1 = tf.keras.layers.Conv1D(config.intermediate_size, kernel_size=config.intermediate_kernel_size, kernel_initializer=get_initializer(config.initializer_range), padding=... | the_stack_v2_python_sparse | tensorflow_tts/modules/FFT.py | ivenlau/FS2_TTS | train | 0 | |
7336cff6ae114f7ebb5e4c14602950e0367e1eef | [
"graph.reset_visited()\nq = MyQueue()\nstart_node.visited = True\nq.push(start_node)\nwhile q.is_empty() == False:\n node = q.pop()\n if node == destination_node:\n return True\n for adjacent in node.adjacents:\n q.push(adjacent)\nreturn False",
"if reset_visited:\n graph.reset_visited()... | <|body_start_0|>
graph.reset_visited()
q = MyQueue()
start_node.visited = True
q.push(start_node)
while q.is_empty() == False:
node = q.pop()
if node == destination_node:
return True
for adjacent in node.adjacents:
... | Collection of graph searches. | MyGraphSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyGraphSearch:
"""Collection of graph searches."""
def breadth_first_search(graph, start_node, destination_node):
"""BFS. Make use of a queue, and make sure to mark nodes as visited! TODO: Return the path and its cost."""
<|body_0|>
def depth_first_search(graph, start_no... | stack_v2_sparse_classes_75kplus_train_002243 | 5,166 | no_license | [
{
"docstring": "BFS. Make use of a queue, and make sure to mark nodes as visited! TODO: Return the path and its cost.",
"name": "breadth_first_search",
"signature": "def breadth_first_search(graph, start_node, destination_node)"
},
{
"docstring": "DFS. Solve recursively, make sure to mark nodes ... | 2 | stack_v2_sparse_classes_30k_train_025099 | Implement the Python class `MyGraphSearch` described below.
Class description:
Collection of graph searches.
Method signatures and docstrings:
- def breadth_first_search(graph, start_node, destination_node): BFS. Make use of a queue, and make sure to mark nodes as visited! TODO: Return the path and its cost.
- def de... | Implement the Python class `MyGraphSearch` described below.
Class description:
Collection of graph searches.
Method signatures and docstrings:
- def breadth_first_search(graph, start_node, destination_node): BFS. Make use of a queue, and make sure to mark nodes as visited! TODO: Return the path and its cost.
- def de... | cd56d29173cb9fde171f94ad6651ea2f5766d125 | <|skeleton|>
class MyGraphSearch:
"""Collection of graph searches."""
def breadth_first_search(graph, start_node, destination_node):
"""BFS. Make use of a queue, and make sure to mark nodes as visited! TODO: Return the path and its cost."""
<|body_0|>
def depth_first_search(graph, start_no... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyGraphSearch:
"""Collection of graph searches."""
def breadth_first_search(graph, start_node, destination_node):
"""BFS. Make use of a queue, and make sure to mark nodes as visited! TODO: Return the path and its cost."""
graph.reset_visited()
q = MyQueue()
start_node.visi... | the_stack_v2_python_sparse | data_structures/my_graph.py | toebgen/exercises | train | 0 |
88c7e50743a6b0f67ae7506091ebbd45da0c44d7 | [
"try:\n offset = int(offset)\nexcept (TypeError, ValueError):\n raise OffsetNotAnInteger('That offset is not an integer')\nreturn offset",
"number = self.validate_number(self.validate_offset(offset) // self.per_page + 1)\nbottom = (number - 1) * self.per_page\ntop = bottom + self.per_page\nif top + self.orp... | <|body_start_0|>
try:
offset = int(offset)
except (TypeError, ValueError):
raise OffsetNotAnInteger('That offset is not an integer')
return offset
<|end_body_0|>
<|body_start_1|>
number = self.validate_number(self.validate_offset(offset) // self.per_page + 1)
... | Paginator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Paginator:
def validate_offset(self, offset):
"""Validates the given offset."""
<|body_0|>
def page_by_offset(self, offset):
"""Returns a Page object for the given offset."""
<|body_1|>
def page(self, number):
"""Returns a Page object for the giv... | stack_v2_sparse_classes_75kplus_train_002244 | 1,705 | no_license | [
{
"docstring": "Validates the given offset.",
"name": "validate_offset",
"signature": "def validate_offset(self, offset)"
},
{
"docstring": "Returns a Page object for the given offset.",
"name": "page_by_offset",
"signature": "def page_by_offset(self, offset)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_026132 | Implement the Python class `Paginator` described below.
Class description:
Implement the Paginator class.
Method signatures and docstrings:
- def validate_offset(self, offset): Validates the given offset.
- def page_by_offset(self, offset): Returns a Page object for the given offset.
- def page(self, number): Returns... | Implement the Python class `Paginator` described below.
Class description:
Implement the Paginator class.
Method signatures and docstrings:
- def validate_offset(self, offset): Validates the given offset.
- def page_by_offset(self, offset): Returns a Page object for the given offset.
- def page(self, number): Returns... | 65c9820308b09a6ae1086c265f8d49e36f3724b9 | <|skeleton|>
class Paginator:
def validate_offset(self, offset):
"""Validates the given offset."""
<|body_0|>
def page_by_offset(self, offset):
"""Returns a Page object for the given offset."""
<|body_1|>
def page(self, number):
"""Returns a Page object for the giv... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Paginator:
def validate_offset(self, offset):
"""Validates the given offset."""
try:
offset = int(offset)
except (TypeError, ValueError):
raise OffsetNotAnInteger('That offset is not an integer')
return offset
def page_by_offset(self, offset):
... | the_stack_v2_python_sparse | publication_backbone/utils/paginator.py | Excentrics/publication-backbone | train | 6 | |
623b3856c5f69c64c368f2b851a4f296abab5538 | [
"super(GnocchiS3Test, cls).setUpClass()\nsession = openstack_utils.get_overcloud_keystone_session()\nks_client = openstack_utils.get_keystone_session_client(session)\ntoken_data = ks_client.tokens.get_token_data(session.get_token())\nproject_id = token_data['token']['project']['id']\nuser_id = token_data['token']['... | <|body_start_0|>
super(GnocchiS3Test, cls).setUpClass()
session = openstack_utils.get_overcloud_keystone_session()
ks_client = openstack_utils.get_keystone_session_client(session)
token_data = ks_client.tokens.get_token_data(session.get_token())
project_id = token_data['token']['... | Test Gnocchi for S3 storage backend. | GnocchiS3Test | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GnocchiS3Test:
"""Test Gnocchi for S3 storage backend."""
def setUpClass(cls):
"""Run class setup for running tests."""
<|body_0|>
def test_s3_list_gnocchi_buckets(self):
"""Verify that the gnocchi buckets were created in the S3 backend."""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus_train_002245 | 5,572 | permissive | [
{
"docstring": "Run class setup for running tests.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Verify that the gnocchi buckets were created in the S3 backend.",
"name": "test_s3_list_gnocchi_buckets",
"signature": "def test_s3_list_gnocchi_buckets(self)"... | 2 | stack_v2_sparse_classes_30k_train_024121 | Implement the Python class `GnocchiS3Test` described below.
Class description:
Test Gnocchi for S3 storage backend.
Method signatures and docstrings:
- def setUpClass(cls): Run class setup for running tests.
- def test_s3_list_gnocchi_buckets(self): Verify that the gnocchi buckets were created in the S3 backend. | Implement the Python class `GnocchiS3Test` described below.
Class description:
Test Gnocchi for S3 storage backend.
Method signatures and docstrings:
- def setUpClass(cls): Run class setup for running tests.
- def test_s3_list_gnocchi_buckets(self): Verify that the gnocchi buckets were created in the S3 backend.
<|s... | 3b17ad9d97c57b6e62797d4e3333e4b83e43a447 | <|skeleton|>
class GnocchiS3Test:
"""Test Gnocchi for S3 storage backend."""
def setUpClass(cls):
"""Run class setup for running tests."""
<|body_0|>
def test_s3_list_gnocchi_buckets(self):
"""Verify that the gnocchi buckets were created in the S3 backend."""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GnocchiS3Test:
"""Test Gnocchi for S3 storage backend."""
def setUpClass(cls):
"""Run class setup for running tests."""
super(GnocchiS3Test, cls).setUpClass()
session = openstack_utils.get_overcloud_keystone_session()
ks_client = openstack_utils.get_keystone_session_client... | the_stack_v2_python_sparse | zaza/openstack/charm_tests/gnocchi/tests.py | openstack-charmers/zaza-openstack-tests | train | 7 |
0ff048b088303cb2296a9a454cba73c33fa65373 | [
"if isinstance(key, int):\n return Option(key)\nif key not in Option._member_map_:\n extend_enum(Option, key, default)\nreturn Option[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 35 <= value <= 68:\n extend_enum(c... | <|body_start_0|>
if isinstance(key, int):
return Option(key)
if key not in Option._member_map_:
extend_enum(Option, key, default)
return Option[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
raise ValueErro... | [Option] TCP Option Kind Numbers | Option | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Option:
"""[Option] TCP Option Kind Numbers"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_002246 | 3,365 | permissive | [
{
"docstring": "Backport support for original codes.",
"name": "get",
"signature": "def get(key, default=-1)"
},
{
"docstring": "Lookup function used when value is not found.",
"name": "_missing_",
"signature": "def _missing_(cls, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052696 | Implement the Python class `Option` described below.
Class description:
[Option] TCP Option Kind Numbers
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found. | Implement the Python class `Option` described below.
Class description:
[Option] TCP Option Kind Numbers
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found.
<|skeleton|>
class Option:
"""[Opt... | 71363d7948003fec88cedcf5bc80b6befa2ba244 | <|skeleton|>
class Option:
"""[Option] TCP Option Kind Numbers"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Option:
"""[Option] TCP Option Kind Numbers"""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Option(key)
if key not in Option._member_map_:
extend_enum(Option, key, default)
return Option[key]
... | the_stack_v2_python_sparse | pcapkit/const/tcp/option.py | hiok2000/PyPCAPKit | train | 0 |
3bfa8ea332f9d5bb5b0145342d470922c42e2b61 | [
"if not root:\n return '[]'\nqueue = list()\nqueue.append(root)\nres = []\nwhile queue:\n node = queue.pop(0)\n if node:\n res.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\n else:\n res.append('null')\nwhile res[-1] == 'null':\n res.pop()\nres... | <|body_start_0|>
if not root:
return '[]'
queue = list()
queue.append(root)
res = []
while queue:
node = queue.pop(0)
if node:
res.append(str(node.val))
queue.append(node.left)
queue.append(node.r... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. 时间复杂度 O(N) : N 为二叉树的节点数,层序遍历需要访问所有节点, 最差情况下需要访问 N + 1 个 null ,总体复杂度为 O(2N + 1) = O(N)。 空间复杂度 O(N) : 最差情况下,队列 queue 同时存储 (N+1) / 2 个节点(或 N+1 个 null ),使用 O(N) ; 列表 res 使用 O(N) 。 :type root: TreeNode :rtype: str"""
... | stack_v2_sparse_classes_75kplus_train_002247 | 2,800 | no_license | [
{
"docstring": "Encodes a tree to a single string. 时间复杂度 O(N) : N 为二叉树的节点数,层序遍历需要访问所有节点, 最差情况下需要访问 N + 1 个 null ,总体复杂度为 O(2N + 1) = O(N)。 空间复杂度 O(N) : 最差情况下,队列 queue 同时存储 (N+1) / 2 个节点(或 N+1 个 null ),使用 O(N) ; 列表 res 使用 O(N) 。 :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def ser... | 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. 时间复杂度 O(N) : N 为二叉树的节点数,层序遍历需要访问所有节点, 最差情况下需要访问 N + 1 个 null ,总体复杂度为 O(2N + 1) = O(N)。 空间复杂度 O(N) : 最差情况下,队列 queue 同时存储 (N... | 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. 时间复杂度 O(N) : N 为二叉树的节点数,层序遍历需要访问所有节点, 最差情况下需要访问 N + 1 个 null ,总体复杂度为 O(2N + 1) = O(N)。 空间复杂度 O(N) : 最差情况下,队列 queue 同时存储 (N... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. 时间复杂度 O(N) : N 为二叉树的节点数,层序遍历需要访问所有节点, 最差情况下需要访问 N + 1 个 null ,总体复杂度为 O(2N + 1) = O(N)。 空间复杂度 O(N) : 最差情况下,队列 queue 同时存储 (N+1) / 2 个节点(或 N+1 个 null ),使用 O(N) ; 列表 res 使用 O(N) 。 :type root: TreeNode :rtype: str"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. 时间复杂度 O(N) : N 为二叉树的节点数,层序遍历需要访问所有节点, 最差情况下需要访问 N + 1 个 null ,总体复杂度为 O(2N + 1) = O(N)。 空间复杂度 O(N) : 最差情况下,队列 queue 同时存储 (N+1) / 2 个节点(或 N+1 个 null ),使用 O(N) ; 列表 res 使用 O(N) 。 :type root: TreeNode :rtype: str"""
if not roo... | the_stack_v2_python_sparse | 剑指 Offer(第 2 版)/serialize_deserialize.py | MaoningGuan/LeetCode | train | 3 | |
95911b7442ade4ac4df9d38b27e632ebe0756c47 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IdentityProtectionRoot()",
"from .risk_detection import RiskDetection\nfrom .risky_service_principal import RiskyServicePrincipal\nfrom .risky_user import RiskyUser\nfrom .service_principal_risk_detection import ServicePrincipalRiskDet... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IdentityProtectionRoot()
<|end_body_0|>
<|body_start_1|>
from .risk_detection import RiskDetection
from .risky_service_principal import RiskyServicePrincipal
from .risky_user imp... | IdentityProtectionRoot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityProtectionRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProtectionRoot:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create ... | stack_v2_sparse_classes_75kplus_train_002248 | 4,560 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: IdentityProtectionRoot",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | stack_v2_sparse_classes_30k_train_046243 | Implement the Python class `IdentityProtectionRoot` described below.
Class description:
Implement the IdentityProtectionRoot class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProtectionRoot: Creates a new instance of the appropriate class b... | Implement the Python class `IdentityProtectionRoot` described below.
Class description:
Implement the IdentityProtectionRoot class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProtectionRoot: Creates a new instance of the appropriate class b... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IdentityProtectionRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProtectionRoot:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IdentityProtectionRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProtectionRoot:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | the_stack_v2_python_sparse | msgraph/generated/models/identity_protection_root.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
0f3f726942fe8a215f6578ca956c9a7834fe2ae9 | [
"if not root:\n return '#'\nreturn str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)",
"ls = data.split(',')\n\ndef des(ls):\n val = ls.pop(0)\n if val == '#':\n return None\n node = TreeNode(int(val))\n node.left = des(ls)\n node.right = des(ls)\n retu... | <|body_start_0|>
if not root:
return '#'
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)
<|end_body_0|>
<|body_start_1|>
ls = data.split(',')
def des(ls):
val = ls.pop(0)
if val == '#':
return... | 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_75kplus_train_002249 | 2,977 | 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 | stack_v2_sparse_classes_30k_train_028013 | 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:... | 76ee1dcd3b2c0568a55cd577f42194bf92ff83f9 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '#'
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)
def deserialize(self, data):
"""Decodes... | the_stack_v2_python_sparse | 297H. Serialize and Deserialize Binary Tree /297H.py | arianacai1997/take_your_dog_to_work | train | 0 | |
037a6fa00e212aab4b67f82144f554664ac83697 | [
"coords = [0, 0, 0]\nif self.direction not in ['x', 'y', 'z']:\n raise ValueError(f'Invalid value for direction {self.direction}')\ncoords['xyz'.index(self.direction)] = self.coord\nx_map, y_map, z_map = (int(np.round(c)) for c in coord_transform(coords[0], coords[1], coords[2], np.linalg.inv(affine)))\nif self.... | <|body_start_0|>
coords = [0, 0, 0]
if self.direction not in ['x', 'y', 'z']:
raise ValueError(f'Invalid value for direction {self.direction}')
coords['xyz'.index(self.direction)] = self.coord
x_map, y_map, z_map = (int(np.round(c)) for c in coord_transform(coords[0], coords[... | An MPL axis-like object that displays a cut of 3D volumes. Parameters ---------- %(ax)s direction : {'x', 'y', 'z'} The directions of the view. coord : :obj:`float` The coordinate along the direction of the cut. | CutAxes | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CutAxes:
"""An MPL axis-like object that displays a cut of 3D volumes. Parameters ---------- %(ax)s direction : {'x', 'y', 'z'} The directions of the view. coord : :obj:`float` The coordinate along the direction of the cut."""
def transform_to_2d(self, data, affine):
"""Cut the 3D vo... | stack_v2_sparse_classes_75kplus_train_002250 | 21,879 | permissive | [
{
"docstring": "Cut the 3D volume into a 2D slice. Parameters ---------- data : 3D :class:`~numpy.ndarray` The 3D volume to cut. affine : 4x4 :class:`~numpy.ndarray` The affine of the volume.",
"name": "transform_to_2d",
"signature": "def transform_to_2d(self, data, affine)"
},
{
"docstring": "D... | 2 | stack_v2_sparse_classes_30k_train_024536 | Implement the Python class `CutAxes` described below.
Class description:
An MPL axis-like object that displays a cut of 3D volumes. Parameters ---------- %(ax)s direction : {'x', 'y', 'z'} The directions of the view. coord : :obj:`float` The coordinate along the direction of the cut.
Method signatures and docstrings:... | Implement the Python class `CutAxes` described below.
Class description:
An MPL axis-like object that displays a cut of 3D volumes. Parameters ---------- %(ax)s direction : {'x', 'y', 'z'} The directions of the view. coord : :obj:`float` The coordinate along the direction of the cut.
Method signatures and docstrings:... | f0852e127b620a64af0a1ce02282106ce6f068ba | <|skeleton|>
class CutAxes:
"""An MPL axis-like object that displays a cut of 3D volumes. Parameters ---------- %(ax)s direction : {'x', 'y', 'z'} The directions of the view. coord : :obj:`float` The coordinate along the direction of the cut."""
def transform_to_2d(self, data, affine):
"""Cut the 3D vo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CutAxes:
"""An MPL axis-like object that displays a cut of 3D volumes. Parameters ---------- %(ax)s direction : {'x', 'y', 'z'} The directions of the view. coord : :obj:`float` The coordinate along the direction of the cut."""
def transform_to_2d(self, data, affine):
"""Cut the 3D volume into a 2... | the_stack_v2_python_sparse | nilearn/plotting/displays/_axes.py | nilearn/nilearn | train | 1,049 |
a3bd30115c1f70a03f896f87c8c555995b579e64 | [
"if static_type not in STATIC_MAPPER:\n raise InvalidRouterStatic('invalid static type[%s]' % static_type)\nclazz = STATIC_MAPPER[static_type]\nkw = clazz.extract(kw)\ninst = clazz(**kw)\ninst.router_static_id = router_static_id\nreturn inst",
"data = json.loads(string)\nif isinstance(data, dict):\n return ... | <|body_start_0|>
if static_type not in STATIC_MAPPER:
raise InvalidRouterStatic('invalid static type[%s]' % static_type)
clazz = STATIC_MAPPER[static_type]
kw = clazz.extract(kw)
inst = clazz(**kw)
inst.router_static_id = router_static_id
return inst
<|end_bod... | Use this factory to facilitate to create router static Example: static = RouterStaticFactory.create( RouterStaticFactory.TYPE_PORT_FORWARDING, src_port=80, dst_ip="192.168.0.2", dst_port=80, protocol="tcp", ) statics = [static.to_json()] conn.add_router_statics(router_id, statics) | RouterStaticFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouterStaticFactory:
"""Use this factory to facilitate to create router static Example: static = RouterStaticFactory.create( RouterStaticFactory.TYPE_PORT_FORWARDING, src_port=80, dst_ip="192.168.0.2", dst_port=80, protocol="tcp", ) statics = [static.to_json()] conn.add_router_statics(router_id, ... | stack_v2_sparse_classes_75kplus_train_002251 | 12,301 | permissive | [
{
"docstring": "Create router static.",
"name": "create",
"signature": "def create(cls, static_type, router_static_id='', **kw)"
},
{
"docstring": "Create router static from json formatted string.",
"name": "create_from_string",
"signature": "def create_from_string(cls, string)"
}
] | 2 | null | Implement the Python class `RouterStaticFactory` described below.
Class description:
Use this factory to facilitate to create router static Example: static = RouterStaticFactory.create( RouterStaticFactory.TYPE_PORT_FORWARDING, src_port=80, dst_ip="192.168.0.2", dst_port=80, protocol="tcp", ) statics = [static.to_json... | Implement the Python class `RouterStaticFactory` described below.
Class description:
Use this factory to facilitate to create router static Example: static = RouterStaticFactory.create( RouterStaticFactory.TYPE_PORT_FORWARDING, src_port=80, dst_ip="192.168.0.2", dst_port=80, protocol="tcp", ) statics = [static.to_json... | 70992bf676983a0b1a5e9c80b453dec4ea0c2370 | <|skeleton|>
class RouterStaticFactory:
"""Use this factory to facilitate to create router static Example: static = RouterStaticFactory.create( RouterStaticFactory.TYPE_PORT_FORWARDING, src_port=80, dst_ip="192.168.0.2", dst_port=80, protocol="tcp", ) statics = [static.to_json()] conn.add_router_statics(router_id, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RouterStaticFactory:
"""Use this factory to facilitate to create router static Example: static = RouterStaticFactory.create( RouterStaticFactory.TYPE_PORT_FORWARDING, src_port=80, dst_ip="192.168.0.2", dst_port=80, protocol="tcp", ) statics = [static.to_json()] conn.add_router_statics(router_id, statics)"""
... | the_stack_v2_python_sparse | qingcloud/iaas/router_static.py | yunify/qingcloud-sdk-python | train | 56 |
126771773b18aeaeee6fc47592d43ccbc9344cf3 | [
"super().save_model(request, obj, form, change)\nfrom celery_tasks.tasks import generate_static_index_html\ngenerate_static_index_html.delay()\ncache.delete('index_page_data')",
"super().delete_model(request, obj)\nfrom celery_tasks.tasks import generate_static_index_html\ngenerate_static_index_html.delay()\ncach... | <|body_start_0|>
super().save_model(request, obj, form, change)
from celery_tasks.tasks import generate_static_index_html
generate_static_index_html.delay()
cache.delete('index_page_data')
<|end_body_0|>
<|body_start_1|>
super().delete_model(request, obj)
from celery_tas... | BaseModelAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseModelAdmin:
def save_model(self, request, obj, form, change):
"""向表中添加数据,或者 更新 表中的数据时,调用该方法"""
<|body_0|>
def delete_model(self, request, obj):
"""删除表中的数据时,调用该方法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().save_model(request, obj, fo... | stack_v2_sparse_classes_75kplus_train_002252 | 3,109 | no_license | [
{
"docstring": "向表中添加数据,或者 更新 表中的数据时,调用该方法",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "删除表中的数据时,调用该方法",
"name": "delete_model",
"signature": "def delete_model(self, request, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005639 | Implement the Python class `BaseModelAdmin` described below.
Class description:
Implement the BaseModelAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 向表中添加数据,或者 更新 表中的数据时,调用该方法
- def delete_model(self, request, obj): 删除表中的数据时,调用该方法 | Implement the Python class `BaseModelAdmin` described below.
Class description:
Implement the BaseModelAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 向表中添加数据,或者 更新 表中的数据时,调用该方法
- def delete_model(self, request, obj): 删除表中的数据时,调用该方法
<|skeleton|>
class BaseModelAdmin... | 6fca25416412603c0952c3fcf931f71acf0f9606 | <|skeleton|>
class BaseModelAdmin:
def save_model(self, request, obj, form, change):
"""向表中添加数据,或者 更新 表中的数据时,调用该方法"""
<|body_0|>
def delete_model(self, request, obj):
"""删除表中的数据时,调用该方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseModelAdmin:
def save_model(self, request, obj, form, change):
"""向表中添加数据,或者 更新 表中的数据时,调用该方法"""
super().save_model(request, obj, form, change)
from celery_tasks.tasks import generate_static_index_html
generate_static_index_html.delay()
cache.delete('index_page_data')... | the_stack_v2_python_sparse | apps/goods/admin.py | uhuo/dailyfresh | train | 0 | |
930fb6c2f8ea7f5baa64809512b6ec74367f41e8 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('adsouza_mcsmocha', 'adsouza_mcsmocha')\nurl = 'https://data.boston.gov/export/c8c/54c/c8c54c49-3097-40fc-b3f2-c9508b8d393a.json'\nresponse = urllib.request.urlopen(url).read().decode('utf-8')\nresponse =... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('adsouza_mcsmocha', 'adsouza_mcsmocha')
url = 'https://data.boston.gov/export/c8c/54c/c8c54c49-3097-40fc-b3f2-c9508b8d393a.json'
response = urllib.... | requestBigBelly | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class requestBigBelly:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythi... | stack_v2_sparse_classes_75kplus_train_002253 | 3,717 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_005266 | Implement the Python class `requestBigBelly` described below.
Class description:
Implement the requestBigBelly class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=Non... | Implement the Python class `requestBigBelly` described below.
Class description:
Implement the requestBigBelly class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=Non... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class requestBigBelly:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class requestBigBelly:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('adsouza_mcsmocha', 'adsouza_mcsmoch... | the_stack_v2_python_sparse | adsouza_mcsmocha/requestBigBelly.py | ROODAY/course-2017-fal-proj | train | 3 | |
bf1b0bda59cd12f84b4b2d773bf8c8b5572cf2db | [
"farthest_index_possible = 0\nfor i, n in enumerate(nums):\n if i > farthest_index_possible:\n return False\n farthest_index_possible = max(farthest_index_possible, i + n)\nreturn True",
"goal = len(nums) - 1\nfor i in range(len(nums))[::-1]:\n if i + nums[i] >= goal:\n goal = i\nreturn goa... | <|body_start_0|>
farthest_index_possible = 0
for i, n in enumerate(nums):
if i > farthest_index_possible:
return False
farthest_index_possible = max(farthest_index_possible, i + n)
return True
<|end_body_0|>
<|body_start_1|>
goal = len(nums) - 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def can_jump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def can_jump2(self, nums):
"""going back version"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
farthest_index_possible = 0
for i, n in enumerate(nums):... | stack_v2_sparse_classes_75kplus_train_002254 | 608 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "can_jump",
"signature": "def can_jump(self, nums)"
},
{
"docstring": "going back version",
"name": "can_jump2",
"signature": "def can_jump2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039477 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def can_jump(self, nums): :type nums: List[int] :rtype: bool
- def can_jump2(self, nums): going back version | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def can_jump(self, nums): :type nums: List[int] :rtype: bool
- def can_jump2(self, nums): going back version
<|skeleton|>
class Solution:
def can_jump(self, nums):
... | 2b7f4a9fefbfd358f8ff31362d60e2007641ca29 | <|skeleton|>
class Solution:
def can_jump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def can_jump2(self, nums):
"""going back version"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def can_jump(self, nums):
""":type nums: List[int] :rtype: bool"""
farthest_index_possible = 0
for i, n in enumerate(nums):
if i > farthest_index_possible:
return False
farthest_index_possible = max(farthest_index_possible, i + n)
... | the_stack_v2_python_sparse | Week_03/G20190343020166/LeetCode_55_0166.py | algorithm005-class01/algorithm005-class01 | train | 27 | |
7748e8e74819b573c6c9de4855844b0e7770f92d | [
"for field_axes in self.field_axes.itervalues():\n if len(field_axes) != 0:\n raise ce.DataError('Maps can only have scalar fields.')\nbase_data.BaseData.verify(self)",
"if self.field.has_key('CRPIX3') and self.field.has_key('CDELT3') and self.field.has_key('CRVAL3'):\n self.freq = (sp.arange(self.di... | <|body_start_0|>
for field_axes in self.field_axes.itervalues():
if len(field_axes) != 0:
raise ce.DataError('Maps can only have scalar fields.')
base_data.BaseData.verify(self)
<|end_body_0|>
<|body_start_1|>
if self.field.has_key('CRPIX3') and self.field.has_key('C... | This class holds data from a map. | DataMap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataMap:
"""This class holds data from a map."""
def verify(self):
"""Mostly the same as BaseData.verify, but with added checks."""
<|body_0|>
def calc_axes(self):
"""Calculates that frequency, lat and long axes. These are not stored as fields as all fields have ... | stack_v2_sparse_classes_75kplus_train_002255 | 1,978 | no_license | [
{
"docstring": "Mostly the same as BaseData.verify, but with added checks.",
"name": "verify",
"signature": "def verify(self)"
},
{
"docstring": "Calculates that frequency, lat and long axes. These are not stored as fields as all fields have to be writable to the fits file.",
"name": "calc_a... | 2 | null | Implement the Python class `DataMap` described below.
Class description:
This class holds data from a map.
Method signatures and docstrings:
- def verify(self): Mostly the same as BaseData.verify, but with added checks.
- def calc_axes(self): Calculates that frequency, lat and long axes. These are not stored as field... | Implement the Python class `DataMap` described below.
Class description:
This class holds data from a map.
Method signatures and docstrings:
- def verify(self): Mostly the same as BaseData.verify, but with added checks.
- def calc_axes(self): Calculates that frequency, lat and long axes. These are not stored as field... | 0bc00624a37029445111f933e7470f05f76459f8 | <|skeleton|>
class DataMap:
"""This class holds data from a map."""
def verify(self):
"""Mostly the same as BaseData.verify, but with added checks."""
<|body_0|>
def calc_axes(self):
"""Calculates that frequency, lat and long axes. These are not stored as fields as all fields have ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataMap:
"""This class holds data from a map."""
def verify(self):
"""Mostly the same as BaseData.verify, but with added checks."""
for field_axes in self.field_axes.itervalues():
if len(field_axes) != 0:
raise ce.DataError('Maps can only have scalar fields.')
... | the_stack_v2_python_sparse | core/data_map.py | YichaoLi/project_TL | train | 0 |
5ae1e46d0b45d8204e8190d05d8b30ef3657fe9f | [
"self.latitude = lat\nself.longitude = lon\nself.altitude = alt\nself._swiss_coords_done = False\nself.ch_y = None\nself.ch_x = None\nself.ch_alt = None\nself.traj_assigned = False\nself.elevation_vec = None\nself.azimuth_vec = None\nself.range_vec = None\nself._velocity_vecs_assigned = False\nself.v_abs = None\nse... | <|body_start_0|>
self.latitude = lat
self.longitude = lon
self.altitude = alt
self._swiss_coords_done = False
self.ch_y = None
self.ch_x = None
self.ch_alt = None
self.traj_assigned = False
self.elevation_vec = None
self.azimuth_vec = None
... | A class for holding the trajectory data assigned to a radar. Attributes ---------- latitude : float WGS84 radar latitude [deg] longitude : float WGS84 radar longitude [deg] altitude : float radar altitude [m] (non WGS84) ch_y, ch_x, ch_alt : float radar coordinates in swiss CH1903 coordinates elevation_vec : float list... | _Radar_Trajectory | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Radar_Trajectory:
"""A class for holding the trajectory data assigned to a radar. Attributes ---------- latitude : float WGS84 radar latitude [deg] longitude : float WGS84 radar longitude [deg] altitude : float radar altitude [m] (non WGS84) ch_y, ch_x, ch_alt : float radar coordinates in swiss ... | stack_v2_sparse_classes_75kplus_train_002256 | 24,155 | permissive | [
{
"docstring": "Initalize the object. Parameters ---------- lat, lon , alt : radar location coordinates nsamps : number of samples",
"name": "__init__",
"signature": "def __init__(self, lat, lon, alt)"
},
{
"docstring": "Check if the given coordinates are the same. Parameters ---------- lat, lon... | 5 | stack_v2_sparse_classes_30k_train_039233 | Implement the Python class `_Radar_Trajectory` described below.
Class description:
A class for holding the trajectory data assigned to a radar. Attributes ---------- latitude : float WGS84 radar latitude [deg] longitude : float WGS84 radar longitude [deg] altitude : float radar altitude [m] (non WGS84) ch_y, ch_x, ch_... | Implement the Python class `_Radar_Trajectory` described below.
Class description:
A class for holding the trajectory data assigned to a radar. Attributes ---------- latitude : float WGS84 radar latitude [deg] longitude : float WGS84 radar longitude [deg] altitude : float radar altitude [m] (non WGS84) ch_y, ch_x, ch_... | c3ed17103947ea4a54cfdd72a2308792e1a22eb0 | <|skeleton|>
class _Radar_Trajectory:
"""A class for holding the trajectory data assigned to a radar. Attributes ---------- latitude : float WGS84 radar latitude [deg] longitude : float WGS84 radar longitude [deg] altitude : float radar altitude [m] (non WGS84) ch_y, ch_x, ch_alt : float radar coordinates in swiss ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Radar_Trajectory:
"""A class for holding the trajectory data assigned to a radar. Attributes ---------- latitude : float WGS84 radar latitude [deg] longitude : float WGS84 radar longitude [deg] altitude : float radar altitude [m] (non WGS84) ch_y, ch_x, ch_alt : float radar coordinates in swiss CH1903 coordi... | the_stack_v2_python_sparse | src/pyrad_proc/pyrad/io/trajectory.py | wolfidan/pyrad | train | 0 |
b2fbdc572174b4974b0cc4bfee1c8f6203e9fe5d | [
"IPAddress.__init__(self)\nif not self.IsValid(address):\n raise errors.IPAddressError('IPv6 Address [%s] invalid' % address)\nself.address = address",
"doublecolons = address.count('::')\nassert not doublecolons > 1\nif doublecolons == 1:\n parts = []\n twoparts = address.split('::')\n sep = len(twop... | <|body_start_0|>
IPAddress.__init__(self)
if not self.IsValid(address):
raise errors.IPAddressError('IPv6 Address [%s] invalid' % address)
self.address = address
<|end_body_0|>
<|body_start_1|>
doublecolons = address.count('::')
assert not doublecolons > 1
if... | IPv6 address class. | IP6Address | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IP6Address:
"""IPv6 address class."""
def __init__(self, address):
"""Constructor for IPv6 address. @type address: str @param address: IP address @raises errors.IPAddressError: if address invalid"""
<|body_0|>
def _GetIPIntFromString(address):
"""Get integer valu... | stack_v2_sparse_classes_75kplus_train_002257 | 20,645 | permissive | [
{
"docstring": "Constructor for IPv6 address. @type address: str @param address: IP address @raises errors.IPAddressError: if address invalid",
"name": "__init__",
"signature": "def __init__(self, address)"
},
{
"docstring": "Get integer value of IPv6 address. @type address: str @param address: ... | 2 | stack_v2_sparse_classes_30k_train_047408 | Implement the Python class `IP6Address` described below.
Class description:
IPv6 address class.
Method signatures and docstrings:
- def __init__(self, address): Constructor for IPv6 address. @type address: str @param address: IP address @raises errors.IPAddressError: if address invalid
- def _GetIPIntFromString(addre... | Implement the Python class `IP6Address` described below.
Class description:
IPv6 address class.
Method signatures and docstrings:
- def __init__(self, address): Constructor for IPv6 address. @type address: str @param address: IP address @raises errors.IPAddressError: if address invalid
- def _GetIPIntFromString(addre... | 456ea285a7583183c2c8e5bcffe9006ec8a9d658 | <|skeleton|>
class IP6Address:
"""IPv6 address class."""
def __init__(self, address):
"""Constructor for IPv6 address. @type address: str @param address: IP address @raises errors.IPAddressError: if address invalid"""
<|body_0|>
def _GetIPIntFromString(address):
"""Get integer valu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IP6Address:
"""IPv6 address class."""
def __init__(self, address):
"""Constructor for IPv6 address. @type address: str @param address: IP address @raises errors.IPAddressError: if address invalid"""
IPAddress.__init__(self)
if not self.IsValid(address):
raise errors.IP... | the_stack_v2_python_sparse | lib/netutils.py | ganeti/ganeti | train | 465 |
3e7795302d1f23482fa8a82e33dc816fadb7c2fa | [
"super().__init__()\nself.conv_block_1 = ConvBnRelu(num_input_channels, num_output_channels, kernel_size=kernel_size, strides=strides, activation='None', use_bias=use_bias, dilation_rate=dilation_rate, do_batchnorm=True)\nself.conv_block_2 = ConvBnRelu(num_output_channels, num_output_channels, kernel_size=kernel_si... | <|body_start_0|>
super().__init__()
self.conv_block_1 = ConvBnRelu(num_input_channels, num_output_channels, kernel_size=kernel_size, strides=strides, activation='None', use_bias=use_bias, dilation_rate=dilation_rate, do_batchnorm=True)
self.conv_block_2 = ConvBnRelu(num_output_channels, num_outp... | Residual Convolution block. Args: num_input_channels (int): Number of channels in input. num_output_channels (int): Number of channels in output. kernel_size (int): Size of the kernel in all convolution layers. strides (int): Size of the stride in all convolution layers. use_bias (bool): Whether to use bias in the conv... | ResidualConv | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualConv:
"""Residual Convolution block. Args: num_input_channels (int): Number of channels in input. num_output_channels (int): Number of channels in output. kernel_size (int): Size of the kernel in all convolution layers. strides (int): Size of the stride in all convolution layers. use_bias... | stack_v2_sparse_classes_75kplus_train_002258 | 21,033 | permissive | [
{
"docstring": "Initialize :class:`ResidualConv`.",
"name": "__init__",
"signature": "def __init__(self, num_input_channels: int, num_output_channels: int=32, kernel_size: tuple[int, int] | np.ndarray=(3, 3), strides: tuple[int, int] | np.ndarray=(1, 1), dilation_rate: tuple[int, int] | np.ndarray=(1, 1... | 2 | stack_v2_sparse_classes_30k_train_052306 | Implement the Python class `ResidualConv` described below.
Class description:
Residual Convolution block. Args: num_input_channels (int): Number of channels in input. num_output_channels (int): Number of channels in output. kernel_size (int): Size of the kernel in all convolution layers. strides (int): Size of the str... | Implement the Python class `ResidualConv` described below.
Class description:
Residual Convolution block. Args: num_input_channels (int): Number of channels in input. num_output_channels (int): Number of channels in output. kernel_size (int): Size of the kernel in all convolution layers. strides (int): Size of the str... | f26387f46f675a7b9a8a48c95dad26e819229f2f | <|skeleton|>
class ResidualConv:
"""Residual Convolution block. Args: num_input_channels (int): Number of channels in input. num_output_channels (int): Number of channels in output. kernel_size (int): Size of the kernel in all convolution layers. strides (int): Size of the stride in all convolution layers. use_bias... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResidualConv:
"""Residual Convolution block. Args: num_input_channels (int): Number of channels in input. num_output_channels (int): Number of channels in output. kernel_size (int): Size of the kernel in all convolution layers. strides (int): Size of the stride in all convolution layers. use_bias (bool): Whet... | the_stack_v2_python_sparse | tiatoolbox/models/architecture/nuclick.py | TissueImageAnalytics/tiatoolbox | train | 222 |
05e3f156ebc537a3fa03dc0c8c32802d4954f670 | [
"if 'case_name' not in kwargs:\n kwargs['case_name'] = 'rally_jobs'\nsuper().__init__(**kwargs)\nself.task_file = os.path.join(self.rally_dir, 'rally_jobs.yaml')\nself.task_yaml = None",
"super().prepare_run(**kwargs)\nwith open(os.path.join(self.rally_dir, 'rally_jobs.yaml'), 'r', encoding='utf-8') as task_fi... | <|body_start_0|>
if 'case_name' not in kwargs:
kwargs['case_name'] = 'rally_jobs'
super().__init__(**kwargs)
self.task_file = os.path.join(self.rally_dir, 'rally_jobs.yaml')
self.task_yaml = None
<|end_body_0|>
<|body_start_1|>
super().prepare_run(**kwargs)
w... | Rally OpenStack CI testcase implementation. | RallyJobs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RallyJobs:
"""Rally OpenStack CI testcase implementation."""
def __init__(self, **kwargs):
"""Initialize RallyJobs object."""
<|body_0|>
def prepare_run(self, **kwargs):
"""Create resources needed by test scenarios."""
<|body_1|>
def apply_blacklist(... | stack_v2_sparse_classes_75kplus_train_002259 | 32,891 | permissive | [
{
"docstring": "Initialize RallyJobs object.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Create resources needed by test scenarios.",
"name": "prepare_run",
"signature": "def prepare_run(self, **kwargs)"
},
{
"docstring": "Apply blacklist.... | 5 | stack_v2_sparse_classes_30k_train_029670 | Implement the Python class `RallyJobs` described below.
Class description:
Rally OpenStack CI testcase implementation.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialize RallyJobs object.
- def prepare_run(self, **kwargs): Create resources needed by test scenarios.
- def apply_blacklist(self... | Implement the Python class `RallyJobs` described below.
Class description:
Rally OpenStack CI testcase implementation.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialize RallyJobs object.
- def prepare_run(self, **kwargs): Create resources needed by test scenarios.
- def apply_blacklist(self... | 27107d1f871dd7eb9eeab5f7c51086f3ef7e2ebe | <|skeleton|>
class RallyJobs:
"""Rally OpenStack CI testcase implementation."""
def __init__(self, **kwargs):
"""Initialize RallyJobs object."""
<|body_0|>
def prepare_run(self, **kwargs):
"""Create resources needed by test scenarios."""
<|body_1|>
def apply_blacklist(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RallyJobs:
"""Rally OpenStack CI testcase implementation."""
def __init__(self, **kwargs):
"""Initialize RallyJobs object."""
if 'case_name' not in kwargs:
kwargs['case_name'] = 'rally_jobs'
super().__init__(**kwargs)
self.task_file = os.path.join(self.rally_di... | the_stack_v2_python_sparse | functest/opnfv_tests/openstack/rally/rally.py | opnfv/functest | train | 23 |
6e50d615bd3d02f876a01ac7073ea94299f2d57e | [
"self.fealist = fealist\nself.dview = dview\nself.alignments = alignments\nself.callback = callback\nself.dir_path = tmpdir\nself.epochs = int(train_args.get('epochs', 1))\nself.initial_pruning = int(train_args.get('initial_pruning_threshold', 500))\nself.pruning = int(train_args.get('pruning_threshold', 100))\nwit... | <|body_start_0|>
self.fealist = fealist
self.dview = dview
self.alignments = alignments
self.callback = callback
self.dir_path = tmpdir
self.epochs = int(train_args.get('epochs', 1))
self.initial_pruning = int(train_args.get('initial_pruning_threshold', 500))
... | Standard mean-field Variational Bayes training of the phone loop model. | StandardVariationalBayes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StandardVariationalBayes:
"""Standard mean-field Variational Bayes training of the phone loop model."""
def __init__(self, fealist, dview, train_args, tmpdir, alignments=None, callback=None):
"""Parameters ---------- fealist : list List of features file. dview : object Remote client ... | stack_v2_sparse_classes_75kplus_train_002260 | 15,009 | no_license | [
{
"docstring": "Parameters ---------- fealist : list List of features file. dview : object Remote client objects to parallelize the training. train_args : dict Training specific arguments. tmpdir : str Path to the directory where to store temporary results. alignments : MLF data Unit level alignments (optional)... | 3 | null | Implement the Python class `StandardVariationalBayes` described below.
Class description:
Standard mean-field Variational Bayes training of the phone loop model.
Method signatures and docstrings:
- def __init__(self, fealist, dview, train_args, tmpdir, alignments=None, callback=None): Parameters ---------- fealist : ... | Implement the Python class `StandardVariationalBayes` described below.
Class description:
Standard mean-field Variational Bayes training of the phone loop model.
Method signatures and docstrings:
- def __init__(self, fealist, dview, train_args, tmpdir, alignments=None, callback=None): Parameters ---------- fealist : ... | 936a27dfb45446868eeb545210d554012a945361 | <|skeleton|>
class StandardVariationalBayes:
"""Standard mean-field Variational Bayes training of the phone loop model."""
def __init__(self, fealist, dview, train_args, tmpdir, alignments=None, callback=None):
"""Parameters ---------- fealist : list List of features file. dview : object Remote client ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StandardVariationalBayes:
"""Standard mean-field Variational Bayes training of the phone loop model."""
def __init__(self, fealist, dview, train_args, tmpdir, alignments=None, callback=None):
"""Parameters ---------- fealist : list List of features file. dview : object Remote client objects to pa... | the_stack_v2_python_sparse | code/amdtk/build/lib/amdtk/training/optimizer.py | esteng/ULD | train | 0 |
74b76d5f3a141a0d90afeecd51eefe633230f1dd | [
"self.degree = degree\nself.gamma = gamma\nself.coef0 = coef0\nif degree <= 0:\n raise ValueError('KPoly needs positive degree')\nif not np.allclose(degree, int(degree)):\n raise ValueError('KPoly needs integral degree')",
"dot = np.dot(X, Y.T)\ngamma = 1 / X.shape[1] if self.gamma is None else self.gamma\n... | <|body_start_0|>
self.degree = degree
self.gamma = gamma
self.coef0 = coef0
if degree <= 0:
raise ValueError('KPoly needs positive degree')
if not np.allclose(degree, int(degree)):
raise ValueError('KPoly needs integral degree')
<|end_body_0|>
<|body_star... | KPoly | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KPoly:
def __init__(self, degree=3, gamma=None, coef0=1):
"""Polynomial kernel (gamma X^T Y + coef0)^degree degree: default 3 gamma: default 1/dim coef0: float, default 1"""
<|body_0|>
def eval(self, X, Y):
"""Evaluate the kernel on data X and Y X: nx x d where each ... | stack_v2_sparse_classes_75kplus_train_002261 | 22,155 | permissive | [
{
"docstring": "Polynomial kernel (gamma X^T Y + coef0)^degree degree: default 3 gamma: default 1/dim coef0: float, default 1",
"name": "__init__",
"signature": "def __init__(self, degree=3, gamma=None, coef0=1)"
},
{
"docstring": "Evaluate the kernel on data X and Y X: nx x d where each row rep... | 6 | stack_v2_sparse_classes_30k_train_024592 | Implement the Python class `KPoly` described below.
Class description:
Implement the KPoly class.
Method signatures and docstrings:
- def __init__(self, degree=3, gamma=None, coef0=1): Polynomial kernel (gamma X^T Y + coef0)^degree degree: default 3 gamma: default 1/dim coef0: float, default 1
- def eval(self, X, Y):... | Implement the Python class `KPoly` described below.
Class description:
Implement the KPoly class.
Method signatures and docstrings:
- def __init__(self, degree=3, gamma=None, coef0=1): Polynomial kernel (gamma X^T Y + coef0)^degree degree: default 3 gamma: default 1/dim coef0: float, default 1
- def eval(self, X, Y):... | 039a95ed9d8062e283da6bd051b7161a190b4876 | <|skeleton|>
class KPoly:
def __init__(self, degree=3, gamma=None, coef0=1):
"""Polynomial kernel (gamma X^T Y + coef0)^degree degree: default 3 gamma: default 1/dim coef0: float, default 1"""
<|body_0|>
def eval(self, X, Y):
"""Evaluate the kernel on data X and Y X: nx x d where each ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KPoly:
def __init__(self, degree=3, gamma=None, coef0=1):
"""Polynomial kernel (gamma X^T Y + coef0)^degree degree: default 3 gamma: default 1/dim coef0: float, default 1"""
self.degree = degree
self.gamma = gamma
self.coef0 = coef0
if degree <= 0:
raise Val... | the_stack_v2_python_sparse | kgof/kernel.py | wittawatj/kernel-gof | train | 69 | |
9d9a710003f6c1d85d64fb7af652826307c50ef9 | [
"if isinstance(value, collections.abc.Iterable):\n return numpy.ones_like(value, dtype=numpy.bool_)\nelse:\n return True",
"data = None if data is None else numpy.array(data, copy=False)\nif data is None or data.size == 0:\n return self.DEFAULT_RANGE\nif mode == 'minmax':\n vmin, vmax = self.autoscale... | <|body_start_0|>
if isinstance(value, collections.abc.Iterable):
return numpy.ones_like(value, dtype=numpy.bool_)
else:
return True
<|end_body_0|>
<|body_start_1|>
data = None if data is None else numpy.array(data, copy=False)
if data is None or data.size == 0:
... | Colormap normalization mix-in class | _NormalizationMixIn | [
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _NormalizationMixIn:
"""Colormap normalization mix-in class"""
def is_valid(self, value):
"""Check if a value is in the valid range for this normalization. Override in subclass. :param Union[float,numpy.ndarray] value: :rtype: Union[bool,numpy.ndarray]"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus_train_002262 | 16,802 | permissive | [
{
"docstring": "Check if a value is in the valid range for this normalization. Override in subclass. :param Union[float,numpy.ndarray] value: :rtype: Union[bool,numpy.ndarray]",
"name": "is_valid",
"signature": "def is_valid(self, value)"
},
{
"docstring": "Returns range for given data and autos... | 4 | stack_v2_sparse_classes_30k_train_035689 | Implement the Python class `_NormalizationMixIn` described below.
Class description:
Colormap normalization mix-in class
Method signatures and docstrings:
- def is_valid(self, value): Check if a value is in the valid range for this normalization. Override in subclass. :param Union[float,numpy.ndarray] value: :rtype: ... | Implement the Python class `_NormalizationMixIn` described below.
Class description:
Colormap normalization mix-in class
Method signatures and docstrings:
- def is_valid(self, value): Check if a value is in the valid range for this normalization. Override in subclass. :param Union[float,numpy.ndarray] value: :rtype: ... | 5e33cb69afd2a8b1cfe3183282acdd8b34c1a74f | <|skeleton|>
class _NormalizationMixIn:
"""Colormap normalization mix-in class"""
def is_valid(self, value):
"""Check if a value is in the valid range for this normalization. Override in subclass. :param Union[float,numpy.ndarray] value: :rtype: Union[bool,numpy.ndarray]"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _NormalizationMixIn:
"""Colormap normalization mix-in class"""
def is_valid(self, value):
"""Check if a value is in the valid range for this normalization. Override in subclass. :param Union[float,numpy.ndarray] value: :rtype: Union[bool,numpy.ndarray]"""
if isinstance(value, collections.... | the_stack_v2_python_sparse | src/silx/math/colormap.py | silx-kit/silx | train | 120 |
5d01544fb8bcde76c43635f24a7413ac13bc5d9f | [
"today = datetime.today()\nyear, month = (today.year, today.month)\ntry:\n limits = await Limit.get_user_limits(self.request.user_id)\n spendings = await Transaction.get_month_report(self.request.user_id, year, month)\nexcept DatabaseError as err:\n return make_response(success=False, message=str(err), htt... | <|body_start_0|>
today = datetime.today()
year, month = (today.year, today.month)
try:
limits = await Limit.get_user_limits(self.request.user_id)
spendings = await Transaction.get_month_report(self.request.user_id, year, month)
except DatabaseError as err:
... | Views to interact with budget limits. | BudgetLimitsView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BudgetLimitsView:
"""Views to interact with budget limits."""
async def get(self):
"""Retrieve user`s budget limits."""
<|body_0|>
async def post(self):
"""Create a new budget limit for user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
today... | stack_v2_sparse_classes_75kplus_train_002263 | 6,481 | permissive | [
{
"docstring": "Retrieve user`s budget limits.",
"name": "get",
"signature": "async def get(self)"
},
{
"docstring": "Create a new budget limit for user.",
"name": "post",
"signature": "async def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019195 | Implement the Python class `BudgetLimitsView` described below.
Class description:
Views to interact with budget limits.
Method signatures and docstrings:
- async def get(self): Retrieve user`s budget limits.
- async def post(self): Create a new budget limit for user. | Implement the Python class `BudgetLimitsView` described below.
Class description:
Views to interact with budget limits.
Method signatures and docstrings:
- async def get(self): Retrieve user`s budget limits.
- async def post(self): Create a new budget limit for user.
<|skeleton|>
class BudgetLimitsView:
"""Views... | 16b7154188f08b33f84d88caea217673cf989b2b | <|skeleton|>
class BudgetLimitsView:
"""Views to interact with budget limits."""
async def get(self):
"""Retrieve user`s budget limits."""
<|body_0|>
async def post(self):
"""Create a new budget limit for user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BudgetLimitsView:
"""Views to interact with budget limits."""
async def get(self):
"""Retrieve user`s budget limits."""
today = datetime.today()
year, month = (today.year, today.month)
try:
limits = await Limit.get_user_limits(self.request.user_id)
... | the_stack_v2_python_sparse | server/app/api/limit.py | SpentlessInc/spentless-server | train | 0 |
b71e1ee02deee6fe263cc290586238f3aeb003d8 | [
"try:\n con = ldap.open(settings.LDAP_SERVER, 389)\n user = User.objects.get(username=username)\nexcept Exception as e:\n user = None\nreturn user",
"try:\n return User.objects.get(pk=user_id)\nexcept User.DoesNotExist:\n return None"
] | <|body_start_0|>
try:
con = ldap.open(settings.LDAP_SERVER, 389)
user = User.objects.get(username=username)
except Exception as e:
user = None
return user
<|end_body_0|>
<|body_start_1|>
try:
return User.objects.get(pk=user_id)
exc... | Provides methods to authenticate against LDAP and get_user from the Auth plug-in. | LDAPBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LDAPBackend:
"""Provides methods to authenticate against LDAP and get_user from the Auth plug-in."""
def authenticate(self, username=None, password=None):
"""Authenticate against the LDAP server provided by settings.LDAP_SERVER. The LDAP server is assumed to listen to port 389."""
... | stack_v2_sparse_classes_75kplus_train_002264 | 1,753 | no_license | [
{
"docstring": "Authenticate against the LDAP server provided by settings.LDAP_SERVER. The LDAP server is assumed to listen to port 389.",
"name": "authenticate",
"signature": "def authenticate(self, username=None, password=None)"
},
{
"docstring": "Get user object from Auth.User.",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_043257 | Implement the Python class `LDAPBackend` described below.
Class description:
Provides methods to authenticate against LDAP and get_user from the Auth plug-in.
Method signatures and docstrings:
- def authenticate(self, username=None, password=None): Authenticate against the LDAP server provided by settings.LDAP_SERVER... | Implement the Python class `LDAPBackend` described below.
Class description:
Provides methods to authenticate against LDAP and get_user from the Auth plug-in.
Method signatures and docstrings:
- def authenticate(self, username=None, password=None): Authenticate against the LDAP server provided by settings.LDAP_SERVER... | 7a337e0e3a20180b9564de68ab22620dc9aa1a36 | <|skeleton|>
class LDAPBackend:
"""Provides methods to authenticate against LDAP and get_user from the Auth plug-in."""
def authenticate(self, username=None, password=None):
"""Authenticate against the LDAP server provided by settings.LDAP_SERVER. The LDAP server is assumed to listen to port 389."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LDAPBackend:
"""Provides methods to authenticate against LDAP and get_user from the Auth plug-in."""
def authenticate(self, username=None, password=None):
"""Authenticate against the LDAP server provided by settings.LDAP_SERVER. The LDAP server is assumed to listen to port 389."""
try:
... | the_stack_v2_python_sparse | project_management/access_control/authentication.py | raveena17/ILASM | train | 0 |
7ef910140a9d2f63ef34668f89c8462a3792b35d | [
"self.prefix_sums = []\nprefix_sum = 0\nfor weight in w:\n prefix_sum += weight\n self.prefix_sums.append(prefix_sum)\nself.total_sum = prefix_sum",
"target = self.total_sum * random()\nlow, high = (0, len(self.prefix_sums))\nwhile low < high:\n mid = low + (high - low) // 2\n if target > self.prefix_... | <|body_start_0|>
self.prefix_sums = []
prefix_sum = 0
for weight in w:
prefix_sum += weight
self.prefix_sums.append(prefix_sum)
self.total_sum = prefix_sum
<|end_body_0|>
<|body_start_1|>
target = self.total_sum * random()
low, high = (0, len(self... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w: List[int]):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self) -> int:
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.prefix_sums = []
prefix_sum = 0
for weight in w:
... | stack_v2_sparse_classes_75kplus_train_002265 | 4,170 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w: List[int])"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_test_000336 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w: List[int]): :type w: List[int]
- def pickIndex(self) -> int: :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w: List[int]): :type w: List[int]
- def pickIndex(self) -> int: :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w: List[int]):
""":ty... | 3c0943ee9b373e4297aa43a4813f0033c284a5b2 | <|skeleton|>
class Solution:
def __init__(self, w: List[int]):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self) -> int:
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, w: List[int]):
""":type w: List[int]"""
self.prefix_sums = []
prefix_sum = 0
for weight in w:
prefix_sum += weight
self.prefix_sums.append(prefix_sum)
self.total_sum = prefix_sum
def pickIndex(self) -> int:
... | the_stack_v2_python_sparse | 528.random-pick-with-weight.py | Joecth/leetcode_3rd_vscode | train | 0 | |
0d979c8243b110a1c7888912e8d3140187df2f4b | [
"from courses.serializers import CourseSerializer\nmodel_class = instance.product.content_type.model_class()\nif model_class is CourseRun:\n return [CourseSerializer(instance.product.content_object.course, context={**self.context, 'filter_products': True}).data]\nelif model_class is Program:\n courses = Cours... | <|body_start_0|>
from courses.serializers import CourseSerializer
model_class = instance.product.content_type.model_class()
if model_class is CourseRun:
return [CourseSerializer(instance.product.content_object.course, context={**self.context, 'filter_products': True}).data]
e... | ProductVersion serializer for viewing/updating items in basket | FullProductVersionSerializer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullProductVersionSerializer:
"""ProductVersion serializer for viewing/updating items in basket"""
def get_courses(self, instance):
"""Return the courses in the product"""
<|body_0|>
def get_thumbnail_url(self, instance):
"""Return the thumbnail for the courserun... | stack_v2_sparse_classes_75kplus_train_002266 | 40,158 | permissive | [
{
"docstring": "Return the courses in the product",
"name": "get_courses",
"signature": "def get_courses(self, instance)"
},
{
"docstring": "Return the thumbnail for the courserun or program",
"name": "get_thumbnail_url",
"signature": "def get_thumbnail_url(self, instance)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_033318 | Implement the Python class `FullProductVersionSerializer` described below.
Class description:
ProductVersion serializer for viewing/updating items in basket
Method signatures and docstrings:
- def get_courses(self, instance): Return the courses in the product
- def get_thumbnail_url(self, instance): Return the thumbn... | Implement the Python class `FullProductVersionSerializer` described below.
Class description:
ProductVersion serializer for viewing/updating items in basket
Method signatures and docstrings:
- def get_courses(self, instance): Return the courses in the product
- def get_thumbnail_url(self, instance): Return the thumbn... | c5d9cda4e1ed87463da74d7956f1e1f9258f365c | <|skeleton|>
class FullProductVersionSerializer:
"""ProductVersion serializer for viewing/updating items in basket"""
def get_courses(self, instance):
"""Return the courses in the product"""
<|body_0|>
def get_thumbnail_url(self, instance):
"""Return the thumbnail for the courserun... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FullProductVersionSerializer:
"""ProductVersion serializer for viewing/updating items in basket"""
def get_courses(self, instance):
"""Return the courses in the product"""
from courses.serializers import CourseSerializer
model_class = instance.product.content_type.model_class()
... | the_stack_v2_python_sparse | ecommerce/serializers.py | mitodl/mitxpro | train | 12 |
8fa945357748d40d4b0f6fd00339ef2fa7ffec11 | [
"queryset = Batch.objects.filter(id=batch_pk)\nbatch = get_object_or_404(queryset)\nserializer = self.serializer_class(instance=batch)\nreturn Response(serializer.data)",
"queryset = Batch.objects.filter(id=batch_pk)\nbatch = get_object_or_404(queryset)\nserializer = self.serializer_class(instance=batch, data=req... | <|body_start_0|>
queryset = Batch.objects.filter(id=batch_pk)
batch = get_object_or_404(queryset)
serializer = self.serializer_class(instance=batch)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
queryset = Batch.objects.filter(id=batch_pk)
batch = get_... | get: Retrieve the current user and group permissions. post: Adds additional users or groups to permissions. put: Replaces user and group permissions. | BatchCustomPermissionsViewSet | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchCustomPermissionsViewSet:
"""get: Retrieve the current user and group permissions. post: Adds additional users or groups to permissions. put: Replaces user and group permissions."""
def list(self, request, batch_pk=None):
"""Retrieve the current user and group permissions."""
... | stack_v2_sparse_classes_75kplus_train_002267 | 11,044 | permissive | [
{
"docstring": "Retrieve the current user and group permissions.",
"name": "list",
"signature": "def list(self, request, batch_pk=None)"
},
{
"docstring": "Adds additional users or groups to permissions.",
"name": "create",
"signature": "def create(self, request, batch_pk=None)"
},
{... | 3 | null | Implement the Python class `BatchCustomPermissionsViewSet` described below.
Class description:
get: Retrieve the current user and group permissions. post: Adds additional users or groups to permissions. put: Replaces user and group permissions.
Method signatures and docstrings:
- def list(self, request, batch_pk=None... | Implement the Python class `BatchCustomPermissionsViewSet` described below.
Class description:
get: Retrieve the current user and group permissions. post: Adds additional users or groups to permissions. put: Replaces user and group permissions.
Method signatures and docstrings:
- def list(self, request, batch_pk=None... | 935f63c94ec4d1e2fa507c8e187fa86e96fad82b | <|skeleton|>
class BatchCustomPermissionsViewSet:
"""get: Retrieve the current user and group permissions. post: Adds additional users or groups to permissions. put: Replaces user and group permissions."""
def list(self, request, batch_pk=None):
"""Retrieve the current user and group permissions."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BatchCustomPermissionsViewSet:
"""get: Retrieve the current user and group permissions. post: Adds additional users or groups to permissions. put: Replaces user and group permissions."""
def list(self, request, batch_pk=None):
"""Retrieve the current user and group permissions."""
queryse... | the_stack_v2_python_sparse | turkle/api/views.py | hltcoe/turkle | train | 142 |
f5af8fe9091827cb53ddc9e62a55466d1c5d2ca3 | [
"super().__init__(n_arms, batch_size)\nif not isinstance(tau, float):\n raise TypeError(\"The hyper-parameter 'tau' must be a float.\")\nassert tau <= 1 and tau >= 0, \"The hyper-parameter 'tau' must be between 0 and 1.\"\nself.tau = tau\nself.name = f'SoftMax(Ï„={self.tau})'",
"z = np.sum(np.exp(self.values) ... | <|body_start_0|>
super().__init__(n_arms, batch_size)
if not isinstance(tau, float):
raise TypeError("The hyper-parameter 'tau' must be a float.")
assert tau <= 1 and tau >= 0, "The hyper-parameter 'tau' must be between 0 and 1."
self.tau = tau
self.name = f'SoftMax(Ï... | SoftMax. Parameters ---------- n_arms: int The number of given bandit arms. tau: float The hyper-parameter which represents how often the algorithm explores. batch_size: int, optional (default=1) The number of data given in each batch. | SoftMax | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftMax:
"""SoftMax. Parameters ---------- n_arms: int The number of given bandit arms. tau: float The hyper-parameter which represents how often the algorithm explores. batch_size: int, optional (default=1) The number of data given in each batch."""
def __init__(self, n_arms: int, tau: floa... | stack_v2_sparse_classes_75kplus_train_002268 | 10,532 | permissive | [
{
"docstring": "Initialize class.",
"name": "__init__",
"signature": "def __init__(self, n_arms: int, tau: float, batch_size: int=1) -> None"
},
{
"docstring": "Select arms according to the policy for new data. Returns ------- result: int The selected arm.",
"name": "select_arm",
"signat... | 2 | null | Implement the Python class `SoftMax` described below.
Class description:
SoftMax. Parameters ---------- n_arms: int The number of given bandit arms. tau: float The hyper-parameter which represents how often the algorithm explores. batch_size: int, optional (default=1) The number of data given in each batch.
Method si... | Implement the Python class `SoftMax` described below.
Class description:
SoftMax. Parameters ---------- n_arms: int The number of given bandit arms. tau: float The hyper-parameter which represents how often the algorithm explores. batch_size: int, optional (default=1) The number of data given in each batch.
Method si... | 8c5dd1496efa662cc636024cc49e2fd374a3daa5 | <|skeleton|>
class SoftMax:
"""SoftMax. Parameters ---------- n_arms: int The number of given bandit arms. tau: float The hyper-parameter which represents how often the algorithm explores. batch_size: int, optional (default=1) The number of data given in each batch."""
def __init__(self, n_arms: int, tau: floa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SoftMax:
"""SoftMax. Parameters ---------- n_arms: int The number of given bandit arms. tau: float The hyper-parameter which represents how often the algorithm explores. batch_size: int, optional (default=1) The number of data given in each batch."""
def __init__(self, n_arms: int, tau: float, batch_size... | the_stack_v2_python_sparse | multi_armed_bandit/pymab/policy/stochastic.py | smn-ailab/ysaito-qiita | train | 15 |
9f8c4e732c00a0ca3001dd53d42b31f673f30d6c | [
"params = ObjectDict({'contentId': id})\nhost, port = (yield self.get_ip_proxy())\nret = (yield http_fetch(path.PAPER_ADD_VOTE, data=params, proxy_host=host, proxy_port=port))\nraise gen.Return(ret)",
"host, port = (yield self.get_ip_proxy())\nret = (yield http_get(path.PAPER_ARTICLE.format(id), res_json=False, p... | <|body_start_0|>
params = ObjectDict({'contentId': id})
host, port = (yield self.get_ip_proxy())
ret = (yield http_fetch(path.PAPER_ADD_VOTE, data=params, proxy_host=host, proxy_port=port))
raise gen.Return(ret)
<|end_body_0|>
<|body_start_1|>
host, port = (yield self.get_ip_pro... | paper刷榜 | PaperDataService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaperDataService:
"""paper刷榜"""
def add_vote(self, id):
"""为文章点赞 :param id: 文章 id :return:"""
<|body_0|>
def read_article(self, id):
"""刷文章浏览数 :param id: 文章 id :return:"""
<|body_1|>
def refresh_article(self, id):
"""利用selenium刷新网页 :param id:... | stack_v2_sparse_classes_75kplus_train_002269 | 1,724 | no_license | [
{
"docstring": "为文章点赞 :param id: 文章 id :return:",
"name": "add_vote",
"signature": "def add_vote(self, id)"
},
{
"docstring": "刷文章浏览数 :param id: 文章 id :return:",
"name": "read_article",
"signature": "def read_article(self, id)"
},
{
"docstring": "利用selenium刷新网页 :param id: :return... | 3 | stack_v2_sparse_classes_30k_train_034293 | Implement the Python class `PaperDataService` described below.
Class description:
paper刷榜
Method signatures and docstrings:
- def add_vote(self, id): 为文章点赞 :param id: 文章 id :return:
- def read_article(self, id): 刷文章浏览数 :param id: 文章 id :return:
- def refresh_article(self, id): 利用selenium刷新网页 :param id: :return: | Implement the Python class `PaperDataService` described below.
Class description:
paper刷榜
Method signatures and docstrings:
- def add_vote(self, id): 为文章点赞 :param id: 文章 id :return:
- def read_article(self, id): 刷文章浏览数 :param id: 文章 id :return:
- def refresh_article(self, id): 利用selenium刷新网页 :param id: :return:
<|sk... | deced3892333f866525b46fa51ddbe0fa5ff8f58 | <|skeleton|>
class PaperDataService:
"""paper刷榜"""
def add_vote(self, id):
"""为文章点赞 :param id: 文章 id :return:"""
<|body_0|>
def read_article(self, id):
"""刷文章浏览数 :param id: 文章 id :return:"""
<|body_1|>
def refresh_article(self, id):
"""利用selenium刷新网页 :param id:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PaperDataService:
"""paper刷榜"""
def add_vote(self, id):
"""为文章点赞 :param id: 文章 id :return:"""
params = ObjectDict({'contentId': id})
host, port = (yield self.get_ip_proxy())
ret = (yield http_fetch(path.PAPER_ADD_VOTE, data=params, proxy_host=host, proxy_port=port))
... | the_stack_v2_python_sparse | service/data/paper/paper.py | cash2one/DL-BIKE | train | 0 |
07331a7afc781298753081e0d6f993df7761cdb7 | [
"CrossValidator.__init__(self, X, Y)\nmap_to_idx = {isolate: idx for idx, isolate in enumerate(isolate_list)}\nsplits = [[map_to_idx[item] for item in fold_list.split() if item in map_to_idx] for fold_list in FileUtility.load_list(fold_file)]\nnew_splits = []\nfor i in range(len(splits)):\n train = [j for i in s... | <|body_start_0|>
CrossValidator.__init__(self, X, Y)
map_to_idx = {isolate: idx for idx, isolate in enumerate(isolate_list)}
splits = [[map_to_idx[item] for item in fold_list.split() if item in map_to_idx] for fold_list in FileUtility.load_list(fold_file)]
new_splits = []
for i i... | Predefined folds | PredefinedFoldCrossVal | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PredefinedFoldCrossVal:
"""Predefined folds"""
def __init__(self, X, Y, isolate_list, fold_file):
""":param X: :param Y: :param folds: :param random_state:"""
<|body_0|>
def tune_and_evaluate(self, estimator, parameters, score='f1_macro', n_jobs=-1, file_name='results'):... | stack_v2_sparse_classes_75kplus_train_002270 | 10,364 | permissive | [
{
"docstring": ":param X: :param Y: :param folds: :param random_state:",
"name": "__init__",
"signature": "def __init__(self, X, Y, isolate_list, fold_file)"
},
{
"docstring": ":param estimator: :param parameters:p :param score: :param n_jobs: :param file_name: directory/tuning/classifier/featur... | 2 | stack_v2_sparse_classes_30k_train_028734 | Implement the Python class `PredefinedFoldCrossVal` described below.
Class description:
Predefined folds
Method signatures and docstrings:
- def __init__(self, X, Y, isolate_list, fold_file): :param X: :param Y: :param folds: :param random_state:
- def tune_and_evaluate(self, estimator, parameters, score='f1_macro', ... | Implement the Python class `PredefinedFoldCrossVal` described below.
Class description:
Predefined folds
Method signatures and docstrings:
- def __init__(self, X, Y, isolate_list, fold_file): :param X: :param Y: :param folds: :param random_state:
- def tune_and_evaluate(self, estimator, parameters, score='f1_macro', ... | 127177deb630ad66520a2fdae1793417cd77ee99 | <|skeleton|>
class PredefinedFoldCrossVal:
"""Predefined folds"""
def __init__(self, X, Y, isolate_list, fold_file):
""":param X: :param Y: :param folds: :param random_state:"""
<|body_0|>
def tune_and_evaluate(self, estimator, parameters, score='f1_macro', n_jobs=-1, file_name='results'):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PredefinedFoldCrossVal:
"""Predefined folds"""
def __init__(self, X, Y, isolate_list, fold_file):
""":param X: :param Y: :param folds: :param random_state:"""
CrossValidator.__init__(self, X, Y)
map_to_idx = {isolate: idx for idx, isolate in enumerate(isolate_list)}
splits... | the_stack_v2_python_sparse | classifier/cross_validation.py | seedpcseed/DiTaxa | train | 0 |
503c625d928300f6b87b6e30cd2505528049d477 | [
"self._name = name\nself._dir_name = dir_name\ncreate_folder(self._dir_name)\nself._model = None\nself._config = None\nself._logger = None\nself._train_statistics = None\nself._data_iterator = None\nself._agent = None\nself._environment = None",
"self._model = model\nself._config = config\nself._logger = logger\n... | <|body_start_0|>
self._name = name
self._dir_name = dir_name
create_folder(self._dir_name)
self._model = None
self._config = None
self._logger = None
self._train_statistics = None
self._data_iterator = None
self._agent = None
self._environm... | Implementation of a simple experiment class. | Experiment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Experiment:
"""Implementation of a simple experiment class."""
def __init__(self, name, dir_name):
"""Initializes an experiment object. Args: name: str, name of the experiment. dir_name: str, absolute path to the directory to save/load the experiment."""
<|body_0|>
def r... | stack_v2_sparse_classes_75kplus_train_002271 | 5,194 | no_license | [
{
"docstring": "Initializes an experiment object. Args: name: str, name of the experiment. dir_name: str, absolute path to the directory to save/load the experiment.",
"name": "__init__",
"signature": "def __init__(self, name, dir_name)"
},
{
"docstring": "Registers all the components of an expe... | 6 | stack_v2_sparse_classes_30k_test_002871 | Implement the Python class `Experiment` described below.
Class description:
Implementation of a simple experiment class.
Method signatures and docstrings:
- def __init__(self, name, dir_name): Initializes an experiment object. Args: name: str, name of the experiment. dir_name: str, absolute path to the directory to s... | Implement the Python class `Experiment` described below.
Class description:
Implementation of a simple experiment class.
Method signatures and docstrings:
- def __init__(self, name, dir_name): Initializes an experiment object. Args: name: str, name of the experiment. dir_name: str, absolute path to the directory to s... | cfbb1ec62ddbda639ab4f21f47d35c6d06e2d55d | <|skeleton|>
class Experiment:
"""Implementation of a simple experiment class."""
def __init__(self, name, dir_name):
"""Initializes an experiment object. Args: name: str, name of the experiment. dir_name: str, absolute path to the directory to save/load the experiment."""
<|body_0|>
def r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Experiment:
"""Implementation of a simple experiment class."""
def __init__(self, name, dir_name):
"""Initializes an experiment object. Args: name: str, name of the experiment. dir_name: str, absolute path to the directory to save/load the experiment."""
self._name = name
self._di... | the_stack_v2_python_sparse | myTorch/utils/experiment.py | apsarath/myTorch | train | 0 |
c27faffcc5f7b4b2bbc782246fb65ffd51045eb8 | [
"if isinstance(shape, dict):\n self._data = {k: ShmBufferContainer(dtype, v) for k, v in shape.items()}\nelif isinstance(shape, (tuple, list)):\n self._data = ShmBuffer(dtype, shape)\nelse:\n raise RuntimeError('not support shape: {}'.format(shape))\nself._shape = shape",
"if isinstance(self._shape, dict... | <|body_start_0|>
if isinstance(shape, dict):
self._data = {k: ShmBufferContainer(dtype, v) for k, v in shape.items()}
elif isinstance(shape, (tuple, list)):
self._data = ShmBuffer(dtype, shape)
else:
raise RuntimeError('not support shape: {}'.format(shape))
... | Overview: Support multiple shared memory buffers. Each key-value is name-buffer. | ShmBufferContainer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShmBufferContainer:
"""Overview: Support multiple shared memory buffers. Each key-value is name-buffer."""
def __init__(self, dtype: np.generic, shape: Union[Dict[Any, tuple], tuple]) -> None:
"""Overview: Initialize the buffer container. Arguments: - dtype (:obj:`np.generic`): dtype... | stack_v2_sparse_classes_75kplus_train_002272 | 32,547 | permissive | [
{
"docstring": "Overview: Initialize the buffer container. Arguments: - dtype (:obj:`np.generic`): dtype of the data to limit the size of the buffer. - shape (:obj:`Union[Dict[Any, tuple], tuple]`): If `Dict[Any, tuple]`, use a dict to manage multiple buffers; If `tuple`, use single buffer.",
"name": "__ini... | 3 | stack_v2_sparse_classes_30k_train_034383 | Implement the Python class `ShmBufferContainer` described below.
Class description:
Overview: Support multiple shared memory buffers. Each key-value is name-buffer.
Method signatures and docstrings:
- def __init__(self, dtype: np.generic, shape: Union[Dict[Any, tuple], tuple]) -> None: Overview: Initialize the buffer... | Implement the Python class `ShmBufferContainer` described below.
Class description:
Overview: Support multiple shared memory buffers. Each key-value is name-buffer.
Method signatures and docstrings:
- def __init__(self, dtype: np.generic, shape: Union[Dict[Any, tuple], tuple]) -> None: Overview: Initialize the buffer... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class ShmBufferContainer:
"""Overview: Support multiple shared memory buffers. Each key-value is name-buffer."""
def __init__(self, dtype: np.generic, shape: Union[Dict[Any, tuple], tuple]) -> None:
"""Overview: Initialize the buffer container. Arguments: - dtype (:obj:`np.generic`): dtype... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShmBufferContainer:
"""Overview: Support multiple shared memory buffers. Each key-value is name-buffer."""
def __init__(self, dtype: np.generic, shape: Union[Dict[Any, tuple], tuple]) -> None:
"""Overview: Initialize the buffer container. Arguments: - dtype (:obj:`np.generic`): dtype of the data ... | the_stack_v2_python_sparse | ding/envs/env_manager/subprocess_env_manager.py | shengxuesun/DI-engine | train | 1 |
5750d9107a833f374b08e6456a4c952f9fcde330 | [
"self.device_name = device_name\nself.id = id\nself.is_root_device = is_root_device\nself.name = name\nself.size_bytes = size_bytes\nself.tags = tags\nself.mtype = mtype",
"if dictionary is None:\n return None\ndevice_name = dictionary.get('deviceName')\nid = dictionary.get('id')\nis_root_device = dictionary.g... | <|body_start_0|>
self.device_name = device_name
self.id = id
self.is_root_device = is_root_device
self.name = name
self.size_bytes = size_bytes
self.tags = tags
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return N... | Implementation of the 'EbsVolumeInfo' model. Specifies information about an AWS volume attached to an EC2 instance. Attributes: device_name (string): Specifies the name of the device. Eg - /dev/sdb. id (string): Specifies the ID of the volume. is_root_device (bool): Specifies if the volume is attached as root device. n... | EbsVolumeInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EbsVolumeInfo:
"""Implementation of the 'EbsVolumeInfo' model. Specifies information about an AWS volume attached to an EC2 instance. Attributes: device_name (string): Specifies the name of the device. Eg - /dev/sdb. id (string): Specifies the ID of the volume. is_root_device (bool): Specifies if... | stack_v2_sparse_classes_75kplus_train_002273 | 2,986 | permissive | [
{
"docstring": "Constructor for the EbsVolumeInfo class",
"name": "__init__",
"signature": "def __init__(self, device_name=None, id=None, is_root_device=None, name=None, size_bytes=None, tags=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictiona... | 2 | stack_v2_sparse_classes_30k_train_025087 | Implement the Python class `EbsVolumeInfo` described below.
Class description:
Implementation of the 'EbsVolumeInfo' model. Specifies information about an AWS volume attached to an EC2 instance. Attributes: device_name (string): Specifies the name of the device. Eg - /dev/sdb. id (string): Specifies the ID of the volu... | Implement the Python class `EbsVolumeInfo` described below.
Class description:
Implementation of the 'EbsVolumeInfo' model. Specifies information about an AWS volume attached to an EC2 instance. Attributes: device_name (string): Specifies the name of the device. Eg - /dev/sdb. id (string): Specifies the ID of the volu... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class EbsVolumeInfo:
"""Implementation of the 'EbsVolumeInfo' model. Specifies information about an AWS volume attached to an EC2 instance. Attributes: device_name (string): Specifies the name of the device. Eg - /dev/sdb. id (string): Specifies the ID of the volume. is_root_device (bool): Specifies if... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EbsVolumeInfo:
"""Implementation of the 'EbsVolumeInfo' model. Specifies information about an AWS volume attached to an EC2 instance. Attributes: device_name (string): Specifies the name of the device. Eg - /dev/sdb. id (string): Specifies the ID of the volume. is_root_device (bool): Specifies if the volume i... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ebs_volume_info.py | cohesity/management-sdk-python | train | 24 |
e4635f7aac269eb4568e437f0a7e0c4c03714325 | [
"if not self._canvas_account_id:\n raise MissingAccountID()\nparams = {'workflow_state': 'all', 'per_page': 500}\nurl = ACCOUNTS_API.format(self._canvas_account_id) + '/terms'\ndata_key = 'enrollment_terms'\nterms = []\nresponse = self._get_paged_resource(url, params, data_key)\nfor data in response[data_key]:\n... | <|body_start_0|>
if not self._canvas_account_id:
raise MissingAccountID()
params = {'workflow_state': 'all', 'per_page': 500}
url = ACCOUNTS_API.format(self._canvas_account_id) + '/terms'
data_key = 'enrollment_terms'
terms = []
response = self._get_paged_reso... | Terms | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Terms:
def get_all_terms(self):
"""Return all of the terms in the account. https://canvas.instructure.com/doc/api/enrollment_terms.html#method.terms_api.index"""
<|body_0|>
def get_term_by_sis_id(self, sis_term_id):
"""Return a term resource for the passed SIS ID."""... | stack_v2_sparse_classes_75kplus_train_002274 | 1,723 | permissive | [
{
"docstring": "Return all of the terms in the account. https://canvas.instructure.com/doc/api/enrollment_terms.html#method.terms_api.index",
"name": "get_all_terms",
"signature": "def get_all_terms(self)"
},
{
"docstring": "Return a term resource for the passed SIS ID.",
"name": "get_term_b... | 3 | stack_v2_sparse_classes_30k_train_007085 | Implement the Python class `Terms` described below.
Class description:
Implement the Terms class.
Method signatures and docstrings:
- def get_all_terms(self): Return all of the terms in the account. https://canvas.instructure.com/doc/api/enrollment_terms.html#method.terms_api.index
- def get_term_by_sis_id(self, sis_... | Implement the Python class `Terms` described below.
Class description:
Implement the Terms class.
Method signatures and docstrings:
- def get_all_terms(self): Return all of the terms in the account. https://canvas.instructure.com/doc/api/enrollment_terms.html#method.terms_api.index
- def get_term_by_sis_id(self, sis_... | 5da7260b2fd8f22f311dcbadc5e6906323eadff4 | <|skeleton|>
class Terms:
def get_all_terms(self):
"""Return all of the terms in the account. https://canvas.instructure.com/doc/api/enrollment_terms.html#method.terms_api.index"""
<|body_0|>
def get_term_by_sis_id(self, sis_term_id):
"""Return a term resource for the passed SIS ID."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Terms:
def get_all_terms(self):
"""Return all of the terms in the account. https://canvas.instructure.com/doc/api/enrollment_terms.html#method.terms_api.index"""
if not self._canvas_account_id:
raise MissingAccountID()
params = {'workflow_state': 'all', 'per_page': 500}
... | the_stack_v2_python_sparse | uw_canvas/terms.py | uw-it-aca/uw-restclients-canvas | train | 2 | |
e099684e1890ce4cb68aad3b5ed8b5b3f46c51d0 | [
"self.method = method\nself.produces = produces\nself.handler = handling_func\nself.requires_authentication = requires_authentication",
"if self.requires_authentication and (not request.user.is_authenticated):\n return JsonResponse({'success': False, 'message': 'You must be logged in to access this Endpoint'},... | <|body_start_0|>
self.method = method
self.produces = produces
self.handler = handling_func
self.requires_authentication = requires_authentication
<|end_body_0|>
<|body_start_1|>
if self.requires_authentication and (not request.user.is_authenticated):
return JsonResp... | Handles a request | Handler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Handler:
"""Handles a request"""
def __init__(self, method, produces, handling_func, requires_authentication=True):
"""Create the handler :param method: Which http verb this handler deals with (e.g. "GET" or "POST") :param produces: Which content type this handler produces (e.g. "tex... | stack_v2_sparse_classes_75kplus_train_002275 | 9,665 | permissive | [
{
"docstring": "Create the handler :param method: Which http verb this handler deals with (e.g. \"GET\" or \"POST\") :param produces: Which content type this handler produces (e.g. \"text/html\") :param handling_func: function used to handle the request. Should take the following arguments: request: the origina... | 2 | stack_v2_sparse_classes_30k_train_050859 | Implement the Python class `Handler` described below.
Class description:
Handles a request
Method signatures and docstrings:
- def __init__(self, method, produces, handling_func, requires_authentication=True): Create the handler :param method: Which http verb this handler deals with (e.g. "GET" or "POST") :param prod... | Implement the Python class `Handler` described below.
Class description:
Handles a request
Method signatures and docstrings:
- def __init__(self, method, produces, handling_func, requires_authentication=True): Create the handler :param method: Which http verb this handler deals with (e.g. "GET" or "POST") :param prod... | ff6df7efab340e6f2798d7581fa3e22ac01cf73e | <|skeleton|>
class Handler:
"""Handles a request"""
def __init__(self, method, produces, handling_func, requires_authentication=True):
"""Create the handler :param method: Which http verb this handler deals with (e.g. "GET" or "POST") :param produces: Which content type this handler produces (e.g. "tex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Handler:
"""Handles a request"""
def __init__(self, method, produces, handling_func, requires_authentication=True):
"""Create the handler :param method: Which http verb this handler deals with (e.g. "GET" or "POST") :param produces: Which content type this handler produces (e.g. "text/html") :par... | the_stack_v2_python_sparse | web_server/social_distribution/utils/endpoint_utils.py | AustinGrey/cmput404-group-project | train | 0 |
a05b2cb6b77a04123bf1d6ac5de59e58cc8274ce | [
"headers = vector['headers']\ntargets = []\nif not vector['data']:\n return []\ncontent_type = headers.get('Content-Type')\nif content_type and content_type.startswith(HTTP.CONTENT_TYPE.MULTIPART):\n parsed = utility.parse_multipart(vector['data'], content_type)\n targets = list(parsed.names())\nreturn tar... | <|body_start_0|>
headers = vector['headers']
targets = []
if not vector['data']:
return []
content_type = headers.get('Content-Type')
if content_type and content_type.startswith(HTTP.CONTENT_TYPE.MULTIPART):
parsed = utility.parse_multipart(vector['data'],... | _MultipartValueHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _MultipartValueHandler:
def _get_targets(self, vector):
"""Returns list of names for multipart data. Content-Type must be multipart/form-data. :param vector: vector dictionary :return: names as list"""
<|body_0|>
def _generate_variations(self, check, vector, target):
... | stack_v2_sparse_classes_75kplus_train_002276 | 2,363 | permissive | [
{
"docstring": "Returns list of names for multipart data. Content-Type must be multipart/form-data. :param vector: vector dictionary :return: names as list",
"name": "_get_targets",
"signature": "def _get_targets(self, vector)"
},
{
"docstring": "Generates variations for value checks. Variations... | 2 | stack_v2_sparse_classes_30k_train_035803 | Implement the Python class `_MultipartValueHandler` described below.
Class description:
Implement the _MultipartValueHandler class.
Method signatures and docstrings:
- def _get_targets(self, vector): Returns list of names for multipart data. Content-Type must be multipart/form-data. :param vector: vector dictionary :... | Implement the Python class `_MultipartValueHandler` described below.
Class description:
Implement the _MultipartValueHandler class.
Method signatures and docstrings:
- def _get_targets(self, vector): Returns list of names for multipart data. Content-Type must be multipart/form-data. :param vector: vector dictionary :... | 4483b301034a096b716646a470a6642b3df8ce61 | <|skeleton|>
class _MultipartValueHandler:
def _get_targets(self, vector):
"""Returns list of names for multipart data. Content-Type must be multipart/form-data. :param vector: vector dictionary :return: names as list"""
<|body_0|>
def _generate_variations(self, check, vector, target):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _MultipartValueHandler:
def _get_targets(self, vector):
"""Returns list of names for multipart data. Content-Type must be multipart/form-data. :param vector: vector dictionary :return: names as list"""
headers = vector['headers']
targets = []
if not vector['data']:
... | the_stack_v2_python_sparse | ava/auditors/multipart.py | indeedsecurity/ava-ce | train | 3 | |
ed01d783da097b71de112097f1bbaa9a5a37a6fe | [
"if not s:\n return ''\nif len(s) == 1:\n return s\n\ndef isPalindrome(l, r):\n while l < r:\n if s[l] != s[r]:\n return False\n l += 1\n r -= 1\n return True\nindicies = []\nmax_lenght = 0\nfor i in range(0, len(s) - 1):\n for j in range(i + 1, len(s)):\n if is... | <|body_start_0|>
if not s:
return ''
if len(s) == 1:
return s
def isPalindrome(l, r):
while l < r:
if s[l] != s[r]:
return False
l += 1
r -= 1
return True
indicies = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_2|>
<|en... | stack_v2_sparse_classes_75kplus_train_002277 | 4,948 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome2",
"signature": "def longestPalindrome2(self, s)"
},
{
"docstring": ":type s: str :rtype:... | 3 | stack_v2_sparse_classes_30k_train_046520 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome2(self, s): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome2(self, s): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str
<... | b925bb22d1daa4a56c5a238a5758a926905559b4 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_2|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
if not s:
return ''
if len(s) == 1:
return s
def isPalindrome(l, r):
while l < r:
if s[l] != s[r]:
return False
l +=... | the_stack_v2_python_sparse | String/5. Longest Palindromic Substring.py | beninghton/notGivenUpToG | train | 0 | |
ec293dc5066b4ad55ae8bd5aecb501e12849106e | [
"super().__init__(name='RosettaFolding')\ntry:\n prs\nexcept NameError as e:\n raise ImportError('Error: Pyrosetta not installed. Source, binary, and conda installations available at http://www.pyrosetta.org/dow') from e\nprs.init('-mute all')\nself.pose = prs.pose_from_pdb(pdb_file)\nself.wt_pose = self.pose... | <|body_start_0|>
super().__init__(name='RosettaFolding')
try:
prs
except NameError as e:
raise ImportError('Error: Pyrosetta not installed. Source, binary, and conda installations available at http://www.pyrosetta.org/dow') from e
prs.init('-mute all')
sel... | This oracle scores sequences using a fixed conformation design energy. In this case, both backbone and side chain conformations are fixed (no repacking). In this setting, we have a 3-D structure that we'd like to design for (given by the PDB file), so we look for sequences that might stably fold to the given conformati... | RosettaFolding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RosettaFolding:
"""This oracle scores sequences using a fixed conformation design energy. In this case, both backbone and side chain conformations are fixed (no repacking). In this setting, we have a 3-D structure that we'd like to design for (given by the PDB file), so we look for sequences that... | stack_v2_sparse_classes_75kplus_train_002278 | 8,488 | permissive | [
{
"docstring": "Create a RosettaFolding landscape from a .pdb file with structure. Args: pdb_file: Path to .pdb file with structure information. sigmoid_center: Center of sigmoid function. sigmoid_norm_value: 1 / scale of sigmoid function.",
"name": "__init__",
"signature": "def __init__(self, pdb_file:... | 4 | stack_v2_sparse_classes_30k_train_042288 | Implement the Python class `RosettaFolding` described below.
Class description:
This oracle scores sequences using a fixed conformation design energy. In this case, both backbone and side chain conformations are fixed (no repacking). In this setting, we have a 3-D structure that we'd like to design for (given by the P... | Implement the Python class `RosettaFolding` described below.
Class description:
This oracle scores sequences using a fixed conformation design energy. In this case, both backbone and side chain conformations are fixed (no repacking). In this setting, we have a 3-D structure that we'd like to design for (given by the P... | 744e792456d93e8c48fc58220689c0b4cff6ded9 | <|skeleton|>
class RosettaFolding:
"""This oracle scores sequences using a fixed conformation design energy. In this case, both backbone and side chain conformations are fixed (no repacking). In this setting, we have a 3-D structure that we'd like to design for (given by the PDB file), so we look for sequences that... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RosettaFolding:
"""This oracle scores sequences using a fixed conformation design energy. In this case, both backbone and side chain conformations are fixed (no repacking). In this setting, we have a 3-D structure that we'd like to design for (given by the PDB file), so we look for sequences that might stably... | the_stack_v2_python_sparse | flexs/landscapes/rosetta.py | jonshao/FLEXS | train | 0 |
6cdb3adfdbc3a14202ca58d75f46d53aedf4b7cd | [
"seen = []\nwhile head:\n if head in seen:\n return True\n else:\n seen.append(head)\n head = head.next\nreturn False",
"if not head:\n return False\npointer1 = head\npointer2 = head.next\nwhile pointer1 != pointer2:\n if not pointer2 or not pointer2.next:\n return False\n p... | <|body_start_0|>
seen = []
while head:
if head in seen:
return True
else:
seen.append(head)
head = head.next
return False
<|end_body_0|>
<|body_start_1|>
if not head:
return False
pointer1 = head
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasCycle(self, head: ListNode) -> bool:
"""Hash table solution. Appends head instead of head.val because head records different objects. It is a solution to storing the same value to seen and having the same value show up in a different object. Time Complexity: O(n), Space ... | stack_v2_sparse_classes_75kplus_train_002279 | 1,398 | no_license | [
{
"docstring": "Hash table solution. Appends head instead of head.val because head records different objects. It is a solution to storing the same value to seen and having the same value show up in a different object. Time Complexity: O(n), Space Complexity: O(n)",
"name": "hasCycle",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_050522 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle(self, head: ListNode) -> bool: Hash table solution. Appends head instead of head.val because head records different objects. It is a solution to storing the same val... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle(self, head: ListNode) -> bool: Hash table solution. Appends head instead of head.val because head records different objects. It is a solution to storing the same val... | f33d004d7629d46fbc5670f5b384f8a604d7f1e7 | <|skeleton|>
class Solution:
def hasCycle(self, head: ListNode) -> bool:
"""Hash table solution. Appends head instead of head.val because head records different objects. It is a solution to storing the same value to seen and having the same value show up in a different object. Time Complexity: O(n), Space ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def hasCycle(self, head: ListNode) -> bool:
"""Hash table solution. Appends head instead of head.val because head records different objects. It is a solution to storing the same value to seen and having the same value show up in a different object. Time Complexity: O(n), Space Complexity: O(... | the_stack_v2_python_sparse | Linked List Cycle.py | aulee888/LeetCode | train | 0 | |
cbf8502b9e1a3143f2d77e621480380a6ea0e042 | [
"self.call_id = call_id\nself.parent_call_id = parent_call_id\nself.application_id = application_id\nself.account_id = account_id\nself.to = to\nself.mfrom = mfrom\nself.direction = direction\nself.state = state\nself.identity = identity\nself.stir_shaken = stir_shaken\nself.start_time = APIHelper.RFC3339DateTime(s... | <|body_start_0|>
self.call_id = call_id
self.parent_call_id = parent_call_id
self.application_id = application_id
self.account_id = account_id
self.to = to
self.mfrom = mfrom
self.direction = direction
self.state = state
self.identity = identity
... | Implementation of the 'CallState' model. TODO: type model description here. Attributes: call_id (string): TODO: type description here. parent_call_id (string): TODO: type description here. application_id (string): TODO: type description here. account_id (string): TODO: type description here. to (string): TODO: type des... | CallState | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallState:
"""Implementation of the 'CallState' model. TODO: type model description here. Attributes: call_id (string): TODO: type description here. parent_call_id (string): TODO: type description here. application_id (string): TODO: type description here. account_id (string): TODO: type descript... | stack_v2_sparse_classes_75kplus_train_002280 | 6,933 | permissive | [
{
"docstring": "Constructor for the CallState class",
"name": "__init__",
"signature": "def __init__(self, call_id=None, parent_call_id=None, application_id=None, account_id=None, to=None, mfrom=None, direction=None, state=None, identity=None, stir_shaken=None, start_time=None, enqueued_time=None, answe... | 2 | stack_v2_sparse_classes_30k_train_041400 | Implement the Python class `CallState` described below.
Class description:
Implementation of the 'CallState' model. TODO: type model description here. Attributes: call_id (string): TODO: type description here. parent_call_id (string): TODO: type description here. application_id (string): TODO: type description here. a... | Implement the Python class `CallState` described below.
Class description:
Implementation of the 'CallState' model. TODO: type model description here. Attributes: call_id (string): TODO: type description here. parent_call_id (string): TODO: type description here. application_id (string): TODO: type description here. a... | 447df3cc8cb7acaf3361d842630c432a9c31ce6e | <|skeleton|>
class CallState:
"""Implementation of the 'CallState' model. TODO: type model description here. Attributes: call_id (string): TODO: type description here. parent_call_id (string): TODO: type description here. application_id (string): TODO: type description here. account_id (string): TODO: type descript... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CallState:
"""Implementation of the 'CallState' model. TODO: type model description here. Attributes: call_id (string): TODO: type description here. parent_call_id (string): TODO: type description here. application_id (string): TODO: type description here. account_id (string): TODO: type description here. to ... | the_stack_v2_python_sparse | bandwidth/voice/models/call_state.py | Bandwidth/python-sdk | train | 10 |
3853b67663ea0886d64ca79ba50c7c7f68e4570a | [
"d = {}\nfor c in deck:\n if c not in d:\n d[c] = 1\n else:\n d[c] += 1\nminimum = min(d.values())\nif minimum == 1:\n return False\nelse:\n divisors = self.allDivisors(minimum)\n for k, v in d.items():\n res = [v % div == 0 for div in divisors]\n if any(res):\n ... | <|body_start_0|>
d = {}
for c in deck:
if c not in d:
d[c] = 1
else:
d[c] += 1
minimum = min(d.values())
if minimum == 1:
return False
else:
divisors = self.allDivisors(minimum)
for k, v i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasGroupsSizeX(self, deck):
""":type deck: List[int] :rtype: bool"""
<|body_0|>
def allDivisors(self, number):
""":type number: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = {}
for c in deck:
... | stack_v2_sparse_classes_75kplus_train_002281 | 1,366 | no_license | [
{
"docstring": ":type deck: List[int] :rtype: bool",
"name": "hasGroupsSizeX",
"signature": "def hasGroupsSizeX(self, deck)"
},
{
"docstring": ":type number: int :rtype: List[int]",
"name": "allDivisors",
"signature": "def allDivisors(self, number)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasGroupsSizeX(self, deck): :type deck: List[int] :rtype: bool
- def allDivisors(self, number): :type number: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasGroupsSizeX(self, deck): :type deck: List[int] :rtype: bool
- def allDivisors(self, number): :type number: int :rtype: List[int]
<|skeleton|>
class Solution:
def has... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def hasGroupsSizeX(self, deck):
""":type deck: List[int] :rtype: bool"""
<|body_0|>
def allDivisors(self, number):
""":type number: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def hasGroupsSizeX(self, deck):
""":type deck: List[int] :rtype: bool"""
d = {}
for c in deck:
if c not in d:
d[c] = 1
else:
d[c] += 1
minimum = min(d.values())
if minimum == 1:
return False
... | the_stack_v2_python_sparse | 10.MATH/914_X_of_a_Kind_in_a_Deck_of_Cards/solution.py | kimmyoo/python_leetcode | train | 1 | |
d5b4e4adf500be2c9c8aa3cb8482de54665e122f | [
"base.LIMIT_FLAG.AddToParser(parser)\nparser.add_argument('log_filter', help='A filter expression that specifies the log entries to return.', nargs='?')\nparser.add_argument('--order', required=False, choices=('DESC', 'ASC'), default='DESC', help='Ordering of returned log entries based on timestamp field.')\nparser... | <|body_start_0|>
base.LIMIT_FLAG.AddToParser(parser)
parser.add_argument('log_filter', help='A filter expression that specifies the log entries to return.', nargs='?')
parser.add_argument('--order', required=False, choices=('DESC', 'ASC'), default='DESC', help='Ordering of returned log entries b... | Reads log entries. | Read | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Read:
"""Reads log entries."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this co... | stack_v2_sparse_classes_75kplus_train_002282 | 3,729 | permissive | [
{
"docstring": "Register flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: The list of... | 2 | null | Implement the Python class `Read` described below.
Class description:
Reads log entries.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that wer... | Implement the Python class `Read` described below.
Class description:
Reads log entries.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that wer... | c98b58aeb0994e011df960163541e9379ae7ea06 | <|skeleton|>
class Read:
"""Reads log entries."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Read:
"""Reads log entries."""
def Args(parser):
"""Register flags for this command."""
base.LIMIT_FLAG.AddToParser(parser)
parser.add_argument('log_filter', help='A filter expression that specifies the log entries to return.', nargs='?')
parser.add_argument('--order', req... | the_stack_v2_python_sparse | google-cloud-sdk/.install/.backup/lib/surface/logging/read.py | KaranToor/MA450 | train | 1 |
c017564474bc8acdf5dc261e94bb3511259eb62a | [
"exporter_class = story_export_manager.StoryExportManager.get_exporter(export_format)\nif not exporter_class:\n return b''\nwith exporter_class() as exporter:\n data_fetcher = story_api_fetcher.ApiDataFetcher()\n data_fetcher.set_sketch_id(sketch_id)\n exporter.set_data_fetcher(data_fetcher)\n export... | <|body_start_0|>
exporter_class = story_export_manager.StoryExportManager.get_exporter(export_format)
if not exporter_class:
return b''
with exporter_class() as exporter:
data_fetcher = story_api_fetcher.ApiDataFetcher()
data_fetcher.set_sketch_id(sketch_id)
... | Resource to get a story. | StoryResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoryResource:
"""Resource to get a story."""
def _export_story(story, sketch_id, export_format='markdown'):
"""Returns a story in a format as requested in export_format. Args: story: a story object (instance of Story) that is to be exported. sketch_id: integer with the sketch ID. ex... | stack_v2_sparse_classes_75kplus_train_002283 | 9,982 | permissive | [
{
"docstring": "Returns a story in a format as requested in export_format. Args: story: a story object (instance of Story) that is to be exported. sketch_id: integer with the sketch ID. export_format: string with the name of the format to export the story to. Defaults to \"markdown\". Returns: The exported stor... | 4 | stack_v2_sparse_classes_30k_train_017348 | Implement the Python class `StoryResource` described below.
Class description:
Resource to get a story.
Method signatures and docstrings:
- def _export_story(story, sketch_id, export_format='markdown'): Returns a story in a format as requested in export_format. Args: story: a story object (instance of Story) that is ... | Implement the Python class `StoryResource` described below.
Class description:
Resource to get a story.
Method signatures and docstrings:
- def _export_story(story, sketch_id, export_format='markdown'): Returns a story in a format as requested in export_format. Args: story: a story object (instance of Story) that is ... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class StoryResource:
"""Resource to get a story."""
def _export_story(story, sketch_id, export_format='markdown'):
"""Returns a story in a format as requested in export_format. Args: story: a story object (instance of Story) that is to be exported. sketch_id: integer with the sketch ID. ex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StoryResource:
"""Resource to get a story."""
def _export_story(story, sketch_id, export_format='markdown'):
"""Returns a story in a format as requested in export_format. Args: story: a story object (instance of Story) that is to be exported. sketch_id: integer with the sketch ID. export_format: ... | the_stack_v2_python_sparse | timesketch/api/v1/resources/story.py | google/timesketch | train | 2,263 |
b3107d9f37245b9800def315c79ee9d9df4fa0fa | [
"http_x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\nif http_x_forwarded_for:\n ip = http_x_forwarded_for.split(',')[-1].strip()\nelse:\n ip = request.META.get('REMOTE_ADDR')\nreturn ip",
"try:\n profile = request.user.profile\nexcept cls.DoesNotExist:\n profile = cls.objects.create(user=... | <|body_start_0|>
http_x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if http_x_forwarded_for:
ip = http_x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
return ip
<|end_body_0|>
<|body_start_1|>
try:
... | This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0 | Profile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Profile:
"""This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0"""
def get_user_ip(request):
"""Return user IP from request. :param request: django requ... | stack_v2_sparse_classes_75kplus_train_002284 | 3,000 | permissive | [
{
"docstring": "Return user IP from request. :param request: django request :return: IP",
"name": "get_user_ip",
"signature": "def get_user_ip(request)"
},
{
"docstring": "Check if self.timezone is empty - get timezone from pygeoip and store it there. :param request: django request :return: noth... | 2 | stack_v2_sparse_classes_30k_train_033797 | Implement the Python class `Profile` described below.
Class description:
This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0
Method signatures and docstrings:
- def get_user_ip(request):... | Implement the Python class `Profile` described below.
Class description:
This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0
Method signatures and docstrings:
- def get_user_ip(request):... | 2e7dd9d2ec687f68ca8ca341cf5f1b3b8809c820 | <|skeleton|>
class Profile:
"""This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0"""
def get_user_ip(request):
"""Return user IP from request. :param request: django requ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Profile:
"""This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0"""
def get_user_ip(request):
"""Return user IP from request. :param request: django request :return: ... | the_stack_v2_python_sparse | mysite/accounts/models.py | cjlee112/socraticqs2 | train | 8 |
87a368408756c0dfec2f5f4fd0813045dbd19d0b | [
"self.num_units = num_units\nself.layer_norm = layer_norm\nself.recurrent_dropout = recurrent_dropout\nself.activation_fn = activation_fn\nself.separate_directions = separate_directions\nself.linear_out_flag = linear_out_flag\nself.fast_version = fast_version",
"with tf.variable_scope(scope or type(self).__name__... | <|body_start_0|>
self.num_units = num_units
self.layer_norm = layer_norm
self.recurrent_dropout = recurrent_dropout
self.activation_fn = activation_fn
self.separate_directions = separate_directions
self.linear_out_flag = linear_out_flag
self.fast_version = fast_ve... | a BLSTM layer | BLSTMLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BLSTMLayer:
"""a BLSTM layer"""
def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, activation_fn=tf.nn.tanh, separate_directions=False, linear_out_flag=False, fast_version=False):
"""BLSTMLayer constructor Args: num_units: The number of units in the one directon l... | stack_v2_sparse_classes_75kplus_train_002285 | 49,091 | permissive | [
{
"docstring": "BLSTMLayer constructor Args: num_units: The number of units in the one directon layer_norm: whether layer normalization should be applied recurrent_dropout: the recurrent dropout keep probability separate_directions: wether the forward and backward directions should be separated for deep network... | 2 | null | Implement the Python class `BLSTMLayer` described below.
Class description:
a BLSTM layer
Method signatures and docstrings:
- def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, activation_fn=tf.nn.tanh, separate_directions=False, linear_out_flag=False, fast_version=False): BLSTMLayer constructor A... | Implement the Python class `BLSTMLayer` described below.
Class description:
a BLSTM layer
Method signatures and docstrings:
- def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, activation_fn=tf.nn.tanh, separate_directions=False, linear_out_flag=False, fast_version=False): BLSTMLayer constructor A... | 5e862cbf846d45b8a317f87588533f3fde9f0726 | <|skeleton|>
class BLSTMLayer:
"""a BLSTM layer"""
def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, activation_fn=tf.nn.tanh, separate_directions=False, linear_out_flag=False, fast_version=False):
"""BLSTMLayer constructor Args: num_units: The number of units in the one directon l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BLSTMLayer:
"""a BLSTM layer"""
def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, activation_fn=tf.nn.tanh, separate_directions=False, linear_out_flag=False, fast_version=False):
"""BLSTMLayer constructor Args: num_units: The number of units in the one directon layer_norm: wh... | the_stack_v2_python_sparse | nabu/neuralnetworks/components/layer.py | JeroenZegers/Nabu-MSSS | train | 19 |
fca015be2d8426e93771cf203cdf077095a8a6b0 | [
"self.capacity = capacity\nself.num = 0\nself.dic = dict()\nself.head = Node(0, 0)\nself.tail = Node(0, 0)\nself.head.nxt = self.tail\nself.tail.pre = self.head",
"if key in self.dic:\n n = self.dic[key]\n res = n.val\n self.add(n)\n self.remove(n)\n return res\nelse:\n return -1",
"if key in ... | <|body_start_0|>
self.capacity = capacity
self.num = 0
self.dic = dict()
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.nxt = self.tail
self.tail.pre = self.head
<|end_body_0|>
<|body_start_1|>
if key in self.dic:
n = self.dic[key]
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
def add(self, n... | stack_v2_sparse_classes_75kplus_train_002286 | 1,901 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 5 | stack_v2_sparse_classes_30k_train_053803 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
- def add(self, n... | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
- def add(self, n... | c7ec2d0c09bce3e70579518dd446329bb97b3132 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
def add(self, n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.num = 0
self.dic = dict()
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.nxt = self.tail
self.tail.pre = self.head
def get(self, key):
... | the_stack_v2_python_sparse | Python/LRUcache.py | runzedong/Leetcode_record | train | 2 | |
945d1d70883afcd6b84dfbe6c7457509e94f9623 | [
"params = kwarg['params']\ncmd = 'bridge mdb {} '.format(command)\nreturn cmd",
"params = kwarg['params']\ncmd = 'bridge mdb {} '.format(command)\nreturn cmd"
] | <|body_start_0|>
params = kwarg['params']
cmd = 'bridge mdb {} '.format(command)
return cmd
<|end_body_0|>
<|body_start_1|>
params = kwarg['params']
cmd = 'bridge mdb {} '.format(command)
return cmd
<|end_body_1|>
| The corresponding commands display mdb entries, add new entries, and delete old ones. | LinuxBridgeMdbImpl | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinuxBridgeMdbImpl:
"""The corresponding commands display mdb entries, add new entries, and delete old ones."""
def format_update(self, command, *argv, **kwarg):
"""bridge mdb { add | del } dev DEV port PORT grp GROUP [ permanent | temp ] [ vid VID ]"""
<|body_0|>
def fo... | stack_v2_sparse_classes_75kplus_train_002287 | 820 | permissive | [
{
"docstring": "bridge mdb { add | del } dev DEV port PORT grp GROUP [ permanent | temp ] [ vid VID ]",
"name": "format_update",
"signature": "def format_update(self, command, *argv, **kwarg)"
},
{
"docstring": "bridge mdb show [ dev DEV ]",
"name": "format_show",
"signature": "def forma... | 2 | stack_v2_sparse_classes_30k_train_039381 | Implement the Python class `LinuxBridgeMdbImpl` described below.
Class description:
The corresponding commands display mdb entries, add new entries, and delete old ones.
Method signatures and docstrings:
- def format_update(self, command, *argv, **kwarg): bridge mdb { add | del } dev DEV port PORT grp GROUP [ permane... | Implement the Python class `LinuxBridgeMdbImpl` described below.
Class description:
The corresponding commands display mdb entries, add new entries, and delete old ones.
Method signatures and docstrings:
- def format_update(self, command, *argv, **kwarg): bridge mdb { add | del } dev DEV port PORT grp GROUP [ permane... | e4c8221e18cd94e7424c30e12eb0fb82f7767267 | <|skeleton|>
class LinuxBridgeMdbImpl:
"""The corresponding commands display mdb entries, add new entries, and delete old ones."""
def format_update(self, command, *argv, **kwarg):
"""bridge mdb { add | del } dev DEV port PORT grp GROUP [ permanent | temp ] [ vid VID ]"""
<|body_0|>
def fo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinuxBridgeMdbImpl:
"""The corresponding commands display mdb entries, add new entries, and delete old ones."""
def format_update(self, command, *argv, **kwarg):
"""bridge mdb { add | del } dev DEV port PORT grp GROUP [ permanent | temp ] [ vid VID ]"""
params = kwarg['params']
cm... | the_stack_v2_python_sparse | Amazon_Framework/DentOsTestbedLib/src/dent_os_testbed/lib/bridge/linux/linux_bridge_mdb_impl.py | tld3daniel/testing | train | 0 |
79ea8c9f796521822e835e9fde4c46269a4d2098 | [
"self.allow_api_based_fetch = allow_api_based_fetch\nself.cluster_destroy_hmac_key = cluster_destroy_hmac_key\nself.cluster_name = cluster_name\nself.enable_cluster_destroy = enable_cluster_destroy\nself.encryption_config = encryption_config\nself.ip_preference = ip_preference\nself.ipmi_config = ipmi_config\nself.... | <|body_start_0|>
self.allow_api_based_fetch = allow_api_based_fetch
self.cluster_destroy_hmac_key = cluster_destroy_hmac_key
self.cluster_name = cluster_name
self.enable_cluster_destroy = enable_cluster_destroy
self.encryption_config = encryption_config
self.ip_preference... | Implementation of the 'CreatePhysicalClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: allow_api_based_fetch (bool): Specifies if API based GET should be enabled for cluster destroy params. cluster_destroy_hmac_key (string): Specifies HMAC secret key that will be used ... | CreatePhysicalClusterParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreatePhysicalClusterParameters:
"""Implementation of the 'CreatePhysicalClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: allow_api_based_fetch (bool): Specifies if API based GET should be enabled for cluster destroy params. cluster_destroy_hmac... | stack_v2_sparse_classes_75kplus_train_002288 | 5,957 | permissive | [
{
"docstring": "Constructor for the CreatePhysicalClusterParameters class",
"name": "__init__",
"signature": "def __init__(self, allow_api_based_fetch=None, cluster_destroy_hmac_key=None, cluster_name=None, enable_cluster_destroy=None, encryption_config=None, ip_preference=None, ipmi_config=None, metada... | 2 | stack_v2_sparse_classes_30k_train_024801 | Implement the Python class `CreatePhysicalClusterParameters` described below.
Class description:
Implementation of the 'CreatePhysicalClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: allow_api_based_fetch (bool): Specifies if API based GET should be enabled for clust... | Implement the Python class `CreatePhysicalClusterParameters` described below.
Class description:
Implementation of the 'CreatePhysicalClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: allow_api_based_fetch (bool): Specifies if API based GET should be enabled for clust... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CreatePhysicalClusterParameters:
"""Implementation of the 'CreatePhysicalClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: allow_api_based_fetch (bool): Specifies if API based GET should be enabled for cluster destroy params. cluster_destroy_hmac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreatePhysicalClusterParameters:
"""Implementation of the 'CreatePhysicalClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: allow_api_based_fetch (bool): Specifies if API based GET should be enabled for cluster destroy params. cluster_destroy_hmac_key (string)... | the_stack_v2_python_sparse | cohesity_management_sdk/models/create_physical_cluster_parameters.py | cohesity/management-sdk-python | train | 24 |
32d6f85fe9a503371e77c221fb8ff75a36535b0f | [
"super().__init__()\nassert len(weights) == len(values), 'The values and weights parameters must have same length.'\nself.weights = weights\nself.max_capacity = max_capacity\nself.values = values",
"selected_elements = individual.get_gen()\ntotal_weight = np.sum(np.array(self.weights) * np.array(selected_elements... | <|body_start_0|>
super().__init__()
assert len(weights) == len(values), 'The values and weights parameters must have same length.'
self.weights = weights
self.max_capacity = max_capacity
self.values = values
<|end_body_0|>
<|body_start_1|>
selected_elements = individual.... | Fitness Function Class for the 0-1 Knapsack problem. | KnapSackFitness_01 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnapSackFitness_01:
"""Fitness Function Class for the 0-1 Knapsack problem."""
def __init__(self, weights: list, values: list, max_capacity: int):
"""Generic constructor for the KnapSackFitness_01 class. :param weights: The weights of each kind of item. :param values: The values of e... | stack_v2_sparse_classes_75kplus_train_002289 | 1,826 | permissive | [
{
"docstring": "Generic constructor for the KnapSackFitness_01 class. :param weights: The weights of each kind of item. :param values: The values of each kind of item. :param max_capacity: Max amount of total weight supported.",
"name": "__init__",
"signature": "def __init__(self, weights: list, values:... | 2 | stack_v2_sparse_classes_30k_train_025719 | Implement the Python class `KnapSackFitness_01` described below.
Class description:
Fitness Function Class for the 0-1 Knapsack problem.
Method signatures and docstrings:
- def __init__(self, weights: list, values: list, max_capacity: int): Generic constructor for the KnapSackFitness_01 class. :param weights: The wei... | Implement the Python class `KnapSackFitness_01` described below.
Class description:
Fitness Function Class for the 0-1 Knapsack problem.
Method signatures and docstrings:
- def __init__(self, weights: list, values: list, max_capacity: int): Generic constructor for the KnapSackFitness_01 class. :param weights: The wei... | 16ee51ef168ff395ece6cd4e4bb04a01ee8277cd | <|skeleton|>
class KnapSackFitness_01:
"""Fitness Function Class for the 0-1 Knapsack problem."""
def __init__(self, weights: list, values: list, max_capacity: int):
"""Generic constructor for the KnapSackFitness_01 class. :param weights: The weights of each kind of item. :param values: The values of e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KnapSackFitness_01:
"""Fitness Function Class for the 0-1 Knapsack problem."""
def __init__(self, weights: list, values: list, max_capacity: int):
"""Generic constructor for the KnapSackFitness_01 class. :param weights: The weights of each kind of item. :param values: The values of each kind of i... | the_stack_v2_python_sparse | src/genetic_algorithm/FitnessGuys/KnapSack01Fitness.py | rudyn2/cc5114 | train | 3 |
866b3f169d931c9255c731bf768155a6ca175f94 | [
"items = [Selector(text=section) for section in re.split('\\\\<hr\\\\s*/?\\\\>', ' '.join(response.css('.box4 > *').extract()))]\nfor item in items:\n item_str = re.sub('\\\\s+', ' ', ' '.join(item.css('*::text').extract()))\n title = self._parse_title(item_str)\n if not title:\n continue\n class... | <|body_start_0|>
items = [Selector(text=section) for section in re.split('\\<hr\\s*/?\\>', ' '.join(response.css('.box4 > *').extract()))]
for item in items:
item_str = re.sub('\\s+', ' ', ' '.join(item.css('*::text').extract()))
title = self._parse_title(item_str)
if... | CuyaSoldiersSailorsMonumentSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CuyaSoldiersSailorsMonumentSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_title(self, item_str):
"""Parse or generate meeti... | stack_v2_sparse_classes_75kplus_train_002290 | 3,364 | permissive | [
{
"docstring": "`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Parse or generate meeting title.",
"name": "_parse_title",
"signa... | 5 | stack_v2_sparse_classes_30k_train_046481 | Implement the Python class `CuyaSoldiersSailorsMonumentSpider` described below.
Class description:
Implement the CuyaSoldiersSailorsMonumentSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods t... | Implement the Python class `CuyaSoldiersSailorsMonumentSpider` described below.
Class description:
Implement the CuyaSoldiersSailorsMonumentSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods t... | 105ed65078ab4f7ca54193cc54c8c52dc174d08b | <|skeleton|>
class CuyaSoldiersSailorsMonumentSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_title(self, item_str):
"""Parse or generate meeti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CuyaSoldiersSailorsMonumentSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
items = [Selector(text=section) for section in re.split('\\<hr\\s*/?\\>', ' '.join(response.css('.... | the_stack_v2_python_sparse | city_scrapers/spiders/cuya_soldiers_sailors_monument.py | City-Bureau/city-scrapers-cle | train | 17 | |
138a97d2124d1e38e875f47a964e795cc7f712fb | [
"results = []\ndbUtil = MsqlTools()\npageNo = (page - 1) * limit\nif logName == '':\n sql = string.Template('select * from t_log order by operation_time $sortOrder limit $pageNo,$limit;')\n sql = sql.substitute(pageNo=pageNo, limit=limit, sortOrder=sortOrder)\n items = MsqlTools.get_all(dbUtil, sql)\n s... | <|body_start_0|>
results = []
dbUtil = MsqlTools()
pageNo = (page - 1) * limit
if logName == '':
sql = string.Template('select * from t_log order by operation_time $sortOrder limit $pageNo,$limit;')
sql = sql.substitute(pageNo=pageNo, limit=limit, sortOrder=sortOr... | db_log_list | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class db_log_list:
def show_log_list(self, page, limit, sortOrder, logName):
"""查询t_user表所有数据"""
<|body_0|>
def add_log(self, log_name, operation_type, operation_status, log_describes):
"""添加日志 :return:"""
<|body_1|>
def sector_user(self, login_name):
... | stack_v2_sparse_classes_75kplus_train_002291 | 3,370 | no_license | [
{
"docstring": "查询t_user表所有数据",
"name": "show_log_list",
"signature": "def show_log_list(self, page, limit, sortOrder, logName)"
},
{
"docstring": "添加日志 :return:",
"name": "add_log",
"signature": "def add_log(self, log_name, operation_type, operation_status, log_describes)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_044271 | Implement the Python class `db_log_list` described below.
Class description:
Implement the db_log_list class.
Method signatures and docstrings:
- def show_log_list(self, page, limit, sortOrder, logName): 查询t_user表所有数据
- def add_log(self, log_name, operation_type, operation_status, log_describes): 添加日志 :return:
- def ... | Implement the Python class `db_log_list` described below.
Class description:
Implement the db_log_list class.
Method signatures and docstrings:
- def show_log_list(self, page, limit, sortOrder, logName): 查询t_user表所有数据
- def add_log(self, log_name, operation_type, operation_status, log_describes): 添加日志 :return:
- def ... | 64ced2b9bd1fe9503521024ea2ddc05efc21f969 | <|skeleton|>
class db_log_list:
def show_log_list(self, page, limit, sortOrder, logName):
"""查询t_user表所有数据"""
<|body_0|>
def add_log(self, log_name, operation_type, operation_status, log_describes):
"""添加日志 :return:"""
<|body_1|>
def sector_user(self, login_name):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class db_log_list:
def show_log_list(self, page, limit, sortOrder, logName):
"""查询t_user表所有数据"""
results = []
dbUtil = MsqlTools()
pageNo = (page - 1) * limit
if logName == '':
sql = string.Template('select * from t_log order by operation_time $sortOrder limit $pa... | the_stack_v2_python_sparse | app/db/db_log_list.py | fzj123/auto_test_platform-master | train | 0 | |
18d7a3584f356d197fd4157235e0312993ebb46d | [
"def scale(value):\n if value == 1:\n return 0.4\n elif value < 3:\n return 0.7\n else:\n return 1\npost_count = Post.objects.all().count()\nppm = Post.objects.filter().annotate(m=TruncMonth('published')).values('m').annotate(c=Count('id')).order_by()\ntoday = datetime.today()\ndata = ... | <|body_start_0|>
def scale(value):
if value == 1:
return 0.4
elif value < 3:
return 0.7
else:
return 1
post_count = Post.objects.all().count()
ppm = Post.objects.filter().annotate(m=TruncMonth('published')).value... | Dashboard homepage featuring statistics about the instance. | Dashboard | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dashboard:
"""Dashboard homepage featuring statistics about the instance."""
def count_posts():
"""Count the published posts per month for the last 3 years."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Inject statistics."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_002292 | 5,772 | permissive | [
{
"docstring": "Count the published posts per month for the last 3 years.",
"name": "count_posts",
"signature": "def count_posts()"
},
{
"docstring": "Inject statistics.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023923 | Implement the Python class `Dashboard` described below.
Class description:
Dashboard homepage featuring statistics about the instance.
Method signatures and docstrings:
- def count_posts(): Count the published posts per month for the last 3 years.
- def get_context_data(self, **kwargs): Inject statistics. | Implement the Python class `Dashboard` described below.
Class description:
Dashboard homepage featuring statistics about the instance.
Method signatures and docstrings:
- def count_posts(): Count the published posts per month for the last 3 years.
- def get_context_data(self, **kwargs): Inject statistics.
<|skeleton... | e0a5e2614dd222ccd56a8945aba4fd28de85dd31 | <|skeleton|>
class Dashboard:
"""Dashboard homepage featuring statistics about the instance."""
def count_posts():
"""Count the published posts per month for the last 3 years."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Inject statistics."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dashboard:
"""Dashboard homepage featuring statistics about the instance."""
def count_posts():
"""Count the published posts per month for the last 3 years."""
def scale(value):
if value == 1:
return 0.4
elif value < 3:
return 0.7
... | the_stack_v2_python_sparse | src/dashboard/views.py | thesus/bokstaever | train | 0 |
e77a820a86d3222217a9fbe36cc494e583f4c6c5 | [
"try:\n date = ElectionDay.objects.get(date=self.kwargs['date'])\nexcept:\n raise APIException('No elections on {}.'.format(self.kwargs['date']))\ndivision_ids = []\nfor election in date.elections.all():\n if election.division.level == STATE_LEVEL and election.race.special:\n division_ids.append(ele... | <|body_start_0|>
try:
date = ElectionDay.objects.get(date=self.kwargs['date'])
except:
raise APIException('No elections on {}.'.format(self.kwargs['date']))
division_ids = []
for election in date.elections.all():
if election.division.level == STATE_LEV... | SpecialMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecialMixin:
def get_queryset(self):
"""Returns a queryset of all states holding a special election on a date."""
<|body_0|>
def get_serializer_context(self):
"""Adds ``election_day`` to serializer context."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_002293 | 5,447 | no_license | [
{
"docstring": "Returns a queryset of all states holding a special election on a date.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Adds ``election_day`` to serializer context.",
"name": "get_serializer_context",
"signature": "def get_serializer_cont... | 2 | stack_v2_sparse_classes_30k_train_019932 | Implement the Python class `SpecialMixin` described below.
Class description:
Implement the SpecialMixin class.
Method signatures and docstrings:
- def get_queryset(self): Returns a queryset of all states holding a special election on a date.
- def get_serializer_context(self): Adds ``election_day`` to serializer con... | Implement the Python class `SpecialMixin` described below.
Class description:
Implement the SpecialMixin class.
Method signatures and docstrings:
- def get_queryset(self): Returns a queryset of all states holding a special election on a date.
- def get_serializer_context(self): Adds ``election_day`` to serializer con... | 9137a0c59e044d081d6c34f0e9e97b789e69bdbf | <|skeleton|>
class SpecialMixin:
def get_queryset(self):
"""Returns a queryset of all states holding a special election on a date."""
<|body_0|>
def get_serializer_context(self):
"""Adds ``election_day`` to serializer context."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpecialMixin:
def get_queryset(self):
"""Returns a queryset of all states holding a special election on a date."""
try:
date = ElectionDay.objects.get(date=self.kwargs['date'])
except:
raise APIException('No elections on {}.'.format(self.kwargs['date']))
... | the_stack_v2_python_sparse | theshow/viewsets.py | The-Politico/politico-elections | train | 0 | |
6d5188577d07d7c26f89e138628705f6c5bfac73 | [
"proc = subprocess.Popen(args_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shellind)\nproc_out, proc_err = proc.communicate()\nout, err = ([], [])\nif proc_out is not None and len(proc_out) > 0:\n out = proc_out.decode(errors='ignore')\nif proc_err is not None and len(proc_err) > 0:\n err = pro... | <|body_start_0|>
proc = subprocess.Popen(args_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shellind)
proc_out, proc_err = proc.communicate()
out, err = ([], [])
if proc_out is not None and len(proc_out) > 0:
out = proc_out.decode(errors='ignore')
if pro... | Utilities to work with shell and filesystem | OSUtils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OSUtils:
"""Utilities to work with shell and filesystem"""
def run_subprocess(cls, args_list, shellind=False):
"""Create subprocess and get stdout and stderr"""
<|body_0|>
def checkout_path(cls, path_to_file):
"""Returns ('/home/', 'file.ext', 'file') for input '... | stack_v2_sparse_classes_75kplus_train_002294 | 1,052 | no_license | [
{
"docstring": "Create subprocess and get stdout and stderr",
"name": "run_subprocess",
"signature": "def run_subprocess(cls, args_list, shellind=False)"
},
{
"docstring": "Returns ('/home/', 'file.ext', 'file') for input '/home/file.ext'",
"name": "checkout_path",
"signature": "def chec... | 2 | stack_v2_sparse_classes_30k_train_045539 | Implement the Python class `OSUtils` described below.
Class description:
Utilities to work with shell and filesystem
Method signatures and docstrings:
- def run_subprocess(cls, args_list, shellind=False): Create subprocess and get stdout and stderr
- def checkout_path(cls, path_to_file): Returns ('/home/', 'file.ext'... | Implement the Python class `OSUtils` described below.
Class description:
Utilities to work with shell and filesystem
Method signatures and docstrings:
- def run_subprocess(cls, args_list, shellind=False): Create subprocess and get stdout and stderr
- def checkout_path(cls, path_to_file): Returns ('/home/', 'file.ext'... | fe067bd01d8ed30abfc8f8a868fa8671e9f732a2 | <|skeleton|>
class OSUtils:
"""Utilities to work with shell and filesystem"""
def run_subprocess(cls, args_list, shellind=False):
"""Create subprocess and get stdout and stderr"""
<|body_0|>
def checkout_path(cls, path_to_file):
"""Returns ('/home/', 'file.ext', 'file') for input '... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OSUtils:
"""Utilities to work with shell and filesystem"""
def run_subprocess(cls, args_list, shellind=False):
"""Create subprocess and get stdout and stderr"""
proc = subprocess.Popen(args_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shellind)
proc_out, proc_err = ... | the_stack_v2_python_sparse | helpers/os_helper.py | zab88/mm | train | 0 |
e8d059f09f073f9569871df34e88dae4a05e5a90 | [
"class Group(object):\n group_id = 'group_id'\nself.pool = object()\nself.treq = object()\nself.clock = Clock()\nself.rcs = _FakeRCS()\nself.group = Group()\nself.servers = [{'metadata': {'rax:autoscale:group:id': 'wrong_id'}}, {'metadata': {}}]\n\ndef _list_servers(rcs, pool, _treq):\n self.assertEqual(rcs, ... | <|body_start_0|>
class Group(object):
group_id = 'group_id'
self.pool = object()
self.treq = object()
self.clock = Clock()
self.rcs = _FakeRCS()
self.group = Group()
self.servers = [{'metadata': {'rax:autoscale:group:id': 'wrong_id'}}, {'metadata': {}}... | Tests for :func:`nova.wait_for_server`. | NovaWaitForServersTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NovaWaitForServersTestCase:
"""Tests for :func:`nova.wait_for_server`."""
def setUp(self):
"""Set up fake pool, treq, responses, and RCS."""
<|body_0|>
def test_wait_for_servers_retries_until_matcher_matches(self):
"""If the matcher does not match the nova server... | stack_v2_sparse_classes_75kplus_train_002295 | 9,051 | permissive | [
{
"docstring": "Set up fake pool, treq, responses, and RCS.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "If the matcher does not match the nova servers state, retries until it does.",
"name": "test_wait_for_servers_retries_until_matcher_matches",
"signature": "def... | 4 | stack_v2_sparse_classes_30k_train_037795 | Implement the Python class `NovaWaitForServersTestCase` described below.
Class description:
Tests for :func:`nova.wait_for_server`.
Method signatures and docstrings:
- def setUp(self): Set up fake pool, treq, responses, and RCS.
- def test_wait_for_servers_retries_until_matcher_matches(self): If the matcher does not ... | Implement the Python class `NovaWaitForServersTestCase` described below.
Class description:
Tests for :func:`nova.wait_for_server`.
Method signatures and docstrings:
- def setUp(self): Set up fake pool, treq, responses, and RCS.
- def test_wait_for_servers_retries_until_matcher_matches(self): If the matcher does not ... | 7199cdd67255fe116dbcbedea660c13453671134 | <|skeleton|>
class NovaWaitForServersTestCase:
"""Tests for :func:`nova.wait_for_server`."""
def setUp(self):
"""Set up fake pool, treq, responses, and RCS."""
<|body_0|>
def test_wait_for_servers_retries_until_matcher_matches(self):
"""If the matcher does not match the nova server... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NovaWaitForServersTestCase:
"""Tests for :func:`nova.wait_for_server`."""
def setUp(self):
"""Set up fake pool, treq, responses, and RCS."""
class Group(object):
group_id = 'group_id'
self.pool = object()
self.treq = object()
self.clock = Clock()
... | the_stack_v2_python_sparse | otter/integration/lib/test_nova.py | rackerlabs/otter | train | 20 |
eabecbf81c3141845be41cdfcc84ba952da6ed5d | [
"self.name = name\nself.included_blk = []\nself.load_dat()",
"with open(self.name) as f:\n for line in f:\n if line[0:7].lower() == 'include':\n l_split = line.split()\n included = l_split[1]\n self.included_blk.append(included)"
] | <|body_start_0|>
self.name = name
self.included_blk = []
self.load_dat()
<|end_body_0|>
<|body_start_1|>
with open(self.name) as f:
for line in f:
if line[0:7].lower() == 'include':
l_split = line.split()
included = l_s... | Class of NASTRAN 103 run deck. | DAT103 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DAT103:
"""Class of NASTRAN 103 run deck."""
def __init__(self, name):
"""Initializing the NASTRAN 103 run deck."""
<|body_0|>
def load_dat(self):
"""Method to load the dat file information into the class."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_002296 | 641 | no_license | [
{
"docstring": "Initializing the NASTRAN 103 run deck.",
"name": "__init__",
"signature": "def __init__(self, name)"
},
{
"docstring": "Method to load the dat file information into the class.",
"name": "load_dat",
"signature": "def load_dat(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040223 | Implement the Python class `DAT103` described below.
Class description:
Class of NASTRAN 103 run deck.
Method signatures and docstrings:
- def __init__(self, name): Initializing the NASTRAN 103 run deck.
- def load_dat(self): Method to load the dat file information into the class. | Implement the Python class `DAT103` described below.
Class description:
Class of NASTRAN 103 run deck.
Method signatures and docstrings:
- def __init__(self, name): Initializing the NASTRAN 103 run deck.
- def load_dat(self): Method to load the dat file information into the class.
<|skeleton|>
class DAT103:
"""C... | 6b37842203ff4318a48dbf0258cbe2b253436e7d | <|skeleton|>
class DAT103:
"""Class of NASTRAN 103 run deck."""
def __init__(self, name):
"""Initializing the NASTRAN 103 run deck."""
<|body_0|>
def load_dat(self):
"""Method to load the dat file information into the class."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DAT103:
"""Class of NASTRAN 103 run deck."""
def __init__(self, name):
"""Initializing the NASTRAN 103 run deck."""
self.name = name
self.included_blk = []
self.load_dat()
def load_dat(self):
"""Method to load the dat file information into the class."""
... | the_stack_v2_python_sparse | loads/dat_classes.py | tslowery78/PyLnD | train | 0 |
3eb7607bc9f8e763415a3290bcb21389307eaf27 | [
"self._bp.HandleEvent(StateChartAuthorizationProcess.EVENT_APPROVE)\nself._bp.Commit()\nlimitOid = self._bp.Subject().Name()\nlimit = acm.FLimit[limitOid]\nmandate = Mandate(limit)\nlimit.Name(mandate.Name())\nlimit.LimitTarget().TemplatePath(self._bp.CurrentStep().DiaryEntry().Parameters()['Mandate target'])\nlimi... | <|body_start_0|>
self._bp.HandleEvent(StateChartAuthorizationProcess.EVENT_APPROVE)
self._bp.Commit()
limitOid = self._bp.Subject().Name()
limit = acm.FLimit[limitOid]
mandate = Mandate(limit)
limit.Name(mandate.Name())
limit.LimitTarget().TemplatePath(self._bp.Cu... | MenuItem on Business Process Sheet used to view a historical version of a specific breached mandate. | ApproveMandateMenuItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApproveMandateMenuItem:
"""MenuItem on Business Process Sheet used to view a historical version of a specific breached mandate."""
def _Approve(self):
"""Approve the mandate."""
<|body_0|>
def Invoke(self, eii):
"""OnClick method that executes when the menu item ... | stack_v2_sparse_classes_75kplus_train_002297 | 27,405 | no_license | [
{
"docstring": "Approve the mandate.",
"name": "_Approve",
"signature": "def _Approve(self)"
},
{
"docstring": "OnClick method that executes when the menu item is clicked. :param eii: FExtensionInvokationInfo",
"name": "Invoke",
"signature": "def Invoke(self, eii)"
},
{
"docstrin... | 4 | stack_v2_sparse_classes_30k_train_032861 | Implement the Python class `ApproveMandateMenuItem` described below.
Class description:
MenuItem on Business Process Sheet used to view a historical version of a specific breached mandate.
Method signatures and docstrings:
- def _Approve(self): Approve the mandate.
- def Invoke(self, eii): OnClick method that execute... | Implement the Python class `ApproveMandateMenuItem` described below.
Class description:
MenuItem on Business Process Sheet used to view a historical version of a specific breached mandate.
Method signatures and docstrings:
- def _Approve(self): Approve the mandate.
- def Invoke(self, eii): OnClick method that execute... | 5e7cc7de3495145501ca53deb9efee2233ab7e1c | <|skeleton|>
class ApproveMandateMenuItem:
"""MenuItem on Business Process Sheet used to view a historical version of a specific breached mandate."""
def _Approve(self):
"""Approve the mandate."""
<|body_0|>
def Invoke(self, eii):
"""OnClick method that executes when the menu item ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApproveMandateMenuItem:
"""MenuItem on Business Process Sheet used to view a historical version of a specific breached mandate."""
def _Approve(self):
"""Approve the mandate."""
self._bp.HandleEvent(StateChartAuthorizationProcess.EVENT_APPROVE)
self._bp.Commit()
limitOid =... | the_stack_v2_python_sparse | Extensions/GenericMandates/FPythonCode/GenericMandatesMenu.py | webclinic017/fa-absa-py3 | train | 0 |
bb9c313f4e43ad43334f9e63121f8ab9639d4ccd | [
"self.cluster_entity = cluster_entity\nself.datacenter_entity = datacenter_entity\nself.power_state_config = power_state_config\nself.rename_restored_object_param = rename_restored_object_param\nself.restored_objects_network_config = restored_objects_network_config\nself.storagedomain_entity = storagedomain_entity"... | <|body_start_0|>
self.cluster_entity = cluster_entity
self.datacenter_entity = datacenter_entity
self.power_state_config = power_state_config
self.rename_restored_object_param = rename_restored_object_param
self.restored_objects_network_config = restored_objects_network_config
... | Implementation of the 'RestoreKVMVMsParams' model. TODO: type model description here. Attributes: cluster_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. datacenter_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. power_state_config (Pow... | RestoreKVMVMsParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreKVMVMsParams:
"""Implementation of the 'RestoreKVMVMsParams' model. TODO: type model description here. Attributes: cluster_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. datacenter_entity (EntityProto): Specifies the attributes and the latest stat... | stack_v2_sparse_classes_75kplus_train_002298 | 4,642 | permissive | [
{
"docstring": "Constructor for the RestoreKVMVMsParams class",
"name": "__init__",
"signature": "def __init__(self, cluster_entity=None, datacenter_entity=None, power_state_config=None, rename_restored_object_param=None, restored_objects_network_config=None, storagedomain_entity=None)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_003052 | Implement the Python class `RestoreKVMVMsParams` described below.
Class description:
Implementation of the 'RestoreKVMVMsParams' model. TODO: type model description here. Attributes: cluster_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. datacenter_entity (EntityProto): Speci... | Implement the Python class `RestoreKVMVMsParams` described below.
Class description:
Implementation of the 'RestoreKVMVMsParams' model. TODO: type model description here. Attributes: cluster_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. datacenter_entity (EntityProto): Speci... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreKVMVMsParams:
"""Implementation of the 'RestoreKVMVMsParams' model. TODO: type model description here. Attributes: cluster_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. datacenter_entity (EntityProto): Specifies the attributes and the latest stat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RestoreKVMVMsParams:
"""Implementation of the 'RestoreKVMVMsParams' model. TODO: type model description here. Attributes: cluster_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. datacenter_entity (EntityProto): Specifies the attributes and the latest statistics about ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_kvmv_ms_params.py | cohesity/management-sdk-python | train | 24 |
481b570b049d5bae3905c4fe1f4651c79f43d4f9 | [
"element1 = 1\nelement2 = 2\nelement3 = element1\nelement4 = 4\nelement5 = element4\nelement6 = 6\nunique_list = helpers.UniqueList([element1, element2, element3, element4, element5, element6])\nself.assertEqual(4, len(unique_list))\nself.assertEqual([element1, element2, element4, element6], unique_list.list)",
"... | <|body_start_0|>
element1 = 1
element2 = 2
element3 = element1
element4 = 4
element5 = element4
element6 = 6
unique_list = helpers.UniqueList([element1, element2, element3, element4, element5, element6])
self.assertEqual(4, len(unique_list))
self.a... | Tests for `UniqueList` classes. | UniqueListTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UniqueListTest:
"""Tests for `UniqueList` classes."""
def test_construct(self):
"""Tests the `UniqueList` constructor."""
<|body_0|>
def test_append_raises(self):
"""Tests that "append" raises when given the wrong type."""
<|body_1|>
def test_add(sel... | stack_v2_sparse_classes_75kplus_train_002299 | 5,971 | permissive | [
{
"docstring": "Tests the `UniqueList` constructor.",
"name": "test_construct",
"signature": "def test_construct(self)"
},
{
"docstring": "Tests that \"append\" raises when given the wrong type.",
"name": "test_append_raises",
"signature": "def test_append_raises(self)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_033879 | Implement the Python class `UniqueListTest` described below.
Class description:
Tests for `UniqueList` classes.
Method signatures and docstrings:
- def test_construct(self): Tests the `UniqueList` constructor.
- def test_append_raises(self): Tests that "append" raises when given the wrong type.
- def test_add(self): ... | Implement the Python class `UniqueListTest` described below.
Class description:
Tests for `UniqueList` classes.
Method signatures and docstrings:
- def test_construct(self): Tests the `UniqueList` constructor.
- def test_append_raises(self): Tests that "append" raises when given the wrong type.
- def test_add(self): ... | 2cc7d204b206674d4ca648965c6a3deb4ef6783a | <|skeleton|>
class UniqueListTest:
"""Tests for `UniqueList` classes."""
def test_construct(self):
"""Tests the `UniqueList` constructor."""
<|body_0|>
def test_append_raises(self):
"""Tests that "append" raises when given the wrong type."""
<|body_1|>
def test_add(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UniqueListTest:
"""Tests for `UniqueList` classes."""
def test_construct(self):
"""Tests the `UniqueList` constructor."""
element1 = 1
element2 = 2
element3 = element1
element4 = 4
element5 = element4
element6 = 6
unique_list = helpers.Uniqu... | the_stack_v2_python_sparse | tensorflow_constrained_optimization/python/rates/helpers_test.py | autoih/tensorflow_constrained_optimization | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.