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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
da1d2eda97be2578ba2f29834122b116e3c305f3 | [
"super().__init__(coordinator, entry, system_zone_id, zone_data)\nself._attr_name = f'{zone_data[AZD_NAME]} {description.name}'\nself._attr_unique_id = f'{self._attr_unique_id}_{system_zone_id}_{description.key}'\nself.entity_description = description\nself.values_dict = {v: k for k, v in description.options_dict.i... | <|body_start_0|>
super().__init__(coordinator, entry, system_zone_id, zone_data)
self._attr_name = f'{zone_data[AZD_NAME]} {description.name}'
self._attr_unique_id = f'{self._attr_unique_id}_{system_zone_id}_{description.key}'
self.entity_description = description
self.values_dic... | Define an Airzone Zone select. | AirzoneZoneSelect | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AirzoneZoneSelect:
"""Define an Airzone Zone select."""
def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> None:
"""Initialize."""
<|body_0|>
async def as... | stack_v2_sparse_classes_75kplus_train_070700 | 4,946 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> None"
},
{
"docstring": "Change the selected option.",
"name... | 2 | stack_v2_sparse_classes_30k_train_052402 | Implement the Python class `AirzoneZoneSelect` described below.
Class description:
Define an Airzone Zone select.
Method signatures and docstrings:
- def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> ... | Implement the Python class `AirzoneZoneSelect` described below.
Class description:
Define an Airzone Zone select.
Method signatures and docstrings:
- def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class AirzoneZoneSelect:
"""Define an Airzone Zone select."""
def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> None:
"""Initialize."""
<|body_0|>
async def as... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AirzoneZoneSelect:
"""Define an Airzone Zone select."""
def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> None:
"""Initialize."""
super().__init__(coordinator, entry, syst... | the_stack_v2_python_sparse | homeassistant/components/airzone/select.py | home-assistant/core | train | 35,501 |
d611e45d78aa1ba92ad8ee76474e008b6ac425fc | [
"email_regex = '^\\\\w+([\\\\.-]?\\\\w+)*@\\\\w+([\\\\.-]?\\\\w+)*(\\\\.\\\\w{2,3})+$'\nif 'email' not in login_request:\n raise ValidationError('Missing email!')\nif not re.search(email_regex, login_request['email']):\n raise ValidationError('Email is not valid!')\nCredentialView.validate_credential_request(... | <|body_start_0|>
email_regex = '^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$'
if 'email' not in login_request:
raise ValidationError('Missing email!')
if not re.search(email_regex, login_request['email']):
raise ValidationError('Email is not valid!')
Cred... | Login endpoint and validator | AuthLoginView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthLoginView:
"""Login endpoint and validator"""
def validate_login_request(login_request):
"""Validates the login information received in the request body :param login_request: Login information received in the request"""
<|body_0|>
def post(request):
"""Action... | stack_v2_sparse_classes_75kplus_train_070701 | 3,191 | no_license | [
{
"docstring": "Validates the login information received in the request body :param login_request: Login information received in the request",
"name": "validate_login_request",
"signature": "def validate_login_request(login_request)"
},
{
"docstring": "Action when calling the endpoint with POST ... | 2 | stack_v2_sparse_classes_30k_train_012046 | Implement the Python class `AuthLoginView` described below.
Class description:
Login endpoint and validator
Method signatures and docstrings:
- def validate_login_request(login_request): Validates the login information received in the request body :param login_request: Login information received in the request
- def ... | Implement the Python class `AuthLoginView` described below.
Class description:
Login endpoint and validator
Method signatures and docstrings:
- def validate_login_request(login_request): Validates the login information received in the request body :param login_request: Login information received in the request
- def ... | 941e8b2870f8724db3d5103dda5157fd597cfcc7 | <|skeleton|>
class AuthLoginView:
"""Login endpoint and validator"""
def validate_login_request(login_request):
"""Validates the login information received in the request body :param login_request: Login information received in the request"""
<|body_0|>
def post(request):
"""Action... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthLoginView:
"""Login endpoint and validator"""
def validate_login_request(login_request):
"""Validates the login information received in the request body :param login_request: Login information received in the request"""
email_regex = '^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3}... | the_stack_v2_python_sparse | backend/martin_helder/views/auth_login_view.py | JoaoAlvaroFerreira/FEUP-LGP | train | 1 |
eb3d0df096852244ec10f099054c8f783a4b3960 | [
"if 'ticker' not in request.GET:\n return Response({'error': 'ticker is required in url parameter'})\nticker = request.GET['ticker']\nstart = datetime.datetime.strptime(request.GET['start_date'], '%Y-%m-%d') if 'start_date' in request.GET else None\nend = datetime.datetime.strptime(request.GET['end_date'], '%Y-%... | <|body_start_0|>
if 'ticker' not in request.GET:
return Response({'error': 'ticker is required in url parameter'})
ticker = request.GET['ticker']
start = datetime.datetime.strptime(request.GET['start_date'], '%Y-%m-%d') if 'start_date' in request.GET else None
end = datetime.... | StockQuoteAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StockQuoteAPI:
def get(self, request):
"""Fetches all historical stock quote data on input stock :param request: ticker (required), start_date (optional), end_date (optional) :return:"""
<|body_0|>
def post(self, request):
"""Updates input stock historical quote data... | stack_v2_sparse_classes_75kplus_train_070702 | 5,634 | no_license | [
{
"docstring": "Fetches all historical stock quote data on input stock :param request: ticker (required), start_date (optional), end_date (optional) :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Updates input stock historical quote data from start_date to end... | 2 | stack_v2_sparse_classes_30k_train_039361 | Implement the Python class `StockQuoteAPI` described below.
Class description:
Implement the StockQuoteAPI class.
Method signatures and docstrings:
- def get(self, request): Fetches all historical stock quote data on input stock :param request: ticker (required), start_date (optional), end_date (optional) :return:
- ... | Implement the Python class `StockQuoteAPI` described below.
Class description:
Implement the StockQuoteAPI class.
Method signatures and docstrings:
- def get(self, request): Fetches all historical stock quote data on input stock :param request: ticker (required), start_date (optional), end_date (optional) :return:
- ... | 4152483b1d507da6785b830154283aa76f25cef9 | <|skeleton|>
class StockQuoteAPI:
def get(self, request):
"""Fetches all historical stock quote data on input stock :param request: ticker (required), start_date (optional), end_date (optional) :return:"""
<|body_0|>
def post(self, request):
"""Updates input stock historical quote data... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StockQuoteAPI:
def get(self, request):
"""Fetches all historical stock quote data on input stock :param request: ticker (required), start_date (optional), end_date (optional) :return:"""
if 'ticker' not in request.GET:
return Response({'error': 'ticker is required in url parameter'... | the_stack_v2_python_sparse | backend/bluedresscapital/stock_apis.py | jaysunmah/bdc_v4 | train | 0 | |
8672894bd19dcc176d26377c2996aa508ee10254 | [
"if isinstance(reference, pd.DataFrame):\n reference = reference.values\nself.reference = reference\nself.scalers = {}",
"if not (log, scale) in self.scalers.keys():\n scaler = None\n ref = self.reference.copy()\n if log:\n ref = np.log2(ref + 1)\n if scale == 'minmax':\n scaler = pp.... | <|body_start_0|>
if isinstance(reference, pd.DataFrame):
reference = reference.values
self.reference = reference
self.scalers = {}
<|end_body_0|>
<|body_start_1|>
if not (log, scale) in self.scalers.keys():
scaler = None
ref = self.reference.copy()
... | CustomScaler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomScaler:
def __init__(self, reference: np.ndarray):
""":param reference: np.ndarray or pandas DF on which to fit scaler"""
<|body_0|>
def transform(self, data: np.ndarray, log, scale: str):
""":param data: Data to be scaled. np.ndarray od pandas DF. :param log: ... | stack_v2_sparse_classes_75kplus_train_070703 | 30,611 | no_license | [
{
"docstring": ":param reference: np.ndarray or pandas DF on which to fit scaler",
"name": "__init__",
"signature": "def __init__(self, reference: np.ndarray)"
},
{
"docstring": ":param data: Data to be scaled. np.ndarray od pandas DF. :param log: log2(data+1) :param scale: 'minmax','m0s1','divi... | 2 | null | Implement the Python class `CustomScaler` described below.
Class description:
Implement the CustomScaler class.
Method signatures and docstrings:
- def __init__(self, reference: np.ndarray): :param reference: np.ndarray or pandas DF on which to fit scaler
- def transform(self, data: np.ndarray, log, scale: str): :par... | Implement the Python class `CustomScaler` described below.
Class description:
Implement the CustomScaler class.
Method signatures and docstrings:
- def __init__(self, reference: np.ndarray): :param reference: np.ndarray or pandas DF on which to fit scaler
- def transform(self, data: np.ndarray, log, scale: str): :par... | 7884e1a53f75c94c08d1e2732825c5c52dbb4884 | <|skeleton|>
class CustomScaler:
def __init__(self, reference: np.ndarray):
""":param reference: np.ndarray or pandas DF on which to fit scaler"""
<|body_0|>
def transform(self, data: np.ndarray, log, scale: str):
""":param data: Data to be scaled. np.ndarray od pandas DF. :param log: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomScaler:
def __init__(self, reference: np.ndarray):
""":param reference: np.ndarray or pandas DF on which to fit scaler"""
if isinstance(reference, pd.DataFrame):
reference = reference.values
self.reference = reference
self.scalers = {}
def transform(self,... | the_stack_v2_python_sparse | PC1vsTime_plots.py | biolab/baylor_dicty_paper | train | 0 | |
efbbee2eb34af0ce7b13edd3e8d7d3f267e9322e | [
"add_common_arguments, add_ext_arguments = (mock.Mock(), mock.Mock())\nbase.BaseAction.add_common_arguments = add_common_arguments\nbase.BaseAction.add_ext_arguments = add_ext_arguments\nparser = base.BaseAction.get_argument_parser()\nself.assertEqual(add_common_arguments.call_count, 1)\nself.assertEqual(add_ext_ar... | <|body_start_0|>
add_common_arguments, add_ext_arguments = (mock.Mock(), mock.Mock())
base.BaseAction.add_common_arguments = add_common_arguments
base.BaseAction.add_ext_arguments = add_ext_arguments
parser = base.BaseAction.get_argument_parser()
self.assertEqual(add_common_argum... | BaseActionTest | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseActionTest:
def test_get_argument_parser(self):
""":return:"""
<|body_0|>
def test_add_common_arguments(self):
"""成功调用一次call_count :return:"""
<|body_1|>
def test_main(self):
"""成功调用get_argument_parser,build_directive方法和send_request函数 :return... | stack_v2_sparse_classes_75kplus_train_070704 | 2,547 | permissive | [
{
"docstring": ":return:",
"name": "test_get_argument_parser",
"signature": "def test_get_argument_parser(self)"
},
{
"docstring": "成功调用一次call_count :return:",
"name": "test_add_common_arguments",
"signature": "def test_add_common_arguments(self)"
},
{
"docstring": "成功调用get_argum... | 4 | null | Implement the Python class `BaseActionTest` described below.
Class description:
Implement the BaseActionTest class.
Method signatures and docstrings:
- def test_get_argument_parser(self): :return:
- def test_add_common_arguments(self): 成功调用一次call_count :return:
- def test_main(self): 成功调用get_argument_parser,build_dir... | Implement the Python class `BaseActionTest` described below.
Class description:
Implement the BaseActionTest class.
Method signatures and docstrings:
- def test_get_argument_parser(self): :return:
- def test_add_common_arguments(self): 成功调用一次call_count :return:
- def test_main(self): 成功调用get_argument_parser,build_dir... | ca197a2953ee69c052148f6e2fa686960b3f89bd | <|skeleton|>
class BaseActionTest:
def test_get_argument_parser(self):
""":return:"""
<|body_0|>
def test_add_common_arguments(self):
"""成功调用一次call_count :return:"""
<|body_1|>
def test_main(self):
"""成功调用get_argument_parser,build_directive方法和send_request函数 :return... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseActionTest:
def test_get_argument_parser(self):
""":return:"""
add_common_arguments, add_ext_arguments = (mock.Mock(), mock.Mock())
base.BaseAction.add_common_arguments = add_common_arguments
base.BaseAction.add_ext_arguments = add_ext_arguments
parser = base.BaseAc... | the_stack_v2_python_sparse | cli/instance_op/base_test.py | JiangKui007/qingcloud-cli-mini | train | 0 | |
7311df9e8f4f9c7106d35edc2fa9d71ba4d9b600 | [
"username = self.cleaned_data['username']\nif UserModelClass.objects.filter(username=username):\n raise ValidationError('用户名已被注册')\nelse:\n return username",
"password = self.cleaned_data['password']\nr_pwd = self.cleaned_data['r_pwd']\nif password != r_pwd:\n raise ValidationError('两次密码不一致')\nelse:\n ... | <|body_start_0|>
username = self.cleaned_data['username']
if UserModelClass.objects.filter(username=username):
raise ValidationError('用户名已被注册')
else:
return username
<|end_body_0|>
<|body_start_1|>
password = self.cleaned_data['password']
r_pwd = self.cle... | 利用modelform来控制表,可以读可以新增 | UserModelForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserModelForm:
"""利用modelform来控制表,可以读可以新增"""
def clean_username(self):
"""局部钩子校验用户名是否存在"""
<|body_0|>
def clean_r_pwd(self):
"""局部钩子校验两次密码是否一致"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
username = self.cleaned_data['username']
if Us... | stack_v2_sparse_classes_75kplus_train_070705 | 6,400 | no_license | [
{
"docstring": "局部钩子校验用户名是否存在",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "局部钩子校验两次密码是否一致",
"name": "clean_r_pwd",
"signature": "def clean_r_pwd(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032749 | Implement the Python class `UserModelForm` described below.
Class description:
利用modelform来控制表,可以读可以新增
Method signatures and docstrings:
- def clean_username(self): 局部钩子校验用户名是否存在
- def clean_r_pwd(self): 局部钩子校验两次密码是否一致 | Implement the Python class `UserModelForm` described below.
Class description:
利用modelform来控制表,可以读可以新增
Method signatures and docstrings:
- def clean_username(self): 局部钩子校验用户名是否存在
- def clean_r_pwd(self): 局部钩子校验两次密码是否一致
<|skeleton|>
class UserModelForm:
"""利用modelform来控制表,可以读可以新增"""
def clean_username(self):... | 9f0ccdaa532c5a5bc5f1eddc2c86ed2b0304b2e6 | <|skeleton|>
class UserModelForm:
"""利用modelform来控制表,可以读可以新增"""
def clean_username(self):
"""局部钩子校验用户名是否存在"""
<|body_0|>
def clean_r_pwd(self):
"""局部钩子校验两次密码是否一致"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserModelForm:
"""利用modelform来控制表,可以读可以新增"""
def clean_username(self):
"""局部钩子校验用户名是否存在"""
username = self.cleaned_data['username']
if UserModelClass.objects.filter(username=username):
raise ValidationError('用户名已被注册')
else:
return username
def ... | the_stack_v2_python_sparse | rbac/forms/model_form.py | quegai18/project-demo | train | 0 |
2183df1904056ec1719f5874a743a947446ed481 | [
"self.word_indices = defaultdict(list)\nfor index, word in enumerate(words):\n self.word_indices[word].append(index)",
"list1 = self.word_indices[word1]\nlist2 = self.word_indices[word2]\nptr1 = ptr2 = 0\nans = (1 << 31) - 1\nwhile ptr1 < len(list1) and ptr2 < len(list2):\n while ptr1 < len(list1) and list1... | <|body_start_0|>
self.word_indices = defaultdict(list)
for index, word in enumerate(words):
self.word_indices[word].append(index)
<|end_body_0|>
<|body_start_1|>
list1 = self.word_indices[word1]
list2 = self.word_indices[word2]
ptr1 = ptr2 = 0
ans = (1 << 31)... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.word_indices = defaultdict(list)... | stack_v2_sparse_classes_75kplus_train_070706 | 1,151 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048114 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 5e09a5d36ac55d782628a888ad57d48e234b61ac | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.word_indices = defaultdict(list)
for index, word in enumerate(words):
self.word_indices[word].append(index)
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype:... | the_stack_v2_python_sparse | 244/244.py | sjzyjc/leetcode | train | 0 | |
f15df479c6a2892d19a92f4acc8c92bd9d64a399 | [
"super(PostingList, self).__init__(*arg, **kwargs)\nself.add_handlers({'+': self.move_up, '-': self.move_down})\nself.scroll_exit = True",
"lis = self.values\nif len(lis) < 2:\n return False\nnew_index = move_list_entry(lis=lis, index=self.cursor_line, direction=1)\nself.cursor_line = new_index",
"lis = self... | <|body_start_0|>
super(PostingList, self).__init__(*arg, **kwargs)
self.add_handlers({'+': self.move_up, '-': self.move_down})
self.scroll_exit = True
<|end_body_0|>
<|body_start_1|>
lis = self.values
if len(lis) < 2:
return False
new_index = move_list_entry(... | PostingList holding teh posts. | PostingList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostingList:
"""PostingList holding teh posts."""
def __init__(self, *arg, **kwargs):
"""Initialize the class."""
<|body_0|>
def move_up(self, keypress=None):
"""Move selected offer up in the list."""
<|body_1|>
def move_down(self, keypress=None):
... | stack_v2_sparse_classes_75kplus_train_070707 | 12,594 | no_license | [
{
"docstring": "Initialize the class.",
"name": "__init__",
"signature": "def __init__(self, *arg, **kwargs)"
},
{
"docstring": "Move selected offer up in the list.",
"name": "move_up",
"signature": "def move_up(self, keypress=None)"
},
{
"docstring": "Move selected offer down in... | 3 | stack_v2_sparse_classes_30k_train_034732 | Implement the Python class `PostingList` described below.
Class description:
PostingList holding teh posts.
Method signatures and docstrings:
- def __init__(self, *arg, **kwargs): Initialize the class.
- def move_up(self, keypress=None): Move selected offer up in the list.
- def move_down(self, keypress=None): Move s... | Implement the Python class `PostingList` described below.
Class description:
PostingList holding teh posts.
Method signatures and docstrings:
- def __init__(self, *arg, **kwargs): Initialize the class.
- def move_up(self, keypress=None): Move selected offer up in the list.
- def move_down(self, keypress=None): Move s... | a5b13c2a6191c3074e6b9b2e9c7672220b282911 | <|skeleton|>
class PostingList:
"""PostingList holding teh posts."""
def __init__(self, *arg, **kwargs):
"""Initialize the class."""
<|body_0|>
def move_up(self, keypress=None):
"""Move selected offer up in the list."""
<|body_1|>
def move_down(self, keypress=None):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostingList:
"""PostingList holding teh posts."""
def __init__(self, *arg, **kwargs):
"""Initialize the class."""
super(PostingList, self).__init__(*arg, **kwargs)
self.add_handlers({'+': self.move_up, '-': self.move_down})
self.scroll_exit = True
def move_up(self, ke... | the_stack_v2_python_sparse | npy_gui/npy_transactionform.py | Tagirijus/ledger-add | train | 7 |
d9ee8d8817e3d95297c0e1f1c5df35f1f95ff8a9 | [
"self.legend = legend\nself.ax = ax\nself.colors = ['b', 'g', 'r', 'c', 'm', 'y', 'b']\nself.line_styles = ['-', '-', '--', '-.', ':']\nself.line = []\nself.ax.set_ylabel(ylabel)\nself.ax.set_xlabel(xlabel)\nself.ax.set_title(title)\nself.ax.grid(True)\nself.init = True",
"if self.init == True:\n for i in rang... | <|body_start_0|>
self.legend = legend
self.ax = ax
self.colors = ['b', 'g', 'r', 'c', 'm', 'y', 'b']
self.line_styles = ['-', '-', '--', '-.', ':']
self.line = []
self.ax.set_ylabel(ylabel)
self.ax.set_xlabel(xlabel)
self.ax.set_title(title)
self.a... | Create each individual subplot. | myPlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class myPlot:
"""Create each individual subplot."""
def __init__(self, ax, xlabel='', ylabel='', title='', legend=None):
"""ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis title - Plot title legend - A tuple of strings that identify... | stack_v2_sparse_classes_75kplus_train_070708 | 6,668 | no_license | [
{
"docstring": "ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis title - Plot title legend - A tuple of strings that identify the data. EX: (\"data1\",\"data2\", ... , \"dataN\")",
"name": "__init__",
"signature": "def __init__(self, ax, xlabel=''... | 2 | stack_v2_sparse_classes_30k_train_018141 | Implement the Python class `myPlot` described below.
Class description:
Create each individual subplot.
Method signatures and docstrings:
- def __init__(self, ax, xlabel='', ylabel='', title='', legend=None): ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis tit... | Implement the Python class `myPlot` described below.
Class description:
Create each individual subplot.
Method signatures and docstrings:
- def __init__(self, ax, xlabel='', ylabel='', title='', legend=None): ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis tit... | 498a54f9777c5a849b0af491d9e76fcc470aa083 | <|skeleton|>
class myPlot:
"""Create each individual subplot."""
def __init__(self, ax, xlabel='', ylabel='', title='', legend=None):
"""ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis title - Plot title legend - A tuple of strings that identify... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class myPlot:
"""Create each individual subplot."""
def __init__(self, ax, xlabel='', ylabel='', title='', legend=None):
"""ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis title - Plot title legend - A tuple of strings that identify the data. EX... | the_stack_v2_python_sparse | DeepWNCS/Testbed/Plant-side/Plotter.py | msh0576/RL_WCPS | train | 1 |
597b1d2e98a7ec1dbf7cec6655f6169114c70831 | [
"work_pool = await models.workers.read_work_pool_by_name(session=session, work_pool_name=work_pool_name)\nif not work_pool:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Worker pool \"{work_pool_name}\" not found.')\nreturn work_pool.id",
"work_pool = await models.workers.read_work_pool... | <|body_start_0|>
work_pool = await models.workers.read_work_pool_by_name(session=session, work_pool_name=work_pool_name)
if not work_pool:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Worker pool "{work_pool_name}" not found.')
return work_pool.id
<|end_body_0|... | WorkerLookups | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkerLookups:
async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID:
"""Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
<|body_0|>
async d... | stack_v2_sparse_classes_75kplus_train_070709 | 16,683 | permissive | [
{
"docstring": "Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).",
"name": "_get_work_pool_id_from_name",
"signature": "async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUI... | 3 | stack_v2_sparse_classes_30k_train_020461 | Implement the Python class `WorkerLookups` described below.
Class description:
Implement the WorkerLookups class.
Method signatures and docstrings:
- async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: Given a work pool name, return its ID. Used for translating user-facing... | Implement the Python class `WorkerLookups` described below.
Class description:
Implement the WorkerLookups class.
Method signatures and docstrings:
- async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: Given a work pool name, return its ID. Used for translating user-facing... | 355d5de4b29720d9a81c12fd77ef734fc2c1733b | <|skeleton|>
class WorkerLookups:
async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID:
"""Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
<|body_0|>
async d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkerLookups:
async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID:
"""Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
work_pool = await models.workers.read... | the_stack_v2_python_sparse | src/prefect/orion/api/workers.py | Clearcover/prefect | train | 1 | |
684660be30a101fd1977c5f5efcf03c48f5d7e6a | [
"super().__init__()\nassert hasattr(conv_channels, '__len__')\nassert hasattr(conv_kernels, '__len__')\nassert hasattr(conv_strides, '__len__')\nassert len(conv_channels) == len(conv_kernels)\nassert len(conv_channels) == len(conv_strides)\nassert map_to_emb or rnn_hidden_size * (1 + int(rnn_bidir)) == emb_dim\nsel... | <|body_start_0|>
super().__init__()
assert hasattr(conv_channels, '__len__')
assert hasattr(conv_kernels, '__len__')
assert hasattr(conv_strides, '__len__')
assert len(conv_channels) == len(conv_kernels)
assert len(conv_channels) == len(conv_strides)
assert map_to... | Architecture used in `Learning Deep Representations of Fine-Grained Visual Descriptions`. However, note that the hidden state of only the last layer hidden of the RNN is used to compute the embedding. | HybridCNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HybridCNN:
"""Architecture used in `Learning Deep Representations of Fine-Grained Visual Descriptions`. However, note that the hidden state of only the last layer hidden of the RNN is used to compute the embedding."""
def __init__(self, vocab_dim: int, conv_channels, conv_kernels, conv_strid... | stack_v2_sparse_classes_75kplus_train_070710 | 4,980 | permissive | [
{
"docstring": "Initialize HybridCNN.",
"name": "__init__",
"signature": "def __init__(self, vocab_dim: int, conv_channels, conv_kernels, conv_strides, rnn_hidden_size: int, rnn_num_layers: int, emb_dim=1024, conv_dropout=0.0, rnn_dropout=0.0, lin_dropout=0.0, rnn_bidir=False, lstm=False, map_to_emb=Tru... | 4 | stack_v2_sparse_classes_30k_train_046616 | Implement the Python class `HybridCNN` described below.
Class description:
Architecture used in `Learning Deep Representations of Fine-Grained Visual Descriptions`. However, note that the hidden state of only the last layer hidden of the RNN is used to compute the embedding.
Method signatures and docstrings:
- def __... | Implement the Python class `HybridCNN` described below.
Class description:
Architecture used in `Learning Deep Representations of Fine-Grained Visual Descriptions`. However, note that the hidden state of only the last layer hidden of the RNN is used to compute the embedding.
Method signatures and docstrings:
- def __... | 7a452e581edcd57ef5f0fa78c3a3d47224c80577 | <|skeleton|>
class HybridCNN:
"""Architecture used in `Learning Deep Representations of Fine-Grained Visual Descriptions`. However, note that the hidden state of only the last layer hidden of the RNN is used to compute the embedding."""
def __init__(self, vocab_dim: int, conv_channels, conv_kernels, conv_strid... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HybridCNN:
"""Architecture used in `Learning Deep Representations of Fine-Grained Visual Descriptions`. However, note that the hidden state of only the last layer hidden of the RNN is used to compute the embedding."""
def __init__(self, vocab_dim: int, conv_channels, conv_kernels, conv_strides, rnn_hidde... | the_stack_v2_python_sparse | crnns4captions/encoders/text_encoder.py | JackeyWang777/Deep-Representations-of-Visual-Descriptions | train | 0 |
448505e7ae0e80d6a293fbe24ffb03f0408df040 | [
"super(MultiHeadAttention, self).__init__()\nself.qSize = qSize\nself.kSize = kSize\nself.vSize = vSize\nself.numHeads = numHeads\nself.W_Q = nn.Linear(embSize, qSize * numHeads, bias=bias)\nself.W_K = nn.Linear(embSize, kSize * numHeads, bias=bias)\nself.W_V = nn.Linear(embSize, vSize * numHeads, bias=bias)\nself.... | <|body_start_0|>
super(MultiHeadAttention, self).__init__()
self.qSize = qSize
self.kSize = kSize
self.vSize = vSize
self.numHeads = numHeads
self.W_Q = nn.Linear(embSize, qSize * numHeads, bias=bias)
self.W_K = nn.Linear(embSize, kSize * numHeads, bias=bias)
... | MultiHeadAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
def __init__(self, embSize, qSize, kSize, vSize, numHeads=numHeads, bias=bias):
"""@doc: 该类主要根据输入生成对应的多头注意力,输出维度为[batch_size, len(=seqLen or tgtLen), embSize] @author: Alpaca-Man @date: 2021/2/22 @param: { embSize: 词向量维度 qSize: Q 的维度 kSize: K 的维度(需要与 Q 的维度相等) vSize: V... | stack_v2_sparse_classes_75kplus_train_070711 | 13,592 | no_license | [
{
"docstring": "@doc: 该类主要根据输入生成对应的多头注意力,输出维度为[batch_size, len(=seqLen or tgtLen), embSize] @author: Alpaca-Man @date: 2021/2/22 @param: { embSize: 词向量维度 qSize: Q 的维度 kSize: K 的维度(需要与 Q 的维度相等) vSize: V 的维度 numHeads: 头数 default 8 bias: 偏置 default False } @return: { }",
"name": "__init__",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_test_002535 | Implement the Python class `MultiHeadAttention` described below.
Class description:
Implement the MultiHeadAttention class.
Method signatures and docstrings:
- def __init__(self, embSize, qSize, kSize, vSize, numHeads=numHeads, bias=bias): @doc: 该类主要根据输入生成对应的多头注意力,输出维度为[batch_size, len(=seqLen or tgtLen), embSize] @a... | Implement the Python class `MultiHeadAttention` described below.
Class description:
Implement the MultiHeadAttention class.
Method signatures and docstrings:
- def __init__(self, embSize, qSize, kSize, vSize, numHeads=numHeads, bias=bias): @doc: 该类主要根据输入生成对应的多头注意力,输出维度为[batch_size, len(=seqLen or tgtLen), embSize] @a... | 49824925970f0439634dc66a7f19edc512f18a5f | <|skeleton|>
class MultiHeadAttention:
def __init__(self, embSize, qSize, kSize, vSize, numHeads=numHeads, bias=bias):
"""@doc: 该类主要根据输入生成对应的多头注意力,输出维度为[batch_size, len(=seqLen or tgtLen), embSize] @author: Alpaca-Man @date: 2021/2/22 @param: { embSize: 词向量维度 qSize: Q 的维度 kSize: K 的维度(需要与 Q 的维度相等) vSize: V... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiHeadAttention:
def __init__(self, embSize, qSize, kSize, vSize, numHeads=numHeads, bias=bias):
"""@doc: 该类主要根据输入生成对应的多头注意力,输出维度为[batch_size, len(=seqLen or tgtLen), embSize] @author: Alpaca-Man @date: 2021/2/22 @param: { embSize: 词向量维度 qSize: Q 的维度 kSize: K 的维度(需要与 Q 的维度相等) vSize: V 的维度 numHeads:... | the_stack_v2_python_sparse | Transformer/standard/Math.py | Alpaca-Man/NLP-Newcomer | train | 1 | |
1f7893872d8aed1bbcb3797b0fd888ca3deec3a8 | [
"self.remote_addr = remote_addr\nself.remote_hpai = HPAI(*remote_addr, protocol=HostProtocol.IPV4_TCP)\nself.callbacks = []\nself._connection_lost_cb = connection_lost_cb\nself.transport: asyncio.Transport | None = None\nself._buffer = b''",
"if self._buffer:\n raw = self._buffer + raw\n self._buffer = b''\... | <|body_start_0|>
self.remote_addr = remote_addr
self.remote_hpai = HPAI(*remote_addr, protocol=HostProtocol.IPV4_TCP)
self.callbacks = []
self._connection_lost_cb = connection_lost_cb
self.transport: asyncio.Transport | None = None
self._buffer = b''
<|end_body_0|>
<|bod... | Class for handling (sending and receiving) TCP packets. | TCPTransport | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TCPTransport:
"""Class for handling (sending and receiving) TCP packets."""
def __init__(self, remote_addr: tuple[str, int], connection_lost_cb: Callable[[], None] | None=None):
"""Initialize TCPTransport class."""
<|body_0|>
def data_received_callback(self, raw: bytes) ... | stack_v2_sparse_classes_75kplus_train_070712 | 5,551 | permissive | [
{
"docstring": "Initialize TCPTransport class.",
"name": "__init__",
"signature": "def __init__(self, remote_addr: tuple[str, int], connection_lost_cb: Callable[[], None] | None=None)"
},
{
"docstring": "Parse and process KNXIP frame. Callback for having received data over TCP.",
"name": "da... | 5 | stack_v2_sparse_classes_30k_train_004946 | Implement the Python class `TCPTransport` described below.
Class description:
Class for handling (sending and receiving) TCP packets.
Method signatures and docstrings:
- def __init__(self, remote_addr: tuple[str, int], connection_lost_cb: Callable[[], None] | None=None): Initialize TCPTransport class.
- def data_rece... | Implement the Python class `TCPTransport` described below.
Class description:
Class for handling (sending and receiving) TCP packets.
Method signatures and docstrings:
- def __init__(self, remote_addr: tuple[str, int], connection_lost_cb: Callable[[], None] | None=None): Initialize TCPTransport class.
- def data_rece... | 48d4e31365c15e632b275f0d129cd9f2b2b5717d | <|skeleton|>
class TCPTransport:
"""Class for handling (sending and receiving) TCP packets."""
def __init__(self, remote_addr: tuple[str, int], connection_lost_cb: Callable[[], None] | None=None):
"""Initialize TCPTransport class."""
<|body_0|>
def data_received_callback(self, raw: bytes) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TCPTransport:
"""Class for handling (sending and receiving) TCP packets."""
def __init__(self, remote_addr: tuple[str, int], connection_lost_cb: Callable[[], None] | None=None):
"""Initialize TCPTransport class."""
self.remote_addr = remote_addr
self.remote_hpai = HPAI(*remote_add... | the_stack_v2_python_sparse | xknx/io/transport/tcp_transport.py | XKNX/xknx | train | 248 |
46b675e125d58dd79214bd5a9c45dd5ee0555b16 | [
"self.suitename = suitename\nself._subparser_src = None\nif parent_parser:\n self._subparser_src = parent_parser.add_subparsers(title='subcommands', dest=suitename + '_subcmd')\nself._cmds = {}",
"if not cmdname:\n cmdname = cmdmod.default_name\nsubparser = self._subparser_src.add_parser(cmdname, descriptio... | <|body_start_0|>
self.suitename = suitename
self._subparser_src = None
if parent_parser:
self._subparser_src = parent_parser.add_subparsers(title='subcommands', dest=suitename + '_subcmd')
self._cmds = {}
<|end_body_0|>
<|body_start_1|>
if not cmdname:
cm... | an interface for running the sub-commands of a parent command | CommandSuite | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandSuite:
"""an interface for running the sub-commands of a parent command"""
def __init__(self, suitename, parent_parser):
"""create a command interface :param str suitename: the command name used to access this suites' subcommands :param argparse.ArgumentParser parent_parser: t... | stack_v2_sparse_classes_75kplus_train_070713 | 15,842 | no_license | [
{
"docstring": "create a command interface :param str suitename: the command name used to access this suites' subcommands :param argparse.ArgumentParser parent_parser: the ArgumentParser for the command that this suite will be added into.",
"name": "__init__",
"signature": "def __init__(self, suitename,... | 4 | stack_v2_sparse_classes_30k_train_012358 | Implement the Python class `CommandSuite` described below.
Class description:
an interface for running the sub-commands of a parent command
Method signatures and docstrings:
- def __init__(self, suitename, parent_parser): create a command interface :param str suitename: the command name used to access this suites' su... | Implement the Python class `CommandSuite` described below.
Class description:
an interface for running the sub-commands of a parent command
Method signatures and docstrings:
- def __init__(self, suitename, parent_parser): create a command interface :param str suitename: the command name used to access this suites' su... | da8ddb1984a886e820827d3e757001a6c65af414 | <|skeleton|>
class CommandSuite:
"""an interface for running the sub-commands of a parent command"""
def __init__(self, suitename, parent_parser):
"""create a command interface :param str suitename: the command name used to access this suites' subcommands :param argparse.ArgumentParser parent_parser: t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommandSuite:
"""an interface for running the sub-commands of a parent command"""
def __init__(self, suitename, parent_parser):
"""create a command interface :param str suitename: the command name used to access this suites' subcommands :param argparse.ArgumentParser parent_parser: the ArgumentPa... | the_stack_v2_python_sparse | python/nistoar/pdr/cli.py | usnistgov/oar-pdr | train | 12 |
f5a3a16a56189f67a59a23bb45e4426a4dea559b | [
"gw_cfile = orm.ConfigFile.objects.get(path__contains='server for server in node.tinc.connect_to')\ngw_cfile.path = '[ \"/etc/confine/tinc-gateways/%s\" % server.name for server in node.tinc.connect_to ]'\ngw_cfile.save()",
"gw_cfile = orm.ConfigFile.objects.get(path__contains='server.name for server in node.tinc... | <|body_start_0|>
gw_cfile = orm.ConfigFile.objects.get(path__contains='server for server in node.tinc.connect_to')
gw_cfile.path = '[ "/etc/confine/tinc-gateways/%s" % server.name for server in node.tinc.connect_to ]'
gw_cfile.save()
<|end_body_0|>
<|body_start_1|>
gw_cfile = orm.Config... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Fix ConfigFile '/etc/confine/tinc-gateways/* path generation. Use tinc.name instead of tinc.__unicode__ == ConfigFiles == /etc/confine/tinc-gateways/NAME"""
<|body_0|>
def backwards(self, orm):
"""Undo patch."""
<|body_1... | stack_v2_sparse_classes_75kplus_train_070714 | 10,670 | no_license | [
{
"docstring": "Fix ConfigFile '/etc/confine/tinc-gateways/* path generation. Use tinc.name instead of tinc.__unicode__ == ConfigFiles == /etc/confine/tinc-gateways/NAME",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Undo patch.",
"name": "backwards",
"si... | 2 | stack_v2_sparse_classes_30k_train_020278 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Fix ConfigFile '/etc/confine/tinc-gateways/* path generation. Use tinc.name instead of tinc.__unicode__ == ConfigFiles == /etc/confine/tinc-gateways/NA... | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Fix ConfigFile '/etc/confine/tinc-gateways/* path generation. Use tinc.name instead of tinc.__unicode__ == ConfigFiles == /etc/confine/tinc-gateways/NA... | dd798dc9bd3321b17007ff131e7b1288a2cd3c36 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Fix ConfigFile '/etc/confine/tinc-gateways/* path generation. Use tinc.name instead of tinc.__unicode__ == ConfigFiles == /etc/confine/tinc-gateways/NAME"""
<|body_0|>
def backwards(self, orm):
"""Undo patch."""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Migration:
def forwards(self, orm):
"""Fix ConfigFile '/etc/confine/tinc-gateways/* path generation. Use tinc.name instead of tinc.__unicode__ == ConfigFiles == /etc/confine/tinc-gateways/NAME"""
gw_cfile = orm.ConfigFile.objects.get(path__contains='server for server in node.tinc.connect_to')
... | the_stack_v2_python_sparse | controller/apps/firmware/migrations/0037_datamigration__fix_tinc_gateway.py | m00dy/vct-controller | train | 2 | |
a12d2aa845050eadb8d8c80a8225d041f3fe4fb7 | [
"self._params = Parameters()\nfor path, param in network.get_variables().items():\n self._params.add(path + '_mean_sqr_gradient', numpy.ones_like(param.get_value()))\n self._params.add(path + '_velocity', numpy.zeros_like(param.get_value()))\nif 'gradient_decay_rate' not in optimization_options:\n raise Va... | <|body_start_0|>
self._params = Parameters()
for path, param in network.get_variables().items():
self._params.add(path + '_mean_sqr_gradient', numpy.ones_like(param.get_value()))
self._params.add(path + '_velocity', numpy.zeros_like(param.get_value()))
if 'gradient_decay_... | RMSProp Variation of Nesterov Momentum Optimization Method At the time of writing, RMSProp is an unpublished method. Usually people cite slide 29 of Lecture 6 of Geoff Hinton's Coursera class: http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf The idea is simply to maintain a running average of the... | RMSPropNesterovOptimizer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RMSPropNesterovOptimizer:
"""RMSProp Variation of Nesterov Momentum Optimization Method At the time of writing, RMSProp is an unpublished method. Usually people cite slide 29 of Lecture 6 of Geoff Hinton's Coursera class: http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf The... | stack_v2_sparse_classes_75kplus_train_070715 | 4,384 | permissive | [
{
"docstring": "Creates an RMSProp momentum optimizer. :type optimization_options: dict :param optimization_options: a dictionary of optimization options :type network: Network :param network: the neural network object",
"name": "__init__",
"signature": "def __init__(self, optimization_options, network,... | 2 | null | Implement the Python class `RMSPropNesterovOptimizer` described below.
Class description:
RMSProp Variation of Nesterov Momentum Optimization Method At the time of writing, RMSProp is an unpublished method. Usually people cite slide 29 of Lecture 6 of Geoff Hinton's Coursera class: http://www.cs.toronto.edu/~tijmen/cs... | Implement the Python class `RMSPropNesterovOptimizer` described below.
Class description:
RMSProp Variation of Nesterov Momentum Optimization Method At the time of writing, RMSProp is an unpublished method. Usually people cite slide 29 of Lecture 6 of Geoff Hinton's Coursera class: http://www.cs.toronto.edu/~tijmen/cs... | 9904faec19ad5718470f21927229aad2656e5686 | <|skeleton|>
class RMSPropNesterovOptimizer:
"""RMSProp Variation of Nesterov Momentum Optimization Method At the time of writing, RMSProp is an unpublished method. Usually people cite slide 29 of Lecture 6 of Geoff Hinton's Coursera class: http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf The... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RMSPropNesterovOptimizer:
"""RMSProp Variation of Nesterov Momentum Optimization Method At the time of writing, RMSProp is an unpublished method. Usually people cite slide 29 of Lecture 6 of Geoff Hinton's Coursera class: http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf The idea is simp... | the_stack_v2_python_sparse | theanolm/training/rmspropnesterovoptimizer.py | senarvi/theanolm | train | 95 |
3f8b4cee730b7a4a63e2cededb9c5441f860c244 | [
"super(MultiHeadedAttention, self).__init__()\nassert size % num_heads == 0\nself.head_size = head_size = size // num_heads\nself.num_heads = num_heads\nself.k_layer = nn.Linear(size, num_heads * head_size)\nself.v_layer = nn.Linear(size, num_heads * head_size)\nself.q_layer = nn.Linear(size, num_heads * head_size)... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert size % num_heads == 0
self.head_size = head_size = size // num_heads
self.num_heads = num_heads
self.k_layer = nn.Linear(size, num_heads * head_size)
self.v_layer = nn.Linear(size, num_heads * head_size)... | Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py | MultiHeadedAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
"""Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py"""
def __init__(self, num_heads: int, size: int, dropout: float=0.1, attn_func: str='softmax', attn_alpha: float=1.5):
... | stack_v2_sparse_classes_75kplus_train_070716 | 10,098 | permissive | [
{
"docstring": "Create a multi-headed attention layer. :param num_heads: the number of heads :param size: model size (must be divisible by num_heads) :param dropout: probability of dropping a unit",
"name": "__init__",
"signature": "def __init__(self, num_heads: int, size: int, dropout: float=0.1, attn_... | 2 | null | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py
Method signatures and docstrings:
- def __init__(self, num_heads: int, size: int, dropout: f... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py
Method signatures and docstrings:
- def __init__(self, num_heads: int, size: int, dropout: f... | c987906b032eaa727c8bcbec53f48befb467e515 | <|skeleton|>
class MultiHeadedAttention:
"""Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py"""
def __init__(self, num_heads: int, size: int, dropout: float=0.1, attn_func: str='softmax', attn_alpha: float=1.5):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiHeadedAttention:
"""Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py"""
def __init__(self, num_heads: int, size: int, dropout: float=0.1, attn_func: str='softmax', attn_alpha: float=1.5):
"""Create a m... | the_stack_v2_python_sparse | joeynmt/transformer_layers.py | deep-spin/S7 | train | 7 |
56d67561858ea517483ad47f76c4b85a1913e0ba | [
"ctx = super().get_panel_context(view, request, context)\nif isinstance(view, StockLocationDetail):\n ctx['location'] = view.get_object()\nreturn ctx",
"panels = [{'title': 'No Content'}]\nif self.get_setting('ENABLE_HELLO_WORLD'):\n content = \"\\n <strong>Hello world!</strong>\\n <hr... | <|body_start_0|>
ctx = super().get_panel_context(view, request, context)
if isinstance(view, StockLocationDetail):
ctx['location'] = view.get_object()
return ctx
<|end_body_0|>
<|body_start_1|>
panels = [{'title': 'No Content'}]
if self.get_setting('ENABLE_HELLO_WORL... | A sample plugin which renders some custom panels. | CustomPanelSample | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomPanelSample:
"""A sample plugin which renders some custom panels."""
def get_panel_context(self, view, request, context):
"""Returns enriched context."""
<|body_0|>
def get_custom_panels(self, view, request):
"""You can decide at run-time which custom panel... | stack_v2_sparse_classes_75kplus_train_070717 | 4,420 | permissive | [
{
"docstring": "Returns enriched context.",
"name": "get_panel_context",
"signature": "def get_panel_context(self, view, request, context)"
},
{
"docstring": "You can decide at run-time which custom panels you want to display! - Display on every page - Only on a single page or set of pages - Onl... | 2 | stack_v2_sparse_classes_30k_train_002844 | Implement the Python class `CustomPanelSample` described below.
Class description:
A sample plugin which renders some custom panels.
Method signatures and docstrings:
- def get_panel_context(self, view, request, context): Returns enriched context.
- def get_custom_panels(self, view, request): You can decide at run-ti... | Implement the Python class `CustomPanelSample` described below.
Class description:
A sample plugin which renders some custom panels.
Method signatures and docstrings:
- def get_panel_context(self, view, request, context): Returns enriched context.
- def get_custom_panels(self, view, request): You can decide at run-ti... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class CustomPanelSample:
"""A sample plugin which renders some custom panels."""
def get_panel_context(self, view, request, context):
"""Returns enriched context."""
<|body_0|>
def get_custom_panels(self, view, request):
"""You can decide at run-time which custom panel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomPanelSample:
"""A sample plugin which renders some custom panels."""
def get_panel_context(self, view, request, context):
"""Returns enriched context."""
ctx = super().get_panel_context(view, request, context)
if isinstance(view, StockLocationDetail):
ctx['locati... | the_stack_v2_python_sparse | InvenTree/plugin/samples/integration/custom_panel_sample.py | inventree/InvenTree | train | 3,077 |
bac192a712995eb015617aa410cf905788ae7070 | [
"super().__init__()\nself.input_dim = input_dim\nself.hidden_size = hidden_size\nself.num_layers = num_layers\nself.num_classes = num_classes\nself.output_dim = output_dim\nself.lstm_layer = nn.LSTM(input_dim, hidden_size, num_layers, batch_first=True)\nself.linear = nn.Linear(self.hidden_size, output_dim)\nself.ou... | <|body_start_0|>
super().__init__()
self.input_dim = input_dim
self.hidden_size = hidden_size
self.num_layers = num_layers
self.num_classes = num_classes
self.output_dim = output_dim
self.lstm_layer = nn.LSTM(input_dim, hidden_size, num_layers, batch_first=True)
... | Simple LSTM decoder. | LSTM_attention_embedding_decoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTM_attention_embedding_decoder:
"""Simple LSTM decoder."""
def __init__(self, input_dim, hidden_size, output_dim, num_classes, num_layers=1):
"""Initialize model with params."""
<|body_0|>
def forward(self, inp, hidden):
"""Forward pass through LSTM layer. shap... | stack_v2_sparse_classes_75kplus_train_070718 | 1,863 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, input_dim, hidden_size, output_dim, num_classes, num_layers=1)"
},
{
"docstring": "Forward pass through LSTM layer. shape of lstm_out: [input_size, batch_size, hidden_dim] shape of self.hidden: (... | 2 | stack_v2_sparse_classes_30k_train_041275 | Implement the Python class `LSTM_attention_embedding_decoder` described below.
Class description:
Simple LSTM decoder.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_size, output_dim, num_classes, num_layers=1): Initialize model with params.
- def forward(self, inp, hidden): Forward pass thr... | Implement the Python class `LSTM_attention_embedding_decoder` described below.
Class description:
Simple LSTM decoder.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_size, output_dim, num_classes, num_layers=1): Initialize model with params.
- def forward(self, inp, hidden): Forward pass thr... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class LSTM_attention_embedding_decoder:
"""Simple LSTM decoder."""
def __init__(self, input_dim, hidden_size, output_dim, num_classes, num_layers=1):
"""Initialize model with params."""
<|body_0|>
def forward(self, inp, hidden):
"""Forward pass through LSTM layer. shap... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LSTM_attention_embedding_decoder:
"""Simple LSTM decoder."""
def __init__(self, input_dim, hidden_size, output_dim, num_classes, num_layers=1):
"""Initialize model with params."""
super().__init__()
self.input_dim = input_dim
self.hidden_size = hidden_size
self.num... | the_stack_v2_python_sparse | caspr/models/lstm_decoder.py | microsoft/CASPR | train | 29 |
f48e1782fed55afeb7e0871b409a6cc287fb935c | [
"pre_sum = reduce(lambda x, y: x + [x[-1] + y], A, [0])\ncount = 0\nfor i in range(len(pre_sum)):\n for j in range(i + 1, len(pre_sum)):\n div = pre_sum[j] - pre_sum[i]\n if div % K == 0:\n count += 1\nreturn count",
"pre_sum_div = {0: 1}\ntotal = count = 0\nfor num in A:\n total +=... | <|body_start_0|>
pre_sum = reduce(lambda x, y: x + [x[-1] + y], A, [0])
count = 0
for i in range(len(pre_sum)):
for j in range(i + 1, len(pre_sum)):
div = pre_sum[j] - pre_sum[i]
if div % K == 0:
count += 1
return count
<|en... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarraysDivByK2(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_0|>
def subarraysDivByK(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pre_sum = reduce... | stack_v2_sparse_classes_75kplus_train_070719 | 2,311 | permissive | [
{
"docstring": ":type A: List[int] :type K: int :rtype: int",
"name": "subarraysDivByK2",
"signature": "def subarraysDivByK2(self, A, K)"
},
{
"docstring": ":type A: List[int] :type K: int :rtype: int",
"name": "subarraysDivByK",
"signature": "def subarraysDivByK(self, A, K)"
}
] | 2 | stack_v2_sparse_classes_30k_train_028157 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraysDivByK2(self, A, K): :type A: List[int] :type K: int :rtype: int
- def subarraysDivByK(self, A, K): :type A: List[int] :type K: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraysDivByK2(self, A, K): :type A: List[int] :type K: int :rtype: int
- def subarraysDivByK(self, A, K): :type A: List[int] :type K: int :rtype: int
<|skeleton|>
class S... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def subarraysDivByK2(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_0|>
def subarraysDivByK(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def subarraysDivByK2(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
pre_sum = reduce(lambda x, y: x + [x[-1] + y], A, [0])
count = 0
for i in range(len(pre_sum)):
for j in range(i + 1, len(pre_sum)):
div = pre_sum[j] - pre_s... | the_stack_v2_python_sparse | 974.subarray-sums-divisible-by-k.py | windard/leeeeee | train | 0 | |
0165a4237cbe7017e0aa4f13135bb3cda7dfabd0 | [
"result = {}\nfor name, field in cls.fields.items():\n representation = field.api_representation()\n if not representation['config']['editable']:\n continue\n result[name] = representation\nreturn result",
"instance = cls()\ninstance.validated_data = {}\nfor key, field in cls.fields.items():\n ... | <|body_start_0|>
result = {}
for name, field in cls.fields.items():
representation = field.api_representation()
if not representation['config']['editable']:
continue
result[name] = representation
return result
<|end_body_0|>
<|body_start_1|>
... | BaseConfigurator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseConfigurator:
def get_fields_representation(cls) -> DictFields:
"""Return fields config without values."""
<|body_0|>
def parse(cls, data: DictFields):
"""Parse API data."""
<|body_1|>
def exclude(self, key: str, equal=True):
"""Mutate `.vali... | stack_v2_sparse_classes_75kplus_train_070720 | 1,432 | no_license | [
{
"docstring": "Return fields config without values.",
"name": "get_fields_representation",
"signature": "def get_fields_representation(cls) -> DictFields"
},
{
"docstring": "Parse API data.",
"name": "parse",
"signature": "def parse(cls, data: DictFields)"
},
{
"docstring": "Mut... | 3 | stack_v2_sparse_classes_30k_train_029083 | Implement the Python class `BaseConfigurator` described below.
Class description:
Implement the BaseConfigurator class.
Method signatures and docstrings:
- def get_fields_representation(cls) -> DictFields: Return fields config without values.
- def parse(cls, data: DictFields): Parse API data.
- def exclude(self, key... | Implement the Python class `BaseConfigurator` described below.
Class description:
Implement the BaseConfigurator class.
Method signatures and docstrings:
- def get_fields_representation(cls) -> DictFields: Return fields config without values.
- def parse(cls, data: DictFields): Parse API data.
- def exclude(self, key... | 82a2537c2ae841edec591a36c3f76da97f99701b | <|skeleton|>
class BaseConfigurator:
def get_fields_representation(cls) -> DictFields:
"""Return fields config without values."""
<|body_0|>
def parse(cls, data: DictFields):
"""Parse API data."""
<|body_1|>
def exclude(self, key: str, equal=True):
"""Mutate `.vali... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseConfigurator:
def get_fields_representation(cls) -> DictFields:
"""Return fields config without values."""
result = {}
for name, field in cls.fields.items():
representation = field.api_representation()
if not representation['config']['editable']:
... | the_stack_v2_python_sparse | servers/helpers/configurator/base.py | donkey-engine/donkey-engine | train | 7 | |
01856d0a1cc74717a7604769998e2b50b55fac29 | [
"tk.Frame.__init__(self, parent)\nself.parent = parent\nself.parameters = {}\nself.parameters_lists = load_algorithm_constants(yaml_filename)\nself.parameters_lists_keys = list(self.parameters_lists.keys())\nself.values_lists = []\nfor key in self.parameters_lists_keys:\n self.values_lists.append(self.parameters... | <|body_start_0|>
tk.Frame.__init__(self, parent)
self.parent = parent
self.parameters = {}
self.parameters_lists = load_algorithm_constants(yaml_filename)
self.parameters_lists_keys = list(self.parameters_lists.keys())
self.values_lists = []
for key in self.parame... | A Class used to map all the actions in the GUI Methods ------- get_algorithm_parameters() Description | Return all the selected values for each algorithm parameter (selected value from the combo box) | AlgorithmFrameOptions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlgorithmFrameOptions:
"""A Class used to map all the actions in the GUI Methods ------- get_algorithm_parameters() Description | Return all the selected values for each algorithm parameter (selected value from the combo box)"""
def __init__(self, parent=None, yaml_filename=None):
""... | stack_v2_sparse_classes_75kplus_train_070721 | 4,029 | no_license | [
{
"docstring": "Parameters ---------- parent : ParametersOptionsWindow The parent window which controls the current frame yaml_filename : str The file which suits a specific algorithm in order to construct the frame",
"name": "__init__",
"signature": "def __init__(self, parent=None, yaml_filename=None)"... | 3 | stack_v2_sparse_classes_30k_train_039365 | Implement the Python class `AlgorithmFrameOptions` described below.
Class description:
A Class used to map all the actions in the GUI Methods ------- get_algorithm_parameters() Description | Return all the selected values for each algorithm parameter (selected value from the combo box)
Method signatures and docstring... | Implement the Python class `AlgorithmFrameOptions` described below.
Class description:
A Class used to map all the actions in the GUI Methods ------- get_algorithm_parameters() Description | Return all the selected values for each algorithm parameter (selected value from the combo box)
Method signatures and docstring... | b9ccbb0d863ba7739b2b1913e5a5b97a87977df7 | <|skeleton|>
class AlgorithmFrameOptions:
"""A Class used to map all the actions in the GUI Methods ------- get_algorithm_parameters() Description | Return all the selected values for each algorithm parameter (selected value from the combo box)"""
def __init__(self, parent=None, yaml_filename=None):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlgorithmFrameOptions:
"""A Class used to map all the actions in the GUI Methods ------- get_algorithm_parameters() Description | Return all the selected values for each algorithm parameter (selected value from the combo box)"""
def __init__(self, parent=None, yaml_filename=None):
"""Parameters -... | the_stack_v2_python_sparse | gui/algorithm_frame_options/algorithm_frame_options.py | liorpizman/AnomalyDetection | train | 4 |
1156989b42a28434e153949055e626000e3fd15a | [
"for l, res in self.knownLines:\n cf = cfloader.NannyConfig()\n cf.parseline(l, 0)\n self.assertEqual(str(cf), res)\n cf = cfloader.NannyConfig()\n cf.parseline(res[:-1], 0)\n self.assertEqual(str(cf), res)",
"cf = cfloader.NannyConfig()\ncf.parseline('user cks', 0)\ncf.parseline('actionfile 10'... | <|body_start_0|>
for l, res in self.knownLines:
cf = cfloader.NannyConfig()
cf.parseline(l, 0)
self.assertEqual(str(cf), res)
cf = cfloader.NannyConfig()
cf.parseline(res[:-1], 0)
self.assertEqual(str(cf), res)
<|end_body_0|>
<|body_start_... | basicTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class basicTests:
def testKnownLines(self):
"""Test cfloader's direct parsing of known lines and the invertability of its output."""
<|body_0|>
def testDictAccess(self):
"""Test access to the configuration object as a dictionary."""
<|body_1|>
def testFromfile... | stack_v2_sparse_classes_75kplus_train_070722 | 4,828 | no_license | [
{
"docstring": "Test cfloader's direct parsing of known lines and the invertability of its output.",
"name": "testKnownLines",
"signature": "def testKnownLines(self)"
},
{
"docstring": "Test access to the configuration object as a dictionary.",
"name": "testDictAccess",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_000860 | Implement the Python class `basicTests` described below.
Class description:
Implement the basicTests class.
Method signatures and docstrings:
- def testKnownLines(self): Test cfloader's direct parsing of known lines and the invertability of its output.
- def testDictAccess(self): Test access to the configuration obje... | Implement the Python class `basicTests` described below.
Class description:
Implement the basicTests class.
Method signatures and docstrings:
- def testKnownLines(self): Test cfloader's direct parsing of known lines and the invertability of its output.
- def testDictAccess(self): Test access to the configuration obje... | 41341606e831a42ba36f8e64640e98f098bf0489 | <|skeleton|>
class basicTests:
def testKnownLines(self):
"""Test cfloader's direct parsing of known lines and the invertability of its output."""
<|body_0|>
def testDictAccess(self):
"""Test access to the configuration object as a dictionary."""
<|body_1|>
def testFromfile... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class basicTests:
def testKnownLines(self):
"""Test cfloader's direct parsing of known lines and the invertability of its output."""
for l, res in self.knownLines:
cf = cfloader.NannyConfig()
cf.parseline(l, 0)
self.assertEqual(str(cf), res)
cf = cfloa... | the_stack_v2_python_sparse | test_cfloader.py | siebenmann/portnanny | train | 2 | |
143756d6a9bed0c6e909aba80a806a7e7d528d59 | [
"self.nodes = ''\n\ndef preorder(p):\n if not p:\n self.nodes += ',#'\n return\n self.nodes += ',' + str(p.val)\n preorder(p.left)\n preorder(p.right)\npreorder(root)\nreturn self.nodes[1:]",
"tokens = data.split(',')\nnodes = []\nfor i in tokens:\n if i == '#':\n nodes.append(... | <|body_start_0|>
self.nodes = ''
def preorder(p):
if not p:
self.nodes += ',#'
return
self.nodes += ',' + str(p.val)
preorder(p.left)
preorder(p.right)
preorder(root)
return self.nodes[1:]
<|end_body_0|>
<|... | 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_070723 | 26,198 | 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_039562 | 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:... | 426e09e75309e3ae8be0e946b31d5804f64bc915 | <|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"""
self.nodes = ''
def preorder(p):
if not p:
self.nodes += ',#'
return
self.nodes += ',' + str(p.val)
preorder(... | the_stack_v2_python_sparse | py/leetcode5.py | rzwei/leetcode | train | 0 | |
c608cb67843adb3d589064298bd0732b03a07bb4 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DriveItemUploadableProperties()",
"from .file_system_info import FileSystemInfo\nfrom .file_system_info import FileSystemInfo\nfields: Dict[str, Callable[[Any], None]] = {'description': lambda n: setattr(self, 'description', n.get_str_... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DriveItemUploadableProperties()
<|end_body_0|>
<|body_start_1|>
from .file_system_info import FileSystemInfo
from .file_system_info import FileSystemInfo
fields: Dict[str, Callab... | DriveItemUploadableProperties | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DriveItemUploadableProperties:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DriveItemUploadableProperties:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator val... | stack_v2_sparse_classes_75kplus_train_070724 | 3,548 | 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: DriveItemUploadableProperties",
"name": "create_from_discriminator_value",
"signature": "def create_from_dis... | 3 | stack_v2_sparse_classes_30k_train_017705 | Implement the Python class `DriveItemUploadableProperties` described below.
Class description:
Implement the DriveItemUploadableProperties class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DriveItemUploadableProperties: Creates a new instance of th... | Implement the Python class `DriveItemUploadableProperties` described below.
Class description:
Implement the DriveItemUploadableProperties class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DriveItemUploadableProperties: Creates a new instance of th... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DriveItemUploadableProperties:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DriveItemUploadableProperties:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DriveItemUploadableProperties:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DriveItemUploadableProperties:
"""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_stack_v2_python_sparse | msgraph/generated/models/drive_item_uploadable_properties.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b92e1f1fbb0bb73d62a07b5eee439d670c978405 | [
"logger.info('FastQC')\nTool.__init__(self)\nif configuration is None:\n configuration = {}\nself.configuration.update(configuration)",
"command_line = 'fastqc ' + fastq_file\nlogger.info('FastQC COMMAND: {0}'.format(command_line))\ntry:\n args = shlex.split(command_line)\n process = subprocess.Popen(arg... | <|body_start_0|>
logger.info('FastQC')
Tool.__init__(self)
if configuration is None:
configuration = {}
self.configuration.update(configuration)
<|end_body_0|>
<|body_start_1|>
command_line = 'fastqc ' + fastq_file
logger.info('FastQC COMMAND: {0}'.format(com... | Tool for running indexers over a genome FASTA file | fastqcTool | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fastqcTool:
"""Tool for running indexers over a genome FASTA file"""
def __init__(self, configuration=None):
"""Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried ou... | stack_v2_sparse_classes_75kplus_train_070725 | 5,110 | permissive | [
{
"docstring": "Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are specific to each Tool.",
"name": "__init__",
"signature": "def __init__(self, configuration=None)"
},... | 3 | null | Implement the Python class `fastqcTool` described below.
Class description:
Tool for running indexers over a genome FASTA file
Method signatures and docstrings:
- def __init__(self, configuration=None): Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing para... | Implement the Python class `fastqcTool` described below.
Class description:
Tool for running indexers over a genome FASTA file
Method signatures and docstrings:
- def __init__(self, configuration=None): Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing para... | 50c7115c0c1a6af48dc34f275e469d1b9eb02999 | <|skeleton|>
class fastqcTool:
"""Tool for running indexers over a genome FASTA file"""
def __init__(self, configuration=None):
"""Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried ou... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class fastqcTool:
"""Tool for running indexers over a genome FASTA file"""
def __init__(self, configuration=None):
"""Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are ... | the_stack_v2_python_sparse | tool/validate_fastqc.py | Multiscale-Genomics/mg-process-fastq | train | 2 |
81660fcadf92f26f691af26eefb86546ca9565c4 | [
"expected_topic = 'Hubot-DSC-Resource'\nexpected_message = '\\n[Build Hubot-DSC-Resource 2.0.59 completed](https://ci.appveyor.com/project/joebloggs/hubot-dsc-resource/build/2.0.59):\\n* **Commit**: [c06e208b47: Increment version number.](https://github.com/joebloggs/Hubot-DSC-Resource/commit/c06e208b47) by Joe Blo... | <|body_start_0|>
expected_topic = 'Hubot-DSC-Resource'
expected_message = '\n[Build Hubot-DSC-Resource 2.0.59 completed](https://ci.appveyor.com/project/joebloggs/hubot-dsc-resource/build/2.0.59):\n* **Commit**: [c06e208b47: Increment version number.](https://github.com/joebloggs/Hubot-DSC-Resource/comm... | AppveyorHookTests | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppveyorHookTests:
def test_appveyor_build_success_message(self) -> None:
"""Tests if appveyor build success notification is handled correctly"""
<|body_0|>
def test_appveyor_build_failure_message(self) -> None:
"""Tests if appveyor build failure notification is hand... | stack_v2_sparse_classes_75kplus_train_070726 | 1,547 | permissive | [
{
"docstring": "Tests if appveyor build success notification is handled correctly",
"name": "test_appveyor_build_success_message",
"signature": "def test_appveyor_build_success_message(self) -> None"
},
{
"docstring": "Tests if appveyor build failure notification is handled correctly",
"name... | 2 | stack_v2_sparse_classes_30k_train_002136 | Implement the Python class `AppveyorHookTests` described below.
Class description:
Implement the AppveyorHookTests class.
Method signatures and docstrings:
- def test_appveyor_build_success_message(self) -> None: Tests if appveyor build success notification is handled correctly
- def test_appveyor_build_failure_messa... | Implement the Python class `AppveyorHookTests` described below.
Class description:
Implement the AppveyorHookTests class.
Method signatures and docstrings:
- def test_appveyor_build_success_message(self) -> None: Tests if appveyor build success notification is handled correctly
- def test_appveyor_build_failure_messa... | 965a25d91b6ee2db54038f5df855215fa25146b0 | <|skeleton|>
class AppveyorHookTests:
def test_appveyor_build_success_message(self) -> None:
"""Tests if appveyor build success notification is handled correctly"""
<|body_0|>
def test_appveyor_build_failure_message(self) -> None:
"""Tests if appveyor build failure notification is hand... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AppveyorHookTests:
def test_appveyor_build_success_message(self) -> None:
"""Tests if appveyor build success notification is handled correctly"""
expected_topic = 'Hubot-DSC-Resource'
expected_message = '\n[Build Hubot-DSC-Resource 2.0.59 completed](https://ci.appveyor.com/project/joeb... | the_stack_v2_python_sparse | zerver/webhooks/appveyor/tests.py | zulip/zulip | train | 20,239 | |
f28ae650819b4b1af72f76748cefc61f99d3ba61 | [
"if model._meta.app_label in settings.DATABASE_APPS_MAPPING:\n return settings.DATABASE_APPS_MAPPING[model._meta.app_label]\nreturn 'test' if IS_TEST else 'default'",
"if model._meta.app_label in settings.DATABASE_APPS_MAPPING:\n return settings.DATABASE_APPS_MAPPING[model._meta.app_label]\nreturn 'test' if... | <|body_start_0|>
if model._meta.app_label in settings.DATABASE_APPS_MAPPING:
return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
return 'test' if IS_TEST else 'default'
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label in settings.DATABASE_APPS_MAPPING:
r... | DatabaseRouter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseRouter:
def db_for_read(self, model, **hints):
""""Point all read operations to the specific database."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Point all write operations to the specific database."""
<|body_1|>
def allow_relation(... | stack_v2_sparse_classes_75kplus_train_070727 | 2,139 | permissive | [
{
"docstring": "\"Point all read operations to the specific database.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Point all write operations to the specific database.",
"name": "db_for_write",
"signature": "def db_for_write(self, model... | 4 | stack_v2_sparse_classes_30k_train_037287 | Implement the Python class `DatabaseRouter` described below.
Class description:
Implement the DatabaseRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): "Point all read operations to the specific database.
- def db_for_write(self, model, **hints): Point all write operations to th... | Implement the Python class `DatabaseRouter` described below.
Class description:
Implement the DatabaseRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): "Point all read operations to the specific database.
- def db_for_write(self, model, **hints): Point all write operations to th... | 8c5a00a215b42aad2f6a4167b9cb97fe11d78823 | <|skeleton|>
class DatabaseRouter:
def db_for_read(self, model, **hints):
""""Point all read operations to the specific database."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Point all write operations to the specific database."""
<|body_1|>
def allow_relation(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatabaseRouter:
def db_for_read(self, model, **hints):
""""Point all read operations to the specific database."""
if model._meta.app_label in settings.DATABASE_APPS_MAPPING:
return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
return 'test' if IS_TEST else 'default'... | the_stack_v2_python_sparse | src/ribo_core/dbrouter.py | wahello/RiBo-Core | train | 0 | |
f38e175a330a0268d8c662c990eb0a69c70571b0 | [
"super().__init__()\nself.seqm_parameters = seqm_parameters\nself.method = seqm_parameters['method']\nself.parser = Parser(seqm_parameters)\nself.packpar = Pack_Parameters(seqm_parameters)\nself.hamiltonian = Hamiltonian(seqm_parameters)\nself.Hf_flag = True\nif 'Hf_flag' in seqm_parameters:\n self.Hf_flag = seq... | <|body_start_0|>
super().__init__()
self.seqm_parameters = seqm_parameters
self.method = seqm_parameters['method']
self.parser = Parser(seqm_parameters)
self.packpar = Pack_Parameters(seqm_parameters)
self.hamiltonian = Hamiltonian(seqm_parameters)
self.Hf_flag = ... | Energy | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Energy:
def __init__(self, seqm_parameters):
"""Constructor"""
<|body_0|>
def forward(self, const, coordinates, species, learned_parameters=dict(), all_terms=False, P0=None):
"""get the energy terms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
su... | stack_v2_sparse_classes_75kplus_train_070728 | 17,243 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, seqm_parameters)"
},
{
"docstring": "get the energy terms",
"name": "forward",
"signature": "def forward(self, const, coordinates, species, learned_parameters=dict(), all_terms=False, P0=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004543 | Implement the Python class `Energy` described below.
Class description:
Implement the Energy class.
Method signatures and docstrings:
- def __init__(self, seqm_parameters): Constructor
- def forward(self, const, coordinates, species, learned_parameters=dict(), all_terms=False, P0=None): get the energy terms | Implement the Python class `Energy` described below.
Class description:
Implement the Energy class.
Method signatures and docstrings:
- def __init__(self, seqm_parameters): Constructor
- def forward(self, const, coordinates, species, learned_parameters=dict(), all_terms=False, P0=None): get the energy terms
<|skelet... | dfda08400bb1328ce6cd45ac6b1dd3e7f9d7d4a6 | <|skeleton|>
class Energy:
def __init__(self, seqm_parameters):
"""Constructor"""
<|body_0|>
def forward(self, const, coordinates, species, learned_parameters=dict(), all_terms=False, P0=None):
"""get the energy terms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Energy:
def __init__(self, seqm_parameters):
"""Constructor"""
super().__init__()
self.seqm_parameters = seqm_parameters
self.method = seqm_parameters['method']
self.parser = Parser(seqm_parameters)
self.packpar = Pack_Parameters(seqm_parameters)
self.ha... | the_stack_v2_python_sparse | PYSEQM/seqm/basics.py | roehr-lab/SFast-Singlet-Fission-adiabatic-basis-screening | train | 2 | |
ada36ceb453f472bd5384c80a19ff492eb4088e8 | [
"super().__init__()\nself.ip_address: str | None = None\nself.serial_number = None",
"self.ip_address = discovery_info.ip\n_LOGGER.debug('Discovered Tesla Wall Connector at [%s]', self.ip_address)\nself._async_abort_entries_match({CONF_HOST: self.ip_address})\ntry:\n wall_connector = WallConnector(host=self.ip... | <|body_start_0|>
super().__init__()
self.ip_address: str | None = None
self.serial_number = None
<|end_body_0|>
<|body_start_1|>
self.ip_address = discovery_info.ip
_LOGGER.debug('Discovered Tesla Wall Connector at [%s]', self.ip_address)
self._async_abort_entries_match(... | Handle a config flow for Tesla Wall Connector. | ConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Tesla Wall Connector."""
def __init__(self) -> None:
"""Initialize config flow."""
<|body_0|>
async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResult:
"""Handle dhcp discovery."""
<|body_... | stack_v2_sparse_classes_75kplus_train_070729 | 4,145 | permissive | [
{
"docstring": "Initialize config flow.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Handle dhcp discovery.",
"name": "async_step_dhcp",
"signature": "async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResult"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_000025 | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Tesla Wall Connector.
Method signatures and docstrings:
- def __init__(self) -> None: Initialize config flow.
- async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResult: Handle dhcp discover... | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Tesla Wall Connector.
Method signatures and docstrings:
- def __init__(self) -> None: Initialize config flow.
- async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResult: Handle dhcp discover... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Tesla Wall Connector."""
def __init__(self) -> None:
"""Initialize config flow."""
<|body_0|>
async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResult:
"""Handle dhcp discovery."""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigFlow:
"""Handle a config flow for Tesla Wall Connector."""
def __init__(self) -> None:
"""Initialize config flow."""
super().__init__()
self.ip_address: str | None = None
self.serial_number = None
async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceI... | the_stack_v2_python_sparse | homeassistant/components/tesla_wall_connector/config_flow.py | home-assistant/core | train | 35,501 |
734aece642e9a80449176ded7341d02baeda9fe8 | [
"self.variables['is_started'] = True\nself.deactivate()\nself.activate('EndRace')\nself.deactivate('Characters')\nself.deactivate('Map')\nself.variables['player_regions'] = self.variables['player_regions'][0:self.variables['num_players']]\nself.variables['start_time'] = np.floor(cur_count / self.variables['frame_ra... | <|body_start_0|>
self.variables['is_started'] = True
self.deactivate()
self.activate('EndRace')
self.deactivate('Characters')
self.deactivate('Map')
self.variables['player_regions'] = self.variables['player_regions'][0:self.variables['num_players']]
self.variables... | Handles the beginning of a race in phase_0 | StartRace | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StartRace:
"""Handles the beginning of a race in phase_0"""
def handle(self, frame, player, mask, cur_count, location):
"""Store variables and toggle detectors. Overrides superclass method."""
<|body_0|>
def constrain_roi(self, frame):
"""Constrains frame w.r.t. ... | stack_v2_sparse_classes_75kplus_train_070730 | 15,971 | permissive | [
{
"docstring": "Store variables and toggle detectors. Overrides superclass method.",
"name": "handle",
"signature": "def handle(self, frame, player, mask, cur_count, location)"
},
{
"docstring": "Constrains frame w.r.t. StartRace/BeginRace. Overrides superclass method.",
"name": "constrain_r... | 2 | stack_v2_sparse_classes_30k_train_052047 | Implement the Python class `StartRace` described below.
Class description:
Handles the beginning of a race in phase_0
Method signatures and docstrings:
- def handle(self, frame, player, mask, cur_count, location): Store variables and toggle detectors. Overrides superclass method.
- def constrain_roi(self, frame): Con... | Implement the Python class `StartRace` described below.
Class description:
Handles the beginning of a race in phase_0
Method signatures and docstrings:
- def handle(self, frame, player, mask, cur_count, location): Store variables and toggle detectors. Overrides superclass method.
- def constrain_roi(self, frame): Con... | 6ae92cf98a031825231cc201706b9d936de92b95 | <|skeleton|>
class StartRace:
"""Handles the beginning of a race in phase_0"""
def handle(self, frame, player, mask, cur_count, location):
"""Store variables and toggle detectors. Overrides superclass method."""
<|body_0|>
def constrain_roi(self, frame):
"""Constrains frame w.r.t. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StartRace:
"""Handles the beginning of a race in phase_0"""
def handle(self, frame, player, mask, cur_count, location):
"""Store variables and toggle detectors. Overrides superclass method."""
self.variables['is_started'] = True
self.deactivate()
self.activate('EndRace')
... | the_stack_v2_python_sparse | detection/splitting.py | kartyboyz/n64-img-processing | train | 0 |
6732325006f21a58628517b3b5fb88d4d2bf10fe | [
"self.dirname = Path(dirname).absolute()\nself.basename = basename\nif not self.dirname.is_dir():\n raise ValueError('dirname must be a directory')",
"all_filenames = self.dirname.glob('*')\nd = {}\nfor v in all_filenames:\n split_fn = v.name\n m = glob.re.search('^(\\\\w+)\\\\.%s\\\\.(\\\\d+)$' % typest... | <|body_start_0|>
self.dirname = Path(dirname).absolute()
self.basename = basename
if not self.dirname.is_dir():
raise ValueError('dirname must be a directory')
<|end_body_0|>
<|body_start_1|>
all_filenames = self.dirname.glob('*')
d = {}
for v in all_filename... | Simple class to interpret user's requests into KlustaKwik filenames | FilenameParser | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilenameParser:
"""Simple class to interpret user's requests into KlustaKwik filenames"""
def __init__(self, dirname, basename=None):
"""Initialize a new parser for a directory containing files dirname: directory containing files basename: basename in KlustaKwik format spec If basena... | stack_v2_sparse_classes_75kplus_train_070731 | 17,008 | permissive | [
{
"docstring": "Initialize a new parser for a directory containing files dirname: directory containing files basename: basename in KlustaKwik format spec If basename is left None, then files with any basename in the directory will be used. An error is raised if files with multiple basenames exist in the directo... | 2 | stack_v2_sparse_classes_30k_test_000848 | Implement the Python class `FilenameParser` described below.
Class description:
Simple class to interpret user's requests into KlustaKwik filenames
Method signatures and docstrings:
- def __init__(self, dirname, basename=None): Initialize a new parser for a directory containing files dirname: directory containing fil... | Implement the Python class `FilenameParser` described below.
Class description:
Simple class to interpret user's requests into KlustaKwik filenames
Method signatures and docstrings:
- def __init__(self, dirname, basename=None): Initialize a new parser for a directory containing files dirname: directory containing fil... | 354c8d9d5fbc4daad3547773d2f281f8c163d208 | <|skeleton|>
class FilenameParser:
"""Simple class to interpret user's requests into KlustaKwik filenames"""
def __init__(self, dirname, basename=None):
"""Initialize a new parser for a directory containing files dirname: directory containing files basename: basename in KlustaKwik format spec If basena... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FilenameParser:
"""Simple class to interpret user's requests into KlustaKwik filenames"""
def __init__(self, dirname, basename=None):
"""Initialize a new parser for a directory containing files dirname: directory containing files basename: basename in KlustaKwik format spec If basename is left No... | the_stack_v2_python_sparse | neo/io/klustakwikio.py | NeuralEnsemble/python-neo | train | 265 |
e3baa69e762114808e6b55cf2e8150b55408175c | [
"try:\n now = timezone.now()\n r = cls.objects.get(phone_number=phone_number)\nexcept cls.DoesNotExist:\n return False\nelse:\n return True if code == r.code and now <= r.time_expired else False",
"from datetime import timedelta\nfrom random import Random\ntry:\n r = cls.objects.get(phone_number=ph... | <|body_start_0|>
try:
now = timezone.now()
r = cls.objects.get(phone_number=phone_number)
except cls.DoesNotExist:
return False
else:
return True if code == r.code and now <= r.time_expired else False
<|end_body_0|>
<|body_start_1|>
from d... | 验证码 | ValidationCode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidationCode:
"""验证码"""
def verify(cls, phone_number, code):
"""校验验证码"""
<|body_0|>
def generate(cls, phone_number, minutes=10):
"""为某个手机号生成验证码,有效时间为10分钟"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
now = timezone.now()
... | stack_v2_sparse_classes_75kplus_train_070732 | 30,477 | no_license | [
{
"docstring": "校验验证码",
"name": "verify",
"signature": "def verify(cls, phone_number, code)"
},
{
"docstring": "为某个手机号生成验证码,有效时间为10分钟",
"name": "generate",
"signature": "def generate(cls, phone_number, minutes=10)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001491 | Implement the Python class `ValidationCode` described below.
Class description:
验证码
Method signatures and docstrings:
- def verify(cls, phone_number, code): 校验验证码
- def generate(cls, phone_number, minutes=10): 为某个手机号生成验证码,有效时间为10分钟 | Implement the Python class `ValidationCode` described below.
Class description:
验证码
Method signatures and docstrings:
- def verify(cls, phone_number, code): 校验验证码
- def generate(cls, phone_number, minutes=10): 为某个手机号生成验证码,有效时间为10分钟
<|skeleton|>
class ValidationCode:
"""验证码"""
def verify(cls, phone_number, c... | ce92fb029df1b147ddcf1a8e40bea93f0d0ee888 | <|skeleton|>
class ValidationCode:
"""验证码"""
def verify(cls, phone_number, code):
"""校验验证码"""
<|body_0|>
def generate(cls, phone_number, minutes=10):
"""为某个手机号生成验证码,有效时间为10分钟"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValidationCode:
"""验证码"""
def verify(cls, phone_number, code):
"""校验验证码"""
try:
now = timezone.now()
r = cls.objects.get(phone_number=phone_number)
except cls.DoesNotExist:
return False
else:
return True if code == r.code and... | the_stack_v2_python_sparse | webApp/models.py | xiaohe10/banquetExpert | train | 3 |
3409d84916388d7b558d7743f0b3c097671a9174 | [
"self.restoreIpHelper(s)\nans = self.RESULT.copy()\nself.RESULT.clear()\nreturn ans",
"L = min(3, len(s))\nif parts < 3:\n for i in range(1, L + 1):\n group = s[:i]\n rest = s[i:]\n if len(group) == 1 or (len(group) > 1 and group[0] != '0' and (int(group) <= 255)):\n self.restor... | <|body_start_0|>
self.restoreIpHelper(s)
ans = self.RESULT.copy()
self.RESULT.clear()
return ans
<|end_body_0|>
<|body_start_1|>
L = min(3, len(s))
if parts < 3:
for i in range(1, L + 1):
group = s[:i]
rest = s[i:]
... | Solution_A2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_A2:
def restoreIpAddresses(self, s: str) -> List[str]:
"""Same principle as Version A1, but move the helper external"""
<|body_0|>
def restoreIpHelper(self, s: str, address: str='', parts: int=0):
"""A branch recursive helper (external)"""
<|body_1|>... | stack_v2_sparse_classes_75kplus_train_070733 | 3,356 | permissive | [
{
"docstring": "Same principle as Version A1, but move the helper external",
"name": "restoreIpAddresses",
"signature": "def restoreIpAddresses(self, s: str) -> List[str]"
},
{
"docstring": "A branch recursive helper (external)",
"name": "restoreIpHelper",
"signature": "def restoreIpHelp... | 2 | stack_v2_sparse_classes_30k_train_047187 | Implement the Python class `Solution_A2` described below.
Class description:
Implement the Solution_A2 class.
Method signatures and docstrings:
- def restoreIpAddresses(self, s: str) -> List[str]: Same principle as Version A1, but move the helper external
- def restoreIpHelper(self, s: str, address: str='', parts: in... | Implement the Python class `Solution_A2` described below.
Class description:
Implement the Solution_A2 class.
Method signatures and docstrings:
- def restoreIpAddresses(self, s: str) -> List[str]: Same principle as Version A1, but move the helper external
- def restoreIpHelper(self, s: str, address: str='', parts: in... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_A2:
def restoreIpAddresses(self, s: str) -> List[str]:
"""Same principle as Version A1, but move the helper external"""
<|body_0|>
def restoreIpHelper(self, s: str, address: str='', parts: int=0):
"""A branch recursive helper (external)"""
<|body_1|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution_A2:
def restoreIpAddresses(self, s: str) -> List[str]:
"""Same principle as Version A1, but move the helper external"""
self.restoreIpHelper(s)
ans = self.RESULT.copy()
self.RESULT.clear()
return ans
def restoreIpHelper(self, s: str, address: str='', parts... | the_stack_v2_python_sparse | LeetCode/LC093_restore_ip_addresses.py | jxie0755/Learning_Python | train | 0 | |
ad85057e489e7d3eb3d82fc7e4fb9bf6a23922c0 | [
"record = model.get_email_authorized_for_repo(namespace, repository, email)\nif not record:\n abort(404)\nresponse = record.to_dict()\ndel response['code']\nreturn response",
"with tf(db):\n record = model.get_email_authorized_for_repo(namespace, repository, email)\n if record and record.confirmed:\n ... | <|body_start_0|>
record = model.get_email_authorized_for_repo(namespace, repository, email)
if not record:
abort(404)
response = record.to_dict()
del response['code']
return response
<|end_body_0|>
<|body_start_1|>
with tf(db):
record = model.get_... | Resource for checking and authorizing e-mail addresses to receive repo notifications. | RepositoryAuthorizedEmail | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepositoryAuthorizedEmail:
"""Resource for checking and authorizing e-mail addresses to receive repo notifications."""
def get(self, namespace, repository, email):
"""Checks to see if the given e-mail address is authorized on this repository."""
<|body_0|>
def post(self,... | stack_v2_sparse_classes_75kplus_train_070734 | 2,290 | permissive | [
{
"docstring": "Checks to see if the given e-mail address is authorized on this repository.",
"name": "get",
"signature": "def get(self, namespace, repository, email)"
},
{
"docstring": "Starts the authorization process for an e-mail address on a repository.",
"name": "post",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_033303 | Implement the Python class `RepositoryAuthorizedEmail` described below.
Class description:
Resource for checking and authorizing e-mail addresses to receive repo notifications.
Method signatures and docstrings:
- def get(self, namespace, repository, email): Checks to see if the given e-mail address is authorized on t... | Implement the Python class `RepositoryAuthorizedEmail` described below.
Class description:
Resource for checking and authorizing e-mail addresses to receive repo notifications.
Method signatures and docstrings:
- def get(self, namespace, repository, email): Checks to see if the given e-mail address is authorized on t... | e400a0c22c5f89dd35d571654b13d262b1f6e3b3 | <|skeleton|>
class RepositoryAuthorizedEmail:
"""Resource for checking and authorizing e-mail addresses to receive repo notifications."""
def get(self, namespace, repository, email):
"""Checks to see if the given e-mail address is authorized on this repository."""
<|body_0|>
def post(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RepositoryAuthorizedEmail:
"""Resource for checking and authorizing e-mail addresses to receive repo notifications."""
def get(self, namespace, repository, email):
"""Checks to see if the given e-mail address is authorized on this repository."""
record = model.get_email_authorized_for_rep... | the_stack_v2_python_sparse | endpoints/api/repoemail.py | quay/quay | train | 2,363 |
7387bab29ac5d28b0c2f0d976b5a11cb4da7842b | [
"super(DialogProblems, self).__init__(parent=parent)\nself._parent = parent\nself._problems = problems\nself.style_sheet = None\nself.list = ListWidgetProblems(parent=self)\nself.button_ok = ButtonPrimary('Ok')\nself.frame_title_bar.setVisible(False)\nself.list.setFrameStyle(QFrame.NoFrame)\nself.list.setFrameShape... | <|body_start_0|>
super(DialogProblems, self).__init__(parent=parent)
self._parent = parent
self._problems = problems
self.style_sheet = None
self.list = ListWidgetProblems(parent=self)
self.button_ok = ButtonPrimary('Ok')
self.frame_title_bar.setVisible(False)
... | Dialog to display anaconda project problems. | DialogProblems | [
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DialogProblems:
"""Dialog to display anaconda project problems."""
def __init__(self, parent=None, problems=None):
"""Dialog to display anaconda project problems."""
<|body_0|>
def update_style_sheet(self, style_sheet=None):
"""Update custom css style sheets."""
... | stack_v2_sparse_classes_75kplus_train_070735 | 20,046 | permissive | [
{
"docstring": "Dialog to display anaconda project problems.",
"name": "__init__",
"signature": "def __init__(self, parent=None, problems=None)"
},
{
"docstring": "Update custom css style sheets.",
"name": "update_style_sheet",
"signature": "def update_style_sheet(self, style_sheet=None)... | 3 | stack_v2_sparse_classes_30k_train_049160 | Implement the Python class `DialogProblems` described below.
Class description:
Dialog to display anaconda project problems.
Method signatures and docstrings:
- def __init__(self, parent=None, problems=None): Dialog to display anaconda project problems.
- def update_style_sheet(self, style_sheet=None): Update custom ... | Implement the Python class `DialogProblems` described below.
Class description:
Dialog to display anaconda project problems.
Method signatures and docstrings:
- def __init__(self, parent=None, problems=None): Dialog to display anaconda project problems.
- def update_style_sheet(self, style_sheet=None): Update custom ... | 74476c9f00ee43338af696da7e9cd02b273f9005 | <|skeleton|>
class DialogProblems:
"""Dialog to display anaconda project problems."""
def __init__(self, parent=None, problems=None):
"""Dialog to display anaconda project problems."""
<|body_0|>
def update_style_sheet(self, style_sheet=None):
"""Update custom css style sheets."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DialogProblems:
"""Dialog to display anaconda project problems."""
def __init__(self, parent=None, problems=None):
"""Dialog to display anaconda project problems."""
super(DialogProblems, self).__init__(parent=parent)
self._parent = parent
self._problems = problems
... | the_stack_v2_python_sparse | python/anaconda/lib/python2.7/site-packages/anaconda_navigator/widgets/dialogs/projects.py | locolucco209/MongoScraper | train | 3 |
79b1c00f4eb93f50d3238b3cfa081663232c0d76 | [
"self.done_training = False\nself.metadata = metadata\nself.domain = infer_domain(metadata)\nDomainModel = meta_domain_2_model(self.domain)\nself.domain_model = DomainModel(self.metadata)\nself.has_exception = False\nself.y_pred_last = None",
"try:\n self.domain_model.train(dataset, remaining_time_budget)\n ... | <|body_start_0|>
self.done_training = False
self.metadata = metadata
self.domain = infer_domain(metadata)
DomainModel = meta_domain_2_model(self.domain)
self.domain_model = DomainModel(self.metadata)
self.has_exception = False
self.y_pred_last = None
<|end_body_0|... | A model that combine all winner solutions. Using domain inferring and apply winner solution in the corresponding domain. | Model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
"""A model that combine all winner solutions. Using domain inferring and apply winner solution in the corresponding domain."""
def __init__(self, metadata):
"""Args: metadata: an AutoDLMetadata object. Its definition can be found in AutoDL_ingestion_program/dataset.py"""
... | stack_v2_sparse_classes_75kplus_train_070736 | 3,735 | permissive | [
{
"docstring": "Args: metadata: an AutoDLMetadata object. Its definition can be found in AutoDL_ingestion_program/dataset.py",
"name": "__init__",
"signature": "def __init__(self, metadata)"
},
{
"docstring": "Train method of domain-specific model.",
"name": "train",
"signature": "def tr... | 3 | stack_v2_sparse_classes_30k_train_028039 | Implement the Python class `Model` described below.
Class description:
A model that combine all winner solutions. Using domain inferring and apply winner solution in the corresponding domain.
Method signatures and docstrings:
- def __init__(self, metadata): Args: metadata: an AutoDLMetadata object. Its definition can... | Implement the Python class `Model` described below.
Class description:
A model that combine all winner solutions. Using domain inferring and apply winner solution in the corresponding domain.
Method signatures and docstrings:
- def __init__(self, metadata): Args: metadata: an AutoDLMetadata object. Its definition can... | d108e55da943775953b9f1801311a86ac07e58a0 | <|skeleton|>
class Model:
"""A model that combine all winner solutions. Using domain inferring and apply winner solution in the corresponding domain."""
def __init__(self, metadata):
"""Args: metadata: an AutoDLMetadata object. Its definition can be found in AutoDL_ingestion_program/dataset.py"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Model:
"""A model that combine all winner solutions. Using domain inferring and apply winner solution in the corresponding domain."""
def __init__(self, metadata):
"""Args: metadata: an AutoDLMetadata object. Its definition can be found in AutoDL_ingestion_program/dataset.py"""
self.done_... | the_stack_v2_python_sparse | deepwisdom_rewrite_new/model.py | zichuan-scott-xu/automl-workflow | train | 0 |
5a9317ec492b17cf7b7f5d4649c84741b3a93887 | [
"self.sensor_id = sensor_id\nself.sensor_x_distance = sensor_x_distance\nself.sensor_y_distance = sensor_y_distance\nself.sensor_rotation = sensor_rotation\nself.trust_existance = trust_existance\nself.trust_car = trust_car\nself.trust_truck = trust_truck\nself.trust_motorcycle = trust_motorcycle\nself.trust_bicycl... | <|body_start_0|>
self.sensor_id = sensor_id
self.sensor_x_distance = sensor_x_distance
self.sensor_y_distance = sensor_y_distance
self.sensor_rotation = sensor_rotation
self.trust_existance = trust_existance
self.trust_car = trust_car
self.trust_truck = trust_truc... | This class is used to generate the transformation matrix for the transformation from sensor coordinated to EGO coordinates. The source for the sensor position and orientation is configured in config file: '/SensorFusion/ConfigFiles/sensorconfig.ini'. The config file consists of sensor information which is read and tran... | Sensor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sensor:
"""This class is used to generate the transformation matrix for the transformation from sensor coordinated to EGO coordinates. The source for the sensor position and orientation is configured in config file: '/SensorFusion/ConfigFiles/sensorconfig.ini'. The config file consists of sensor ... | stack_v2_sparse_classes_75kplus_train_070737 | 3,830 | no_license | [
{
"docstring": "This is a class constructor where it contains all the instance attributes. The objects are the different sensors whose parameters are read from the config file: '/SensorFusion/ConfigFiles/sensorconfig.ini' :param sensor_id: :param sensor_x_distance: :param sensor_y_distance: :param sensor_rotati... | 2 | stack_v2_sparse_classes_30k_train_031551 | Implement the Python class `Sensor` described below.
Class description:
This class is used to generate the transformation matrix for the transformation from sensor coordinated to EGO coordinates. The source for the sensor position and orientation is configured in config file: '/SensorFusion/ConfigFiles/sensorconfig.in... | Implement the Python class `Sensor` described below.
Class description:
This class is used to generate the transformation matrix for the transformation from sensor coordinated to EGO coordinates. The source for the sensor position and orientation is configured in config file: '/SensorFusion/ConfigFiles/sensorconfig.in... | de2f4b229f3df4f219a08f3d4d7e8d3d40750c55 | <|skeleton|>
class Sensor:
"""This class is used to generate the transformation matrix for the transformation from sensor coordinated to EGO coordinates. The source for the sensor position and orientation is configured in config file: '/SensorFusion/ConfigFiles/sensorconfig.ini'. The config file consists of sensor ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sensor:
"""This class is used to generate the transformation matrix for the transformation from sensor coordinated to EGO coordinates. The source for the sensor position and orientation is configured in config file: '/SensorFusion/ConfigFiles/sensorconfig.ini'. The config file consists of sensor information w... | the_stack_v2_python_sparse | src/sensor_model/scripts/ClassSensor.py | RedgeCastelino/Master_thesis_shared | train | 0 |
fa56b493c8f0ba1fa99314f211606f6390823b7f | [
"start = 1081827\ncigar = '2557M97N26M1371N135M1126N66M297N96M2755N' + '76=1043N94=425N113=23956N38='\nassert compute_transcript_end(start, cigar) == 1116097",
"start = 203305518\ncigar = '231M1355N1013M1D1504M'\nassert compute_transcript_end(start, cigar) == 203309621",
"start = 167936402\ncigar = '136S114M152... | <|body_start_0|>
start = 1081827
cigar = '2557M97N26M1371N135M1126N66M297N96M2755N' + '76=1043N94=425N113=23956N38='
assert compute_transcript_end(start, cigar) == 1116097
<|end_body_0|>
<|body_start_1|>
start = 203305518
cigar = '231M1355N1013M1D1504M'
assert compute_tr... | TestComputeTranscriptEnd | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestComputeTranscriptEnd:
def test_MN_Only(self):
"""This example (from transcript c3098/f3p2/3199 in GM12878_chr1_clean.sam) contains only M and N operations. The transcript is on the minus strand, but the sequence and CIGAR in BAM are relative to the forward strand."""
<|body_0... | stack_v2_sparse_classes_75kplus_train_070738 | 2,001 | permissive | [
{
"docstring": "This example (from transcript c3098/f3p2/3199 in GM12878_chr1_clean.sam) contains only M and N operations. The transcript is on the minus strand, but the sequence and CIGAR in BAM are relative to the forward strand.",
"name": "test_MN_Only",
"signature": "def test_MN_Only(self)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_042395 | Implement the Python class `TestComputeTranscriptEnd` described below.
Class description:
Implement the TestComputeTranscriptEnd class.
Method signatures and docstrings:
- def test_MN_Only(self): This example (from transcript c3098/f3p2/3199 in GM12878_chr1_clean.sam) contains only M and N operations. The transcript ... | Implement the Python class `TestComputeTranscriptEnd` described below.
Class description:
Implement the TestComputeTranscriptEnd class.
Method signatures and docstrings:
- def test_MN_Only(self): This example (from transcript c3098/f3p2/3199 in GM12878_chr1_clean.sam) contains only M and N operations. The transcript ... | 8014faed5f982e5e106ec05239e47d65878e76c3 | <|skeleton|>
class TestComputeTranscriptEnd:
def test_MN_Only(self):
"""This example (from transcript c3098/f3p2/3199 in GM12878_chr1_clean.sam) contains only M and N operations. The transcript is on the minus strand, but the sequence and CIGAR in BAM are relative to the forward strand."""
<|body_0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestComputeTranscriptEnd:
def test_MN_Only(self):
"""This example (from transcript c3098/f3p2/3199 in GM12878_chr1_clean.sam) contains only M and N operations. The transcript is on the minus strand, but the sequence and CIGAR in BAM are relative to the forward strand."""
start = 1081827
... | the_stack_v2_python_sparse | archived/talon_3.0down_testing_suite/test_compute_transcript_end.py | kopardev/TALON | train | 0 | |
b956dbafc7ec69f6bf3d20267231a46b4c460ad4 | [
"self._num_classes = num_classes\nself._num_attributes = num_attributes\nself._num_convs = num_convs\nself._num_filters = num_filters\nif use_separable_conv:\n self._conv2d_op = functools.partial(tf.layers.separable_conv2d, depth_multiplier=1, bias_initializer=tf.zeros_initializer())\nelse:\n self._conv2d_op ... | <|body_start_0|>
self._num_classes = num_classes
self._num_attributes = num_attributes
self._num_convs = num_convs
self._num_filters = num_filters
if use_separable_conv:
self._conv2d_op = functools.partial(tf.layers.separable_conv2d, depth_multiplier=1, bias_initializ... | Fast R-CNN head with additional attribute prediction. | FastrcnnHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastrcnnHead:
"""Fast R-CNN head with additional attribute prediction."""
def __init__(self, num_classes, num_attributes, num_convs=0, num_filters=256, use_separable_conv=False, num_fcs=2, fc_dims=1024, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormActivation(... | stack_v2_sparse_classes_75kplus_train_070739 | 6,483 | permissive | [
{
"docstring": "Initialize params to build Fast R-CNN head with attribute prediction. Args: num_classes: an integer for the number of classes. num_attributes: an integer for the number of attributes. num_convs: `int` number that represents the number of the intermediate conv layers before the FC layers. num_fil... | 2 | stack_v2_sparse_classes_30k_val_001674 | Implement the Python class `FastrcnnHead` described below.
Class description:
Fast R-CNN head with additional attribute prediction.
Method signatures and docstrings:
- def __init__(self, num_classes, num_attributes, num_convs=0, num_filters=256, use_separable_conv=False, num_fcs=2, fc_dims=1024, activation='relu', us... | Implement the Python class `FastrcnnHead` described below.
Class description:
Fast R-CNN head with additional attribute prediction.
Method signatures and docstrings:
- def __init__(self, num_classes, num_attributes, num_convs=0, num_filters=256, use_separable_conv=False, num_fcs=2, fc_dims=1024, activation='relu', us... | 0f7adb97a93ec3e3485c261d030c507eb16b33e4 | <|skeleton|>
class FastrcnnHead:
"""Fast R-CNN head with additional attribute prediction."""
def __init__(self, num_classes, num_attributes, num_convs=0, num_filters=256, use_separable_conv=False, num_fcs=2, fc_dims=1024, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormActivation(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FastrcnnHead:
"""Fast R-CNN head with additional attribute prediction."""
def __init__(self, num_classes, num_attributes, num_convs=0, num_filters=256, use_separable_conv=False, num_fcs=2, fc_dims=1024, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormActivation(activation='r... | the_stack_v2_python_sparse | models/official/detection/projects/fashionpedia/modeling/architecture/fast_rcnn_head.py | tensorflow/tpu | train | 5,627 |
20efd32f30e3046f1a2ae2e9045be9413bbdfb95 | [
"json_dict = json.loads(request.body.decode())\nreceiver = json_dict.get('receiver')\nprovince_id = json_dict.get('province_id')\ncity_id = json_dict.get('city_id')\ndistrict_id = json_dict.get('district_id')\nplace = json_dict.get('place')\nmobile = json_dict.get('mobile')\ntel = json_dict.get('tel')\nemail = json... | <|body_start_0|>
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('province_id')
city_id = json_dict.get('city_id')
district_id = json_dict.get('district_id')
place = json_dict.get('place')
mobile = jso... | 修改和删除地址 | UpdateDestroyAddressView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""# 1.判断地址数量上限 # 2.接受参数 # 3.校验参数 # 4.判断地址是否存在,并更新地址信息 # 5.构造响应数据 # 6.返回相应"""
<|body_0|>
def delete(self, request, address_id):
"""1.查询(根据地址id)要删除的地址 2.将地址逻辑删除设置为True :param request:要删除的地... | stack_v2_sparse_classes_75kplus_train_070740 | 28,561 | permissive | [
{
"docstring": "# 1.判断地址数量上限 # 2.接受参数 # 3.校验参数 # 4.判断地址是否存在,并更新地址信息 # 5.构造响应数据 # 6.返回相应",
"name": "put",
"signature": "def put(self, request, address_id)"
},
{
"docstring": "1.查询(根据地址id)要删除的地址 2.将地址逻辑删除设置为True :param request:要删除的地址 :param address_id:address_id :return:'errmsg': '删除地址成功'",
"n... | 2 | null | Implement the Python class `UpdateDestroyAddressView` described below.
Class description:
修改和删除地址
Method signatures and docstrings:
- def put(self, request, address_id): # 1.判断地址数量上限 # 2.接受参数 # 3.校验参数 # 4.判断地址是否存在,并更新地址信息 # 5.构造响应数据 # 6.返回相应
- def delete(self, request, address_id): 1.查询(根据地址id)要删除的地址 2.将地址逻辑删除设置为True... | Implement the Python class `UpdateDestroyAddressView` described below.
Class description:
修改和删除地址
Method signatures and docstrings:
- def put(self, request, address_id): # 1.判断地址数量上限 # 2.接受参数 # 3.校验参数 # 4.判断地址是否存在,并更新地址信息 # 5.构造响应数据 # 6.返回相应
- def delete(self, request, address_id): 1.查询(根据地址id)要删除的地址 2.将地址逻辑删除设置为True... | 3f21773d2d98204400ea2c3738969ac2a593b242 | <|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""# 1.判断地址数量上限 # 2.接受参数 # 3.校验参数 # 4.判断地址是否存在,并更新地址信息 # 5.构造响应数据 # 6.返回相应"""
<|body_0|>
def delete(self, request, address_id):
"""1.查询(根据地址id)要删除的地址 2.将地址逻辑删除设置为True :param request:要删除的地... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""# 1.判断地址数量上限 # 2.接受参数 # 3.校验参数 # 4.判断地址是否存在,并更新地址信息 # 5.构造响应数据 # 6.返回相应"""
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('provinc... | the_stack_v2_python_sparse | meiduo_mall02/apps/users/views.py | hongyinwang/meiduo_project02 | train | 0 |
004689b47854587b361623a2645e662928338ddd | [
"self.telescope_mount = telescope_mount\nself.corr_factor = corr_factor\nself.min_offset = min_offset",
"status = None\ntry:\n ra_diff, dec_diff = [f.arcsecond for f in reference_position.spherical_offsets_to(current_position)]\n log.debug(f'radec: {ra_diff} {dec_diff}')\n axis0_diff, axis1_diff = delta_... | <|body_start_0|>
self.telescope_mount = telescope_mount
self.corr_factor = corr_factor
self.min_offset = min_offset
<|end_body_0|>
<|body_start_1|>
status = None
try:
ra_diff, dec_diff = [f.arcsecond for f in reference_position.spherical_offsets_to(current_position)]... | Guide offset based on source detection. | GuideOffsetPWI | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GuideOffsetPWI:
"""Guide offset based on source detection."""
def __init__(self, telescope_mount, corr_factor: float=0.8, min_offset: float=0.8):
"""Initialize"""
<|body_0|>
async def offset(self, reference_position: SkyCoord, current_position: SkyCoord):
"""offs... | stack_v2_sparse_classes_75kplus_train_070741 | 1,858 | permissive | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self, telescope_mount, corr_factor: float=0.8, min_offset: float=0.8)"
},
{
"docstring": "offset mount",
"name": "offset",
"signature": "async def offset(self, reference_position: SkyCoord, current_position: SkyC... | 2 | stack_v2_sparse_classes_30k_train_048722 | Implement the Python class `GuideOffsetPWI` described below.
Class description:
Guide offset based on source detection.
Method signatures and docstrings:
- def __init__(self, telescope_mount, corr_factor: float=0.8, min_offset: float=0.8): Initialize
- async def offset(self, reference_position: SkyCoord, current_posi... | Implement the Python class `GuideOffsetPWI` described below.
Class description:
Guide offset based on source detection.
Method signatures and docstrings:
- def __init__(self, telescope_mount, corr_factor: float=0.8, min_offset: float=0.8): Initialize
- async def offset(self, reference_position: SkyCoord, current_posi... | f04723f708dc6767a57a397e7ed8359eace281ba | <|skeleton|>
class GuideOffsetPWI:
"""Guide offset based on source detection."""
def __init__(self, telescope_mount, corr_factor: float=0.8, min_offset: float=0.8):
"""Initialize"""
<|body_0|>
async def offset(self, reference_position: SkyCoord, current_position: SkyCoord):
"""offs... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GuideOffsetPWI:
"""Guide offset based on source detection."""
def __init__(self, telescope_mount, corr_factor: float=0.8, min_offset: float=0.8):
"""Initialize"""
self.telescope_mount = telescope_mount
self.corr_factor = corr_factor
self.min_offset = min_offset
async ... | the_stack_v2_python_sparse | python/lvmagp/guide/offset/pwi.py | sdss/lvmagp | train | 1 |
d0c34a3185e2333a46fa0f7369266aa4e10b1685 | [
"super(ConditionalAutoencoder, self).__init__()\nn_enc_blks = len(enc_channels) - 1\nn_dec_blks = len(dec_channels) - 1\nassert n_enc_blks > 0\nassert n_dec_blks > 0\nself.n_enc_blks = n_enc_blks\nself.n_dec_blks = n_dec_blks\nself.bottom_width = 4\nself.nonlinearity = nn.ReLU()\nresblk_cls = ConditionalResidualBlo... | <|body_start_0|>
super(ConditionalAutoencoder, self).__init__()
n_enc_blks = len(enc_channels) - 1
n_dec_blks = len(dec_channels) - 1
assert n_enc_blks > 0
assert n_dec_blks > 0
self.n_enc_blks = n_enc_blks
self.n_dec_blks = n_dec_blks
self.bottom_width = ... | ConditionalAutoencoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionalAutoencoder:
def __init__(self, enc_channels, dec_channels, num_classes, dim_z=128, im_channels=3):
"""enc_channels [64, 128, 256, 256] c1 c2 c3 dec_channels [256, 128, 64, 64] c1 c2 c3 num_classes if not None, use conditional batchnorm"""
<|body_0|>
def forward(s... | stack_v2_sparse_classes_75kplus_train_070742 | 18,748 | no_license | [
{
"docstring": "enc_channels [64, 128, 256, 256] c1 c2 c3 dec_channels [256, 128, 64, 64] c1 c2 c3 num_classes if not None, use conditional batchnorm",
"name": "__init__",
"signature": "def __init__(self, enc_channels, dec_channels, num_classes, dim_z=128, im_channels=3)"
},
{
"docstring": "x ba... | 2 | stack_v2_sparse_classes_30k_train_042553 | Implement the Python class `ConditionalAutoencoder` described below.
Class description:
Implement the ConditionalAutoencoder class.
Method signatures and docstrings:
- def __init__(self, enc_channels, dec_channels, num_classes, dim_z=128, im_channels=3): enc_channels [64, 128, 256, 256] c1 c2 c3 dec_channels [256, 12... | Implement the Python class `ConditionalAutoencoder` described below.
Class description:
Implement the ConditionalAutoencoder class.
Method signatures and docstrings:
- def __init__(self, enc_channels, dec_channels, num_classes, dim_z=128, im_channels=3): enc_channels [64, 128, 256, 256] c1 c2 c3 dec_channels [256, 12... | 0a6653a66f1fb2590df9d6697e4cd69d32a2baaa | <|skeleton|>
class ConditionalAutoencoder:
def __init__(self, enc_channels, dec_channels, num_classes, dim_z=128, im_channels=3):
"""enc_channels [64, 128, 256, 256] c1 c2 c3 dec_channels [256, 128, 64, 64] c1 c2 c3 num_classes if not None, use conditional batchnorm"""
<|body_0|>
def forward(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConditionalAutoencoder:
def __init__(self, enc_channels, dec_channels, num_classes, dim_z=128, im_channels=3):
"""enc_channels [64, 128, 256, 256] c1 c2 c3 dec_channels [256, 128, 64, 64] c1 c2 c3 num_classes if not None, use conditional batchnorm"""
super(ConditionalAutoencoder, self).__init_... | the_stack_v2_python_sparse | pe/models_cgan.py | tt6746690/misc_impl | train | 0 | |
c494e93bc6f92afd4b94bbd83c7a2793f60ce8ae | [
"try:\n json_data = api.payload\n resp = User().validate_user(json_data=json_data)\n return masked_json_template(resp, 200, resp_code=403)\nexcept:\n resp = get_json_template(response=False, message='No Json Input Found.', results=-1, total=-1)\n return (resp, 404)",
"is_valid, code, msg = is_token... | <|body_start_0|>
try:
json_data = api.payload
resp = User().validate_user(json_data=json_data)
return masked_json_template(resp, 200, resp_code=403)
except:
resp = get_json_template(response=False, message='No Json Input Found.', results=-1, total=-1)
... | LoginByTokenRoute | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginByTokenRoute:
def post(self):
"""Login to get Server Token"""
<|body_0|>
def get(self):
"""Retrieve login status"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
json_data = api.payload
resp = User().validate_user(js... | stack_v2_sparse_classes_75kplus_train_070743 | 2,493 | permissive | [
{
"docstring": "Login to get Server Token",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Retrieve login status",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041307 | Implement the Python class `LoginByTokenRoute` described below.
Class description:
Implement the LoginByTokenRoute class.
Method signatures and docstrings:
- def post(self): Login to get Server Token
- def get(self): Retrieve login status | Implement the Python class `LoginByTokenRoute` described below.
Class description:
Implement the LoginByTokenRoute class.
Method signatures and docstrings:
- def post(self): Login to get Server Token
- def get(self): Retrieve login status
<|skeleton|>
class LoginByTokenRoute:
def post(self):
"""Login to... | 100fca0d2dd9b0b2ab2fa5974d8126af35ddcfd1 | <|skeleton|>
class LoginByTokenRoute:
def post(self):
"""Login to get Server Token"""
<|body_0|>
def get(self):
"""Retrieve login status"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoginByTokenRoute:
def post(self):
"""Login to get Server Token"""
try:
json_data = api.payload
resp = User().validate_user(json_data=json_data)
return masked_json_template(resp, 200, resp_code=403)
except:
resp = get_json_template(respon... | the_stack_v2_python_sparse | app/controllers/api/auth/auth.py | ardihikaru/api-dashboard-5g-dive | train | 0 | |
cf54c5ff41814fd6663c376df6c581f68b4811e4 | [
"if delay_sec is not None and delay_sec > settings.SQS_MAX_TASK_DELAY_SEC:\n raise exceptions.InvalidTaskDelayException('Invalid task delay_sec (%d > %d).' % (delay_sec, settings.SQS_MAX_TASK_DELAY_SEC))\nqueue_class = utils.class_import_from_path(settings.QUEUE_CLASS)\nq_info = queue_info.QueueInfo(settings.QUE... | <|body_start_0|>
if delay_sec is not None and delay_sec > settings.SQS_MAX_TASK_DELAY_SEC:
raise exceptions.InvalidTaskDelayException('Invalid task delay_sec (%d > %d).' % (delay_sec, settings.SQS_MAX_TASK_DELAY_SEC))
queue_class = utils.class_import_from_path(settings.QUEUE_CLASS)
q... | Class to manage publishing SQS tasks. | Publisher | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Publisher:
"""Class to manage publishing SQS tasks."""
def publish(self, task_class, task_id, payload, current_retry_num=None, current_failure_num=None, delay_sec=None):
"""Publish the given task type to the queue with the provided payload. :param obj task_class: class of the task th... | stack_v2_sparse_classes_75kplus_train_070744 | 3,864 | permissive | [
{
"docstring": "Publish the given task type to the queue with the provided payload. :param obj task_class: class of the task that we are publishing. :param str task_id: unique identifying string for this task. :param dict payload: dictionary for the task payload. :param int current_retry_num: current task retry... | 2 | null | Implement the Python class `Publisher` described below.
Class description:
Class to manage publishing SQS tasks.
Method signatures and docstrings:
- def publish(self, task_class, task_id, payload, current_retry_num=None, current_failure_num=None, delay_sec=None): Publish the given task type to the queue with the prov... | Implement the Python class `Publisher` described below.
Class description:
Class to manage publishing SQS tasks.
Method signatures and docstrings:
- def publish(self, task_class, task_id, payload, current_retry_num=None, current_failure_num=None, delay_sec=None): Publish the given task type to the queue with the prov... | c5782535496c55819fb6966792b923678677a112 | <|skeleton|>
class Publisher:
"""Class to manage publishing SQS tasks."""
def publish(self, task_class, task_id, payload, current_retry_num=None, current_failure_num=None, delay_sec=None):
"""Publish the given task type to the queue with the provided payload. :param obj task_class: class of the task th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Publisher:
"""Class to manage publishing SQS tasks."""
def publish(self, task_class, task_id, payload, current_retry_num=None, current_failure_num=None, delay_sec=None):
"""Publish the given task type to the queue with the provided payload. :param obj task_class: class of the task that we are pub... | the_stack_v2_python_sparse | kale/publisher.py | Nextdoor/ndkale | train | 220 |
0564908a23416d3e164fc30852ded6df37b747d0 | [
"if not strs:\n return chr(258)\nreturn chr(257).join((x for x in strs))",
"if s == chr(258):\n return []\nreturn s.split(chr(257))"
] | <|body_start_0|>
if not strs:
return chr(258)
return chr(257).join((x for x in strs))
<|end_body_0|>
<|body_start_1|>
if s == chr(258):
return []
return s.split(chr(257))
<|end_body_1|>
| Codec1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec1:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s... | stack_v2_sparse_classes_75kplus_train_070745 | 3,675 | no_license | [
{
"docstring": "Encodes a list of strings to a single string.",
"name": "encode",
"signature": "def encode(self, strs: [str]) -> str"
},
{
"docstring": "Decodes a single string to a list of strings.",
"name": "decode",
"signature": "def decode(self, s: str) -> [str]"
}
] | 2 | stack_v2_sparse_classes_30k_test_000260 | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings. | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings.
<|skeleton|>
c... | 647fea5d2c8122468a1c018c6829b1c08717d86a | <|skeleton|>
class Codec1:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec1:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
if not strs:
return chr(258)
return chr(257).join((x for x in strs))
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
... | the_stack_v2_python_sparse | LeetCode/medium/encode_decode_strings.py | jinurajan/Datastructures | train | 0 | |
819e9e040bc18acec8d48c2a8db6af76b2e4e21d | [
"def mutate_polygon(object: GeometricObject):\n return Circle.generate(avg_radius, std_radius)\nreturn mutate_polygon",
"def mutate_polygon(object: GeometricObject):\n points = [rd.randint(0, GeometricIndividualConfiguration.IMAGE_WIDTH) for _ in range(2 * n)]\n color = (rd.randint(0, 255), rd.randint(0,... | <|body_start_0|>
def mutate_polygon(object: GeometricObject):
return Circle.generate(avg_radius, std_radius)
return mutate_polygon
<|end_body_0|>
<|body_start_1|>
def mutate_polygon(object: GeometricObject):
points = [rd.randint(0, GeometricIndividualConfiguration.IMAGE_... | Contains various mutation function generation methods for different geometric objects. The functions are used during the mutation process of a geometric genetic algorithm. | GeometricMutations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeometricMutations:
"""Contains various mutation function generation methods for different geometric objects. The functions are used during the mutation process of a geometric genetic algorithm."""
def mutate_circle_function(avg_radius: int=10, std_radius: int=5):
"""Generates a circ... | stack_v2_sparse_classes_75kplus_train_070746 | 4,235 | no_license | [
{
"docstring": "Generates a circle mutation function which generates a circle based on an expected radius and a standard distribution at a random position with a random color. :param avg_radius: The expected radius. :param std_radius: The standard distribution. :return: The mutation function.",
"name": "mut... | 5 | null | Implement the Python class `GeometricMutations` described below.
Class description:
Contains various mutation function generation methods for different geometric objects. The functions are used during the mutation process of a geometric genetic algorithm.
Method signatures and docstrings:
- def mutate_circle_function... | Implement the Python class `GeometricMutations` described below.
Class description:
Contains various mutation function generation methods for different geometric objects. The functions are used during the mutation process of a geometric genetic algorithm.
Method signatures and docstrings:
- def mutate_circle_function... | 8e0cefa0663f264e15828cde8b2faed4380f5bf9 | <|skeleton|>
class GeometricMutations:
"""Contains various mutation function generation methods for different geometric objects. The functions are used during the mutation process of a geometric genetic algorithm."""
def mutate_circle_function(avg_radius: int=10, std_radius: int=5):
"""Generates a circ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeometricMutations:
"""Contains various mutation function generation methods for different geometric objects. The functions are used during the mutation process of a geometric genetic algorithm."""
def mutate_circle_function(avg_radius: int=10, std_radius: int=5):
"""Generates a circle mutation f... | the_stack_v2_python_sparse | genetic/geometric/geometric_mutations.py | dippel-perk/informaticup | train | 3 |
4238a99e6464ce7aae81b45aafd05c0fd79db01a | [
"if self.sid1 == oriented_segment:\n return self.sid2\nelif self.sid2 == oriented_segment:\n return self.sid1\nelse:\n raise gfapy.NotFoundError(\"Oriented segment '{}' not found\\n\".format(oriented_segment) + 'Line: {}'.format(self))",
"if isinstance(segment, gfapy.Line):\n segment = segment.name\ni... | <|body_start_0|>
if self.sid1 == oriented_segment:
return self.sid2
elif self.sid2 == oriented_segment:
return self.sid1
else:
raise gfapy.NotFoundError("Oriented segment '{}' not found\n".format(oriented_segment) + 'Line: {}'.format(self))
<|end_body_0|>
<|b... | Other | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Other:
def other_oriented_segment(self, oriented_segment):
"""The other oriented segment. Parameters: oriented_segment (gfapy.OrientedLine) : One of the two oriented segments of the line. Returns: gfapy.OrientedLine Raises: gfapy.error.NotFoundError: If segment_end is not a segment end o... | stack_v2_sparse_classes_75kplus_train_070747 | 1,374 | permissive | [
{
"docstring": "The other oriented segment. Parameters: oriented_segment (gfapy.OrientedLine) : One of the two oriented segments of the line. Returns: gfapy.OrientedLine Raises: gfapy.error.NotFoundError: If segment_end is not a segment end of the line.",
"name": "other_oriented_segment",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_020732 | Implement the Python class `Other` described below.
Class description:
Implement the Other class.
Method signatures and docstrings:
- def other_oriented_segment(self, oriented_segment): The other oriented segment. Parameters: oriented_segment (gfapy.OrientedLine) : One of the two oriented segments of the line. Return... | Implement the Python class `Other` described below.
Class description:
Implement the Other class.
Method signatures and docstrings:
- def other_oriented_segment(self, oriented_segment): The other oriented segment. Parameters: oriented_segment (gfapy.OrientedLine) : One of the two oriented segments of the line. Return... | 12b31daac26ab137b6ee4a29b4f14554ba962dcb | <|skeleton|>
class Other:
def other_oriented_segment(self, oriented_segment):
"""The other oriented segment. Parameters: oriented_segment (gfapy.OrientedLine) : One of the two oriented segments of the line. Returns: gfapy.OrientedLine Raises: gfapy.error.NotFoundError: If segment_end is not a segment end o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Other:
def other_oriented_segment(self, oriented_segment):
"""The other oriented segment. Parameters: oriented_segment (gfapy.OrientedLine) : One of the two oriented segments of the line. Returns: gfapy.OrientedLine Raises: gfapy.error.NotFoundError: If segment_end is not a segment end of the line."""... | the_stack_v2_python_sparse | gfapy/line/edge/gfa2/other.py | ggonnella/gfapy | train | 63 | |
e7391aafab8f0e63f9d1488503acf607fe9f0ed1 | [
"if 0 <= i <= 2:\n if 0 <= j <= 2:\n return 0\n elif 3 <= j <= 5:\n return 1\n else:\n return 2\nelif 3 <= i <= 5:\n if 0 <= j <= 2:\n return 3\n elif 3 <= j <= 5:\n return 4\n else:\n return 5\nelif 0 <= j <= 2:\n return 6\nelif 3 <= j <= 5:\n retur... | <|body_start_0|>
if 0 <= i <= 2:
if 0 <= j <= 2:
return 0
elif 3 <= j <= 5:
return 1
else:
return 2
elif 3 <= i <= 5:
if 0 <= j <= 2:
return 3
elif 3 <= j <= 5:
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def find_square(self, i, j):
"""Returns a number of a square(0 - 8), in which cell(i, j) is located."""
<|body_0|>
def is_good(self, num, i, j, rows, cols, squares):
"""Returns True if we can place num in cell(i, j), False otherwise."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_070748 | 4,969 | no_license | [
{
"docstring": "Returns a number of a square(0 - 8), in which cell(i, j) is located.",
"name": "find_square",
"signature": "def find_square(self, i, j)"
},
{
"docstring": "Returns True if we can place num in cell(i, j), False otherwise.",
"name": "is_good",
"signature": "def is_good(self... | 6 | stack_v2_sparse_classes_30k_train_044238 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_square(self, i, j): Returns a number of a square(0 - 8), in which cell(i, j) is located.
- def is_good(self, num, i, j, rows, cols, squares): Returns True if we can plac... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_square(self, i, j): Returns a number of a square(0 - 8), in which cell(i, j) is located.
- def is_good(self, num, i, j, rows, cols, squares): Returns True if we can plac... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def find_square(self, i, j):
"""Returns a number of a square(0 - 8), in which cell(i, j) is located."""
<|body_0|>
def is_good(self, num, i, j, rows, cols, squares):
"""Returns True if we can place num in cell(i, j), False otherwise."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def find_square(self, i, j):
"""Returns a number of a square(0 - 8), in which cell(i, j) is located."""
if 0 <= i <= 2:
if 0 <= j <= 2:
return 0
elif 3 <= j <= 5:
return 1
else:
return 2
elif ... | the_stack_v2_python_sparse | Backtracking/sudoku/sudoku_solver.py | vladn90/Algorithms | train | 0 | |
72938e427af2c57f5bec961ba4675aca3d550f0e | [
"super(TectoTemplateNLG, self).__init__(cfg)\nif not 'NLG' in self.cfg or not 'TectoTemplate' in self.cfg['NLG']:\n raise TemplateNLGException('No configuration found!')\nmycfg = self.cfg['NLG']['TectoTemplate']\nif not 'model' in mycfg or not 'scenario' in mycfg or (not 'data_dir' in mycfg):\n raise Template... | <|body_start_0|>
super(TectoTemplateNLG, self).__init__(cfg)
if not 'NLG' in self.cfg or not 'TectoTemplate' in self.cfg['NLG']:
raise TemplateNLGException('No configuration found!')
mycfg = self.cfg['NLG']['TectoTemplate']
if not 'model' in mycfg or not 'scenario' in mycfg o... | Template generation using tecto-trees and NLG rules. | TectoTemplateNLG | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TectoTemplateNLG:
"""Template generation using tecto-trees and NLG rules."""
def __init__(self, cfg):
"""Initialization, checking configuration, loading templates and NLG rules."""
<|body_0|>
def fill_in_template(self, tpl, svs):
"""Filling in tecto-templates, i.... | stack_v2_sparse_classes_75kplus_train_070749 | 16,994 | permissive | [
{
"docstring": "Initialization, checking configuration, loading templates and NLG rules.",
"name": "__init__",
"signature": "def __init__(self, cfg)"
},
{
"docstring": "Filling in tecto-templates, i.e. filling-in strings to templates and using rules to generate the result.",
"name": "fill_in... | 2 | null | Implement the Python class `TectoTemplateNLG` described below.
Class description:
Template generation using tecto-trees and NLG rules.
Method signatures and docstrings:
- def __init__(self, cfg): Initialization, checking configuration, loading templates and NLG rules.
- def fill_in_template(self, tpl, svs): Filling i... | Implement the Python class `TectoTemplateNLG` described below.
Class description:
Template generation using tecto-trees and NLG rules.
Method signatures and docstrings:
- def __init__(self, cfg): Initialization, checking configuration, loading templates and NLG rules.
- def fill_in_template(self, tpl, svs): Filling i... | e8fdc6f2d908d7a1911b18f29c218ae58d19ed6f | <|skeleton|>
class TectoTemplateNLG:
"""Template generation using tecto-trees and NLG rules."""
def __init__(self, cfg):
"""Initialization, checking configuration, loading templates and NLG rules."""
<|body_0|>
def fill_in_template(self, tpl, svs):
"""Filling in tecto-templates, i.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TectoTemplateNLG:
"""Template generation using tecto-trees and NLG rules."""
def __init__(self, cfg):
"""Initialization, checking configuration, loading templates and NLG rules."""
super(TectoTemplateNLG, self).__init__(cfg)
if not 'NLG' in self.cfg or not 'TectoTemplate' in self.... | the_stack_v2_python_sparse | alex/components/nlg/template.py | beka-evature/alex | train | 1 |
7849e46c19b0c22c76232b08a7561f885e2b425d | [
"if isinstance(key, int):\n return Suite(key)\nif key not in Suite._member_map_:\n extend_enum(Suite, key, default)\nreturn Suite[key]",
"if not (isinstance(value, int) and 0 <= value <= 65535):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 7 <= value <= 65535:\n extend_enum(c... | <|body_start_0|>
if isinstance(key, int):
return Suite(key)
if key not in Suite._member_map_:
extend_enum(Suite, key, default)
return Suite[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 65535):
raise ValueError(... | [Suite] Suite IDs | Suite | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Suite:
"""[Suite] Suite IDs"""
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|>
if isinsta... | stack_v2_sparse_classes_75kplus_train_070750 | 1,476 | 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_052632 | Implement the Python class `Suite` described below.
Class description:
[Suite] Suite IDs
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 `Suite` described below.
Class description:
[Suite] Suite IDs
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 Suite:
"""[Suite] Suite IDs"""
... | 90cd07d67df28d5c5ab0585bc60f467a78d9db33 | <|skeleton|>
class Suite:
"""[Suite] Suite IDs"""
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 Suite:
"""[Suite] Suite IDs"""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Suite(key)
if key not in Suite._member_map_:
extend_enum(Suite, key, default)
return Suite[key]
def _missing_(cl... | the_stack_v2_python_sparse | pcapkit/const/hip/suite.py | stjordanis/PyPCAPKit | train | 0 |
cecd97819b0c6a418632004717153a4f26229faf | [
"changes_detected = self.detect_changes()\nmessage = self.get_message(changes_detected)\nprint(message)\nreturn int(changes_detected)",
"try:\n execute('git diff --exit-code -G \"^(msgid|msgstr)\"')\n return False\nexcept CalledProcessError:\n return True",
"msg = 'Source translation files are current.... | <|body_start_0|>
changes_detected = self.detect_changes()
message = self.get_message(changes_detected)
print(message)
return int(changes_detected)
<|end_body_0|>
<|body_start_1|>
try:
execute('git diff --exit-code -G "^(msgid|msgstr)"')
return False
... | Class used to check if the source translation files are up-to-date | Changed | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Changed:
"""Class used to check if the source translation files are up-to-date"""
def run(self, args):
"""Main entry point of script"""
<|body_0|>
def detect_changes(self):
"""Detect if changes have been made to the msgid or msgstr lines in the translation files.... | stack_v2_sparse_classes_75kplus_train_070751 | 1,485 | permissive | [
{
"docstring": "Main entry point of script",
"name": "run",
"signature": "def run(self, args)"
},
{
"docstring": "Detect if changes have been made to the msgid or msgstr lines in the translation files. Returns: boolean: True, if changes detected; otherwise, False. Note: This method requires ``gi... | 3 | stack_v2_sparse_classes_30k_train_023644 | Implement the Python class `Changed` described below.
Class description:
Class used to check if the source translation files are up-to-date
Method signatures and docstrings:
- def run(self, args): Main entry point of script
- def detect_changes(self): Detect if changes have been made to the msgid or msgstr lines in t... | Implement the Python class `Changed` described below.
Class description:
Class used to check if the source translation files are up-to-date
Method signatures and docstrings:
- def run(self, args): Main entry point of script
- def detect_changes(self): Detect if changes have been made to the msgid or msgstr lines in t... | fff15374a18e8823b2db680b9f9f6fc72e20c29d | <|skeleton|>
class Changed:
"""Class used to check if the source translation files are up-to-date"""
def run(self, args):
"""Main entry point of script"""
<|body_0|>
def detect_changes(self):
"""Detect if changes have been made to the msgid or msgstr lines in the translation files.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Changed:
"""Class used to check if the source translation files are up-to-date"""
def run(self, args):
"""Main entry point of script"""
changes_detected = self.detect_changes()
message = self.get_message(changes_detected)
print(message)
return int(changes_detected)... | the_stack_v2_python_sparse | i18n/changed.py | overhangio/i18n-tools | train | 1 |
de091695b92521c227725d4da5e9e8ae45dac4b2 | [
"if str(self.referred_y1) == '1':\n self.referred_y1 = YES\nif str(self.referred_y1) == '2':\n self.referred_y1 = NO",
"if not self.citizen:\n try:\n clinic_eligibility = ClinicEligibility.objects.get(household_member=household_member)\n self.citizen = clinic_eligibility.citizen\n except... | <|body_start_0|>
if str(self.referred_y1) == '1':
self.referred_y1 = YES
if str(self.referred_y1) == '2':
self.referred_y1 = NO
<|end_body_0|>
<|body_start_1|>
if not self.citizen:
try:
clinic_eligibility = ClinicEligibility.objects.get(househ... | SubjectDataFixMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubjectDataFixMixin:
def fix_referred_yesno(self):
"""Fixes values that are incorrect due to a previous source code bug (Data Fix #1096)."""
<|body_0|>
def fix_clinic_citizen(self, household_member):
"""Gets citizen from Eligibility until Consent is fixed (Bug #1094)... | stack_v2_sparse_classes_75kplus_train_070752 | 3,100 | no_license | [
{
"docstring": "Fixes values that are incorrect due to a previous source code bug (Data Fix #1096).",
"name": "fix_referred_yesno",
"signature": "def fix_referred_yesno(self)"
},
{
"docstring": "Gets citizen from Eligibility until Consent is fixed (Bug #1094).",
"name": "fix_clinic_citizen",... | 4 | stack_v2_sparse_classes_30k_train_021864 | Implement the Python class `SubjectDataFixMixin` described below.
Class description:
Implement the SubjectDataFixMixin class.
Method signatures and docstrings:
- def fix_referred_yesno(self): Fixes values that are incorrect due to a previous source code bug (Data Fix #1096).
- def fix_clinic_citizen(self, household_m... | Implement the Python class `SubjectDataFixMixin` described below.
Class description:
Implement the SubjectDataFixMixin class.
Method signatures and docstrings:
- def fix_referred_yesno(self): Fixes values that are incorrect due to a previous source code bug (Data Fix #1096).
- def fix_clinic_citizen(self, household_m... | fe3363c93d599bfe5d1f32997f79790400871315 | <|skeleton|>
class SubjectDataFixMixin:
def fix_referred_yesno(self):
"""Fixes values that are incorrect due to a previous source code bug (Data Fix #1096)."""
<|body_0|>
def fix_clinic_citizen(self, household_member):
"""Gets citizen from Eligibility until Consent is fixed (Bug #1094)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubjectDataFixMixin:
def fix_referred_yesno(self):
"""Fixes values that are incorrect due to a previous source code bug (Data Fix #1096)."""
if str(self.referred_y1) == '1':
self.referred_y1 = YES
if str(self.referred_y1) == '2':
self.referred_y1 = NO
def f... | the_stack_v2_python_sparse | bhp066/apps/bcpp_export/mixins/subject_data_fix_mixin.py | botswana-combination-prevention-project/bcpp-v1 | train | 0 | |
019c9362a9d03118b14561e470d5de8aafeae4aa | [
"self.id = str(identity)\nself.direction = 'none'\nself.speed = 0",
"self.speed = speed\noutput = '0' + self.id\nif self.speed < 11 and self.speed > -11:\n self.speed = 0\nelif self.speed < 0:\n output += '-'\n self.speed = self.speed * -1\nfor _ in range(4 - len(str(self.speed))):\n output += '0'\nou... | <|body_start_0|>
self.id = str(identity)
self.direction = 'none'
self.speed = 0
<|end_body_0|>
<|body_start_1|>
self.speed = speed
output = '0' + self.id
if self.speed < 11 and self.speed > -11:
self.speed = 0
elif self.speed < 0:
output +... | A Wheel class representing a wheel of the emubot | Wheel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wheel:
"""A Wheel class representing a wheel of the emubot"""
def __init__(self, identity):
"""Wheel.__init__(ID): parameters - the ID of the wheel"""
<|body_0|>
def move_wheel(self, speed):
"""Move the wheel"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_070753 | 2,748 | permissive | [
{
"docstring": "Wheel.__init__(ID): parameters - the ID of the wheel",
"name": "__init__",
"signature": "def __init__(self, identity)"
},
{
"docstring": "Move the wheel",
"name": "move_wheel",
"signature": "def move_wheel(self, speed)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013644 | Implement the Python class `Wheel` described below.
Class description:
A Wheel class representing a wheel of the emubot
Method signatures and docstrings:
- def __init__(self, identity): Wheel.__init__(ID): parameters - the ID of the wheel
- def move_wheel(self, speed): Move the wheel | Implement the Python class `Wheel` described below.
Class description:
A Wheel class representing a wheel of the emubot
Method signatures and docstrings:
- def __init__(self, identity): Wheel.__init__(ID): parameters - the ID of the wheel
- def move_wheel(self, speed): Move the wheel
<|skeleton|>
class Wheel:
""... | a39dc01f7c1213c8079216d49d376b317efbf5f3 | <|skeleton|>
class Wheel:
"""A Wheel class representing a wheel of the emubot"""
def __init__(self, identity):
"""Wheel.__init__(ID): parameters - the ID of the wheel"""
<|body_0|>
def move_wheel(self, speed):
"""Move the wheel"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Wheel:
"""A Wheel class representing a wheel of the emubot"""
def __init__(self, identity):
"""Wheel.__init__(ID): parameters - the ID of the wheel"""
self.id = str(identity)
self.direction = 'none'
self.speed = 0
def move_wheel(self, speed):
"""Move the wheel... | the_stack_v2_python_sparse | Client-Code-2018/CurrentEmuBotCode2/basic_classes.py | maxgodfrey2004/RoboCup-2018-Driving-Code | train | 1 |
b2a5772a1888b790a6ada64bff0f2fe5cb0f2c46 | [
"super(AdamWeightDecayOptimizer, self).__init__(False, name)\nself.learning_rate = learning_rate\nself.weight_decay_rate = weight_decay_rate\nself.beta_1 = beta_1\nself.beta_2 = beta_2\nself.epsilon = epsilon\nself.exclude_from_weight_decay = exclude_from_weight_decay\nself.include_in_weight_decay = include_in_weig... | <|body_start_0|>
super(AdamWeightDecayOptimizer, self).__init__(False, name)
self.learning_rate = learning_rate
self.weight_decay_rate = weight_decay_rate
self.beta_1 = beta_1
self.beta_2 = beta_2
self.epsilon = epsilon
self.exclude_from_weight_decay = exclude_fro... | A basic Adam optimizer that includes "correct" L2 weight decay. | AdamWeightDecayOptimizer | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdamWeightDecayOptimizer:
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=('r_s_bias', 'r_r_bias', 'r_w_bias'), name... | stack_v2_sparse_classes_75kplus_train_070754 | 11,858 | permissive | [
{
"docstring": "Constructs a AdamWeightDecayOptimizer.",
"name": "__init__",
"signature": "def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=('r_s_bias', 'r_r_bias', 'r_w_bias'), name='AdamWeightDecay... | 4 | stack_v2_sparse_classes_30k_val_001213 | Implement the Python class `AdamWeightDecayOptimizer` described below.
Class description:
A basic Adam optimizer that includes "correct" L2 weight decay.
Method signatures and docstrings:
- def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None... | Implement the Python class `AdamWeightDecayOptimizer` described below.
Class description:
A basic Adam optimizer that includes "correct" L2 weight decay.
Method signatures and docstrings:
- def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class AdamWeightDecayOptimizer:
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=('r_s_bias', 'r_r_bias', 'r_w_bias'), name... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdamWeightDecayOptimizer:
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=('r_s_bias', 'r_r_bias', 'r_w_bias'), name='AdamWeightD... | the_stack_v2_python_sparse | spreadsheet_coder/model_utils.py | Jimmy-INL/google-research | train | 1 |
ea0565a332eb121e99f74c4d4b42866fa020cf01 | [
"B, Nt, E = q.shape\nq = q / math.sqrt(E)\nattn = torch.bmm(q, k.transpose(-2, -1))\nif attn_mask is not None:\n attn += attn_mask\nattn = attn.softmax(-1)\noutput = torch.bmm(attn, v)\nreturn (output, attn)",
"inputs = [q, k, v]\nif mask is not None:\n inputs += [mask]\nreturn g.op('mmdeploy::ScaledDotProd... | <|body_start_0|>
B, Nt, E = q.shape
q = q / math.sqrt(E)
attn = torch.bmm(q, k.transpose(-2, -1))
if attn_mask is not None:
attn += attn_mask
attn = attn.softmax(-1)
output = torch.bmm(attn, v)
return (output, attn)
<|end_body_0|>
<|body_start_1|>
... | Caller of scale dot product attention. | ScaledDotProductAttentionTRT | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScaledDotProductAttentionTRT:
"""Caller of scale dot product attention."""
def forward(ctx, q: Tensor, k: Tensor, v: Tensor, attn_mask: Optional[Tensor]=None):
"""forward function."""
<|body_0|>
def symbolic(g, q, k, v, mask):
"""Symbolic function."""
<|b... | stack_v2_sparse_classes_75kplus_train_070755 | 1,811 | permissive | [
{
"docstring": "forward function.",
"name": "forward",
"signature": "def forward(ctx, q: Tensor, k: Tensor, v: Tensor, attn_mask: Optional[Tensor]=None)"
},
{
"docstring": "Symbolic function.",
"name": "symbolic",
"signature": "def symbolic(g, q, k, v, mask)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002319 | Implement the Python class `ScaledDotProductAttentionTRT` described below.
Class description:
Caller of scale dot product attention.
Method signatures and docstrings:
- def forward(ctx, q: Tensor, k: Tensor, v: Tensor, attn_mask: Optional[Tensor]=None): forward function.
- def symbolic(g, q, k, v, mask): Symbolic fun... | Implement the Python class `ScaledDotProductAttentionTRT` described below.
Class description:
Caller of scale dot product attention.
Method signatures and docstrings:
- def forward(ctx, q: Tensor, k: Tensor, v: Tensor, attn_mask: Optional[Tensor]=None): forward function.
- def symbolic(g, q, k, v, mask): Symbolic fun... | 5479c8774f5b88d7ed9d399d4e305cb42cc2e73a | <|skeleton|>
class ScaledDotProductAttentionTRT:
"""Caller of scale dot product attention."""
def forward(ctx, q: Tensor, k: Tensor, v: Tensor, attn_mask: Optional[Tensor]=None):
"""forward function."""
<|body_0|>
def symbolic(g, q, k, v, mask):
"""Symbolic function."""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScaledDotProductAttentionTRT:
"""Caller of scale dot product attention."""
def forward(ctx, q: Tensor, k: Tensor, v: Tensor, attn_mask: Optional[Tensor]=None):
"""forward function."""
B, Nt, E = q.shape
q = q / math.sqrt(E)
attn = torch.bmm(q, k.transpose(-2, -1))
... | the_stack_v2_python_sparse | mmdeploy/pytorch/functions/multi_head_attention_forward.py | open-mmlab/mmdeploy | train | 2,164 |
2185f568dfc58b57aa889ecf6b3751374db57d2f | [
"self.etf_symbol = etfSymbol\nself.universe_settings = universeSettings\nself.universe_filter_function = universeFilterFunc\nself.universe = None",
"if self.universe is None:\n self.universe = algorithm.Universe.ETF(self.etf_symbol, self.universe_settings, self.universe_filter_function)\nreturn [self.universe]... | <|body_start_0|>
self.etf_symbol = etfSymbol
self.universe_settings = universeSettings
self.universe_filter_function = universeFilterFunc
self.universe = None
<|end_body_0|>
<|body_start_1|>
if self.universe is None:
self.universe = algorithm.Universe.ETF(self.etf_sy... | Universe selection model that selects the constituents of an ETF. | ETFConstituentsUniverseSelectionModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ETFConstituentsUniverseSelectionModel:
"""Universe selection model that selects the constituents of an ETF."""
def __init__(self, etfSymbol, universeSettings=None, universeFilterFunc=None):
"""Initializes a new instance of the ETFConstituentsUniverseSelectionModel class Args: etfSymb... | stack_v2_sparse_classes_75kplus_train_070756 | 2,049 | permissive | [
{
"docstring": "Initializes a new instance of the ETFConstituentsUniverseSelectionModel class Args: etfSymbol: Symbol of the ETF to get constituents for universeSettings: Universe settings universeFilterFunc: Function to filter universe results",
"name": "__init__",
"signature": "def __init__(self, etfS... | 2 | stack_v2_sparse_classes_30k_train_046918 | Implement the Python class `ETFConstituentsUniverseSelectionModel` described below.
Class description:
Universe selection model that selects the constituents of an ETF.
Method signatures and docstrings:
- def __init__(self, etfSymbol, universeSettings=None, universeFilterFunc=None): Initializes a new instance of the ... | Implement the Python class `ETFConstituentsUniverseSelectionModel` described below.
Class description:
Universe selection model that selects the constituents of an ETF.
Method signatures and docstrings:
- def __init__(self, etfSymbol, universeSettings=None, universeFilterFunc=None): Initializes a new instance of the ... | b33dd3bc140e14b883f39ecf848a793cf7292277 | <|skeleton|>
class ETFConstituentsUniverseSelectionModel:
"""Universe selection model that selects the constituents of an ETF."""
def __init__(self, etfSymbol, universeSettings=None, universeFilterFunc=None):
"""Initializes a new instance of the ETFConstituentsUniverseSelectionModel class Args: etfSymb... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ETFConstituentsUniverseSelectionModel:
"""Universe selection model that selects the constituents of an ETF."""
def __init__(self, etfSymbol, universeSettings=None, universeFilterFunc=None):
"""Initializes a new instance of the ETFConstituentsUniverseSelectionModel class Args: etfSymbol: Symbol of... | the_stack_v2_python_sparse | Algorithm.Framework/Selection/ETFConstituentsUniverseSelectionModel.py | Capnode/Algoloop | train | 87 |
b1f93a688a4117b9dfd1eb0c597408e1baf3eddb | [
"for c in alsaaudio.card_indexes():\n mixers = alsaaudio.mixers(cardindex=c)\n for m in mixers:\n mixer = alsaaudio.Mixer(m, cardindex=c)\n mixer.close()",
"mixers = alsaaudio.mixers()\nmixer = alsaaudio.Mixer(mixers[0])\nfor m, a in MixerMethods:\n f = alsaaudio.Mixer.__dict__[m]\n if a... | <|body_start_0|>
for c in alsaaudio.card_indexes():
mixers = alsaaudio.mixers(cardindex=c)
for m in mixers:
mixer = alsaaudio.Mixer(m, cardindex=c)
mixer.close()
<|end_body_0|>
<|body_start_1|>
mixers = alsaaudio.mixers()
mixer = alsaaudio... | Test Mixer objects | MixerTest | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixerTest:
"""Test Mixer objects"""
def testMixer(self):
"""Open the default Mixers and the Mixers on every card"""
<|body_0|>
def testMixerAll(self):
"""Run common Mixer methods on an open object"""
<|body_1|>
def testMixerClose(self):
"""Ru... | stack_v2_sparse_classes_75kplus_train_070757 | 4,117 | permissive | [
{
"docstring": "Open the default Mixers and the Mixers on every card",
"name": "testMixer",
"signature": "def testMixer(self)"
},
{
"docstring": "Run common Mixer methods on an open object",
"name": "testMixerAll",
"signature": "def testMixerAll(self)"
},
{
"docstring": "Run comm... | 3 | stack_v2_sparse_classes_30k_train_013829 | Implement the Python class `MixerTest` described below.
Class description:
Test Mixer objects
Method signatures and docstrings:
- def testMixer(self): Open the default Mixers and the Mixers on every card
- def testMixerAll(self): Run common Mixer methods on an open object
- def testMixerClose(self): Run common Mixer ... | Implement the Python class `MixerTest` described below.
Class description:
Test Mixer objects
Method signatures and docstrings:
- def testMixer(self): Open the default Mixers and the Mixers on every card
- def testMixerAll(self): Run common Mixer methods on an open object
- def testMixerClose(self): Run common Mixer ... | 758859b3142cef61e34c663ae9677b955ea1f225 | <|skeleton|>
class MixerTest:
"""Test Mixer objects"""
def testMixer(self):
"""Open the default Mixers and the Mixers on every card"""
<|body_0|>
def testMixerAll(self):
"""Run common Mixer methods on an open object"""
<|body_1|>
def testMixerClose(self):
"""Ru... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MixerTest:
"""Test Mixer objects"""
def testMixer(self):
"""Open the default Mixers and the Mixers on every card"""
for c in alsaaudio.card_indexes():
mixers = alsaaudio.mixers(cardindex=c)
for m in mixers:
mixer = alsaaudio.Mixer(m, cardindex=c)
... | the_stack_v2_python_sparse | lesson-2/pyalsaaudio/test.py | alexyvassili/devman-async | train | 0 |
37b73f13a326bbd752bf966e83ef7b57a077d46d | [
"\"\"\"\n --\n ------\n ---------\n \"\"\"\nif not T:\n return T\nstack = []\nresult = [0] * len(T)\nfor cur_idx, cur_temp in enumerate(T):\n while stack and cur_temp > stack[-1][1]:\n small_idx, small_temp = stack.pop()\n result[small_idx] = cur_idx - small_idx\n... | <|body_start_0|>
"""
--
------
---------
"""
if not T:
return T
stack = []
result = [0] * len(T)
for cur_idx, cur_temp in enumerate(T):
while stack and cur_temp > stack[-1][1]:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures2(self, T):
""":type T: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""
--
... | stack_v2_sparse_classes_75kplus_train_070758 | 2,520 | permissive | [
{
"docstring": ":type T: List[int] :rtype: List[int]",
"name": "dailyTemperatures",
"signature": "def dailyTemperatures(self, T)"
},
{
"docstring": ":type T: List[int] :rtype: List[int]",
"name": "dailyTemperatures2",
"signature": "def dailyTemperatures2(self, T)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054419 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, T): :type T: List[int] :rtype: List[int]
- def dailyTemperatures2(self, T): :type T: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, T): :type T: List[int] :rtype: List[int]
- def dailyTemperatures2(self, T): :type T: List[int] :rtype: List[int]
<|skeleton|>
class Solution:
de... | 64863d9d284a72fa23bed40640f7229a0d904f5b | <|skeleton|>
class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures2(self, T):
""":type T: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
"""
--
------
---------
"""
if not T:
return T
stack = []
result = [0] * len(T)
for cur_idx, cur_... | the_stack_v2_python_sparse | Daily Temperatures.py | happyandy2017/LeetCode | train | 0 | |
cbab6da4352bae84b46d2a15af242c6e95c412aa | [
"ref_obj1 = GenericRef.get_reference_for_object(obj1)\nref_obj2 = GenericRef.get_reference_for_object(obj2)\nrelations = GenericRelation.objects.filter(Q(obj1=ref_obj1, obj2=ref_obj2) | Q(obj1=ref_obj2, obj2=ref_obj1))\nreturn relations.exists()",
"if not cls.has_relation(obj1, obj2):\n ref_obj1 = GenericRef.g... | <|body_start_0|>
ref_obj1 = GenericRef.get_reference_for_object(obj1)
ref_obj2 = GenericRef.get_reference_for_object(obj2)
relations = GenericRelation.objects.filter(Q(obj1=ref_obj1, obj2=ref_obj2) | Q(obj1=ref_obj2, obj2=ref_obj1))
return relations.exists()
<|end_body_0|>
<|body_start_... | Generic Relations Betwen any two objects | GenericRelation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericRelation:
"""Generic Relations Betwen any two objects"""
def has_relation(cls, obj1, obj2):
"""check if any two object has a relation"""
<|body_0|>
def add_relation(cls, obj1, obj2, relation_type=None):
"""add (if dont exist) a relation betwen two objects"... | stack_v2_sparse_classes_75kplus_train_070759 | 12,208 | permissive | [
{
"docstring": "check if any two object has a relation",
"name": "has_relation",
"signature": "def has_relation(cls, obj1, obj2)"
},
{
"docstring": "add (if dont exist) a relation betwen two objects",
"name": "add_relation",
"signature": "def add_relation(cls, obj1, obj2, relation_type=N... | 3 | stack_v2_sparse_classes_30k_train_023448 | Implement the Python class `GenericRelation` described below.
Class description:
Generic Relations Betwen any two objects
Method signatures and docstrings:
- def has_relation(cls, obj1, obj2): check if any two object has a relation
- def add_relation(cls, obj1, obj2, relation_type=None): add (if dont exist) a relatio... | Implement the Python class `GenericRelation` described below.
Class description:
Generic Relations Betwen any two objects
Method signatures and docstrings:
- def has_relation(cls, obj1, obj2): check if any two object has a relation
- def add_relation(cls, obj1, obj2, relation_type=None): add (if dont exist) a relatio... | ead274f45af4aa7e338e816268e5e0a2d21c6974 | <|skeleton|>
class GenericRelation:
"""Generic Relations Betwen any two objects"""
def has_relation(cls, obj1, obj2):
"""check if any two object has a relation"""
<|body_0|>
def add_relation(cls, obj1, obj2, relation_type=None):
"""add (if dont exist) a relation betwen two objects"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenericRelation:
"""Generic Relations Betwen any two objects"""
def has_relation(cls, obj1, obj2):
"""check if any two object has a relation"""
ref_obj1 = GenericRef.get_reference_for_object(obj1)
ref_obj2 = GenericRef.get_reference_for_object(obj2)
relations = GenericRela... | the_stack_v2_python_sparse | mootiro_komoo/apps/main/models.py | LuizArmesto/mootiro-maps | train | 0 |
8541e79f37853bfab328138a5dba6cd679f4fc5f | [
"if self.parentNode is None:\n return None\nsiblings = self.parentNode.childNodes\nfor i in range(siblings.index(self), 0, -1):\n n = siblings[i - 1]\n if n.nodeType == Node.ELEMENT_NODE:\n return n\nreturn None",
"if self.parentNode is None:\n return None\nsiblings = self.parentNode.childNodes... | <|body_start_0|>
if self.parentNode is None:
return None
siblings = self.parentNode.childNodes
for i in range(siblings.index(self), 0, -1):
n = siblings[i - 1]
if n.nodeType == Node.ELEMENT_NODE:
return n
return None
<|end_body_0|>
<|b... | Mixin class for ``CharacterData`` and ``DocumentType`` class. | NonDocumentTypeChildNode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NonDocumentTypeChildNode:
"""Mixin class for ``CharacterData`` and ``DocumentType`` class."""
def previousElementSibling(self) -> Optional[AbstractNode]:
"""Previous Element Node. If this node has no previous element node, return None."""
<|body_0|>
def nextElementSiblin... | stack_v2_sparse_classes_75kplus_train_070760 | 22,053 | permissive | [
{
"docstring": "Previous Element Node. If this node has no previous element node, return None.",
"name": "previousElementSibling",
"signature": "def previousElementSibling(self) -> Optional[AbstractNode]"
},
{
"docstring": "Next Element Node. If this node has no next element node, return None.",... | 2 | stack_v2_sparse_classes_30k_train_032605 | Implement the Python class `NonDocumentTypeChildNode` described below.
Class description:
Mixin class for ``CharacterData`` and ``DocumentType`` class.
Method signatures and docstrings:
- def previousElementSibling(self) -> Optional[AbstractNode]: Previous Element Node. If this node has no previous element node, retu... | Implement the Python class `NonDocumentTypeChildNode` described below.
Class description:
Mixin class for ``CharacterData`` and ``DocumentType`` class.
Method signatures and docstrings:
- def previousElementSibling(self) -> Optional[AbstractNode]: Previous Element Node. If this node has no previous element node, retu... | c7cd8b3428ca154af6fb1ecb6c7d2f0e17551802 | <|skeleton|>
class NonDocumentTypeChildNode:
"""Mixin class for ``CharacterData`` and ``DocumentType`` class."""
def previousElementSibling(self) -> Optional[AbstractNode]:
"""Previous Element Node. If this node has no previous element node, return None."""
<|body_0|>
def nextElementSiblin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NonDocumentTypeChildNode:
"""Mixin class for ``CharacterData`` and ``DocumentType`` class."""
def previousElementSibling(self) -> Optional[AbstractNode]:
"""Previous Element Node. If this node has no previous element node, return None."""
if self.parentNode is None:
return Non... | the_stack_v2_python_sparse | wdom/node.py | miyakogi/wdom | train | 72 |
7bbaef22b09efcac00f9e0a9379433db00e5494d | [
"i = 0\nfor num in nums:\n if i < 2 or num > nums[i - 2]:\n nums[i] = num\n i += 1\nreturn i",
"i = 0\nfor num in nums:\n if i < k or num > nums[i - k]:\n nums[i] = num\n i += 1\nreturn i"
] | <|body_start_0|>
i = 0
for num in nums:
if i < 2 or num > nums[i - 2]:
nums[i] = num
i += 1
return i
<|end_body_0|>
<|body_start_1|>
i = 0
for num in nums:
if i < k or num > nums[i - k]:
nums[i] = num
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeKD(self, nums, k):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i = 0
for num in nums:
... | stack_v2_sparse_classes_75kplus_train_070761 | 640 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeKD",
"signature": "def removeKD(self, nums, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeKD(self, nums, k): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeKD(self, nums, k): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def remove... | bd8df12c0d4afd048cf1b58b04c27fa1f3622769 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeKD(self, nums, k):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
i = 0
for num in nums:
if i < 2 or num > nums[i - 2]:
nums[i] = num
i += 1
return i
def removeKD(self, nums, k):
""":type nums: List[int]... | the_stack_v2_python_sparse | 80_remove_duplicates_from_sorted_array.py | aojugg/leetcode | train | 0 | |
20e6046efa3ba31bf33c31c5b92f37af5c9b552b | [
"self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(X_init, X_init)",
"exp_term = (X1 - X2.T) ** 2\nRBF = self.sigma_f ** 2 * np.exp(exp_term * (-0.5 / self.l ** 2))\nreturn RBF"
] | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(X_init, X_init)
<|end_body_0|>
<|body_start_1|>
exp_term = (X1 - X2.T) ** 2
RBF = self.sigma_f ** 2 * np.exp(exp_term * (-0.5 / self.l ** 2))
return RB... | represents a noiseless 1D Gaussian process | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""class constructor"""
<|body_0|>
def kernel(self, X1, X2):
"""calculates the covariance kernel matrix between two matrices"""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_070762 | 630 | no_license | [
{
"docstring": "class constructor",
"name": "__init__",
"signature": "def __init__(self, X_init, Y_init, l=1, sigma_f=1)"
},
{
"docstring": "calculates the covariance kernel matrix between two matrices",
"name": "kernel",
"signature": "def kernel(self, X1, X2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025312 | Implement the Python class `GaussianProcess` described below.
Class description:
represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): class constructor
- def kernel(self, X1, X2): calculates the covariance kernel matrix between two matrices | Implement the Python class `GaussianProcess` described below.
Class description:
represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): class constructor
- def kernel(self, X1, X2): calculates the covariance kernel matrix between two matrices... | 80bf8d3354702f7fb9f79bbb5ed7e00fc19f788d | <|skeleton|>
class GaussianProcess:
"""represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""class constructor"""
<|body_0|>
def kernel(self, X1, X2):
"""calculates the covariance kernel matrix between two matrices"""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussianProcess:
"""represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""class constructor"""
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(X_init, X_init)
def ker... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/0-gp.py | Immaannn2222/holbertonschool-machine_learning | train | 1 |
0c9f8071ca564e83b7c144dbb64727199dd413cf | [
"try:\n py_obj = XML_Objectify(fname, EXPAT).make_instance()\n if not py_obj:\n raise 'BadPaserError'\n py_obj = XML_Objectify(fname, DOM).make_instance()\n if self.quiet < 5:\n print('Indexing', fname)\nexcept IOError:\n return 0\nself.fname_prefix = fname\nself.recurse_nodes(py_ob... | <|body_start_0|>
try:
py_obj = XML_Objectify(fname, EXPAT).make_instance()
if not py_obj:
raise 'BadPaserError'
py_obj = XML_Objectify(fname, DOM).make_instance()
if self.quiet < 5:
print('Indexing', fname)
except IOErro... | Concrete Indexer for XML-as-hierarchical-filesystem | XML_Indexer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XML_Indexer:
"""Concrete Indexer for XML-as-hierarchical-filesystem"""
def add_file(self, fname):
"""Index the nodes of an XML file"""
<|body_0|>
def recurse_nodes(self, currnode, xpath_suffix=''):
"""Recurse and process nodes in XML file"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_070763 | 5,657 | no_license | [
{
"docstring": "Index the nodes of an XML file",
"name": "add_file",
"signature": "def add_file(self, fname)"
},
{
"docstring": "Recurse and process nodes in XML file",
"name": "recurse_nodes",
"signature": "def recurse_nodes(self, currnode, xpath_suffix='')"
},
{
"docstring": "A... | 3 | stack_v2_sparse_classes_30k_train_024832 | Implement the Python class `XML_Indexer` described below.
Class description:
Concrete Indexer for XML-as-hierarchical-filesystem
Method signatures and docstrings:
- def add_file(self, fname): Index the nodes of an XML file
- def recurse_nodes(self, currnode, xpath_suffix=''): Recurse and process nodes in XML file
- d... | Implement the Python class `XML_Indexer` described below.
Class description:
Concrete Indexer for XML-as-hierarchical-filesystem
Method signatures and docstrings:
- def add_file(self, fname): Index the nodes of an XML file
- def recurse_nodes(self, currnode, xpath_suffix=''): Recurse and process nodes in XML file
- d... | 2c5338334c88f52fd0d609df77f317d8bcabfe1a | <|skeleton|>
class XML_Indexer:
"""Concrete Indexer for XML-as-hierarchical-filesystem"""
def add_file(self, fname):
"""Index the nodes of an XML file"""
<|body_0|>
def recurse_nodes(self, currnode, xpath_suffix=''):
"""Recurse and process nodes in XML file"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XML_Indexer:
"""Concrete Indexer for XML-as-hierarchical-filesystem"""
def add_file(self, fname):
"""Index the nodes of an XML file"""
try:
py_obj = XML_Objectify(fname, EXPAT).make_instance()
if not py_obj:
raise 'BadPaserError'
py_... | the_stack_v2_python_sparse | gnosis/xml/indexer.py | firegod2018/GUI_For_CanFestival | train | 3 |
b8e3337de8744c4cf3e29485b2c334ac5d24d3bf | [
"business = Business.query.get(business_id)\nif business:\n reviews = Review.query.filter_by(business=business_id).order_by(Review.name).all()\n if reviews:\n reviews_list = [review.review_as_dict() for review in reviews]\n return make_response(jsonify(reviews_list), 200)\n return make_respon... | <|body_start_0|>
business = Business.query.get(business_id)
if business:
reviews = Review.query.filter_by(business=business_id).order_by(Review.name).all()
if reviews:
reviews_list = [review.review_as_dict() for review in reviews]
return make_respo... | Business Reviews | BusinessReviews | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BusinessReviews:
"""Business Reviews"""
def get(self, business_id):
"""Get all reviews for a business"""
<|body_0|>
def post(self, business_id):
"""Add a review for a business"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
business = Business.q... | stack_v2_sparse_classes_75kplus_train_070764 | 14,152 | no_license | [
{
"docstring": "Get all reviews for a business",
"name": "get",
"signature": "def get(self, business_id)"
},
{
"docstring": "Add a review for a business",
"name": "post",
"signature": "def post(self, business_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050506 | Implement the Python class `BusinessReviews` described below.
Class description:
Business Reviews
Method signatures and docstrings:
- def get(self, business_id): Get all reviews for a business
- def post(self, business_id): Add a review for a business | Implement the Python class `BusinessReviews` described below.
Class description:
Business Reviews
Method signatures and docstrings:
- def get(self, business_id): Get all reviews for a business
- def post(self, business_id): Add a review for a business
<|skeleton|>
class BusinessReviews:
"""Business Reviews"""
... | 6bc3620482e24fd5ead5bdd916900a84e13b7d77 | <|skeleton|>
class BusinessReviews:
"""Business Reviews"""
def get(self, business_id):
"""Get all reviews for a business"""
<|body_0|>
def post(self, business_id):
"""Add a review for a business"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BusinessReviews:
"""Business Reviews"""
def get(self, business_id):
"""Get all reviews for a business"""
business = Business.query.get(business_id)
if business:
reviews = Review.query.filter_by(business=business_id).order_by(Review.name).all()
if reviews:
... | the_stack_v2_python_sparse | api/v2/business.py | Rwothoromo/WeConnect-App | train | 2 |
56e6d5a817f7f6e47ff3be0bef633d953cea7be6 | [
"self.aggregate = aggregate\nself.aggregate_id = aggregate_id\nself.aggregate_path_names = aggregate_path_names\nself.device_ids = device_ids\nself.resolution = resolution\nself.calculation = calculation\nself.data_signal = data_signal\nself.data = data",
"if dictionary is None:\n return None\naggregate = dict... | <|body_start_0|>
self.aggregate = aggregate
self.aggregate_id = aggregate_id
self.aggregate_path_names = aggregate_path_names
self.device_ids = device_ids
self.resolution = resolution
self.calculation = calculation
self.data_signal = data_signal
self.data ... | Implementation of the 'DataItem' model. An object containing time-series data for a specific aggregate, data signal and interval. Attributes: aggregate (AggregateModeEnum): How data is aggregated in the asset structure. aggregate_id (int): The id of this aggregate group: device id, site id, or the constant -1 for portf... | DataItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataItem:
"""Implementation of the 'DataItem' model. An object containing time-series data for a specific aggregate, data signal and interval. Attributes: aggregate (AggregateModeEnum): How data is aggregated in the asset structure. aggregate_id (int): The id of this aggregate group: device id, s... | stack_v2_sparse_classes_75kplus_train_070765 | 4,139 | permissive | [
{
"docstring": "Constructor for the DataItem class",
"name": "__init__",
"signature": "def __init__(self, aggregate='device', aggregate_id=None, device_ids=None, resolution=None, calculation=None, data_signal=None, data=None, aggregate_path_names=None)"
},
{
"docstring": "Creates an instance of ... | 2 | null | Implement the Python class `DataItem` described below.
Class description:
Implementation of the 'DataItem' model. An object containing time-series data for a specific aggregate, data signal and interval. Attributes: aggregate (AggregateModeEnum): How data is aggregated in the asset structure. aggregate_id (int): The i... | Implement the Python class `DataItem` described below.
Class description:
Implementation of the 'DataItem' model. An object containing time-series data for a specific aggregate, data signal and interval. Attributes: aggregate (AggregateModeEnum): How data is aggregated in the asset structure. aggregate_id (int): The i... | 6835ee1f6a667b5c7827c5248391081f06b75513 | <|skeleton|>
class DataItem:
"""Implementation of the 'DataItem' model. An object containing time-series data for a specific aggregate, data signal and interval. Attributes: aggregate (AggregateModeEnum): How data is aggregated in the asset structure. aggregate_id (int): The id of this aggregate group: device id, s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataItem:
"""Implementation of the 'DataItem' model. An object containing time-series data for a specific aggregate, data signal and interval. Attributes: aggregate (AggregateModeEnum): How data is aggregated in the asset structure. aggregate_id (int): The id of this aggregate group: device id, site id, or th... | the_stack_v2_python_sparse | greenbyteapi/models/data_item.py | charlie9578/greenbyte-api-sdk | train | 0 |
3335e602714908a6f43a1d7cd55b1905d9e2af4e | [
"self.cache = []\nself.hash_map = {}\nself.capacity = capacity",
"if key in self.hash_map:\n index = self.cache.index(key)\n del self.cache[index]\n self.cache.append(key)\n return self.hash_map[key]\nelse:\n return -1",
"\"\"\"\n Add element\n \"\"\"\nif key not in self.hash_map:\n... | <|body_start_0|>
self.cache = []
self.hash_map = {}
self.capacity = capacity
<|end_body_0|>
<|body_start_1|>
if key in self.hash_map:
index = self.cache.index(key)
del self.cache[index]
self.cache.append(key)
return self.hash_map[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|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_070766 | 1,548 | 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... | 3 | stack_v2_sparse_classes_30k_train_030279 | 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 | 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
<|skeleton|>
cla... | 6dfdffc075488af717b4e8d486bc3a9222f2721c | <|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|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cache = []
self.hash_map = {}
self.capacity = capacity
def get(self, key):
""":rtype: int"""
if key in self.hash_map:
index = self.cache.index(key)
del self.cache... | the_stack_v2_python_sparse | LRUcache.py | kns94/algorithms_practice | train | 0 | |
f95e632615a3fca54e4e7388e60e43e25ee6c96b | [
"if self.value is not None:\n return self.value * u.Unit(self.unit)\nelse:\n return np.nan * u.Unit(self.unit)",
"newclass = type(name, (cls, Base), {'__tablename__': tablename, 'file': sqlalchemy.Column(sqlalchemy.String, sqlalchemy.ForeignKey(entrycls.file)), 'entry': sqlalchemy.orm.relationship(entrycls,... | <|body_start_0|>
if self.value is not None:
return self.value * u.Unit(self.unit)
else:
return np.nan * u.Unit(self.unit)
<|end_body_0|>
<|body_start_1|>
newclass = type(name, (cls, Base), {'__tablename__': tablename, 'file': sqlalchemy.Column(sqlalchemy.String, sqlalche... | A mixin object for a cache entry object to inherit, providing the relevant columns and accessors | Cache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cache:
"""A mixin object for a cache entry object to inherit, providing the relevant columns and accessors"""
def get_value(self):
"""Return the current cache value (with appropriate AstroPy units)"""
<|body_0|>
def CacheFactory(cls, name, entrycls, tablename, **kwargs):... | stack_v2_sparse_classes_75kplus_train_070767 | 23,976 | no_license | [
{
"docstring": "Return the current cache value (with appropriate AstroPy units)",
"name": "get_value",
"signature": "def get_value(self)"
},
{
"docstring": "Create a cache object inside of cls that is itself a SQLAlchemy entry object",
"name": "CacheFactory",
"signature": "def CacheFacto... | 3 | stack_v2_sparse_classes_30k_train_013267 | Implement the Python class `Cache` described below.
Class description:
A mixin object for a cache entry object to inherit, providing the relevant columns and accessors
Method signatures and docstrings:
- def get_value(self): Return the current cache value (with appropriate AstroPy units)
- def CacheFactory(cls, name,... | Implement the Python class `Cache` described below.
Class description:
A mixin object for a cache entry object to inherit, providing the relevant columns and accessors
Method signatures and docstrings:
- def get_value(self): Return the current cache value (with appropriate AstroPy units)
- def CacheFactory(cls, name,... | 514af926494daa52d1e9699ffe295529492117a2 | <|skeleton|>
class Cache:
"""A mixin object for a cache entry object to inherit, providing the relevant columns and accessors"""
def get_value(self):
"""Return the current cache value (with appropriate AstroPy units)"""
<|body_0|>
def CacheFactory(cls, name, entrycls, tablename, **kwargs):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cache:
"""A mixin object for a cache entry object to inherit, providing the relevant columns and accessors"""
def get_value(self):
"""Return the current cache value (with appropriate AstroPy units)"""
if self.value is not None:
return self.value * u.Unit(self.unit)
els... | the_stack_v2_python_sparse | kepler_utils/database/database.py | brownjustinmichael/KEPLER-Utilities | train | 0 |
e97d4601914796154a725d4ec7c3b963347c00f1 | [
"settings.addListsToRepository('skeinforge_tools.craft_plugins.export_plugins.gcode_step.html', '', self)\nself.addFeedRateEvenWhenUnchanging = settings.BooleanSetting().getFromValue('Add Feed Rate Even When Unchanging', self, True)\nself.addSpaceBetweenWords = settings.BooleanSetting().getFromValue('Add Space Betw... | <|body_start_0|>
settings.addListsToRepository('skeinforge_tools.craft_plugins.export_plugins.gcode_step.html', '', self)
self.addFeedRateEvenWhenUnchanging = settings.BooleanSetting().getFromValue('Add Feed Rate Even When Unchanging', self, True)
self.addSpaceBetweenWords = settings.BooleanSett... | A class to handle the export settings. | GcodeStepRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GcodeStepRepository:
"""A class to handle the export settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Convert to gcode step button has been clicked."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_070768 | 9,522 | no_license | [
{
"docstring": "Set the default settings, execute title & settings fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Convert to gcode step button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012729 | Implement the Python class `GcodeStepRepository` described below.
Class description:
A class to handle the export settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Convert to gcode step button has been clicked. | Implement the Python class `GcodeStepRepository` described below.
Class description:
A class to handle the export settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Convert to gcode step button has been clicked.
<|skelet... | fd69d8e856780c826386dc973ceabcc03623f3e8 | <|skeleton|>
class GcodeStepRepository:
"""A class to handle the export settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Convert to gcode step button has been clicked."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GcodeStepRepository:
"""A class to handle the export settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
settings.addListsToRepository('skeinforge_tools.craft_plugins.export_plugins.gcode_step.html', '', self)
self.addFeedRateEvenWhe... | the_stack_v2_python_sparse | skeinforge_tools/craft_plugins/export_plugins/gcode_step.py | bmander/skeinforge | train | 34 |
036c3f6c4ae6c1cba1161688c7cc9180f114a99a | [
"self.payment_method = payment_method\nself.credit_card = credit_card\nself.debit_card = debit_card\nself.boleto = boleto\nself.currency = currency\nself.voucher = voucher\nself.split = split\nself.bank_transfer = bank_transfer\nself.gateway_affiliation_id = gateway_affiliation_id\nself.amount = amount\nself.checko... | <|body_start_0|>
self.payment_method = payment_method
self.credit_card = credit_card
self.debit_card = debit_card
self.boleto = boleto
self.currency = currency
self.voucher = voucher
self.split = split
self.bank_transfer = bank_transfer
self.gatewa... | Implementation of the 'CreatePaymentRequest' model. Payment data Attributes: payment_method (string): Payment method credit_card (CreditCard1): TODO: type description here. debit_card (DebitCard1): TODO: type description here. boleto (Boleto1): TODO: type description here. currency (string): Currency. Must be informed ... | CreatePaymentRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreatePaymentRequest:
"""Implementation of the 'CreatePaymentRequest' model. Payment data Attributes: payment_method (string): Payment method credit_card (CreditCard1): TODO: type description here. debit_card (DebitCard1): TODO: type description here. boleto (Boleto1): TODO: type description here... | stack_v2_sparse_classes_75kplus_train_070769 | 6,948 | permissive | [
{
"docstring": "Constructor for the CreatePaymentRequest class",
"name": "__init__",
"signature": "def __init__(self, payment_method=None, private_label=None, credit_card=None, debit_card=None, boleto=None, currency=None, voucher=None, split=None, bank_transfer=None, gateway_affiliation_id=None, amount=... | 2 | null | Implement the Python class `CreatePaymentRequest` described below.
Class description:
Implementation of the 'CreatePaymentRequest' model. Payment data Attributes: payment_method (string): Payment method credit_card (CreditCard1): TODO: type description here. debit_card (DebitCard1): TODO: type description here. boleto... | Implement the Python class `CreatePaymentRequest` described below.
Class description:
Implementation of the 'CreatePaymentRequest' model. Payment data Attributes: payment_method (string): Payment method credit_card (CreditCard1): TODO: type description here. debit_card (DebitCard1): TODO: type description here. boleto... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class CreatePaymentRequest:
"""Implementation of the 'CreatePaymentRequest' model. Payment data Attributes: payment_method (string): Payment method credit_card (CreditCard1): TODO: type description here. debit_card (DebitCard1): TODO: type description here. boleto (Boleto1): TODO: type description here... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreatePaymentRequest:
"""Implementation of the 'CreatePaymentRequest' model. Payment data Attributes: payment_method (string): Payment method credit_card (CreditCard1): TODO: type description here. debit_card (DebitCard1): TODO: type description here. boleto (Boleto1): TODO: type description here. currency (s... | the_stack_v2_python_sparse | mundiapi/models/create_payment_request.py | mundipagg/MundiAPI-PYTHON | train | 10 |
91a94c41246c58f418563d0df14136eb7a3e4069 | [
"super(PredictorMockingjay, self).__init__()\nif type(config) is dict:\n config = TransformerConfig(**config)\nself.output_size = output_dim\nif input_dim is None:\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\nelse:\n self.dense = nn.Linear(input_dim, config.hidden_size)\nif isinstance(... | <|body_start_0|>
super(PredictorMockingjay, self).__init__()
if type(config) is dict:
config = TransformerConfig(**config)
self.output_size = output_dim
if input_dim is None:
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
else:
... | The predictor model for SSL pre-training tasks. Currently supporting SSL problems of Mockingjay, Tera, and Audio Albert. | PredictorMockingjay | [
"Apache-2.0",
"CC-BY-NC-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PredictorMockingjay:
"""The predictor model for SSL pre-training tasks. Currently supporting SSL problems of Mockingjay, Tera, and Audio Albert."""
def __init__(self, config, output_dim, input_dim=None, **kwargs):
"""Args: config (TransformerConfig): A `TransformerConfig` class insta... | stack_v2_sparse_classes_75kplus_train_070770 | 2,584 | permissive | [
{
"docstring": "Args: config (TransformerConfig): A `TransformerConfig` class instance with the configuration to build a new model, can also be a `dict` that initializes the TransformerConfig class output_dim (int): The output dimension of predictor input_dim (int): The input dimension of predictor, if `None` i... | 2 | stack_v2_sparse_classes_30k_train_028298 | Implement the Python class `PredictorMockingjay` described below.
Class description:
The predictor model for SSL pre-training tasks. Currently supporting SSL problems of Mockingjay, Tera, and Audio Albert.
Method signatures and docstrings:
- def __init__(self, config, output_dim, input_dim=None, **kwargs): Args: conf... | Implement the Python class `PredictorMockingjay` described below.
Class description:
The predictor model for SSL pre-training tasks. Currently supporting SSL problems of Mockingjay, Tera, and Audio Albert.
Method signatures and docstrings:
- def __init__(self, config, output_dim, input_dim=None, **kwargs): Args: conf... | 76a9432b824f6ae3eae09a35a67782c4ed582832 | <|skeleton|>
class PredictorMockingjay:
"""The predictor model for SSL pre-training tasks. Currently supporting SSL problems of Mockingjay, Tera, and Audio Albert."""
def __init__(self, config, output_dim, input_dim=None, **kwargs):
"""Args: config (TransformerConfig): A `TransformerConfig` class insta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PredictorMockingjay:
"""The predictor model for SSL pre-training tasks. Currently supporting SSL problems of Mockingjay, Tera, and Audio Albert."""
def __init__(self, config, output_dim, input_dim=None, **kwargs):
"""Args: config (TransformerConfig): A `TransformerConfig` class instance with the ... | the_stack_v2_python_sparse | s3prl/nn/predictor_mockingjay.py | s3prl/s3prl | train | 1,549 |
9cd46d8d3d83e8c378e1622f67dcd1781b826156 | [
"FixedstepIntegrator.__init__(self, func, order=4)\nself._half_step = None\nself._one_third_step = None\nself._one_sixth_step = None",
"self._half_step = h / 2.0\nself._one_third_step = h / 3.0\nself._one_sixth_step = h / 6.0",
"middle_time = t + self._half_step\nf1 = self._func(t, x)\nx1 = x + self._half_step ... | <|body_start_0|>
FixedstepIntegrator.__init__(self, func, order=4)
self._half_step = None
self._one_third_step = None
self._one_sixth_step = None
<|end_body_0|>
<|body_start_1|>
self._half_step = h / 2.0
self._one_third_step = h / 3.0
self._one_sixth_step = h / 6... | Class implementing the classic Runge-Kutta 4 integration scheme. Attributes: _half_step (Union[float, ComplexMultivarTaylor]): stored half step-size. _one_third_step (Union[float, ComplexMultivarTaylor]): stored one third of step-size. _one_sixth_step (Union[float, ComplexMultivarTaylor]): stored one sixth of step-size... | RK4 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RK4:
"""Class implementing the classic Runge-Kutta 4 integration scheme. Attributes: _half_step (Union[float, ComplexMultivarTaylor]): stored half step-size. _one_third_step (Union[float, ComplexMultivarTaylor]): stored one third of step-size. _one_sixth_step (Union[float, ComplexMultivarTaylor])... | stack_v2_sparse_classes_75kplus_train_070771 | 40,130 | permissive | [
{
"docstring": "Constructor for RK4 class. Args: func (Callable): function of the independent variable and the state vector defining the derivative of the latter w.r.t. the former.",
"name": "__init__",
"signature": "def __init__(self, func: Callable) -> None"
},
{
"docstring": "Overload parent ... | 3 | null | Implement the Python class `RK4` described below.
Class description:
Class implementing the classic Runge-Kutta 4 integration scheme. Attributes: _half_step (Union[float, ComplexMultivarTaylor]): stored half step-size. _one_third_step (Union[float, ComplexMultivarTaylor]): stored one third of step-size. _one_sixth_ste... | Implement the Python class `RK4` described below.
Class description:
Class implementing the classic Runge-Kutta 4 integration scheme. Attributes: _half_step (Union[float, ComplexMultivarTaylor]): stored half step-size. _one_third_step (Union[float, ComplexMultivarTaylor]): stored one third of step-size. _one_sixth_ste... | 14ded5fd4eea3e647bcd3dfe5b5c89ca80f939e8 | <|skeleton|>
class RK4:
"""Class implementing the classic Runge-Kutta 4 integration scheme. Attributes: _half_step (Union[float, ComplexMultivarTaylor]): stored half step-size. _one_third_step (Union[float, ComplexMultivarTaylor]): stored one third of step-size. _one_sixth_step (Union[float, ComplexMultivarTaylor])... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RK4:
"""Class implementing the classic Runge-Kutta 4 integration scheme. Attributes: _half_step (Union[float, ComplexMultivarTaylor]): stored half step-size. _one_third_step (Union[float, ComplexMultivarTaylor]): stored one third of step-size. _one_sixth_step (Union[float, ComplexMultivarTaylor]): stored one ... | the_stack_v2_python_sparse | swiftt/integrators.py | Serrof/swiftt | train | 0 |
c8d66656b8874ec5b8aaca3de7d15eac157e2b92 | [
"super(LookupRes, self).__init__(name, coap_server=None, visible=True, observable=False)\nself.resource_type = 'core.rd-lookup-res'\nself.content_type = 'application/link-format'",
"if request.accept != defines.Content_types['application/link-format'] and request.accept is not None:\n response.code = defines.C... | <|body_start_0|>
super(LookupRes, self).__init__(name, coap_server=None, visible=True, observable=False)
self.resource_type = 'core.rd-lookup-res'
self.content_type = 'application/link-format'
<|end_body_0|>
<|body_start_1|>
if request.accept != defines.Content_types['application/link-f... | Implementation of the resource lookup resource. | LookupRes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LookupRes:
"""Implementation of the resource lookup resource."""
def __init__(self, name='rd-lookup/res'):
"""Initialize a resource for resource lookup. :param name: the name of the resource."""
<|body_0|>
def render_GET_advanced(self, request, response):
"""Meth... | stack_v2_sparse_classes_75kplus_train_070772 | 1,492 | permissive | [
{
"docstring": "Initialize a resource for resource lookup. :param name: the name of the resource.",
"name": "__init__",
"signature": "def __init__(self, name='rd-lookup/res')"
},
{
"docstring": "Method GET to search resource links. :param request: the request of the GET message. :param response:... | 2 | stack_v2_sparse_classes_30k_train_039833 | Implement the Python class `LookupRes` described below.
Class description:
Implementation of the resource lookup resource.
Method signatures and docstrings:
- def __init__(self, name='rd-lookup/res'): Initialize a resource for resource lookup. :param name: the name of the resource.
- def render_GET_advanced(self, req... | Implement the Python class `LookupRes` described below.
Class description:
Implementation of the resource lookup resource.
Method signatures and docstrings:
- def __init__(self, name='rd-lookup/res'): Initialize a resource for resource lookup. :param name: the name of the resource.
- def render_GET_advanced(self, req... | 6eb8514701e9282b402ef9f21da070d90e52f5f6 | <|skeleton|>
class LookupRes:
"""Implementation of the resource lookup resource."""
def __init__(self, name='rd-lookup/res'):
"""Initialize a resource for resource lookup. :param name: the name of the resource."""
<|body_0|>
def render_GET_advanced(self, request, response):
"""Meth... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LookupRes:
"""Implementation of the resource lookup resource."""
def __init__(self, name='rd-lookup/res'):
"""Initialize a resource for resource lookup. :param name: the name of the resource."""
super(LookupRes, self).__init__(name, coap_server=None, visible=True, observable=False)
... | the_stack_v2_python_sparse | coapthon/resource_directory/lookupRes.py | eliasgranderubio/CoAPthon | train | 0 |
117834f33476068f0619777ee3c113af9ecd5d4f | [
"self.defaultCharWidth = 600\nself.fileName = '/Users/garymenchen/python/pdf/pdfFontMetrics.json'\nself.fonts = []\nself.readFontMetrics()",
"vReturn = None\nfor font in self.fonts:\n if font['key'] == pFontKey:\n vReturn = font\n break\nreturn vReturn",
"font = self.findFont(pFontKey)\nif font... | <|body_start_0|>
self.defaultCharWidth = 600
self.fileName = '/Users/garymenchen/python/pdf/pdfFontMetrics.json'
self.fonts = []
self.readFontMetrics()
<|end_body_0|>
<|body_start_1|>
vReturn = None
for font in self.fonts:
if font['key'] == pFontKey:
... | PdfFontMetrics loads detailed character-specific size information for the built-in variable fonts in a standard version 1.2/1.3 pdf file: Helvetica regular, oblique, bold, and bold-oblique: F2 F2I F2B F2IB Times regular, oblique, bold and bold-oblique (or italic) F3 F3B F3I F3IB These sizes can be used as the basis for... | PdfFontMetrics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PdfFontMetrics:
"""PdfFontMetrics loads detailed character-specific size information for the built-in variable fonts in a standard version 1.2/1.3 pdf file: Helvetica regular, oblique, bold, and bold-oblique: F2 F2I F2B F2IB Times regular, oblique, bold and bold-oblique (or italic) F3 F3B F3I F3I... | stack_v2_sparse_classes_75kplus_train_070773 | 3,525 | no_license | [
{
"docstring": "Calls readFontMetrics to load the font data.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Internal function used to extract data for a specific font",
"name": "findFont",
"signature": "def findFont(self, pFontKey)"
},
{
"docstring": "... | 6 | stack_v2_sparse_classes_30k_train_009225 | Implement the Python class `PdfFontMetrics` described below.
Class description:
PdfFontMetrics loads detailed character-specific size information for the built-in variable fonts in a standard version 1.2/1.3 pdf file: Helvetica regular, oblique, bold, and bold-oblique: F2 F2I F2B F2IB Times regular, oblique, bold and ... | Implement the Python class `PdfFontMetrics` described below.
Class description:
PdfFontMetrics loads detailed character-specific size information for the built-in variable fonts in a standard version 1.2/1.3 pdf file: Helvetica regular, oblique, bold, and bold-oblique: F2 F2I F2B F2IB Times regular, oblique, bold and ... | bdc8534bd6171bfe79556d6f94a0f5bfd54b9025 | <|skeleton|>
class PdfFontMetrics:
"""PdfFontMetrics loads detailed character-specific size information for the built-in variable fonts in a standard version 1.2/1.3 pdf file: Helvetica regular, oblique, bold, and bold-oblique: F2 F2I F2B F2IB Times regular, oblique, bold and bold-oblique (or italic) F3 F3B F3I F3I... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PdfFontMetrics:
"""PdfFontMetrics loads detailed character-specific size information for the built-in variable fonts in a standard version 1.2/1.3 pdf file: Helvetica regular, oblique, bold, and bold-oblique: F2 F2I F2B F2IB Times regular, oblique, bold and bold-oblique (or italic) F3 F3B F3I F3IB These sizes... | the_stack_v2_python_sparse | PdfFontMetrics.py | pagesofpages/python-pdf | train | 0 |
71c9cc2a032206956189f91c02c101b92fead551 | [
"assert not np.isinf(domain[0]) and (not np.isinf(domain[1]))\nif not domain[0] < 0 < domain[1]:\n print('Domain must contain 0!')\n raise AssertionError\nx_pts_p, x_pts_m, self.dx_p, self.dx_m = get_symmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=True, **kwarg... | <|body_start_0|>
assert not np.isinf(domain[0]) and (not np.isinf(domain[1]))
if not domain[0] < 0 < domain[1]:
print('Domain must contain 0!')
raise AssertionError
x_pts_p, x_pts_m, self.dx_p, self.dx_m = get_symmetric_interval_points(domain, max_nof_coefficients, interv... | MidptDiscretizedSymmetricBath | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MidptDiscretizedSymmetricBath:
def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs):
"""Generates direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ ga... | stack_v2_sparse_classes_75kplus_train_070774 | 3,867 | permissive | [
{
"docstring": "Generates direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ gamma_i^2 :param J: Spectral density. A function defined on 'domain', must be >0 in the inner part of domain :param domain: List/tup... | 2 | stack_v2_sparse_classes_30k_train_005328 | Implement the Python class `MidptDiscretizedSymmetricBath` described below.
Class description:
Implement the MidptDiscretizedSymmetricBath class.
Method signatures and docstrings:
- def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): Generates direct discretization coefficients fro... | Implement the Python class `MidptDiscretizedSymmetricBath` described below.
Class description:
Implement the MidptDiscretizedSymmetricBath class.
Method signatures and docstrings:
- def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): Generates direct discretization coefficients fro... | daf37f522f8acb6af2285d44f39cab31f34b01a4 | <|skeleton|>
class MidptDiscretizedSymmetricBath:
def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs):
"""Generates direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ ga... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MidptDiscretizedSymmetricBath:
def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs):
"""Generates direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ gamma_i^2 :param... | the_stack_v2_python_sparse | mapping/star/discretized_bath/symmetric_midpt.py | fhoeb/py-mapping | train | 2 | |
e77b4d3cf4c520ecb3eb35652d606b252e4aa7bc | [
"M = MeterialView()\nresdata = M.get_meterial()\nreturn resdata['data']['item'][0]['id']",
"M = MeterialView()\nform_data = {'image': 'http://wisdom-youxuan-dev.oss-cn-chengdu.aliyuncs.com/images/a9f15e98bff56309f3bb31739420e1df.jpg', 'meterial_code': '', 'meterial_name': 'huanghua菜', 'type_name': '', 'type_id': ... | <|body_start_0|>
M = MeterialView()
resdata = M.get_meterial()
return resdata['data']['item'][0]['id']
<|end_body_0|>
<|body_start_1|>
M = MeterialView()
form_data = {'image': 'http://wisdom-youxuan-dev.oss-cn-chengdu.aliyuncs.com/images/a9f15e98bff56309f3bb31739420e1df.jpg', 'm... | TestMeterial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMeterial:
def test_get_meterial(self):
"""测试材料列表接口"""
<|body_0|>
def test_meterial_add(self):
"""测试添加材料接口"""
<|body_1|>
def test_get_meterial_approval(self):
"""测试材料审核列表接口"""
<|body_2|>
def test_meterial_approval_check(self):
... | stack_v2_sparse_classes_75kplus_train_070775 | 2,615 | no_license | [
{
"docstring": "测试材料列表接口",
"name": "test_get_meterial",
"signature": "def test_get_meterial(self)"
},
{
"docstring": "测试添加材料接口",
"name": "test_meterial_add",
"signature": "def test_meterial_add(self)"
},
{
"docstring": "测试材料审核列表接口",
"name": "test_get_meterial_approval",
"... | 4 | null | Implement the Python class `TestMeterial` described below.
Class description:
Implement the TestMeterial class.
Method signatures and docstrings:
- def test_get_meterial(self): 测试材料列表接口
- def test_meterial_add(self): 测试添加材料接口
- def test_get_meterial_approval(self): 测试材料审核列表接口
- def test_meterial_approval_check(self):... | Implement the Python class `TestMeterial` described below.
Class description:
Implement the TestMeterial class.
Method signatures and docstrings:
- def test_get_meterial(self): 测试材料列表接口
- def test_meterial_add(self): 测试添加材料接口
- def test_get_meterial_approval(self): 测试材料审核列表接口
- def test_meterial_approval_check(self):... | 0465f041b56e009392b32f1681890f4b710febd5 | <|skeleton|>
class TestMeterial:
def test_get_meterial(self):
"""测试材料列表接口"""
<|body_0|>
def test_meterial_add(self):
"""测试添加材料接口"""
<|body_1|>
def test_get_meterial_approval(self):
"""测试材料审核列表接口"""
<|body_2|>
def test_meterial_approval_check(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMeterial:
def test_get_meterial(self):
"""测试材料列表接口"""
M = MeterialView()
resdata = M.get_meterial()
return resdata['data']['item'][0]['id']
def test_meterial_add(self):
"""测试添加材料接口"""
M = MeterialView()
form_data = {'image': 'http://wisdom-youxu... | the_stack_v2_python_sparse | case/test_meterial.py | wmf1992/wisdomApi | train | 0 | |
4876c2f8e1e8545bf619b73a06439d40ef21ce1d | [
"self.method = Req.methods[method.lower()]\nself.args = args\nself.sleep = kws.pop('sleep', None)\nself.parser = kws.pop('parser', None)\nself.kws = kws",
"try:\n response = self.method(*self.args, **self.kws)\n result = self.parser(context, response, queue)\n if self.sleep:\n gevent.sleep(self.sl... | <|body_start_0|>
self.method = Req.methods[method.lower()]
self.args = args
self.sleep = kws.pop('sleep', None)
self.parser = kws.pop('parser', None)
self.kws = kws
<|end_body_0|>
<|body_start_1|>
try:
response = self.method(*self.args, **self.kws)
... | 该对象用于描述HTTP请求 | Req | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Req:
"""该对象用于描述HTTP请求"""
def __init__(self, method, *args, **kws):
""":param method: HTTP请求方法 :param parser: 响应解析器 :param *args: requests参数 :param **kws: requests参数"""
<|body_0|>
def __call__(self, context, queue):
""":param context: 上下文 :param queue: 抓取队列"""
... | stack_v2_sparse_classes_75kplus_train_070776 | 3,713 | permissive | [
{
"docstring": ":param method: HTTP请求方法 :param parser: 响应解析器 :param *args: requests参数 :param **kws: requests参数",
"name": "__init__",
"signature": "def __init__(self, method, *args, **kws)"
},
{
"docstring": ":param context: 上下文 :param queue: 抓取队列",
"name": "__call__",
"signature": "def _... | 2 | stack_v2_sparse_classes_30k_train_034840 | Implement the Python class `Req` described below.
Class description:
该对象用于描述HTTP请求
Method signatures and docstrings:
- def __init__(self, method, *args, **kws): :param method: HTTP请求方法 :param parser: 响应解析器 :param *args: requests参数 :param **kws: requests参数
- def __call__(self, context, queue): :param context: 上下文 :par... | Implement the Python class `Req` described below.
Class description:
该对象用于描述HTTP请求
Method signatures and docstrings:
- def __init__(self, method, *args, **kws): :param method: HTTP请求方法 :param parser: 响应解析器 :param *args: requests参数 :param **kws: requests参数
- def __call__(self, context, queue): :param context: 上下文 :par... | 1a894fd1f5f1f3e160d9e388036a8add6d369438 | <|skeleton|>
class Req:
"""该对象用于描述HTTP请求"""
def __init__(self, method, *args, **kws):
""":param method: HTTP请求方法 :param parser: 响应解析器 :param *args: requests参数 :param **kws: requests参数"""
<|body_0|>
def __call__(self, context, queue):
""":param context: 上下文 :param queue: 抓取队列"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Req:
"""该对象用于描述HTTP请求"""
def __init__(self, method, *args, **kws):
""":param method: HTTP请求方法 :param parser: 响应解析器 :param *args: requests参数 :param **kws: requests参数"""
self.method = Req.methods[method.lower()]
self.args = args
self.sleep = kws.pop('sleep', None)
se... | the_stack_v2_python_sparse | girlfriend/plugin/crawl.py | chihz/girlfriend | train | 0 |
e689fd809bff6dbe6fd18ab48fae7d3163e065ee | [
"self._t1s = np.asarray(t1s)\nself._t2s = np.asarray(t2s)\nif excited_state_populations is not None:\n self._p1s = np.asarray(excited_state_populations)\nelse:\n self._p1s = np.zeros(len(t1s))\nself._dt = dt\nsuper().__init__(self._thermal_relaxation_error, op_types=op_types, method='append')",
"if not op.d... | <|body_start_0|>
self._t1s = np.asarray(t1s)
self._t2s = np.asarray(t2s)
if excited_state_populations is not None:
self._p1s = np.asarray(excited_state_populations)
else:
self._p1s = np.zeros(len(t1s))
self._dt = dt
super().__init__(self._thermal_r... | Add duration dependent thermal relaxation noise after instructions. | RelaxationNoisePass | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelaxationNoisePass:
"""Add duration dependent thermal relaxation noise after instructions."""
def __init__(self, t1s: List[float], t2s: List[float], dt: Optional[float]=None, op_types: Optional[Union[type, Sequence[type]]]=None, excited_state_populations: Optional[List[float]]=None):
... | stack_v2_sparse_classes_75kplus_train_070777 | 3,957 | permissive | [
{
"docstring": "Initialize RelaxationNoisePass. Args: t1s: List of T1 times in seconds for each qubit. t2s: List of T2 times in seconds for each qubit. dt: Backend sample time (resolution) in seconds. This is required for converting dt-unit op durations to times in scheduled circuits. op_types: Optional, the op... | 2 | stack_v2_sparse_classes_30k_train_007641 | Implement the Python class `RelaxationNoisePass` described below.
Class description:
Add duration dependent thermal relaxation noise after instructions.
Method signatures and docstrings:
- def __init__(self, t1s: List[float], t2s: List[float], dt: Optional[float]=None, op_types: Optional[Union[type, Sequence[type]]]=... | Implement the Python class `RelaxationNoisePass` described below.
Class description:
Add duration dependent thermal relaxation noise after instructions.
Method signatures and docstrings:
- def __init__(self, t1s: List[float], t2s: List[float], dt: Optional[float]=None, op_types: Optional[Union[type, Sequence[type]]]=... | f9a6691269397f41db6934927d344e0f8076feea | <|skeleton|>
class RelaxationNoisePass:
"""Add duration dependent thermal relaxation noise after instructions."""
def __init__(self, t1s: List[float], t2s: List[float], dt: Optional[float]=None, op_types: Optional[Union[type, Sequence[type]]]=None, excited_state_populations: Optional[List[float]]=None):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RelaxationNoisePass:
"""Add duration dependent thermal relaxation noise after instructions."""
def __init__(self, t1s: List[float], t2s: List[float], dt: Optional[float]=None, op_types: Optional[Union[type, Sequence[type]]]=None, excited_state_populations: Optional[List[float]]=None):
"""Initiali... | the_stack_v2_python_sparse | qiskit_aer/noise/passes/relaxation_noise_pass.py | Qiskit/qiskit-aer | train | 416 |
d03e7b3eae0f57d2674def94936e660632db8039 | [
"serialized_data = self._serialize_request(request)\ntoken = serialized_data['token']\nsip_user_id = serialized_data['sip_user_id']\napp_id = serialized_data['app']\nremote_logging_id = serialized_data.get('remote_logging_id')\napp = get_object_or_404(App, app_id=app_id, platform=platform)\ndevice, created = Device... | <|body_start_0|>
serialized_data = self._serialize_request(request)
token = serialized_data['token']
sip_user_id = serialized_data['sip_user_id']
app_id = serialized_data['app']
remote_logging_id = serialized_data.get('remote_logging_id')
app = get_object_or_404(App, app_... | View for creating, updating and deleting a device. | DeviceView | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceView:
"""View for creating, updating and deleting a device."""
def post(self, request, platform):
"""Function to create or update a Device."""
<|body_0|>
def delete(self, request, platform):
"""Function for deleting a Device."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_070778 | 24,741 | permissive | [
{
"docstring": "Function to create or update a Device.",
"name": "post",
"signature": "def post(self, request, platform)"
},
{
"docstring": "Function for deleting a Device.",
"name": "delete",
"signature": "def delete(self, request, platform)"
}
] | 2 | null | Implement the Python class `DeviceView` described below.
Class description:
View for creating, updating and deleting a device.
Method signatures and docstrings:
- def post(self, request, platform): Function to create or update a Device.
- def delete(self, request, platform): Function for deleting a Device. | Implement the Python class `DeviceView` described below.
Class description:
View for creating, updating and deleting a device.
Method signatures and docstrings:
- def post(self, request, platform): Function to create or update a Device.
- def delete(self, request, platform): Function for deleting a Device.
<|skeleto... | 744f9a2b3c3859884038acdf1659a8177d5e8a2f | <|skeleton|>
class DeviceView:
"""View for creating, updating and deleting a device."""
def post(self, request, platform):
"""Function to create or update a Device."""
<|body_0|>
def delete(self, request, platform):
"""Function for deleting a Device."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeviceView:
"""View for creating, updating and deleting a device."""
def post(self, request, platform):
"""Function to create or update a Device."""
serialized_data = self._serialize_request(request)
token = serialized_data['token']
sip_user_id = serialized_data['sip_user_... | the_stack_v2_python_sparse | api/views.py | VoIPGRID/vialer-middleware | train | 10 |
ea869c82f7a936540284892e369196b85547c1ba | [
"p = symmetrica.t_SCHUBERT_POLYNOM(self)\nif not is_MPolynomial(p):\n R = PolynomialRing(self.parent().base_ring(), 1, 'x')\n p = R(p)\nreturn p",
"if isinstance(i, Integer):\n return symmetrica.divdiff_schubert(i, self)\nelif i in permutation.Permutations():\n return symmetrica.divdiff_perm_schubert(... | <|body_start_0|>
p = symmetrica.t_SCHUBERT_POLYNOM(self)
if not is_MPolynomial(p):
R = PolynomialRing(self.parent().base_ring(), 1, 'x')
p = R(p)
return p
<|end_body_0|>
<|body_start_1|>
if isinstance(i, Integer):
return symmetrica.divdiff_schubert(i,... | SchubertPolynomial_class | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchubertPolynomial_class:
def expand(self):
"""EXAMPLES:: sage: X = SchubertPolynomialRing(ZZ) sage: X([2,1,3]).expand() x0 sage: map(lambda x: x.expand(), [X(p) for p in Permutations(3)]) [1, x0 + x1, x0, x0*x1, x0^2, x0^2*x1] TESTS: Calling .expand() should always return an element of ... | stack_v2_sparse_classes_75kplus_train_070779 | 8,642 | no_license | [
{
"docstring": "EXAMPLES:: sage: X = SchubertPolynomialRing(ZZ) sage: X([2,1,3]).expand() x0 sage: map(lambda x: x.expand(), [X(p) for p in Permutations(3)]) [1, x0 + x1, x0, x0*x1, x0^2, x0^2*x1] TESTS: Calling .expand() should always return an element of an MPolynomialRing :: sage: X = SchubertPolynomialRing(... | 4 | stack_v2_sparse_classes_30k_train_054519 | Implement the Python class `SchubertPolynomial_class` described below.
Class description:
Implement the SchubertPolynomial_class class.
Method signatures and docstrings:
- def expand(self): EXAMPLES:: sage: X = SchubertPolynomialRing(ZZ) sage: X([2,1,3]).expand() x0 sage: map(lambda x: x.expand(), [X(p) for p in Perm... | Implement the Python class `SchubertPolynomial_class` described below.
Class description:
Implement the SchubertPolynomial_class class.
Method signatures and docstrings:
- def expand(self): EXAMPLES:: sage: X = SchubertPolynomialRing(ZZ) sage: X([2,1,3]).expand() x0 sage: map(lambda x: x.expand(), [X(p) for p in Perm... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class SchubertPolynomial_class:
def expand(self):
"""EXAMPLES:: sage: X = SchubertPolynomialRing(ZZ) sage: X([2,1,3]).expand() x0 sage: map(lambda x: x.expand(), [X(p) for p in Permutations(3)]) [1, x0 + x1, x0, x0*x1, x0^2, x0^2*x1] TESTS: Calling .expand() should always return an element of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SchubertPolynomial_class:
def expand(self):
"""EXAMPLES:: sage: X = SchubertPolynomialRing(ZZ) sage: X([2,1,3]).expand() x0 sage: map(lambda x: x.expand(), [X(p) for p in Permutations(3)]) [1, x0 + x1, x0, x0*x1, x0^2, x0^2*x1] TESTS: Calling .expand() should always return an element of an MPolynomial... | the_stack_v2_python_sparse | sage/src/sage/combinat/schubert_polynomial.py | bopopescu/geosci | train | 0 | |
c0709abf22677b6e7f3185fdb1cf4b579b0db506 | [
"if not to_date:\n to_date = dt.date.today()\ntry:\n last_entry = self.latest('start_date')\nexcept UsageStats.DoesNotExist:\n start_date = dt.date(2014, 5, 5)\nelse:\n start_date = last_entry.start_date + dt.timedelta(7)\ncourt_list = Court.objects.filter(test_mode=False)\nwhile start_date + dt.timedel... | <|body_start_0|>
if not to_date:
to_date = dt.date.today()
try:
last_entry = self.latest('start_date')
except UsageStats.DoesNotExist:
start_date = dt.date(2014, 5, 5)
else:
start_date = last_entry.start_date + dt.timedelta(7)
court... | UsageStatsManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsageStatsManager:
def calculate_weekly_stats(self, to_date=None):
"""Occupy UsageStats with the latest weekly aggregate stats. This function will create entries in UsageStats for each Monday from the last inserted date up to today. An associated management command runs this function."""... | stack_v2_sparse_classes_75kplus_train_070780 | 40,722 | permissive | [
{
"docstring": "Occupy UsageStats with the latest weekly aggregate stats. This function will create entries in UsageStats for each Monday from the last inserted date up to today. An associated management command runs this function.",
"name": "calculate_weekly_stats",
"signature": "def calculate_weekly_s... | 2 | stack_v2_sparse_classes_30k_train_047307 | Implement the Python class `UsageStatsManager` described below.
Class description:
Implement the UsageStatsManager class.
Method signatures and docstrings:
- def calculate_weekly_stats(self, to_date=None): Occupy UsageStats with the latest weekly aggregate stats. This function will create entries in UsageStats for ea... | Implement the Python class `UsageStatsManager` described below.
Class description:
Implement the UsageStatsManager class.
Method signatures and docstrings:
- def calculate_weekly_stats(self, to_date=None): Occupy UsageStats with the latest weekly aggregate stats. This function will create entries in UsageStats for ea... | 0b584b40a17654118201cac6be8b6ac3f302eda4 | <|skeleton|>
class UsageStatsManager:
def calculate_weekly_stats(self, to_date=None):
"""Occupy UsageStats with the latest weekly aggregate stats. This function will create entries in UsageStats for each Monday from the last inserted date up to today. An associated management command runs this function."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UsageStatsManager:
def calculate_weekly_stats(self, to_date=None):
"""Occupy UsageStats with the latest weekly aggregate stats. This function will create entries in UsageStats for each Monday from the last inserted date up to today. An associated management command runs this function."""
if no... | the_stack_v2_python_sparse | apps/plea/models.py | ministryofjustice/manchester_traffic_offences_pleas | train | 4 | |
bfa23529263e6c479f45427434bbf346e2cc932a | [
"n = len(nums)\ntarget_index = n - k\nleft, right = (0, n - 1)\nwhile True:\n index = self._partition(nums, left, right)\n if index == target_index:\n return nums[index]\n elif index < target_index:\n left = index + 1\n else:\n right = index - 1",
"pivot = left\ni, j = (left, righ... | <|body_start_0|>
n = len(nums)
target_index = n - k
left, right = (0, n - 1)
while True:
index = self._partition(nums, left, right)
if index == target_index:
return nums[index]
elif index < target_index:
left = index + 1... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def find_kth_largest(self, nums: List[int], k: int) -> int:
"""基于快速排序的选择方法。"""
<|body_0|>
def _partition(self, nums: List[int], left, right: int) -> int:
"""快排分区。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
... | stack_v2_sparse_classes_75kplus_train_070781 | 2,954 | no_license | [
{
"docstring": "基于快速排序的选择方法。",
"name": "find_kth_largest",
"signature": "def find_kth_largest(self, nums: List[int], k: int) -> int"
},
{
"docstring": "快排分区。",
"name": "_partition",
"signature": "def _partition(self, nums: List[int], left, right: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_007956 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def find_kth_largest(self, nums: List[int], k: int) -> int: 基于快速排序的选择方法。
- def _partition(self, nums: List[int], left, right: int) -> int: 快排分区。 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def find_kth_largest(self, nums: List[int], k: int) -> int: 基于快速排序的选择方法。
- def _partition(self, nums: List[int], left, right: int) -> int: 快排分区。
<|skeleton|>
cla... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def find_kth_largest(self, nums: List[int], k: int) -> int:
"""基于快速排序的选择方法。"""
<|body_0|>
def _partition(self, nums: List[int], left, right: int) -> int:
"""快排分区。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OfficialSolution:
def find_kth_largest(self, nums: List[int], k: int) -> int:
"""基于快速排序的选择方法。"""
n = len(nums)
target_index = n - k
left, right = (0, n - 1)
while True:
index = self._partition(nums, left, right)
if index == target_index:
... | the_stack_v2_python_sparse | 0215_kth-largest-element-in-an-array.py | Nigirimeshi/leetcode | train | 0 | |
bee308e837992120f3fcf1fac4d84cb19c026dfd | [
"self.is_passed = is_passed\nself.message = message\nself.validation = validation",
"if dictionary is None:\n return None\nis_passed = dictionary.get('isPassed')\nmessage = dictionary.get('message')\nvalidation = dictionary.get('validation')\nreturn cls(is_passed, message, validation)"
] | <|body_start_0|>
self.is_passed = is_passed
self.message = message
self.validation = validation
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_passed = dictionary.get('isPassed')
message = dictionary.get('message')
validation = ... | Implementation of the 'PreCheckValidation' model. PreCheckValidation specifies the validations with the pass/fail status Attributes: is_passed (bool): IsPassed indicates validation passed or failed message (string): Message specifies the validation failure message validation (string): Validation specifies the type of v... | PreCheckValidation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreCheckValidation:
"""Implementation of the 'PreCheckValidation' model. PreCheckValidation specifies the validations with the pass/fail status Attributes: is_passed (bool): IsPassed indicates validation passed or failed message (string): Message specifies the validation failure message validatio... | stack_v2_sparse_classes_75kplus_train_070782 | 1,854 | permissive | [
{
"docstring": "Constructor for the PreCheckValidation class",
"name": "__init__",
"signature": "def __init__(self, is_passed=None, message=None, validation=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of... | 2 | null | Implement the Python class `PreCheckValidation` described below.
Class description:
Implementation of the 'PreCheckValidation' model. PreCheckValidation specifies the validations with the pass/fail status Attributes: is_passed (bool): IsPassed indicates validation passed or failed message (string): Message specifies t... | Implement the Python class `PreCheckValidation` described below.
Class description:
Implementation of the 'PreCheckValidation' model. PreCheckValidation specifies the validations with the pass/fail status Attributes: is_passed (bool): IsPassed indicates validation passed or failed message (string): Message specifies t... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class PreCheckValidation:
"""Implementation of the 'PreCheckValidation' model. PreCheckValidation specifies the validations with the pass/fail status Attributes: is_passed (bool): IsPassed indicates validation passed or failed message (string): Message specifies the validation failure message validatio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PreCheckValidation:
"""Implementation of the 'PreCheckValidation' model. PreCheckValidation specifies the validations with the pass/fail status Attributes: is_passed (bool): IsPassed indicates validation passed or failed message (string): Message specifies the validation failure message validation (string): V... | the_stack_v2_python_sparse | cohesity_management_sdk/models/pre_check_validation.py | cohesity/management-sdk-python | train | 24 |
aa490c87a3bebd5e6f9b9527a9326b04b80e6f09 | [
"self._road_net = road_network\nself._max_drv = max_drivers\nself._exclude_prefix = exclude_prefix\nself._aux_id_prefix = aux_id_prefix\nself._num_drv = 0\nself._insertions = 0",
"num_veh = 0\nfor veh_id in traci.vehicle.getIDList():\n if self._exclude_prefix is None or self._exclude_prefix not in veh_id:\n ... | <|body_start_0|>
self._road_net = road_network
self._max_drv = max_drivers
self._exclude_prefix = exclude_prefix
self._aux_id_prefix = aux_id_prefix
self._num_drv = 0
self._insertions = 0
<|end_body_0|>
<|body_start_1|>
num_veh = 0
for veh_id in traci.veh... | Inserts vehicles in the simulation until the maximum allowed number of auxiliary vehicles is reached. New vehicles are inserted with random OD pairs. | DynamicLoadController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicLoadController:
"""Inserts vehicles in the simulation until the maximum allowed number of auxiliary vehicles is reached. New vehicles are inserted with random OD pairs."""
def __init__(self, road_network, max_drivers, aux_id_prefix='aux', exclude_prefix=None):
"""Initializes t... | stack_v2_sparse_classes_75kplus_train_070783 | 3,823 | no_license | [
{
"docstring": "Initializes the auxiliary load controller class :param road_network: the road network :type road_network: sumolib.net.Net :param max_drivers: the maximum allowed number of auxiliary drivers :type max_drivers: int :param aux_id_prefix: :type aux_id_prefix: str :param exclude_prefix: exclude these... | 2 | stack_v2_sparse_classes_30k_train_010480 | Implement the Python class `DynamicLoadController` described below.
Class description:
Inserts vehicles in the simulation until the maximum allowed number of auxiliary vehicles is reached. New vehicles are inserted with random OD pairs.
Method signatures and docstrings:
- def __init__(self, road_network, max_drivers,... | Implement the Python class `DynamicLoadController` described below.
Class description:
Inserts vehicles in the simulation until the maximum allowed number of auxiliary vehicles is reached. New vehicles are inserted with random OD pairs.
Method signatures and docstrings:
- def __init__(self, road_network, max_drivers,... | 773cae4d2e15b1b42ffddeb5eb0be6d158085a3b | <|skeleton|>
class DynamicLoadController:
"""Inserts vehicles in the simulation until the maximum allowed number of auxiliary vehicles is reached. New vehicles are inserted with random OD pairs."""
def __init__(self, road_network, max_drivers, aux_id_prefix='aux', exclude_prefix=None):
"""Initializes t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DynamicLoadController:
"""Inserts vehicles in the simulation until the maximum allowed number of auxiliary vehicles is reached. New vehicles are inserted with random OD pairs."""
def __init__(self, road_network, max_drivers, aux_id_prefix='aux', exclude_prefix=None):
"""Initializes the auxiliary ... | the_stack_v2_python_sparse | roadpricing/auxiliaryload.py | maslab-ufrgs/road-pricing | train | 1 |
4d763fb7ca65a5d3ee23b0c684c48efcf8a07672 | [
"set1 = []\nset2 = []\nfor i, c in enumerate(s):\n if c not in set2:\n if c not in set1:\n set1.append(c)\n else:\n set1.remove(c)\n set2.append(c)\n else:\n continue\nif set1:\n for i, c in enumerate(s):\n if c == set1[0]:\n return i\... | <|body_start_0|>
set1 = []
set2 = []
for i, c in enumerate(s):
if c not in set2:
if c not in set1:
set1.append(c)
else:
set1.remove(c)
set2.append(c)
else:
continue... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstUniqChar_myself(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
set1 = []
set2 = []
for i, c in enumerate(... | stack_v2_sparse_classes_75kplus_train_070784 | 2,279 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar_myself",
"signature": "def firstUniqChar_myself(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar",
"signature": "def firstUniqChar(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar_myself(self, s): :type s: str :rtype: int
- def firstUniqChar(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar_myself(self, s): :type s: str :rtype: int
- def firstUniqChar(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def firstUniqChar_myself(sel... | 93266095329e2e8e949a72371b88b07382a60e0d | <|skeleton|>
class Solution:
def firstUniqChar_myself(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def firstUniqChar_myself(self, s):
""":type s: str :rtype: int"""
set1 = []
set2 = []
for i, c in enumerate(s):
if c not in set2:
if c not in set1:
set1.append(c)
else:
set1.remove(c)
... | the_stack_v2_python_sparse | firstUniqChar.py | shivangi-prog/leetcode | train | 0 | |
8f8df6a5d0f59e6f22f400809bd4bf2087368e4a | [
"self.image_list = image_list\nself.base_num = base_num\nself.pxpys = pxpys\nself.bss = bss\nself.scale = scale\nself.shift = shift\nself.method = method\nself.fit = Fitting(fit_method=fit_method, shift=self.shift, fit_range=self.scale).fit()\nself.one_point_calculation = self.with_eec if eec else self.without_eec\... | <|body_start_0|>
self.image_list = image_list
self.base_num = base_num
self.pxpys = pxpys
self.bss = bss
self.scale = scale
self.shift = shift
self.method = method
self.fit = Fitting(fit_method=fit_method, shift=self.shift, fit_range=self.scale).fit()
... | 変位計測用クラス | Displacement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Displacement:
"""変位計測用クラス"""
def __init__(self, image_list, base_num, pxpys, bss, scale, shift, fit_method='para', eec=True, method='abs'):
""":param image_list: 画像のファイルパスリスト :param base_num: 基準フレームの番号 :param pxpys: 計測点の座標 :param bss: ブロックサイズ :param scale: 画像拡大率 :param shift: 探索範囲 :p... | stack_v2_sparse_classes_75kplus_train_070785 | 16,682 | no_license | [
{
"docstring": ":param image_list: 画像のファイルパスリスト :param base_num: 基準フレームの番号 :param pxpys: 計測点の座標 :param bss: ブロックサイズ :param scale: 画像拡大率 :param shift: 探索範囲 :param fit_method: フィッティング手法 :param eec: Estimate Error Cancellation :param method: 基準フレームからの絶対変位 or 前後フレームでの相対変位",
"name": "__init__",
"signature": ... | 6 | stack_v2_sparse_classes_30k_train_027359 | Implement the Python class `Displacement` described below.
Class description:
変位計測用クラス
Method signatures and docstrings:
- def __init__(self, image_list, base_num, pxpys, bss, scale, shift, fit_method='para', eec=True, method='abs'): :param image_list: 画像のファイルパスリスト :param base_num: 基準フレームの番号 :param pxpys: 計測点の座標 :par... | Implement the Python class `Displacement` described below.
Class description:
変位計測用クラス
Method signatures and docstrings:
- def __init__(self, image_list, base_num, pxpys, bss, scale, shift, fit_method='para', eec=True, method='abs'): :param image_list: 画像のファイルパスリスト :param base_num: 基準フレームの番号 :param pxpys: 計測点の座標 :par... | dd0b0f1310c7a3eb5a5a589bb86d24486cbb37b1 | <|skeleton|>
class Displacement:
"""変位計測用クラス"""
def __init__(self, image_list, base_num, pxpys, bss, scale, shift, fit_method='para', eec=True, method='abs'):
""":param image_list: 画像のファイルパスリスト :param base_num: 基準フレームの番号 :param pxpys: 計測点の座標 :param bss: ブロックサイズ :param scale: 画像拡大率 :param shift: 探索範囲 :p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Displacement:
"""変位計測用クラス"""
def __init__(self, image_list, base_num, pxpys, bss, scale, shift, fit_method='para', eec=True, method='abs'):
""":param image_list: 画像のファイルパスリスト :param base_num: 基準フレームの番号 :param pxpys: 計測点の座標 :param bss: ブロックサイズ :param scale: 画像拡大率 :param shift: 探索範囲 :param fit_meth... | the_stack_v2_python_sparse | my_utils/displacement/displacement.py | salem7mg/test4 | train | 0 |
32d673c9ca22a4d74c7671b269d1a971628d65eb | [
"self.n = len(words)\nself.word2idx = {}\nfor i in range(self.n):\n if words[i] not in self.word2idx:\n self.word2idx[words[i]] = [i]\n else:\n self.word2idx[words[i]] += [i]",
"shortestDis = self.n\nfor i in self.word2idx[word1]:\n for j in self.word2idx[word2]:\n if abs(i - j) < sh... | <|body_start_0|>
self.n = len(words)
self.word2idx = {}
for i in range(self.n):
if words[i] not in self.word2idx:
self.word2idx[words[i]] = [i]
else:
self.word2idx[words[i]] += [i]
<|end_body_0|>
<|body_start_1|>
shortestDis = self... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.n = len(words)
self.word... | stack_v2_sparse_classes_75kplus_train_070786 | 1,870 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001715 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 167a196a9c36f0eaf3d94b07919f4ed138cf4728 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.n = len(words)
self.word2idx = {}
for i in range(self.n):
if words[i] not in self.word2idx:
self.word2idx[words[i]] = [i]
else:
self.word2idx[words... | the_stack_v2_python_sparse | shortestworddisii.py | tristaaa/lcproblems | train | 0 | |
e5d0dbfe5b80b37b7347685d97ebb1103bb77dd4 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | UserGroupAppServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserGroupAppServiceServicer:
"""Missing associated documentation comment in .proto file."""
def user_group_by_name(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def user_group_by_id(self, request, context):
"""... | stack_v2_sparse_classes_75kplus_train_070787 | 8,639 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "user_group_by_name",
"signature": "def user_group_by_name(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "user_group_by_id",
"signature": "d... | 4 | stack_v2_sparse_classes_30k_train_009289 | Implement the Python class `UserGroupAppServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def user_group_by_name(self, request, context): Missing associated documentation comment in .proto file.
- def user_group_by_id(self... | Implement the Python class `UserGroupAppServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def user_group_by_name(self, request, context): Missing associated documentation comment in .proto file.
- def user_group_by_id(self... | 55d36c068e26e13ee5bae5c033e2e17784c63feb | <|skeleton|>
class UserGroupAppServiceServicer:
"""Missing associated documentation comment in .proto file."""
def user_group_by_name(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def user_group_by_id(self, request, context):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserGroupAppServiceServicer:
"""Missing associated documentation comment in .proto file."""
def user_group_by_name(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method no... | the_stack_v2_python_sparse | src/resource/proto/_generated/identity/user_group_app_service_pb2_grpc.py | arkanmgerges/cafm.identity | train | 0 |
94dfbea49d648d211a72dbae07fb1d7a9f7e437c | [
"UserSim.__init__(self, error_evaluator)\nself.user_type = 'real'\nself.bool_undo = bool_undo\nself.undo_semantic_units = []",
"self.questioned_pointers.append(pointer)\nif self.bool_undo:\n answer = input('Please enter yes(y)/no(n)/undo/exit: ').lower().strip()\n while answer not in {'yes', 'no', 'exit', '... | <|body_start_0|>
UserSim.__init__(self, error_evaluator)
self.user_type = 'real'
self.bool_undo = bool_undo
self.undo_semantic_units = []
<|end_body_0|>
<|body_start_1|>
self.questioned_pointers.append(pointer)
if self.bool_undo:
answer = input('Please enter ... | This is the class for real users (used in user study). | RealUser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RealUser:
"""This is the class for real users (used in user study)."""
def __init__(self, error_evaluator, bool_undo=True):
"""Constructor of RealUser. :param error_evaluator: An instance of ErrorEvaluator."""
<|body_0|>
def get_answer(self, pointer, *args):
"""R... | stack_v2_sparse_classes_75kplus_train_070788 | 9,856 | permissive | [
{
"docstring": "Constructor of RealUser. :param error_evaluator: An instance of ErrorEvaluator.",
"name": "__init__",
"signature": "def __init__(self, error_evaluator, bool_undo=True)"
},
{
"docstring": "Request for user answers. :param pointer: the pointer to the questioned semantic unit. :para... | 3 | stack_v2_sparse_classes_30k_train_028930 | Implement the Python class `RealUser` described below.
Class description:
This is the class for real users (used in user study).
Method signatures and docstrings:
- def __init__(self, error_evaluator, bool_undo=True): Constructor of RealUser. :param error_evaluator: An instance of ErrorEvaluator.
- def get_answer(sel... | Implement the Python class `RealUser` described below.
Class description:
This is the class for real users (used in user study).
Method signatures and docstrings:
- def __init__(self, error_evaluator, bool_undo=True): Constructor of RealUser. :param error_evaluator: An instance of ErrorEvaluator.
- def get_answer(sel... | 7870566ab6b9e121d648478968367bc79c12f7ef | <|skeleton|>
class RealUser:
"""This is the class for real users (used in user study)."""
def __init__(self, error_evaluator, bool_undo=True):
"""Constructor of RealUser. :param error_evaluator: An instance of ErrorEvaluator."""
<|body_0|>
def get_answer(self, pointer, *args):
"""R... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RealUser:
"""This is the class for real users (used in user study)."""
def __init__(self, error_evaluator, bool_undo=True):
"""Constructor of RealUser. :param error_evaluator: An instance of ErrorEvaluator."""
UserSim.__init__(self, error_evaluator)
self.user_type = 'real'
... | the_stack_v2_python_sparse | MISP_SQL/environment.py | sunlab-osu/MISP | train | 59 |
92c2688651802de503ccfa1e9dcb3c38f5e938da | [
"length = len(nums)\nfor i in range(length):\n flag = False\n for j in range(length):\n if nums[i] == nums[j] and i != j:\n flag = True\n break\n if not flag:\n return nums[i]\nreturn 0",
"table = {}\nfor i in nums:\n if i in table:\n if table[i] == 1:\n ... | <|body_start_0|>
length = len(nums)
for i in range(length):
flag = False
for j in range(length):
if nums[i] == nums[j] and i != j:
flag = True
break
if not flag:
return nums[i]
return 0
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = len(nums)
for i in range(... | stack_v2_sparse_classes_75kplus_train_070789 | 854 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber1",
"signature": "def singleNumber1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048018 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber1(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber1(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def singleNu... | 8cde0af5a9de3f01e71093e5cdbe58908db16c69 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
length = len(nums)
for i in range(length):
flag = False
for j in range(length):
if nums[i] == nums[j] and i != j:
flag = True
... | the_stack_v2_python_sparse | test_136.py | huangbenyu/leetcode | train | 0 | |
edd9edce56896948402695c41423ff48c23c1503 | [
"edges = defaultdict(set)\nindegrees = [0] * numCourses\nfor second, first in prerequisites:\n indegrees[second] += 1\n edges[first].add(second)\nqueue = []\nfor i in range(numCourses):\n if indegrees[i] == 0:\n queue.append(i)\nvisited = 0\nwhile queue:\n course = queue.pop(0)\n visited += 1\... | <|body_start_0|>
edges = defaultdict(set)
indegrees = [0] * numCourses
for second, first in prerequisites:
indegrees[second] += 1
edges[first].add(second)
queue = []
for i in range(numCourses):
if indegrees[i] == 0:
queue.append... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
"""BFS"""
<|body_0|>
def canFinishDFS(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
"""DFS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
edge... | stack_v2_sparse_classes_75kplus_train_070790 | 3,200 | no_license | [
{
"docstring": "BFS",
"name": "canFinish",
"signature": "def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool"
},
{
"docstring": "DFS",
"name": "canFinishDFS",
"signature": "def canFinishDFS(self, numCourses: int, prerequisites: List[List[int]]) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_006433 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: BFS
- def canFinishDFS(self, numCourses: int, prerequisites: List[List[int]]) -> bool: DFS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: BFS
- def canFinishDFS(self, numCourses: int, prerequisites: List[List[int]]) -> bool: DFS
<|skelet... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
"""BFS"""
<|body_0|>
def canFinishDFS(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
"""DFS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
"""BFS"""
edges = defaultdict(set)
indegrees = [0] * numCourses
for second, first in prerequisites:
indegrees[second] += 1
edges[first].add(second)
queue = []... | the_stack_v2_python_sparse | 207.课程表/solution.py | QtTao/daily_leetcode | train | 0 | |
ddb02206b15d2a580adf10325ac377fd48e98298 | [
"super().__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)\nself.gru = tf.keras.layers.GRU(units=units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)",
"initializer = tf.keras.initializers.Zeros... | <|body_start_0|>
super().__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)
self.gru = tf.keras.layers.GRU(units=units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True... | class RNNEncoder | RNNEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""class RNNEncoder"""
def __init__(self, vocab, embedding, units, batch):
"""* vocab is an integer representing the size of the input vocabulary * embedding is an integer representing the dimensionality of the embedding vector * units is an integer representing the numbe... | stack_v2_sparse_classes_75kplus_train_070791 | 2,703 | no_license | [
{
"docstring": "* vocab is an integer representing the size of the input vocabulary * embedding is an integer representing the dimensionality of the embedding vector * units is an integer representing the number of hidden units in the RNN cell * batch is an integer representing the batch size * Sets the followi... | 3 | stack_v2_sparse_classes_30k_train_033546 | Implement the Python class `RNNEncoder` described below.
Class description:
class RNNEncoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): * vocab is an integer representing the size of the input vocabulary * embedding is an integer representing the dimensionality of the embe... | Implement the Python class `RNNEncoder` described below.
Class description:
class RNNEncoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): * vocab is an integer representing the size of the input vocabulary * embedding is an integer representing the dimensionality of the embe... | 8ad4c2594ff78b345dbd92e9d54d2a143ac4071a | <|skeleton|>
class RNNEncoder:
"""class RNNEncoder"""
def __init__(self, vocab, embedding, units, batch):
"""* vocab is an integer representing the size of the input vocabulary * embedding is an integer representing the dimensionality of the embedding vector * units is an integer representing the numbe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNEncoder:
"""class RNNEncoder"""
def __init__(self, vocab, embedding, units, batch):
"""* vocab is an integer representing the size of the input vocabulary * embedding is an integer representing the dimensionality of the embedding vector * units is an integer representing the number of hidden u... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/0-rnn_encoder.py | jorgezafra94/holbertonschool-machine_learning | train | 1 |
b0bd9f115305a5cd221b21808dcc015c201e4479 | [
"super(ImportFilesPopUp, self).__init__(title='Import files', imported_files=imported_files, default_path=media_path, callback=self.import_files_for_presentation, file_handling_mode=ImportMultipleFiles, callback_button_text='Import', filters=AllSupportedFormats, selected_presentations=selected_presentations, presen... | <|body_start_0|>
super(ImportFilesPopUp, self).__init__(title='Import files', imported_files=imported_files, default_path=media_path, callback=self.import_files_for_presentation, file_handling_mode=ImportMultipleFiles, callback_button_text='Import', filters=AllSupportedFormats, selected_presentations=selected_p... | A file selection and importing popup | ImportFilesPopUp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportFilesPopUp:
"""A file selection and importing popup"""
def __init__(self, listener, imported_files, presentations, selected_presentations, media_path, test_mode=False):
"""Constructs a popup that supports the selection and importing of multiple files at once to a single or mult... | stack_v2_sparse_classes_75kplus_train_070792 | 4,600 | permissive | [
{
"docstring": "Constructs a popup that supports the selection and importing of multiple files at once to a single or multiple presentations. If a file with the same name already exists in the media path, opens a popup to query the user for the desirable action. :param listener: the object to inform when a sing... | 4 | null | Implement the Python class `ImportFilesPopUp` described below.
Class description:
A file selection and importing popup
Method signatures and docstrings:
- def __init__(self, listener, imported_files, presentations, selected_presentations, media_path, test_mode=False): Constructs a popup that supports the selection an... | Implement the Python class `ImportFilesPopUp` described below.
Class description:
A file selection and importing popup
Method signatures and docstrings:
- def __init__(self, listener, imported_files, presentations, selected_presentations, media_path, test_mode=False): Constructs a popup that supports the selection an... | a7d100ff9002b1b1d27249f8adf510b5a89c09e3 | <|skeleton|>
class ImportFilesPopUp:
"""A file selection and importing popup"""
def __init__(self, listener, imported_files, presentations, selected_presentations, media_path, test_mode=False):
"""Constructs a popup that supports the selection and importing of multiple files at once to a single or mult... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImportFilesPopUp:
"""A file selection and importing popup"""
def __init__(self, listener, imported_files, presentations, selected_presentations, media_path, test_mode=False):
"""Constructs a popup that supports the selection and importing of multiple files at once to a single or multiple presenta... | the_stack_v2_python_sparse | project/GUI/PopUps/ImportFilesPopUp.py | RemuTeam/Remu | train | 2 |
c1a182c1833b99ce9ff9603d43f64e67236902b8 | [
"if not self._is_required_to_record_request(command):\n return\nrequest = session_services.get_current_session().get_client_request()\ncoordinator_services.record_request(command.get_option('recorder_type'), request)\nlogging_services.debug('Request [{0}] for service [{1}] recorded.'.format(request.id, command.g... | <|body_start_0|>
if not self._is_required_to_record_request(command):
return
request = session_services.get_current_session().get_client_request()
coordinator_services.record_request(command.get_option('recorder_type'), request)
logging_services.debug('Request [{0}] for servi... | Transaction Coordinator Command Execution Hook | TransactionCoordinatorCommandExecutionHook | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransactionCoordinatorCommandExecutionHook:
"""Transaction Coordinator Command Execution Hook"""
def before_execute(self, commander, command, *args, **kargs):
"""This method will be called before command execution. @param commander: commander @param command: command"""
<|body... | stack_v2_sparse_classes_75kplus_train_070793 | 2,805 | no_license | [
{
"docstring": "This method will be called before command execution. @param commander: commander @param command: command",
"name": "before_execute",
"signature": "def before_execute(self, commander, command, *args, **kargs)"
},
{
"docstring": "This method will be called after command execution. ... | 4 | null | Implement the Python class `TransactionCoordinatorCommandExecutionHook` described below.
Class description:
Transaction Coordinator Command Execution Hook
Method signatures and docstrings:
- def before_execute(self, commander, command, *args, **kargs): This method will be called before command execution. @param comma... | Implement the Python class `TransactionCoordinatorCommandExecutionHook` described below.
Class description:
Transaction Coordinator Command Execution Hook
Method signatures and docstrings:
- def before_execute(self, commander, command, *args, **kargs): This method will be called before command execution. @param comma... | a2ee333d2a4fe9821f3d24ee15d458f226ffcde5 | <|skeleton|>
class TransactionCoordinatorCommandExecutionHook:
"""Transaction Coordinator Command Execution Hook"""
def before_execute(self, commander, command, *args, **kargs):
"""This method will be called before command execution. @param commander: commander @param command: command"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransactionCoordinatorCommandExecutionHook:
"""Transaction Coordinator Command Execution Hook"""
def before_execute(self, commander, command, *args, **kargs):
"""This method will be called before command execution. @param commander: commander @param command: command"""
if not self._is_req... | the_stack_v2_python_sparse | src/deltapy/request_processor/coordinator/commander_hook.py | hamed1361554/sportmagazine-server | train | 0 |
4891f18282a88fca4882d1ecd2162bff6d25203f | [
"parser.add_argument('name', metavar='NAME', help='The name of the cluster to update.')\nparser.add_argument('--monitoring-service', dest='monitoring_service', required=True, help='The monitoring service to use for the cluster. Options are: \"monitoring.googleapis.com\" (the Google Cloud Monitoring service), \"non... | <|body_start_0|>
parser.add_argument('name', metavar='NAME', help='The name of the cluster to update.')
parser.add_argument('--monitoring-service', dest='monitoring_service', required=True, help='The monitoring service to use for the cluster. Options are: "monitoring.googleapis.com" (the Google Cloud Mo... | Update cluster settings for an existing container cluster. | Update | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Update:
"""Update cluster settings for an existing container cluster."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
<... | stack_v2_sparse_classes_75kplus_train_070794 | 2,352 | permissive | [
{
"docstring": "Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the... | 2 | stack_v2_sparse_classes_30k_train_050934 | Implement the Python class `Update` described below.
Class description:
Update cluster settings for an existing container cluster.
Method signatures and docstrings:
- def Args(parser): Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some info... | Implement the Python class `Update` described below.
Class description:
Update cluster settings for an existing container cluster.
Method signatures and docstrings:
- def Args(parser): Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some info... | 1f9b424c40a87b46656fc9f5e2e9c81895c7e614 | <|skeleton|>
class Update:
"""Update cluster settings for an existing container cluster."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Update:
"""Update cluster settings for an existing container cluster."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
parser.add_arg... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/surface/container/clusters/update.py | twistedpair/google-cloud-sdk | train | 58 |
4bcfb8eef1ee60bbe53f9e567cebb54a6045cf6b | [
"nums.sort()\nres = []\nself._dfs(nums, [], res)\nreturn res",
"res.append(path.copy())\nif len(nums) == 0:\n return\nfor i in range(len(nums)):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n path.append(nums[i])\n self._dfs(nums[i + 1:], path, res)\n path.pop(-1)"
] | <|body_start_0|>
nums.sort()
res = []
self._dfs(nums, [], res)
return res
<|end_body_0|>
<|body_start_1|>
res.append(path.copy())
if len(nums) == 0:
return
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
con... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""思路: DFS !!! 在做重复元素进行DFS时,如果需要去重重复元素,一定要记得将数组进行排序排序排序!!! :param nums: :return:"""
<|body_0|>
def _dfs(self, nums, path, res):
"""nums choose path res 终止条件target :return:"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_070795 | 1,064 | no_license | [
{
"docstring": "思路: DFS !!! 在做重复元素进行DFS时,如果需要去重重复元素,一定要记得将数组进行排序排序排序!!! :param nums: :return:",
"name": "subsetsWithDup",
"signature": "def subsetsWithDup(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "nums choose path res 终止条件target :return:",
"name": "_dfs",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_004170 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: 思路: DFS !!! 在做重复元素进行DFS时,如果需要去重重复元素,一定要记得将数组进行排序排序排序!!! :param nums: :return:
- def _dfs(self, nums, path, res): num... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: 思路: DFS !!! 在做重复元素进行DFS时,如果需要去重重复元素,一定要记得将数组进行排序排序排序!!! :param nums: :return:
- def _dfs(self, nums, path, res): num... | 6708479302cca3ea3d930e6e80264f213ea29c5f | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""思路: DFS !!! 在做重复元素进行DFS时,如果需要去重重复元素,一定要记得将数组进行排序排序排序!!! :param nums: :return:"""
<|body_0|>
def _dfs(self, nums, path, res):
"""nums choose path res 终止条件target :return:"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""思路: DFS !!! 在做重复元素进行DFS时,如果需要去重重复元素,一定要记得将数组进行排序排序排序!!! :param nums: :return:"""
nums.sort()
res = []
self._dfs(nums, [], res)
return res
def _dfs(self, nums, path, res):
"""nums cho... | the_stack_v2_python_sparse | DFS回溯/leetcode_90_排列子集+有重复元素+一定要记得对数组进行排序.py | Gyczero/Leetcode_practice | train | 0 | |
65c6dbc2cb47fb1a241b755383d29e710bb82586 | [
"g = GED_Repo([os.path.join(os.getcwd(), 'test_directory', 'US09', 'US09_Birth_After_Death_Mom_Bad.ged')])\ncapturedOutput = io.StringIO()\nsys.stdout = capturedOutput\ng.check_bday()\nsys.stdout = sys.__stdout__\noutput_str1 = 'US09 - Jimmy /John_3/ birthday after mom death date on line 21\\n'\nself.assertEqual(ca... | <|body_start_0|>
g = GED_Repo([os.path.join(os.getcwd(), 'test_directory', 'US09', 'US09_Birth_After_Death_Mom_Bad.ged')])
capturedOutput = io.StringIO()
sys.stdout = capturedOutput
g.check_bday()
sys.stdout = sys.__stdout__
output_str1 = 'US09 - Jimmy /John_3/ birthday a... | Tests that the check_bday function throws when expected. | Test_US09 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_US09:
"""Tests that the check_bday function throws when expected."""
def test_check_bday1(self):
"""Tests that check_bday rejects illegitimate birthdays by throwing a ValueError."""
<|body_0|>
def test_check_bday2(self):
"""Tests that check_bday rejects ille... | stack_v2_sparse_classes_75kplus_train_070796 | 2,578 | no_license | [
{
"docstring": "Tests that check_bday rejects illegitimate birthdays by throwing a ValueError.",
"name": "test_check_bday1",
"signature": "def test_check_bday1(self)"
},
{
"docstring": "Tests that check_bday rejects illegitimate birthdays by throwing a ValueError.",
"name": "test_check_bday2... | 4 | stack_v2_sparse_classes_30k_train_012943 | Implement the Python class `Test_US09` described below.
Class description:
Tests that the check_bday function throws when expected.
Method signatures and docstrings:
- def test_check_bday1(self): Tests that check_bday rejects illegitimate birthdays by throwing a ValueError.
- def test_check_bday2(self): Tests that ch... | Implement the Python class `Test_US09` described below.
Class description:
Tests that the check_bday function throws when expected.
Method signatures and docstrings:
- def test_check_bday1(self): Tests that check_bday rejects illegitimate birthdays by throwing a ValueError.
- def test_check_bday2(self): Tests that ch... | ccfc3b5e11a48a93c53ff745cb254c4c79fab95f | <|skeleton|>
class Test_US09:
"""Tests that the check_bday function throws when expected."""
def test_check_bday1(self):
"""Tests that check_bday rejects illegitimate birthdays by throwing a ValueError."""
<|body_0|>
def test_check_bday2(self):
"""Tests that check_bday rejects ille... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_US09:
"""Tests that the check_bday function throws when expected."""
def test_check_bday1(self):
"""Tests that check_bday rejects illegitimate birthdays by throwing a ValueError."""
g = GED_Repo([os.path.join(os.getcwd(), 'test_directory', 'US09', 'US09_Birth_After_Death_Mom_Bad.ged'... | the_stack_v2_python_sparse | test_directory/US09/US09_Test.py | AkshayLavhagale/SSW555A_GEDCOM_analyzer | train | 0 |
a7a935e17e4a551c4986fc4106fac8b74e866e63 | [
"create_hm_flow = linear_flow.Flow(constants.CREATE_HEALTH_MONITOR_FLOW)\ncreate_hm_flow.add(lifecycle_tasks.HealthMonitorToErrorOnRevertTask(requires=[constants.HEALTH_MON, constants.LISTENERS, constants.LOADBALANCER]))\ncreate_hm_flow.add(database_tasks.MarkHealthMonitorPendingCreateInDB(requires=constants.HEALTH... | <|body_start_0|>
create_hm_flow = linear_flow.Flow(constants.CREATE_HEALTH_MONITOR_FLOW)
create_hm_flow.add(lifecycle_tasks.HealthMonitorToErrorOnRevertTask(requires=[constants.HEALTH_MON, constants.LISTENERS, constants.LOADBALANCER]))
create_hm_flow.add(database_tasks.MarkHealthMonitorPendingCr... | HealthMonitorFlows | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HealthMonitorFlows:
def get_create_health_monitor_flow(self):
"""Create a flow to create a health monitor :returns: The flow for creating a health monitor"""
<|body_0|>
def get_delete_health_monitor_flow(self):
"""Create a flow to delete a health monitor :returns: Th... | stack_v2_sparse_classes_75kplus_train_070797 | 4,639 | permissive | [
{
"docstring": "Create a flow to create a health monitor :returns: The flow for creating a health monitor",
"name": "get_create_health_monitor_flow",
"signature": "def get_create_health_monitor_flow(self)"
},
{
"docstring": "Create a flow to delete a health monitor :returns: The flow for deletin... | 3 | stack_v2_sparse_classes_30k_train_025115 | Implement the Python class `HealthMonitorFlows` described below.
Class description:
Implement the HealthMonitorFlows class.
Method signatures and docstrings:
- def get_create_health_monitor_flow(self): Create a flow to create a health monitor :returns: The flow for creating a health monitor
- def get_delete_health_mo... | Implement the Python class `HealthMonitorFlows` described below.
Class description:
Implement the HealthMonitorFlows class.
Method signatures and docstrings:
- def get_create_health_monitor_flow(self): Create a flow to create a health monitor :returns: The flow for creating a health monitor
- def get_delete_health_mo... | 0426285a41464a5015494584f109eed35a0d44db | <|skeleton|>
class HealthMonitorFlows:
def get_create_health_monitor_flow(self):
"""Create a flow to create a health monitor :returns: The flow for creating a health monitor"""
<|body_0|>
def get_delete_health_monitor_flow(self):
"""Create a flow to delete a health monitor :returns: Th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HealthMonitorFlows:
def get_create_health_monitor_flow(self):
"""Create a flow to create a health monitor :returns: The flow for creating a health monitor"""
create_hm_flow = linear_flow.Flow(constants.CREATE_HEALTH_MONITOR_FLOW)
create_hm_flow.add(lifecycle_tasks.HealthMonitorToErrorO... | the_stack_v2_python_sparse | octavia/controller/worker/v2/flows/health_monitor_flows.py | openstack/octavia | train | 147 | |
b6c6d9c6c0350a8cf5e1027aa8c843127d9c157e | [
"logs.log_info('You are using the T-type vgCa channel type: Cav3p1')\nself.time_unit = 1000.0\nself.vrev = 30\nTexpt = 0.0\nself.qt = 1.0\nself.m = 1 / (1 + np.exp((V - -42.921064) / -5.163208))\nself.h = 1 / (1 + np.exp((V - -72.90742) / 4.575763))\nself._mpower = 1\nself._hpower = 1",
"self._mInf = 1 / (1 + np.... | <|body_start_0|>
logs.log_info('You are using the T-type vgCa channel type: Cav3p1')
self.time_unit = 1000.0
self.vrev = 30
Texpt = 0.0
self.qt = 1.0
self.m = 1 / (1 + np.exp((V - -42.921064) / -5.163208))
self.h = 1 / (1 + np.exp((V - -72.90742) / 4.575763))
... | T-type calcium channel model from Traboulsie et al, based on Cav3p1. Reference: Traboulsie A. et al. Subunit-specific modulation of T-type calcium channels by zinc. J. Physiol. (Lond.), 2007 Jan 1 , 578 (159-71). | Cav3p1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cav3p1:
"""T-type calcium channel model from Traboulsie et al, based on Cav3p1. Reference: Traboulsie A. et al. Subunit-specific modulation of T-type calcium channels by zinc. J. Physiol. (Lond.), 2007 Jan 1 , 578 (159-71)."""
def _init_state(self, V):
"""Run initialization calculati... | stack_v2_sparse_classes_75kplus_train_070798 | 22,487 | no_license | [
{
"docstring": "Run initialization calculation for m and h gates of the channel at starting Vmem value.",
"name": "_init_state",
"signature": "def _init_state(self, V)"
},
{
"docstring": "Update the state of m and h gates of the channel given their present value and present simulation Vmem.",
... | 2 | null | Implement the Python class `Cav3p1` described below.
Class description:
T-type calcium channel model from Traboulsie et al, based on Cav3p1. Reference: Traboulsie A. et al. Subunit-specific modulation of T-type calcium channels by zinc. J. Physiol. (Lond.), 2007 Jan 1 , 578 (159-71).
Method signatures and docstrings:... | Implement the Python class `Cav3p1` described below.
Class description:
T-type calcium channel model from Traboulsie et al, based on Cav3p1. Reference: Traboulsie A. et al. Subunit-specific modulation of T-type calcium channels by zinc. J. Physiol. (Lond.), 2007 Jan 1 , 578 (159-71).
Method signatures and docstrings:... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class Cav3p1:
"""T-type calcium channel model from Traboulsie et al, based on Cav3p1. Reference: Traboulsie A. et al. Subunit-specific modulation of T-type calcium channels by zinc. J. Physiol. (Lond.), 2007 Jan 1 , 578 (159-71)."""
def _init_state(self, V):
"""Run initialization calculati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cav3p1:
"""T-type calcium channel model from Traboulsie et al, based on Cav3p1. Reference: Traboulsie A. et al. Subunit-specific modulation of T-type calcium channels by zinc. J. Physiol. (Lond.), 2007 Jan 1 , 578 (159-71)."""
def _init_state(self, V):
"""Run initialization calculation for m and ... | the_stack_v2_python_sparse | betse/science/channels/vg_ca.py | R-Stefano/betse-ml | train | 0 |
6c8eab7ac2d0dbdb7bd59c68071698a4a0b00c27 | [
"sums = [0] * (len(nums) + 1)\nfor i in range(len(nums)):\n sums[i + 1] = nums[i] + sums[i]\nres = 0\nfor i in range(1, len(nums) + 1):\n for j in range(i):\n if sums[i] - sums[j] == k:\n res += 1\nreturn res",
"pre_sum_freq = dict()\npre_sum_freq[0] = 1\npre_sum = 0\ncount = 0\nfor num in... | <|body_start_0|>
sums = [0] * (len(nums) + 1)
for i in range(len(nums)):
sums[i + 1] = nums[i] + sums[i]
res = 0
for i in range(1, len(nums) + 1):
for j in range(i):
if sums[i] - sums[j] == k:
res += 1
return res
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""前缀和,数组长度20000 :param nums: :param k: :return:"""
<|body_0|>
def subarraySum1(self, nums: List[int], k: int) -> int:
"""使用字典优化前缀和 :param nums: :param k: :return:"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_070799 | 1,228 | no_license | [
{
"docstring": "前缀和,数组长度20000 :param nums: :param k: :return:",
"name": "subarraySum",
"signature": "def subarraySum(self, nums: List[int], k: int) -> int"
},
{
"docstring": "使用字典优化前缀和 :param nums: :param k: :return:",
"name": "subarraySum1",
"signature": "def subarraySum1(self, nums: Li... | 2 | stack_v2_sparse_classes_30k_train_014031 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum(self, nums: List[int], k: int) -> int: 前缀和,数组长度20000 :param nums: :param k: :return:
- def subarraySum1(self, nums: List[int], k: int) -> int: 使用字典优化前缀和 :param nu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum(self, nums: List[int], k: int) -> int: 前缀和,数组长度20000 :param nums: :param k: :return:
- def subarraySum1(self, nums: List[int], k: int) -> int: 使用字典优化前缀和 :param nu... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""前缀和,数组长度20000 :param nums: :param k: :return:"""
<|body_0|>
def subarraySum1(self, nums: List[int], k: int) -> int:
"""使用字典优化前缀和 :param nums: :param k: :return:"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""前缀和,数组长度20000 :param nums: :param k: :return:"""
sums = [0] * (len(nums) + 1)
for i in range(len(nums)):
sums[i + 1] = nums[i] + sums[i]
res = 0
for i in range(1, len(nums) + 1):
... | the_stack_v2_python_sparse | datastructure/binary_array/SubarraySum.py | yinhuax/leet_code | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.