blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a65b9994ba227d89d98cb555a13888949d11b1c8 | [
"url = self.novel_url\nlogger.debug('Visiting %s', url)\nsoup = self.get_soup(url)\nself.novel_title = soup.select_one('h1.entry-title').text\nlogger.info('Novel title: %s', self.novel_title)\nself.novel_cover = self.absolute_url(soup.select_one('.info_image img')['src'])\nlogger.info('Novel cover: %s', self.novel_... | <|body_start_0|>
url = self.novel_url
logger.debug('Visiting %s', url)
soup = self.get_soup(url)
self.novel_title = soup.select_one('h1.entry-title').text
logger.info('Novel title: %s', self.novel_title)
self.novel_cover = self.absolute_url(soup.select_one('.info_image im... | WuxiaOnlineCrawler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WuxiaOnlineCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_000600 | 2,803 | permissive | [
{
"docstring": "Get novel title, autor, cover etc",
"name": "read_novel_info",
"signature": "def read_novel_info(self)"
},
{
"docstring": "Download body of a single chapter and return as clean html format.",
"name": "download_chapter_body",
"signature": "def download_chapter_body(self, c... | 2 | null | Implement the Python class `WuxiaOnlineCrawler` described below.
Class description:
Implement the WuxiaOnlineCrawler class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as clean... | Implement the Python class `WuxiaOnlineCrawler` described below.
Class description:
Implement the WuxiaOnlineCrawler class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as clean... | 451e816ab03c8466be90f6f0b3eaa52d799140ce | <|skeleton|>
class WuxiaOnlineCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WuxiaOnlineCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
url = self.novel_url
logger.debug('Visiting %s', url)
soup = self.get_soup(url)
self.novel_title = soup.select_one('h1.entry-title').text
logger.info('Novel title: %s', self.n... | the_stack_v2_python_sparse | lncrawl/sources/wuxiaonline.py | NNTin/lightnovel-crawler | train | 2 | |
69afe462d9997aa28ce30701029fcd2af5069468 | [
"if not grid or not grid[0]:\n return 0\nrows = len(grid)\ncols = len(grid[0])\nres = 0\nfor row in xrange(rows):\n for col in xrange(cols):\n if grid[row][col] == '1':\n res += 1\n queue = [(row, col)]\n while queue:\n r, c = queue.pop(0)\n ... | <|body_start_0|>
if not grid or not grid[0]:
return 0
rows = len(grid)
cols = len(grid[0])
res = 0
for row in xrange(rows):
for col in xrange(cols):
if grid[row][col] == '1':
res += 1
queue = [(row, c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def numIslands2(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not grid or not grid[0]:
... | stack_v2_sparse_classes_36k_train_000601 | 2,357 | no_license | [
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands",
"signature": "def numIslands(self, grid)"
},
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands2",
"signature": "def numIslands2(self, grid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013142 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int
- def numIslands2(self, grid): :type grid: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int
- def numIslands2(self, grid): :type grid: List[List[str]] :rtype: int
<|skeleton|>
class Solution:
def ... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def numIslands2(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
if not grid or not grid[0]:
return 0
rows = len(grid)
cols = len(grid[0])
res = 0
for row in xrange(rows):
for col in xrange(cols):
if gri... | the_stack_v2_python_sparse | LC200.py | Qiao-Liang/LeetCode | train | 0 | |
1c6315bf1ee497701ab03a0319aa9cf1024b13f0 | [
"url = '/dashboard/mooringsite-types'\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.status_code, 302)",
"url = '/dashboard/mooringsite-types'\nself.client.login(username=self.adminUN, password='pass')\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.asse... | <|body_start_0|>
url = '/dashboard/mooringsite-types'
response = self.client.get(url, HTTP_HOST='website.domain')
self.assertEqual(response.status_code, 302)
<|end_body_0|>
<|body_start_1|>
url = '/dashboard/mooringsite-types'
self.client.login(username=self.adminUN, password='p... | DashboardMooringSiteTypesTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DashboardMooringSiteTypesTestCase:
def test_not_logged_in(self):
"""Test that the dashboard mooringsite types view will redirect whilst not logged in."""
<|body_0|>
def test_logged_in_admin(self):
"""Test that the dashboard mooringsite types view will load whilst log... | stack_v2_sparse_classes_36k_train_000602 | 26,818 | permissive | [
{
"docstring": "Test that the dashboard mooringsite types view will redirect whilst not logged in.",
"name": "test_not_logged_in",
"signature": "def test_not_logged_in(self)"
},
{
"docstring": "Test that the dashboard mooringsite types view will load whilst logged in as admin.",
"name": "tes... | 3 | null | Implement the Python class `DashboardMooringSiteTypesTestCase` described below.
Class description:
Implement the DashboardMooringSiteTypesTestCase class.
Method signatures and docstrings:
- def test_not_logged_in(self): Test that the dashboard mooringsite types view will redirect whilst not logged in.
- def test_logg... | Implement the Python class `DashboardMooringSiteTypesTestCase` described below.
Class description:
Implement the DashboardMooringSiteTypesTestCase class.
Method signatures and docstrings:
- def test_not_logged_in(self): Test that the dashboard mooringsite types view will redirect whilst not logged in.
- def test_logg... | 37d2942efcbdaad072f7a06ac876a40e0f69f702 | <|skeleton|>
class DashboardMooringSiteTypesTestCase:
def test_not_logged_in(self):
"""Test that the dashboard mooringsite types view will redirect whilst not logged in."""
<|body_0|>
def test_logged_in_admin(self):
"""Test that the dashboard mooringsite types view will load whilst log... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DashboardMooringSiteTypesTestCase:
def test_not_logged_in(self):
"""Test that the dashboard mooringsite types view will redirect whilst not logged in."""
url = '/dashboard/mooringsite-types'
response = self.client.get(url, HTTP_HOST='website.domain')
self.assertEqual(response.s... | the_stack_v2_python_sparse | mooring/test_views.py | dbca-wa/moorings | train | 0 | |
2e82c087cc030974b260e99fb6526603a3cb9b77 | [
"if cls.__app_driver is None:\n desired_caps = {'platformName': 'Android', 'platformVersion': '5.1', 'deviceName': 'aa', 'appPackage': 'com.yunmall.lc', 'appActivity': 'com.yunmall.ymctoc.ui.activity.MainActivity'}\n cls.__app_driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)\nreturn cls... | <|body_start_0|>
if cls.__app_driver is None:
desired_caps = {'platformName': 'Android', 'platformVersion': '5.1', 'deviceName': 'aa', 'appPackage': 'com.yunmall.lc', 'appActivity': 'com.yunmall.ymctoc.ui.activity.MainActivity'}
cls.__app_driver = webdriver.Remote('http://127.0.0.1:4723/... | Driver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Driver:
def get_app_driver(cls):
"""声明驱动"""
<|body_0|>
def quit_app_driver(cls):
"""退出driver"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if cls.__app_driver is None:
desired_caps = {'platformName': 'Android', 'platformVersion': '5.1'... | stack_v2_sparse_classes_36k_train_000603 | 1,209 | no_license | [
{
"docstring": "声明驱动",
"name": "get_app_driver",
"signature": "def get_app_driver(cls)"
},
{
"docstring": "退出driver",
"name": "quit_app_driver",
"signature": "def quit_app_driver(cls)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014426 | Implement the Python class `Driver` described below.
Class description:
Implement the Driver class.
Method signatures and docstrings:
- def get_app_driver(cls): 声明驱动
- def quit_app_driver(cls): 退出driver | Implement the Python class `Driver` described below.
Class description:
Implement the Driver class.
Method signatures and docstrings:
- def get_app_driver(cls): 声明驱动
- def quit_app_driver(cls): 退出driver
<|skeleton|>
class Driver:
def get_app_driver(cls):
"""声明驱动"""
<|body_0|>
def quit_app_d... | 2b0dee7a4e5d55fcf82d3cb8776bb4ce4c96b07d | <|skeleton|>
class Driver:
def get_app_driver(cls):
"""声明驱动"""
<|body_0|>
def quit_app_driver(cls):
"""退出driver"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Driver:
def get_app_driver(cls):
"""声明驱动"""
if cls.__app_driver is None:
desired_caps = {'platformName': 'Android', 'platformVersion': '5.1', 'deviceName': 'aa', 'appPackage': 'com.yunmall.lc', 'appActivity': 'com.yunmall.ymctoc.ui.activity.MainActivity'}
cls.__app_driv... | the_stack_v2_python_sparse | Utils/driver.py | Xr96/bnal | train | 0 | |
366891be7b7a46568d1d3d579582a7a273f33ea6 | [
"self._device_key: str = config[CONF_DEVICE_KEY]\nself._event: str | None = config.get(CONF_EVENT)\nself._password: str | None = config.get(CONF_PASSWORD)\nself._salt: str | None = config.get(CONF_SALT)",
"title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)\nattachments = None\nevent = None\nif (data := kwargs.get... | <|body_start_0|>
self._device_key: str = config[CONF_DEVICE_KEY]
self._event: str | None = config.get(CONF_EVENT)
self._password: str | None = config.get(CONF_PASSWORD)
self._salt: str | None = config.get(CONF_SALT)
<|end_body_0|>
<|body_start_1|>
title = kwargs.get(ATTR_TITLE, ... | Implementation of the notification service for Simplepush. | SimplePushNotificationService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimplePushNotificationService:
"""Implementation of the notification service for Simplepush."""
def __init__(self, config: dict[str, Any]) -> None:
"""Initialize the Simplepush notification service."""
<|body_0|>
def send_message(self, message: str, **kwargs: Any) -> Non... | stack_v2_sparse_classes_36k_train_000604 | 3,660 | permissive | [
{
"docstring": "Initialize the Simplepush notification service.",
"name": "__init__",
"signature": "def __init__(self, config: dict[str, Any]) -> None"
},
{
"docstring": "Send a message to a Simplepush user.",
"name": "send_message",
"signature": "def send_message(self, message: str, **k... | 2 | null | Implement the Python class `SimplePushNotificationService` described below.
Class description:
Implementation of the notification service for Simplepush.
Method signatures and docstrings:
- def __init__(self, config: dict[str, Any]) -> None: Initialize the Simplepush notification service.
- def send_message(self, mes... | Implement the Python class `SimplePushNotificationService` described below.
Class description:
Implementation of the notification service for Simplepush.
Method signatures and docstrings:
- def __init__(self, config: dict[str, Any]) -> None: Initialize the Simplepush notification service.
- def send_message(self, mes... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SimplePushNotificationService:
"""Implementation of the notification service for Simplepush."""
def __init__(self, config: dict[str, Any]) -> None:
"""Initialize the Simplepush notification service."""
<|body_0|>
def send_message(self, message: str, **kwargs: Any) -> Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimplePushNotificationService:
"""Implementation of the notification service for Simplepush."""
def __init__(self, config: dict[str, Any]) -> None:
"""Initialize the Simplepush notification service."""
self._device_key: str = config[CONF_DEVICE_KEY]
self._event: str | None = confi... | the_stack_v2_python_sparse | homeassistant/components/simplepush/notify.py | home-assistant/core | train | 35,501 |
cd89bf2b39ba8673e0757503d3b0619bcc62b825 | [
"self.dataset = dataset\nself.interval = interval\nself.metrics = metrics\nself.output_file = output_file\nself.save_dir = save_dir\nself.save_metric = save_metric\nself.save_on_minimum = save_on_minimum\nself._best_score = None\nself.transformers = transformers",
"if step % self.interval != 0:\n return\nscore... | <|body_start_0|>
self.dataset = dataset
self.interval = interval
self.metrics = metrics
self.output_file = output_file
self.save_dir = save_dir
self.save_metric = save_metric
self.save_on_minimum = save_on_minimum
self._best_score = None
self.trans... | Performs validation while training a KerasModel. This is a callback that can be passed to fit(). It periodically computes a set of metrics over a validation set, writes them to a file, and keeps track of the best score. In addition, it can save the best model parameters found so far to a directory on disk, updating the... | ValidationCallback | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidationCallback:
"""Performs validation while training a KerasModel. This is a callback that can be passed to fit(). It periodically computes a set of metrics over a validation set, writes them to a file, and keeps track of the best score. In addition, it can save the best model parameters fou... | stack_v2_sparse_classes_36k_train_000605 | 4,414 | permissive | [
{
"docstring": "Create a ValidationCallback. Parameters ---------- dataset: dc.data.Dataset the validation set on which to compute the metrics interval: int the interval (in training steps) at which to perform validation metrics: list of dc.metrics.Metric metrics to compute on the validation set output_file: fi... | 3 | null | Implement the Python class `ValidationCallback` described below.
Class description:
Performs validation while training a KerasModel. This is a callback that can be passed to fit(). It periodically computes a set of metrics over a validation set, writes them to a file, and keeps track of the best score. In addition, it... | Implement the Python class `ValidationCallback` described below.
Class description:
Performs validation while training a KerasModel. This is a callback that can be passed to fit(). It periodically computes a set of metrics over a validation set, writes them to a file, and keeps track of the best score. In addition, it... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class ValidationCallback:
"""Performs validation while training a KerasModel. This is a callback that can be passed to fit(). It periodically computes a set of metrics over a validation set, writes them to a file, and keeps track of the best score. In addition, it can save the best model parameters fou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidationCallback:
"""Performs validation while training a KerasModel. This is a callback that can be passed to fit(). It periodically computes a set of metrics over a validation set, writes them to a file, and keeps track of the best score. In addition, it can save the best model parameters found so far to ... | the_stack_v2_python_sparse | deepchem/models/callbacks.py | deepchem/deepchem | train | 4,876 |
a93d2d689109b36239173c0104826ff19bb3c541 | [
"error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}\nerror_map.update(kwargs.pop('error_map', {}) or {})\n_headers = case_insensitive_dict(kwargs.pop('headers', {}) or {})\n_params = case_insensitive_dict(kwargs.pop('params', {}) or {})\napi_version = kwargs.pop('api_... | <|body_start_0|>
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}) or {})
_headers = case_insensitive_dict(kwargs.pop('headers', {}) or {})
_params = case_insensitive_dict(kwargs.pop('params', {... | AuthenticationOperations | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthenticationOperations:
async def exchange_aad_access_token_for_acr_refresh_token(self, grant_type: Union[str, '_models.PostContentSchemaGrantType'], service: str, tenant: Optional[str]=None, refresh_token: Optional[str]=None, access_token: Optional[str]=None, **kwargs: Any) -> _models.AcrRefr... | stack_v2_sparse_classes_36k_train_000606 | 8,679 | permissive | [
{
"docstring": "Exchange AAD tokens for an ACR refresh Token. :param grant_type: Can take a value of access_token_refresh_token, or access_token, or refresh_token. :type grant_type: str or ~container_registry.models.PostContentSchemaGrantType :param service: Indicates the name of your Azure container registry. ... | 2 | stack_v2_sparse_classes_30k_train_017932 | Implement the Python class `AuthenticationOperations` described below.
Class description:
Implement the AuthenticationOperations class.
Method signatures and docstrings:
- async def exchange_aad_access_token_for_acr_refresh_token(self, grant_type: Union[str, '_models.PostContentSchemaGrantType'], service: str, tenant... | Implement the Python class `AuthenticationOperations` described below.
Class description:
Implement the AuthenticationOperations class.
Method signatures and docstrings:
- async def exchange_aad_access_token_for_acr_refresh_token(self, grant_type: Union[str, '_models.PostContentSchemaGrantType'], service: str, tenant... | c2ca191e736bb06bfbbbc9493e8325763ba990bb | <|skeleton|>
class AuthenticationOperations:
async def exchange_aad_access_token_for_acr_refresh_token(self, grant_type: Union[str, '_models.PostContentSchemaGrantType'], service: str, tenant: Optional[str]=None, refresh_token: Optional[str]=None, access_token: Optional[str]=None, **kwargs: Any) -> _models.AcrRefr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthenticationOperations:
async def exchange_aad_access_token_for_acr_refresh_token(self, grant_type: Union[str, '_models.PostContentSchemaGrantType'], service: str, tenant: Optional[str]=None, refresh_token: Optional[str]=None, access_token: Optional[str]=None, **kwargs: Any) -> _models.AcrRefreshToken:
... | the_stack_v2_python_sparse | sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/aio/operations/_patch.py | Azure/azure-sdk-for-python | train | 4,046 | |
232df1b07995329430a3df7898d5e762ea03eb3c | [
"try:\n state = self.add_model_schema.load(request.json)\n key = CreateExplorePermalinkCommand(state=state).run()\n http_origin = request.headers.environ.get('HTTP_ORIGIN')\n url = f'{http_origin}/superset/explore/p/{key}/'\n return self.response(201, key=key, url=url)\nexcept ValidationError as ex:\... | <|body_start_0|>
try:
state = self.add_model_schema.load(request.json)
key = CreateExplorePermalinkCommand(state=state).run()
http_origin = request.headers.environ.get('HTTP_ORIGIN')
url = f'{http_origin}/superset/explore/p/{key}/'
return self.response... | ExplorePermalinkRestApi | [
"Apache-2.0",
"OFL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExplorePermalinkRestApi:
def post(self) -> Response:
"""Stores a new permanent link. --- post: description: >- Stores a new permanent link. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ExplorePermalinkPostSchema' responses: 201: description: ... | stack_v2_sparse_classes_36k_train_000607 | 6,288 | permissive | [
{
"docstring": "Stores a new permanent link. --- post: description: >- Stores a new permanent link. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ExplorePermalinkPostSchema' responses: 201: description: The permanent link was stored successfully. content: application... | 2 | stack_v2_sparse_classes_30k_train_011351 | Implement the Python class `ExplorePermalinkRestApi` described below.
Class description:
Implement the ExplorePermalinkRestApi class.
Method signatures and docstrings:
- def post(self) -> Response: Stores a new permanent link. --- post: description: >- Stores a new permanent link. requestBody: required: true content:... | Implement the Python class `ExplorePermalinkRestApi` described below.
Class description:
Implement the ExplorePermalinkRestApi class.
Method signatures and docstrings:
- def post(self) -> Response: Stores a new permanent link. --- post: description: >- Stores a new permanent link. requestBody: required: true content:... | 0945d4a2f46667aebb9b93d0d7685215627ad237 | <|skeleton|>
class ExplorePermalinkRestApi:
def post(self) -> Response:
"""Stores a new permanent link. --- post: description: >- Stores a new permanent link. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ExplorePermalinkPostSchema' responses: 201: description: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExplorePermalinkRestApi:
def post(self) -> Response:
"""Stores a new permanent link. --- post: description: >- Stores a new permanent link. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ExplorePermalinkPostSchema' responses: 201: description: The permanent ... | the_stack_v2_python_sparse | superset/explore/permalink/api.py | apache-superset/incubator-superset | train | 21 | |
635ee813dfa4ab2565d44a33ffd6de022200e2ae | [
"test = u'\\x00\\u202a\\u202b\\u202c\\u202d\\u202e'\nexpected = u''\nresult = request.normalizePagename(test)\nself.assertEqual(result, expected, 'Expected \"%(expected)s\" but got \"%(result)s\"' % locals())",
"cases = ((u'/////', u''), (u'/a', u'a'), (u'a/', u'a'), (u'a/////b/////c', u'a/b/c'), (u'a b/////c d//... | <|body_start_0|>
test = u'\x00\u202a\u202b\u202c\u202d\u202e'
expected = u''
result = request.normalizePagename(test)
self.assertEqual(result, expected, 'Expected "%(expected)s" but got "%(result)s"' % locals())
<|end_body_0|>
<|body_start_1|>
cases = ((u'/////', u''), (u'/a', u... | NormalizePagenameTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormalizePagenameTestCase:
def testPageInvalidChars(self):
"""request: normalize pagename: remove invalid unicode chars Assume the default setting"""
<|body_0|>
def testNormalizeSlashes(self):
"""request: normalize pagename: normalize slashes"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_000608 | 4,171 | no_license | [
{
"docstring": "request: normalize pagename: remove invalid unicode chars Assume the default setting",
"name": "testPageInvalidChars",
"signature": "def testPageInvalidChars(self)"
},
{
"docstring": "request: normalize pagename: normalize slashes",
"name": "testNormalizeSlashes",
"signat... | 4 | stack_v2_sparse_classes_30k_train_018479 | Implement the Python class `NormalizePagenameTestCase` described below.
Class description:
Implement the NormalizePagenameTestCase class.
Method signatures and docstrings:
- def testPageInvalidChars(self): request: normalize pagename: remove invalid unicode chars Assume the default setting
- def testNormalizeSlashes(... | Implement the Python class `NormalizePagenameTestCase` described below.
Class description:
Implement the NormalizePagenameTestCase class.
Method signatures and docstrings:
- def testPageInvalidChars(self): request: normalize pagename: remove invalid unicode chars Assume the default setting
- def testNormalizeSlashes(... | a2c30c3b742c65fb2c5bfbab1267d643823882a5 | <|skeleton|>
class NormalizePagenameTestCase:
def testPageInvalidChars(self):
"""request: normalize pagename: remove invalid unicode chars Assume the default setting"""
<|body_0|>
def testNormalizeSlashes(self):
"""request: normalize pagename: normalize slashes"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NormalizePagenameTestCase:
def testPageInvalidChars(self):
"""request: normalize pagename: remove invalid unicode chars Assume the default setting"""
test = u'\x00\u202a\u202b\u202c\u202d\u202e'
expected = u''
result = request.normalizePagename(test)
self.assertEqual(re... | the_stack_v2_python_sparse | mysocietyorg/moin/lib/python2.4/site-packages/MoinMoin/_tests/test_request.py | MyfanwyNixon/orgsites | train | 0 | |
a57637e13030d2d006ca9a225a2765a675b9785e | [
"self.discount = discount\nself.tau = tau\nself.target_update_period = target_update_period\nself.critic = Critic(state_dim, action_dim, hidden_dims=hidden_dims)\nself.critic_target = Critic(state_dim, action_dim, hidden_dims=hidden_dims)\nsoft_update(self.critic, self.critic_target, tau=1.0)\nself.critic_optimizer... | <|body_start_0|>
self.discount = discount
self.tau = tau
self.target_update_period = target_update_period
self.critic = Critic(state_dim, action_dim, hidden_dims=hidden_dims)
self.critic_target = Critic(state_dim, action_dim, hidden_dims=hidden_dims)
soft_update(self.crit... | Class performing critic fitting. | CriticLearner | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CriticLearner:
"""Class performing critic fitting."""
def __init__(self, state_dim, action_dim, critic_lr=0.0003, discount=0.99, tau=0.005, target_update_period=1, hidden_dims=(256, 256)):
"""Initializes critic learner. Args: state_dim: State size. action_dim: Action size. critic_lr:... | stack_v2_sparse_classes_36k_train_000609 | 10,984 | permissive | [
{
"docstring": "Initializes critic learner. Args: state_dim: State size. action_dim: Action size. critic_lr: Critic learning rate. discount: MDP discount. tau: Soft target update parameter. target_update_period: Target network update period. hidden_dims: List of hidden dimensions.",
"name": "__init__",
... | 2 | null | Implement the Python class `CriticLearner` described below.
Class description:
Class performing critic fitting.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, critic_lr=0.0003, discount=0.99, tau=0.005, target_update_period=1, hidden_dims=(256, 256)): Initializes critic learner. Args: s... | Implement the Python class `CriticLearner` described below.
Class description:
Class performing critic fitting.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, critic_lr=0.0003, discount=0.99, tau=0.005, target_update_period=1, hidden_dims=(256, 256)): Initializes critic learner. Args: s... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class CriticLearner:
"""Class performing critic fitting."""
def __init__(self, state_dim, action_dim, critic_lr=0.0003, discount=0.99, tau=0.005, target_update_period=1, hidden_dims=(256, 256)):
"""Initializes critic learner. Args: state_dim: State size. action_dim: Action size. critic_lr:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CriticLearner:
"""Class performing critic fitting."""
def __init__(self, state_dim, action_dim, critic_lr=0.0003, discount=0.99, tau=0.005, target_update_period=1, hidden_dims=(256, 256)):
"""Initializes critic learner. Args: state_dim: State size. action_dim: Action size. critic_lr: Critic learn... | the_stack_v2_python_sparse | rl_repr/batch_rl/critic.py | Jimmy-INL/google-research | train | 1 |
6a2b77197a95c0c6c3b2deb9324a25979bd63c35 | [
"if self.value is not None:\n return [self.value]\nelse:\n return []",
"if self.value is not None:\n return [self.value]\nelse:\n return []"
] | <|body_start_0|>
if self.value is not None:
return [self.value]
else:
return []
<|end_body_0|>
<|body_start_1|>
if self.value is not None:
return [self.value]
else:
return []
<|end_body_1|>
| Class for a leaf of a binary tree with methods pre-order and post-order. Attributes: Value: The value of the leaf node Methods: Preorder and Postorder traversing that return the value of the leaves if they are not None. | Leaf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Leaf:
"""Class for a leaf of a binary tree with methods pre-order and post-order. Attributes: Value: The value of the leaf node Methods: Preorder and Postorder traversing that return the value of the leaves if they are not None."""
def preorder(self):
"""Preorder traversing"""
... | stack_v2_sparse_classes_36k_train_000610 | 3,387 | no_license | [
{
"docstring": "Preorder traversing",
"name": "preorder",
"signature": "def preorder(self)"
},
{
"docstring": "Preorder traversing",
"name": "posstorder",
"signature": "def posstorder(self)"
}
] | 2 | null | Implement the Python class `Leaf` described below.
Class description:
Class for a leaf of a binary tree with methods pre-order and post-order. Attributes: Value: The value of the leaf node Methods: Preorder and Postorder traversing that return the value of the leaves if they are not None.
Method signatures and docstr... | Implement the Python class `Leaf` described below.
Class description:
Class for a leaf of a binary tree with methods pre-order and post-order. Attributes: Value: The value of the leaf node Methods: Preorder and Postorder traversing that return the value of the leaves if they are not None.
Method signatures and docstr... | e89b329bc9edd37d5d9986f07ca8a63d50686882 | <|skeleton|>
class Leaf:
"""Class for a leaf of a binary tree with methods pre-order and post-order. Attributes: Value: The value of the leaf node Methods: Preorder and Postorder traversing that return the value of the leaves if they are not None."""
def preorder(self):
"""Preorder traversing"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Leaf:
"""Class for a leaf of a binary tree with methods pre-order and post-order. Attributes: Value: The value of the leaf node Methods: Preorder and Postorder traversing that return the value of the leaves if they are not None."""
def preorder(self):
"""Preorder traversing"""
if self.val... | the_stack_v2_python_sparse | StudentProblem/10.21.11.36/8/1569576977.py | LennartElbe/codeEvo | train | 0 |
b4d80942c203d4d2c2267610f6dce8f059be9bc5 | [
"self.key = generate_random_aes_key()\nself.keysize = len(self.key)\nself.iv = b'0' * len(self.key)\nself.prefix = 'comment1=cooking%20MCs;userdata='\nself.suffix = ';comment2=%20like%20a%20pound%20of%20bacon'",
"print_line(f'{BOLD_START}CBC bitflipping attacks{BOLD_END}', color=BLUE)\nprint_line('Generate a rand... | <|body_start_0|>
self.key = generate_random_aes_key()
self.keysize = len(self.key)
self.iv = b'0' * len(self.key)
self.prefix = 'comment1=cooking%20MCs;userdata='
self.suffix = ';comment2=%20like%20a%20pound%20of%20bacon'
<|end_body_0|>
<|body_start_1|>
print_line(f'{BOL... | Challenge16 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Challenge16:
def __init__(self):
"""Init"""
<|body_0|>
def display(self):
"""Display challenge info :return:"""
<|body_1|>
def run(self):
"""The idea is we are filling the prefix up to full block size as usual Then we inject a dummy block with kn... | stack_v2_sparse_classes_36k_train_000611 | 5,228 | no_license | [
{
"docstring": "Init",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Display challenge info :return:",
"name": "display",
"signature": "def display(self)"
},
{
"docstring": "The idea is we are filling the prefix up to full block size as usual Then we in... | 5 | stack_v2_sparse_classes_30k_train_019964 | Implement the Python class `Challenge16` described below.
Class description:
Implement the Challenge16 class.
Method signatures and docstrings:
- def __init__(self): Init
- def display(self): Display challenge info :return:
- def run(self): The idea is we are filling the prefix up to full block size as usual Then we ... | Implement the Python class `Challenge16` described below.
Class description:
Implement the Challenge16 class.
Method signatures and docstrings:
- def __init__(self): Init
- def display(self): Display challenge info :return:
- def run(self): The idea is we are filling the prefix up to full block size as usual Then we ... | 8e5a5b8216b3ee91b72a7388289bb5658721d375 | <|skeleton|>
class Challenge16:
def __init__(self):
"""Init"""
<|body_0|>
def display(self):
"""Display challenge info :return:"""
<|body_1|>
def run(self):
"""The idea is we are filling the prefix up to full block size as usual Then we inject a dummy block with kn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Challenge16:
def __init__(self):
"""Init"""
self.key = generate_random_aes_key()
self.keysize = len(self.key)
self.iv = b'0' * len(self.key)
self.prefix = 'comment1=cooking%20MCs;userdata='
self.suffix = ';comment2=%20like%20a%20pound%20of%20bacon'
def disp... | the_stack_v2_python_sparse | challenges/set_02_block_crypto/challenge_16_cbc_bit_flipping_attack.py | matei/cryptopals | train | 0 | |
acba12e75ad9d77ae306d7423cef12565f1643a2 | [
"already_seen_nodes = []\ninput_sizes = {}\noutput_sizes = {}\nfor _, (_, node, input_size, output_size) in sorted(node_info.items(), key=lambda x: x[1].order):\n for inp_name in node.input:\n self.assertIn(inp_name, already_seen_nodes)\n input_sizes[node.name] = input_size\n output_sizes[node.name]... | <|body_start_0|>
already_seen_nodes = []
input_sizes = {}
output_sizes = {}
for _, (_, node, input_size, output_size) in sorted(node_info.items(), key=lambda x: x[1].order):
for inp_name in node.input:
self.assertIn(inp_name, already_seen_nodes)
in... | GraphComputeOrderTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphComputeOrderTest:
def check_topological_sort_and_sizes(self, node_info, expected_input_sizes=None, expected_output_sizes=None):
"""Helper function to check topological sorting and sizes are correct. The arguments expected_input_sizes and expected_output_sizes are used to check that ... | stack_v2_sparse_classes_36k_train_000612 | 5,947 | permissive | [
{
"docstring": "Helper function to check topological sorting and sizes are correct. The arguments expected_input_sizes and expected_output_sizes are used to check that the sizes are correct, if they are given. Args: node_info: Default dict keyed by node name, mapping to a named tuple with the following keys: {o... | 2 | null | Implement the Python class `GraphComputeOrderTest` described below.
Class description:
Implement the GraphComputeOrderTest class.
Method signatures and docstrings:
- def check_topological_sort_and_sizes(self, node_info, expected_input_sizes=None, expected_output_sizes=None): Helper function to check topological sorti... | Implement the Python class `GraphComputeOrderTest` described below.
Class description:
Implement the GraphComputeOrderTest class.
Method signatures and docstrings:
- def check_topological_sort_and_sizes(self, node_info, expected_input_sizes=None, expected_output_sizes=None): Helper function to check topological sorti... | 7cbba04a2ee16d21309eefad5be6585183a2d5a9 | <|skeleton|>
class GraphComputeOrderTest:
def check_topological_sort_and_sizes(self, node_info, expected_input_sizes=None, expected_output_sizes=None):
"""Helper function to check topological sorting and sizes are correct. The arguments expected_input_sizes and expected_output_sizes are used to check that ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphComputeOrderTest:
def check_topological_sort_and_sizes(self, node_info, expected_input_sizes=None, expected_output_sizes=None):
"""Helper function to check topological sorting and sizes are correct. The arguments expected_input_sizes and expected_output_sizes are used to check that the sizes are ... | the_stack_v2_python_sparse | tensorflow/contrib/receptive_field/python/util/graph_compute_order_test.py | NVIDIA/tensorflow | train | 763 | |
930fb6c2f8ea7f5baa64809512b6ec74367f41e8 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('adsouza_mcsmocha', 'adsouza_mcsmocha')\nurl = 'https://data.boston.gov/export/c8c/54c/c8c54c49-3097-40fc-b3f2-c9508b8d393a.json'\nresponse = urllib.request.urlopen(url).read().decode('utf-8')\nresponse =... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('adsouza_mcsmocha', 'adsouza_mcsmocha')
url = 'https://data.boston.gov/export/c8c/54c/c8c54c49-3097-40fc-b3f2-c9508b8d393a.json'
response = urllib.... | requestBigBelly | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class requestBigBelly:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythi... | stack_v2_sparse_classes_36k_train_000613 | 3,717 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_006141 | Implement the Python class `requestBigBelly` described below.
Class description:
Implement the requestBigBelly class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=Non... | Implement the Python class `requestBigBelly` described below.
Class description:
Implement the requestBigBelly class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=Non... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class requestBigBelly:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class requestBigBelly:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('adsouza_mcsmocha', 'adsouza_mcsmoch... | the_stack_v2_python_sparse | adsouza_mcsmocha/requestBigBelly.py | ROODAY/course-2017-fal-proj | train | 3 | |
bff6c89b0c8ea66530f94386a56141d475d625c3 | [
"pipeline = kwargs.pop('pipeline')\nwx.Frame.__init__(self, *args, **kwargs)\ndatasource = pipeline.root.datasource\ndatasource_panel = DatasourcePanel(self, -1, datasource=datasource)\npipeline_panel = PipelinePanel(self, -1)\nvisualizer_panel = VisualizerPanel(self, -1)\ninspector_panel = InspectorPanel(self, -1)... | <|body_start_0|>
pipeline = kwargs.pop('pipeline')
wx.Frame.__init__(self, *args, **kwargs)
datasource = pipeline.root.datasource
datasource_panel = DatasourcePanel(self, -1, datasource=datasource)
pipeline_panel = PipelinePanel(self, -1)
visualizer_panel = VisualizerPane... | Browser window. Window layout:: +------------+------------+-----------+ | | | | | (LEFT) | | | | Datasource | | | | Panel | | | | | (CENTER) | (RIGHT) | +------------+ Visualizer | Inspector | | | Panel | Panel | | (LEFT) | | | | Pipeline | | | | Panel | | | | | | | +------------+------------+-----------+ | (BOTTOM) Co... | BrowserFrame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrowserFrame:
"""Browser window. Window layout:: +------------+------------+-----------+ | | | | | (LEFT) | | | | Datasource | | | | Panel | | | | | (CENTER) | (RIGHT) | +------------+ Visualizer | Inspector | | | Panel | Panel | | (LEFT) | | | | Pipeline | | | | Panel | | | | | | | +------------... | stack_v2_sparse_classes_36k_train_000614 | 5,099 | no_license | [
{
"docstring": "Initializer.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Finalizer.",
"name": "finalize",
"signature": "def finalize(self)"
},
{
"docstring": "Make sure to destroy aui_manager, otherwise it crashes.",
"name": "On... | 3 | stack_v2_sparse_classes_30k_train_005198 | Implement the Python class `BrowserFrame` described below.
Class description:
Browser window. Window layout:: +------------+------------+-----------+ | | | | | (LEFT) | | | | Datasource | | | | Panel | | | | | (CENTER) | (RIGHT) | +------------+ Visualizer | Inspector | | | Panel | Panel | | (LEFT) | | | | Pipeline | ... | Implement the Python class `BrowserFrame` described below.
Class description:
Browser window. Window layout:: +------------+------------+-----------+ | | | | | (LEFT) | | | | Datasource | | | | Panel | | | | | (CENTER) | (RIGHT) | +------------+ Visualizer | Inspector | | | Panel | Panel | | (LEFT) | | | | Pipeline | ... | 016515772e3ca4d9e59319450fc7a13668f00d11 | <|skeleton|>
class BrowserFrame:
"""Browser window. Window layout:: +------------+------------+-----------+ | | | | | (LEFT) | | | | Datasource | | | | Panel | | | | | (CENTER) | (RIGHT) | +------------+ Visualizer | Inspector | | | Panel | Panel | | (LEFT) | | | | Pipeline | | | | Panel | | | | | | | +------------... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrowserFrame:
"""Browser window. Window layout:: +------------+------------+-----------+ | | | | | (LEFT) | | | | Datasource | | | | Panel | | | | | (CENTER) | (RIGHT) | +------------+ Visualizer | Inspector | | | Panel | Panel | | (LEFT) | | | | Pipeline | | | | Panel | | | | | | | +------------+------------... | the_stack_v2_python_sparse | ec4vis/browser.py | ecell/ecell4-vis | train | 0 |
07e722aad14f035fc6c4408b2b49093b6fcc10f9 | [
"super().__init__(compute_on_call=compute_on_call, prefix=prefix, suffix=suffix, num_classes=num_classes)\nself.compute_per_class_metrics = compute_per_class_metrics\nself.zero_division = zero_division\nself.num_classes = num_classes\nself.reset()",
"kv_metrics = {}\nfor aggregation_name, aggregated_metrics in zi... | <|body_start_0|>
super().__init__(compute_on_call=compute_on_call, prefix=prefix, suffix=suffix, num_classes=num_classes)
self.compute_per_class_metrics = compute_per_class_metrics
self.zero_division = zero_division
self.num_classes = num_classes
self.reset()
<|end_body_0|>
<|bo... | Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be one of 0 or 1 compute_on_call: if True, allows compute metric's value on call compute_per_class_metrics: bool... | MultilabelPrecisionRecallF1SupportMetric | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultilabelPrecisionRecallF1SupportMetric:
"""Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be one of 0 or 1 compute_on_call: if True, a... | stack_v2_sparse_classes_36k_train_000615 | 34,447 | permissive | [
{
"docstring": "Init PrecisionRecallF1SupportMetric instance",
"name": "__init__",
"signature": "def __init__(self, zero_division: int=0, compute_on_call: bool=True, compute_per_class_metrics: bool=SETTINGS.compute_per_class_metrics, prefix: str=None, suffix: str=None, num_classes: Optional[int]=None) -... | 6 | stack_v2_sparse_classes_30k_train_002301 | Implement the Python class `MultilabelPrecisionRecallF1SupportMetric` described below.
Class description:
Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be on... | Implement the Python class `MultilabelPrecisionRecallF1SupportMetric` described below.
Class description:
Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be on... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class MultilabelPrecisionRecallF1SupportMetric:
"""Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be one of 0 or 1 compute_on_call: if True, a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultilabelPrecisionRecallF1SupportMetric:
"""Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be one of 0 or 1 compute_on_call: if True, allows compute... | the_stack_v2_python_sparse | catalyst/metrics/_classification.py | catalyst-team/catalyst | train | 3,038 |
a466d4e73543c0124692b9e4c4b8ad714b5a82ec | [
"intervals = self.coordinator.data[self.entity_description.key].get(self.channel_type)\nif not intervals:\n return None\ninterval = intervals[0]\nif interval.channel_type == ChannelType.FEED_IN:\n return format_cents_to_dollars(interval.per_kwh) * -1\nreturn format_cents_to_dollars(interval.per_kwh)",
"inte... | <|body_start_0|>
intervals = self.coordinator.data[self.entity_description.key].get(self.channel_type)
if not intervals:
return None
interval = intervals[0]
if interval.channel_type == ChannelType.FEED_IN:
return format_cents_to_dollars(interval.per_kwh) * -1
... | Amber Forecast Sensor. | AmberForecastSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmberForecastSensor:
"""Amber Forecast Sensor."""
def native_value(self) -> float | None:
"""Return the first forecast price in $/kWh."""
<|body_0|>
def extra_state_attributes(self) -> Mapping[str, Any] | None:
"""Return additional pieces of information about the... | stack_v2_sparse_classes_36k_train_000616 | 9,224 | permissive | [
{
"docstring": "Return the first forecast price in $/kWh.",
"name": "native_value",
"signature": "def native_value(self) -> float | None"
},
{
"docstring": "Return additional pieces of information about the price.",
"name": "extra_state_attributes",
"signature": "def extra_state_attribut... | 2 | stack_v2_sparse_classes_30k_train_008976 | Implement the Python class `AmberForecastSensor` described below.
Class description:
Amber Forecast Sensor.
Method signatures and docstrings:
- def native_value(self) -> float | None: Return the first forecast price in $/kWh.
- def extra_state_attributes(self) -> Mapping[str, Any] | None: Return additional pieces of ... | Implement the Python class `AmberForecastSensor` described below.
Class description:
Amber Forecast Sensor.
Method signatures and docstrings:
- def native_value(self) -> float | None: Return the first forecast price in $/kWh.
- def extra_state_attributes(self) -> Mapping[str, Any] | None: Return additional pieces of ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class AmberForecastSensor:
"""Amber Forecast Sensor."""
def native_value(self) -> float | None:
"""Return the first forecast price in $/kWh."""
<|body_0|>
def extra_state_attributes(self) -> Mapping[str, Any] | None:
"""Return additional pieces of information about the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AmberForecastSensor:
"""Amber Forecast Sensor."""
def native_value(self) -> float | None:
"""Return the first forecast price in $/kWh."""
intervals = self.coordinator.data[self.entity_description.key].get(self.channel_type)
if not intervals:
return None
interva... | the_stack_v2_python_sparse | homeassistant/components/amberelectric/sensor.py | home-assistant/core | train | 35,501 |
c1155c50c6fef91dd8c275c01c8503caee6206cb | [
"st = []\nres, start, n = (0, 0, len(s))\nfor i in range(n):\n if s[i] == '(':\n st.append(i)\n if s[i] == ')':\n if not st:\n start = i + 1\n else:\n st.pop()\n if not st:\n res = max(res, i - start + 1)\n else:\n ... | <|body_start_0|>
st = []
res, start, n = (0, 0, len(s))
for i in range(n):
if s[i] == '(':
st.append(i)
if s[i] == ')':
if not st:
start = i + 1
else:
st.pop()
if n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestValidParenthesesDP(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
st = []
res, start, n = (0, 0, len(... | stack_v2_sparse_classes_36k_train_000617 | 2,705 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "longestValidParentheses",
"signature": "def longestValidParentheses(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "longestValidParenthesesDP",
"signature": "def longestValidParenthesesDP(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011778 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses(self, s): :type s: str :rtype: int
- def longestValidParenthesesDP(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 longestValidParentheses(self, s): :type s: str :rtype: int
- def longestValidParenthesesDP(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def longestVa... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestValidParenthesesDP(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
st = []
res, start, n = (0, 0, len(s))
for i in range(n):
if s[i] == '(':
st.append(i)
if s[i] == ')':
if not st:
start = i... | the_stack_v2_python_sparse | L/LongestValidParentheses.py | bssrdf/pyleet | train | 2 | |
dc453d1892cdb5a0459c1274388b9bdb5820eb02 | [
"super(GGCNN, self).__init__()\nself.conv1 = Conv2D(input_channels, filter_sizes[0], kernel_sizes[0], stride=strides[0], padding=3, act='relu', param_attr=fluid.initializer.Xavier(uniform=False))\nself.conv2 = Conv2D(filter_sizes[0], filter_sizes[1], kernel_sizes[1], stride=strides[1], padding=2, act='relu', param_... | <|body_start_0|>
super(GGCNN, self).__init__()
self.conv1 = Conv2D(input_channels, filter_sizes[0], kernel_sizes[0], stride=strides[0], padding=3, act='relu', param_attr=fluid.initializer.Xavier(uniform=False))
self.conv2 = Conv2D(filter_sizes[0], filter_sizes[1], kernel_sizes[1], stride=strides... | GGCNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GGCNN:
def __init__(self, input_channels=1):
""":功能 :类初始化函数 :参数 input_channels :int,输入数据的通道数,1或3或4 :返回 :None"""
<|body_0|>
def forward(self, x):
""":功能 :前向传播函数 :参数 x :tensors,一次网络输入 :返回 :tensors,各参数的预测结果"""
<|body_1|>
def compute_loss(self, xc, yc):
... | stack_v2_sparse_classes_36k_train_000618 | 4,477 | no_license | [
{
"docstring": ":功能 :类初始化函数 :参数 input_channels :int,输入数据的通道数,1或3或4 :返回 :None",
"name": "__init__",
"signature": "def __init__(self, input_channels=1)"
},
{
"docstring": ":功能 :前向传播函数 :参数 x :tensors,一次网络输入 :返回 :tensors,各参数的预测结果",
"name": "forward",
"signature": "def forward(self, x)"
},
... | 3 | stack_v2_sparse_classes_30k_train_003136 | Implement the Python class `GGCNN` described below.
Class description:
Implement the GGCNN class.
Method signatures and docstrings:
- def __init__(self, input_channels=1): :功能 :类初始化函数 :参数 input_channels :int,输入数据的通道数,1或3或4 :返回 :None
- def forward(self, x): :功能 :前向传播函数 :参数 x :tensors,一次网络输入 :返回 :tensors,各参数的预测结果
- def... | Implement the Python class `GGCNN` described below.
Class description:
Implement the GGCNN class.
Method signatures and docstrings:
- def __init__(self, input_channels=1): :功能 :类初始化函数 :参数 input_channels :int,输入数据的通道数,1或3或4 :返回 :None
- def forward(self, x): :功能 :前向传播函数 :参数 x :tensors,一次网络输入 :返回 :tensors,各参数的预测结果
- def... | d0b7b14fa8b76ba95118c8b1af53fbd627860c00 | <|skeleton|>
class GGCNN:
def __init__(self, input_channels=1):
""":功能 :类初始化函数 :参数 input_channels :int,输入数据的通道数,1或3或4 :返回 :None"""
<|body_0|>
def forward(self, x):
""":功能 :前向传播函数 :参数 x :tensors,一次网络输入 :返回 :tensors,各参数的预测结果"""
<|body_1|>
def compute_loss(self, xc, yc):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GGCNN:
def __init__(self, input_channels=1):
""":功能 :类初始化函数 :参数 input_channels :int,输入数据的通道数,1或3或4 :返回 :None"""
super(GGCNN, self).__init__()
self.conv1 = Conv2D(input_channels, filter_sizes[0], kernel_sizes[0], stride=strides[0], padding=3, act='relu', param_attr=fluid.initializer.Xav... | the_stack_v2_python_sparse | 10.pdpd/ggcnn_fluid.py | Nhiemth1985/ggcnn_cornell_dataset | train | 0 | |
35c7d123bbcd8384da5fccc413523aa6b531cd7d | [
"if pairs is None:\n pairs = []\nif redditors is None:\n redditors = []\nif subreddits is None:\n subreddits = []\nif things is None:\n things = []\nif not pairs + redditors + subreddits + things:\n msg = \"Either the 'pairs', 'redditors', 'subreddits', or 'things' parameters must be provided.\"\n ... | <|body_start_0|>
if pairs is None:
pairs = []
if redditors is None:
redditors = []
if subreddits is None:
subreddits = []
if things is None:
things = []
if not pairs + redditors + subreddits + things:
msg = "Either the '... | Provides methods to interact with moderator notes at a global level. .. note:: The authenticated user must be a moderator of the provided subreddit(s). For example, the latest note for u/spez in r/redditdev and r/test, and for u/bboe in r/redditdev can be iterated through like so: .. code-block:: python redditor = redd... | RedditModNotes | [
"GPL-3.0-only",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedditModNotes:
"""Provides methods to interact with moderator notes at a global level. .. note:: The authenticated user must be a moderator of the provided subreddit(s). For example, the latest note for u/spez in r/redditdev and r/test, and for u/bboe in r/redditdev can be iterated through like ... | stack_v2_sparse_classes_36k_train_000619 | 25,425 | permissive | [
{
"docstring": "Get note(s) for each subreddit/user pair, or ``None`` if they don't have any. :param all_notes: Whether to return all notes or only the latest note for each subreddit/redditor pair (default: ``False``). .. note:: Setting this to ``True`` will result in a request for each unique subreddit/reddito... | 2 | stack_v2_sparse_classes_30k_train_009732 | Implement the Python class `RedditModNotes` described below.
Class description:
Provides methods to interact with moderator notes at a global level. .. note:: The authenticated user must be a moderator of the provided subreddit(s). For example, the latest note for u/spez in r/redditdev and r/test, and for u/bboe in r/... | Implement the Python class `RedditModNotes` described below.
Class description:
Provides methods to interact with moderator notes at a global level. .. note:: The authenticated user must be a moderator of the provided subreddit(s). For example, the latest note for u/spez in r/redditdev and r/test, and for u/bboe in r/... | f1d5506b7a3df240f748e1b7749fd5636aa67b32 | <|skeleton|>
class RedditModNotes:
"""Provides methods to interact with moderator notes at a global level. .. note:: The authenticated user must be a moderator of the provided subreddit(s). For example, the latest note for u/spez in r/redditdev and r/test, and for u/bboe in r/redditdev can be iterated through like ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RedditModNotes:
"""Provides methods to interact with moderator notes at a global level. .. note:: The authenticated user must be a moderator of the provided subreddit(s). For example, the latest note for u/spez in r/redditdev and r/test, and for u/bboe in r/redditdev can be iterated through like so: .. code-b... | the_stack_v2_python_sparse | praw/models/mod_notes.py | praw-dev/praw | train | 2,825 |
109a7f4b043dc9bb993cd3ba83c004b66adc1b9c | [
"plugin = NeighbourSelection()\nx_points = np.array([0, 10, 20])\ny_points = np.array([0, 0, 10])\nexpected = [[0.0, 0.0], [1111782.53516264, 0.0], [2189747.33076441, 1121357.32401753]]\nresult = plugin._transform_sites_coordinate_system(x_points, y_points, self.region_orography.coord_system().as_cartopy_crs())\nse... | <|body_start_0|>
plugin = NeighbourSelection()
x_points = np.array([0, 10, 20])
y_points = np.array([0, 0, 10])
expected = [[0.0, 0.0], [1111782.53516264, 0.0], [2189747.33076441, 1121357.32401753]]
result = plugin._transform_sites_coordinate_system(x_points, y_points, self.regio... | Test the function for converting arrays of site coordinates into the correct coordinate system for the model/grid cube. | Test__transform_sites_coordinate_system | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__transform_sites_coordinate_system:
"""Test the function for converting arrays of site coordinates into the correct coordinate system for the model/grid cube."""
def test_global_to_region(self):
"""Test coordinates generated when transforming from a global to regional coordinate... | stack_v2_sparse_classes_36k_train_000620 | 40,371 | permissive | [
{
"docstring": "Test coordinates generated when transforming from a global to regional coordinate system, in this case PlateCarree to Lambert Azimuthal Equal Areas.",
"name": "test_global_to_region",
"signature": "def test_global_to_region(self)"
},
{
"docstring": "Test coordinates generated whe... | 4 | null | Implement the Python class `Test__transform_sites_coordinate_system` described below.
Class description:
Test the function for converting arrays of site coordinates into the correct coordinate system for the model/grid cube.
Method signatures and docstrings:
- def test_global_to_region(self): Test coordinates generat... | Implement the Python class `Test__transform_sites_coordinate_system` described below.
Class description:
Test the function for converting arrays of site coordinates into the correct coordinate system for the model/grid cube.
Method signatures and docstrings:
- def test_global_to_region(self): Test coordinates generat... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__transform_sites_coordinate_system:
"""Test the function for converting arrays of site coordinates into the correct coordinate system for the model/grid cube."""
def test_global_to_region(self):
"""Test coordinates generated when transforming from a global to regional coordinate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__transform_sites_coordinate_system:
"""Test the function for converting arrays of site coordinates into the correct coordinate system for the model/grid cube."""
def test_global_to_region(self):
"""Test coordinates generated when transforming from a global to regional coordinate system, in t... | the_stack_v2_python_sparse | improver_tests/spotdata/test_NeighbourSelection.py | metoppv/improver | train | 101 |
46aa752faeaf6715f7310e1134068c8bb0897a25 | [
"super(LSTM, self).__init__()\nself.input_dim = input_dim\nself.hidden_dim = hidden_dim\nself.num_layers = num_layers\nself.learning_rate = learning_rate\nself.num_epochs = num_epochs\nself.lstm = nn.LSTM(self.input_dim, self.hidden_dim, self.num_layers, batch_first=True)\nself.linear = nn.Linear(self.hidden_dim, o... | <|body_start_0|>
super(LSTM, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.learning_rate = learning_rate
self.num_epochs = num_epochs
self.lstm = nn.LSTM(self.input_dim, self.hidden_dim, self.num_layers,... | Class for LSTM | LSTM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTM:
"""Class for LSTM"""
def __init__(self, input_dim, output_dim=1, hidden_dim=10, num_layers=2, learning_rate=0.001, num_epochs=100):
"""Initilize LSTM model Args: input_dim: int -- dimension of expected features in input X output_dim: int -- dimension of the output feature, for ... | stack_v2_sparse_classes_36k_train_000621 | 3,540 | no_license | [
{
"docstring": "Initilize LSTM model Args: input_dim: int -- dimension of expected features in input X output_dim: int -- dimension of the output feature, for regrssion problem, the output_dim = 1 hidden_dim: int -- number of hidden units for LSTM num_layers: int -- number of stacked recurrent layers. num_epoch... | 4 | stack_v2_sparse_classes_30k_test_000779 | Implement the Python class `LSTM` described below.
Class description:
Class for LSTM
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim=1, hidden_dim=10, num_layers=2, learning_rate=0.001, num_epochs=100): Initilize LSTM model Args: input_dim: int -- dimension of expected features in input X... | Implement the Python class `LSTM` described below.
Class description:
Class for LSTM
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim=1, hidden_dim=10, num_layers=2, learning_rate=0.001, num_epochs=100): Initilize LSTM model Args: input_dim: int -- dimension of expected features in input X... | d7e651024b07587b46497183d90934561a4839e2 | <|skeleton|>
class LSTM:
"""Class for LSTM"""
def __init__(self, input_dim, output_dim=1, hidden_dim=10, num_layers=2, learning_rate=0.001, num_epochs=100):
"""Initilize LSTM model Args: input_dim: int -- dimension of expected features in input X output_dim: int -- dimension of the output feature, for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSTM:
"""Class for LSTM"""
def __init__(self, input_dim, output_dim=1, hidden_dim=10, num_layers=2, learning_rate=0.001, num_epochs=100):
"""Initilize LSTM model Args: input_dim: int -- dimension of expected features in input X output_dim: int -- dimension of the output feature, for regrssion pro... | the_stack_v2_python_sparse | model/recnet.py | SSF-climate/SSF | train | 7 |
fbe6330197adcf0c74bd6917a81d1e4de6597b7d | [
"skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge.html', self)\nself.fileNameInput = settings.FileNameInput().getFromFileName(fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Skeinforge', self, '')\nself.profileType = settings.MenuButtonDisplay().getFromN... | <|body_start_0|>
skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge.html', self)
self.fileNameInput = settings.FileNameInput().getFromFileName(fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Skeinforge', self, '')
self.profileType = set... | A class to handle the skeinforge settings. | SkeinforgeRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkeinforgeRepository:
"""A class to handle the skeinforge settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Skeinforge button has been clicked."""
<|body_1|>
def save(... | stack_v2_sparse_classes_36k_train_000622 | 29,747 | no_license | [
{
"docstring": "Set the default settings, execute title & settings fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Skeinforge button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
},
{
"docstring": "Profile has been sa... | 3 | stack_v2_sparse_classes_30k_train_003231 | Implement the Python class `SkeinforgeRepository` described below.
Class description:
A class to handle the skeinforge settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Skeinforge button has been clicked.
- def save(self... | Implement the Python class `SkeinforgeRepository` described below.
Class description:
A class to handle the skeinforge settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Skeinforge button has been clicked.
- def save(self... | c1b00a76f1550df2cbb457248205159e51fd4308 | <|skeleton|>
class SkeinforgeRepository:
"""A class to handle the skeinforge settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Skeinforge button has been clicked."""
<|body_1|>
def save(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SkeinforgeRepository:
"""A class to handle the skeinforge settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge.html', self)
self.fileNameInput = setti... | the_stack_v2_python_sparse | skeinforge_application/skeinforge.py | amsler/skeinforge | train | 10 |
eb0b30bf221802038424252bb8254addc37523c0 | [
"self.population = []\nfor i in range(simulation.population_size):\n person = Person()\n self.population.append(person)",
"infected_count = int(round(simulation.infection_percent * simulation.population_size, 0))\nfor i in range(infected_count):\n self.population[i].is_infected = True\n self.populatio... | <|body_start_0|>
self.population = []
for i in range(simulation.population_size):
person = Person()
self.population.append(person)
<|end_body_0|>
<|body_start_1|>
infected_count = int(round(simulation.infection_percent * simulation.population_size, 0))
for i in r... | A class to model a whole population of Person objects | Population | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Population:
"""A class to model a whole population of Person objects"""
def __init__(self, simulation):
"""Initialize attributes"""
<|body_0|>
def initial_infection(self, simulation):
"""Infect an initial portion of the population."""
<|body_1|>
def ... | stack_v2_sparse_classes_36k_train_000623 | 8,550 | permissive | [
{
"docstring": "Initialize attributes",
"name": "__init__",
"signature": "def __init__(self, simulation)"
},
{
"docstring": "Infect an initial portion of the population.",
"name": "initial_infection",
"signature": "def initial_infection(self, simulation)"
},
{
"docstring": "Sprea... | 6 | stack_v2_sparse_classes_30k_train_020882 | Implement the Python class `Population` described below.
Class description:
A class to model a whole population of Person objects
Method signatures and docstrings:
- def __init__(self, simulation): Initialize attributes
- def initial_infection(self, simulation): Infect an initial portion of the population.
- def spre... | Implement the Python class `Population` described below.
Class description:
A class to model a whole population of Person objects
Method signatures and docstrings:
- def __init__(self, simulation): Initialize attributes
- def initial_infection(self, simulation): Infect an initial portion of the population.
- def spre... | a9f44d20ae212b5cbc190ac49ca7acc638ff4228 | <|skeleton|>
class Population:
"""A class to model a whole population of Person objects"""
def __init__(self, simulation):
"""Initialize attributes"""
<|body_0|>
def initial_infection(self, simulation):
"""Infect an initial portion of the population."""
<|body_1|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Population:
"""A class to model a whole population of Person objects"""
def __init__(self, simulation):
"""Initialize attributes"""
self.population = []
for i in range(simulation.population_size):
person = Person()
self.population.append(person)
def in... | the_stack_v2_python_sparse | 9_Classes/challenge_39_code.py | demoanddemo/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today | train | 0 |
db4c22b10baed17e8c3fef587df2e4840457f94d | [
"email = self.cleaned_data['email']\nif User._default_manager.filter(email=email):\n raise forms.ValidationError(self.error_messages['duplicate_email'])\nreturn email",
"auth_code = self.cleaned_data['auth_code']\nif auth_code not in (settings.AUTH_CODE_USER, settings.AUTH_CODE_ADMIN):\n raise forms.Validat... | <|body_start_0|>
email = self.cleaned_data['email']
if User._default_manager.filter(email=email):
raise forms.ValidationError(self.error_messages['duplicate_email'])
return email
<|end_body_0|>
<|body_start_1|>
auth_code = self.cleaned_data['auth_code']
if auth_code ... | Form to create a user that includes first_name and last_name. Also includes an authorization code that must be entered correctly. | RegisterForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterForm:
"""Form to create a user that includes first_name and last_name. Also includes an authorization code that must be entered correctly."""
def clean_email(self):
"""Validates that the email address entered does not already exist in the database."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_000624 | 5,229 | permissive | [
{
"docstring": "Validates that the email address entered does not already exist in the database.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Validates that the auth code is one of the two valid authorization codes so the user can create his account.",
"na... | 4 | stack_v2_sparse_classes_30k_train_001453 | Implement the Python class `RegisterForm` described below.
Class description:
Form to create a user that includes first_name and last_name. Also includes an authorization code that must be entered correctly.
Method signatures and docstrings:
- def clean_email(self): Validates that the email address entered does not a... | Implement the Python class `RegisterForm` described below.
Class description:
Form to create a user that includes first_name and last_name. Also includes an authorization code that must be entered correctly.
Method signatures and docstrings:
- def clean_email(self): Validates that the email address entered does not a... | cb54d8bddb184b35f6d62c17b44b311617b76b4f | <|skeleton|>
class RegisterForm:
"""Form to create a user that includes first_name and last_name. Also includes an authorization code that must be entered correctly."""
def clean_email(self):
"""Validates that the email address entered does not already exist in the database."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterForm:
"""Form to create a user that includes first_name and last_name. Also includes an authorization code that must be entered correctly."""
def clean_email(self):
"""Validates that the email address entered does not already exist in the database."""
email = self.cleaned_data['em... | the_stack_v2_python_sparse | accounts/forms.py | kmollee/gallery | train | 3 |
4323a234d087b27a709e67ed7091db42f8b1705e | [
"if not head:\n return None\nif not head.next:\n return TreeNode(head.val)\nmidPre = self.midPreOfLists(head)\nmid = midPre.next\nright = midPre.next.next\nmidPre.next = None\nmid.next = None\nroot = TreeNode(mid.val)\nroot.left = self.sortedListToBST(head)\nroot.right = self.sortedListToBST(right)\nreturn ro... | <|body_start_0|>
if not head:
return None
if not head.next:
return TreeNode(head.val)
midPre = self.midPreOfLists(head)
mid = midPre.next
right = midPre.next.next
midPre.next = None
mid.next = None
root = TreeNode(mid.val)
r... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_0|>
def midPreOfLists(self, head):
"""qiu中间节点的前一个节点 :param head: :return:"""
<|body_1|>
def sortedArrayToBST(self, array):
"""排序数组-->BST :param array: :... | stack_v2_sparse_classes_36k_train_000625 | 2,216 | permissive | [
{
"docstring": ":type head: ListNode :rtype: TreeNode",
"name": "sortedListToBST",
"signature": "def sortedListToBST(self, head)"
},
{
"docstring": "qiu中间节点的前一个节点 :param head: :return:",
"name": "midPreOfLists",
"signature": "def midPreOfLists(self, head)"
},
{
"docstring": "排序数组... | 4 | stack_v2_sparse_classes_30k_train_013322 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedListToBST(self, head): :type head: ListNode :rtype: TreeNode
- def midPreOfLists(self, head): qiu中间节点的前一个节点 :param head: :return:
- def sortedArrayToBST(self, array): 排... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedListToBST(self, head): :type head: ListNode :rtype: TreeNode
- def midPreOfLists(self, head): qiu中间节点的前一个节点 :param head: :return:
- def sortedArrayToBST(self, array): 排... | f5e1c94c99628e7fb04ba158f686a55a8093e933 | <|skeleton|>
class Solution:
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_0|>
def midPreOfLists(self, head):
"""qiu中间节点的前一个节点 :param head: :return:"""
<|body_1|>
def sortedArrayToBST(self, array):
"""排序数组-->BST :param array: :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
if not head:
return None
if not head.next:
return TreeNode(head.val)
midPre = self.midPreOfLists(head)
mid = midPre.next
right = midPre.next.next
... | the_stack_v2_python_sparse | 03LinkedList/109ConvertSortedListtoBinarySearchTree.py | zhaoxinlu/leetcode-algorithms | train | 0 | |
472da661567a0e09553063aaa774ee2069f700af | [
"if divid == 'scratch_div_id':\n divid += '_%s' % str(uuid.uuid4()).replace('-', '')\nself.filename = filename\nself.divid = divid if divid else str(uuid.uuid4()).replace('-', '')\nself.width = width\nself.height = height",
"w = self.width\nh = self.height\ndivid = self.divid\njs_path = os.path.dirname(locatio... | <|body_start_0|>
if divid == 'scratch_div_id':
divid += '_%s' % str(uuid.uuid4()).replace('-', '')
self.filename = filename
self.divid = divid if divid else str(uuid.uuid4()).replace('-', '')
self.width = width
self.height = height
<|end_body_0|>
<|body_start_1|>
... | Renders `Snap <https://snap.berkeley.edu/>`_ using javascript. | RenderSnapRaw | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RenderSnapRaw:
"""Renders `Snap <https://snap.berkeley.edu/>`_ using javascript."""
def __init__(self, width='1000', height='600', divid=None, filename=None):
"""initialize @param width (str) width @param height (str) height @param divid (str|None) id of the div @param filename (str|... | stack_v2_sparse_classes_36k_train_000626 | 2,981 | permissive | [
{
"docstring": "initialize @param width (str) width @param height (str) height @param divid (str|None) id of the div @param filename (str|None) filename",
"name": "__init__",
"signature": "def __init__(self, width='1000', height='600', divid=None, filename=None)"
},
{
"docstring": "Return a coup... | 2 | stack_v2_sparse_classes_30k_train_008810 | Implement the Python class `RenderSnapRaw` described below.
Class description:
Renders `Snap <https://snap.berkeley.edu/>`_ using javascript.
Method signatures and docstrings:
- def __init__(self, width='1000', height='600', divid=None, filename=None): initialize @param width (str) width @param height (str) height @p... | Implement the Python class `RenderSnapRaw` described below.
Class description:
Renders `Snap <https://snap.berkeley.edu/>`_ using javascript.
Method signatures and docstrings:
- def __init__(self, width='1000', height='600', divid=None, filename=None): initialize @param width (str) width @param height (str) height @p... | e39f8ae416c23940c1a227c11c667c19104b2ff4 | <|skeleton|>
class RenderSnapRaw:
"""Renders `Snap <https://snap.berkeley.edu/>`_ using javascript."""
def __init__(self, width='1000', height='600', divid=None, filename=None):
"""initialize @param width (str) width @param height (str) height @param divid (str|None) id of the div @param filename (str|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RenderSnapRaw:
"""Renders `Snap <https://snap.berkeley.edu/>`_ using javascript."""
def __init__(self, width='1000', height='600', divid=None, filename=None):
"""initialize @param width (str) width @param height (str) height @param divid (str|None) id of the div @param filename (str|None) filenam... | the_stack_v2_python_sparse | src/code_beatrix/jsscripts/nbsnap.py | sdpython/code_beatrix | train | 1 |
9f2e4d849b32d4bd6ad9ab3bb2acb07619584a31 | [
"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. | BGPServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BGPServicer:
"""Missing associated documentation comment in .proto file."""
def StartService(self, request, context):
"""Start/Stop."""
<|body_0|>
def StopService(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|bo... | stack_v2_sparse_classes_36k_train_000627 | 5,304 | no_license | [
{
"docstring": "Start/Stop.",
"name": "StartService",
"signature": "def StartService(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "StopService",
"signature": "def StopService(self, request, context)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_006040 | Implement the Python class `BGPServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def StartService(self, request, context): Start/Stop.
- def StopService(self, request, context): Missing associated documentation comment in .proto ... | Implement the Python class `BGPServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def StartService(self, request, context): Start/Stop.
- def StopService(self, request, context): Missing associated documentation comment in .proto ... | d1235c4edc475f593657fc4576287ed08a658532 | <|skeleton|>
class BGPServicer:
"""Missing associated documentation comment in .proto file."""
def StartService(self, request, context):
"""Start/Stop."""
<|body_0|>
def StopService(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BGPServicer:
"""Missing associated documentation comment in .proto file."""
def StartService(self, request, context):
"""Start/Stop."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not impl... | the_stack_v2_python_sparse | py-test-cases/grpc_lib/bgpd_pb2_grpc.py | abhijit-dhar/automation | train | 0 |
0ab0b0c37a84d9b350b48acb1b70954d5714ac12 | [
"with pytest.raises(SystemExit):\n main.main([])\nout, err = capsys.readouterr()\nassert out == ''\nassert 'error: too few arguments' in err or 'error: the following arguments are required: source' in err",
"with pytest.raises(SystemExit):\n main.main(['foo', '-i', 'bar.bmp'])\nout, err = capsys.readouterr(... | <|body_start_0|>
with pytest.raises(SystemExit):
main.main([])
out, err = capsys.readouterr()
assert out == ''
assert 'error: too few arguments' in err or 'error: the following arguments are required: source' in err
<|end_body_0|>
<|body_start_1|>
with pytest.raises(... | TestArguments | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestArguments:
def test_fails_without_source(self, capsys):
"""Fail If no source is passed."""
<|body_0|>
def test_fails_with_unknown_icon(self, capsys):
"""Fail if icon is not PNG."""
<|body_1|>
def test_handles_unknown_doc_types(self, monkeypatch, tmpd... | stack_v2_sparse_classes_36k_train_000628 | 35,122 | no_license | [
{
"docstring": "Fail If no source is passed.",
"name": "test_fails_without_source",
"signature": "def test_fails_without_source(self, capsys)"
},
{
"docstring": "Fail if icon is not PNG.",
"name": "test_fails_with_unknown_icon",
"signature": "def test_fails_with_unknown_icon(self, capsys... | 3 | null | Implement the Python class `TestArguments` described below.
Class description:
Implement the TestArguments class.
Method signatures and docstrings:
- def test_fails_without_source(self, capsys): Fail If no source is passed.
- def test_fails_with_unknown_icon(self, capsys): Fail if icon is not PNG.
- def test_handles_... | Implement the Python class `TestArguments` described below.
Class description:
Implement the TestArguments class.
Method signatures and docstrings:
- def test_fails_without_source(self, capsys): Fail If no source is passed.
- def test_fails_with_unknown_icon(self, capsys): Fail if icon is not PNG.
- def test_handles_... | 0ac6653219c2701c13c508c5c4fc9bc3437eea06 | <|skeleton|>
class TestArguments:
def test_fails_without_source(self, capsys):
"""Fail If no source is passed."""
<|body_0|>
def test_fails_with_unknown_icon(self, capsys):
"""Fail if icon is not PNG."""
<|body_1|>
def test_handles_unknown_doc_types(self, monkeypatch, tmpd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestArguments:
def test_fails_without_source(self, capsys):
"""Fail If no source is passed."""
with pytest.raises(SystemExit):
main.main([])
out, err = capsys.readouterr()
assert out == ''
assert 'error: too few arguments' in err or 'error: the following arg... | the_stack_v2_python_sparse | repoData/hynek-doc2dash/allPythonContent.py | aCoffeeYin/pyreco | train | 0 | |
ec9cbd063d1e8abd78b02efdb4786be675090d4b | [
"input_specs = tf.keras.layers.InputSpec(shape=[None] + self.task_config.model.input_size)\nl2_weight_decay = self.task_config.losses.l2_weight_decay\nl2_regularizer = tf.keras.regularizers.l2(l2_weight_decay / 2.0) if l2_weight_decay else None\nmodel = mosaic_model.build_mosaic_segmentation_model(input_specs=input... | <|body_start_0|>
input_specs = tf.keras.layers.InputSpec(shape=[None] + self.task_config.model.input_size)
l2_weight_decay = self.task_config.losses.l2_weight_decay
l2_regularizer = tf.keras.regularizers.l2(l2_weight_decay / 2.0) if l2_weight_decay else None
model = mosaic_model.build_mo... | A task for semantic segmentation using MOSAIC model. | MosaicSemanticSegmentationTask | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MosaicSemanticSegmentationTask:
"""A task for semantic segmentation using MOSAIC model."""
def build_model(self, training: bool=True) -> tf.keras.Model:
"""Builds MOSAIC segmentation model."""
<|body_0|>
def initialize(self, model: tf.keras.Model):
"""Loads pretr... | stack_v2_sparse_classes_36k_train_000629 | 4,303 | permissive | [
{
"docstring": "Builds MOSAIC segmentation model.",
"name": "build_model",
"signature": "def build_model(self, training: bool=True) -> tf.keras.Model"
},
{
"docstring": "Loads pretrained checkpoint.",
"name": "initialize",
"signature": "def initialize(self, model: tf.keras.Model)"
}
] | 2 | null | Implement the Python class `MosaicSemanticSegmentationTask` described below.
Class description:
A task for semantic segmentation using MOSAIC model.
Method signatures and docstrings:
- def build_model(self, training: bool=True) -> tf.keras.Model: Builds MOSAIC segmentation model.
- def initialize(self, model: tf.kera... | Implement the Python class `MosaicSemanticSegmentationTask` described below.
Class description:
A task for semantic segmentation using MOSAIC model.
Method signatures and docstrings:
- def build_model(self, training: bool=True) -> tf.keras.Model: Builds MOSAIC segmentation model.
- def initialize(self, model: tf.kera... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class MosaicSemanticSegmentationTask:
"""A task for semantic segmentation using MOSAIC model."""
def build_model(self, training: bool=True) -> tf.keras.Model:
"""Builds MOSAIC segmentation model."""
<|body_0|>
def initialize(self, model: tf.keras.Model):
"""Loads pretr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MosaicSemanticSegmentationTask:
"""A task for semantic segmentation using MOSAIC model."""
def build_model(self, training: bool=True) -> tf.keras.Model:
"""Builds MOSAIC segmentation model."""
input_specs = tf.keras.layers.InputSpec(shape=[None] + self.task_config.model.input_size)
... | the_stack_v2_python_sparse | official/projects/mosaic/mosaic_tasks.py | jianzhnie/models | train | 2 |
ec24ec71735f09d4f07a3287b931473406082bdc | [
"if 'instance' in kwargs:\n initial = {}\n for byte_setting in self.base_fields.keys():\n initial[byte_setting] = '{:.0e}'.format(getattr(kwargs['instance'], byte_setting))\n kwargs['initial'] = initial\nsuper(QuotaForm, self).__init__(*args, **kwargs)",
"cleaned_data = self.data\nfor byte_setting... | <|body_start_0|>
if 'instance' in kwargs:
initial = {}
for byte_setting in self.base_fields.keys():
initial[byte_setting] = '{:.0e}'.format(getattr(kwargs['instance'], byte_setting))
kwargs['initial'] = initial
super(QuotaForm, self).__init__(*args, **... | QuotaForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuotaForm:
def __init__(self, *args, **kwargs):
"""Initialize file size quota form with friendlier values"""
<|body_0|>
def clean(self):
"""Converts file size quota form input values with friendlier values"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_000630 | 3,445 | no_license | [
{
"docstring": "Initialize file size quota form with friendlier values",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Converts file size quota form input values with friendlier values",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010720 | Implement the Python class `QuotaForm` described below.
Class description:
Implement the QuotaForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize file size quota form with friendlier values
- def clean(self): Converts file size quota form input values with friendlier values | Implement the Python class `QuotaForm` described below.
Class description:
Implement the QuotaForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize file size quota form with friendlier values
- def clean(self): Converts file size quota form input values with friendlier values... | 64b129e67b4d183667808947f6c15dc4c8f33809 | <|skeleton|>
class QuotaForm:
def __init__(self, *args, **kwargs):
"""Initialize file size quota form with friendlier values"""
<|body_0|>
def clean(self):
"""Converts file size quota form input values with friendlier values"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuotaForm:
def __init__(self, *args, **kwargs):
"""Initialize file size quota form with friendlier values"""
if 'instance' in kwargs:
initial = {}
for byte_setting in self.base_fields.keys():
initial[byte_setting] = '{:.0e}'.format(getattr(kwargs['instan... | the_stack_v2_python_sparse | users/admin.py | shaunrance/Verygd-Web-Portal | train | 0 | |
48222a242e4f09aaf36396c975d8b1685538ddc1 | [
"params = ParamsParser(request.GET)\nlimit = params.int('limit', desc='每页最大渲染数', require=False, default=10)\npage = params.int('page', desc='当前页数', require=False, default=1)\nattendances = PracticeAttendance.objects.filter(arrangement_id=aid).values('id', 'update_time')\nif params.has('leaver'):\n attendances = ... | <|body_start_0|>
params = ParamsParser(request.GET)
limit = params.int('limit', desc='每页最大渲染数', require=False, default=10)
page = params.int('page', desc='当前页数', require=False, default=1)
attendances = PracticeAttendance.objects.filter(arrangement_id=aid).values('id', 'update_time')
... | PracticeAttendanceListMgetView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PracticeAttendanceListMgetView:
def get(self, request, sid, cid, aid):
"""获取排课考勤 :param request: :param sid: :param cid: :param aid: :return:"""
<|body_0|>
def post(self, request, sid, cid, aid):
"""批量获取考勤信息 :param request: :param sid: :param cid: :param aid: :return... | stack_v2_sparse_classes_36k_train_000631 | 2,392 | no_license | [
{
"docstring": "获取排课考勤 :param request: :param sid: :param cid: :param aid: :return:",
"name": "get",
"signature": "def get(self, request, sid, cid, aid)"
},
{
"docstring": "批量获取考勤信息 :param request: :param sid: :param cid: :param aid: :return:",
"name": "post",
"signature": "def post(self... | 2 | stack_v2_sparse_classes_30k_train_005954 | Implement the Python class `PracticeAttendanceListMgetView` described below.
Class description:
Implement the PracticeAttendanceListMgetView class.
Method signatures and docstrings:
- def get(self, request, sid, cid, aid): 获取排课考勤 :param request: :param sid: :param cid: :param aid: :return:
- def post(self, request, s... | Implement the Python class `PracticeAttendanceListMgetView` described below.
Class description:
Implement the PracticeAttendanceListMgetView class.
Method signatures and docstrings:
- def get(self, request, sid, cid, aid): 获取排课考勤 :param request: :param sid: :param cid: :param aid: :return:
- def post(self, request, s... | 7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b | <|skeleton|>
class PracticeAttendanceListMgetView:
def get(self, request, sid, cid, aid):
"""获取排课考勤 :param request: :param sid: :param cid: :param aid: :return:"""
<|body_0|>
def post(self, request, sid, cid, aid):
"""批量获取考勤信息 :param request: :param sid: :param cid: :param aid: :return... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PracticeAttendanceListMgetView:
def get(self, request, sid, cid, aid):
"""获取排课考勤 :param request: :param sid: :param cid: :param aid: :return:"""
params = ParamsParser(request.GET)
limit = params.int('limit', desc='每页最大渲染数', require=False, default=10)
page = params.int('page', d... | the_stack_v2_python_sparse | FireHydrant/server/practice/views/attendance/list_mget.py | shoogoome/FireHydrant | train | 4 | |
3f9e81b8ab8e6d91c2619f1a6c36a8f698d679d6 | [
"self.capacity = capacity\nself.cur_size = 0\nself.freq_stack = collections.defaultdict(DoubleLL)\nself.key_node_map = {}\nself.key_freq_map = {}\nself.min_freq = 1",
"if not self.capacity:\n return -1\nif key in self.key_freq_map:\n freq = self.key_freq_map[key]\n incoming = self.key_node_map[key]\n ... | <|body_start_0|>
self.capacity = capacity
self.cur_size = 0
self.freq_stack = collections.defaultdict(DoubleLL)
self.key_node_map = {}
self.key_freq_map = {}
self.min_freq = 1
<|end_body_0|>
<|body_start_1|>
if not self.capacity:
return -1
if ... | LFUCache | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int Each frequency has a custom linked list We track the minimum frequency with hashmaps. This frequency can always be found whenever we override it, usually by resetting it to one."""
<|body_0|>
def get(self, key):
... | stack_v2_sparse_classes_36k_train_000632 | 4,600 | permissive | [
{
"docstring": ":type capacity: int Each frequency has a custom linked list We track the minimum frequency with hashmaps. This frequency can always be found whenever we override it, usually by resetting it to one.",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring"... | 3 | null | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int Each frequency has a custom linked list We track the minimum frequency with hashmaps. This frequency can always be found wheneve... | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int Each frequency has a custom linked list We track the minimum frequency with hashmaps. This frequency can always be found wheneve... | e8bffeb457936d28c75ecfefb5a1f316c15a9b6c | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int Each frequency has a custom linked list We track the minimum frequency with hashmaps. This frequency can always be found whenever we override it, usually by resetting it to one."""
<|body_0|>
def get(self, key):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
""":type capacity: int Each frequency has a custom linked list We track the minimum frequency with hashmaps. This frequency can always be found whenever we override it, usually by resetting it to one."""
self.capacity = capacity
self.cur_size = 0... | the_stack_v2_python_sparse | Leetcode/460-LFU-cache.py | EdwaRen/Competitve-Programming | train | 1 | |
06bdb34f3ffc77a71db13eed330ae21a129c0a1f | [
"self.body_spec = body_spec\nself.nn_spec = nn_spec\nself.body_decoder = BodyDecoder(body_spec)\nself.brain_decoder = NeuralNetworkDecoder(nn_spec, body_spec)",
"obj = yaml.load(stream)\nrobot = Robot()\nrobot.id = obj.get('id', 0)\nrobot.body.CopyFrom(self.body_decoder.decode(obj))\nrobot.brain.CopyFrom(self.bra... | <|body_start_0|>
self.body_spec = body_spec
self.nn_spec = nn_spec
self.body_decoder = BodyDecoder(body_spec)
self.brain_decoder = NeuralNetworkDecoder(nn_spec, body_spec)
<|end_body_0|>
<|body_start_1|>
obj = yaml.load(stream)
robot = Robot()
robot.id = obj.get(... | Sample converter creates a Robot protobuf message from a YAML stream and a body / neural net spec. | YamlToRobot | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YamlToRobot:
"""Sample converter creates a Robot protobuf message from a YAML stream and a body / neural net spec."""
def __init__(self, body_spec, nn_spec):
""":param body_spec: :type body_spec: BodyImplementation :param nn_spec: :type nn_spec: NeuralNetImplementation"""
<|b... | stack_v2_sparse_classes_36k_train_000633 | 3,202 | permissive | [
{
"docstring": ":param body_spec: :type body_spec: BodyImplementation :param nn_spec: :type nn_spec: NeuralNetImplementation",
"name": "__init__",
"signature": "def __init__(self, body_spec, nn_spec)"
},
{
"docstring": "Returns a protobuf `Robot` for the given stream. :param stream: :type stream... | 2 | stack_v2_sparse_classes_30k_train_005321 | Implement the Python class `YamlToRobot` described below.
Class description:
Sample converter creates a Robot protobuf message from a YAML stream and a body / neural net spec.
Method signatures and docstrings:
- def __init__(self, body_spec, nn_spec): :param body_spec: :type body_spec: BodyImplementation :param nn_sp... | Implement the Python class `YamlToRobot` described below.
Class description:
Sample converter creates a Robot protobuf message from a YAML stream and a body / neural net spec.
Method signatures and docstrings:
- def __init__(self, body_spec, nn_spec): :param body_spec: :type body_spec: BodyImplementation :param nn_sp... | 70e65320a28fe04e121145b2cdde289d3052728a | <|skeleton|>
class YamlToRobot:
"""Sample converter creates a Robot protobuf message from a YAML stream and a body / neural net spec."""
def __init__(self, body_spec, nn_spec):
""":param body_spec: :type body_spec: BodyImplementation :param nn_spec: :type nn_spec: NeuralNetImplementation"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YamlToRobot:
"""Sample converter creates a Robot protobuf message from a YAML stream and a body / neural net spec."""
def __init__(self, body_spec, nn_spec):
""":param body_spec: :type body_spec: BodyImplementation :param nn_spec: :type nn_spec: NeuralNetImplementation"""
self.body_spec =... | the_stack_v2_python_sparse | revolve/convert/yaml.py | ElteHupkes/revolve | train | 0 |
47c71ca91a7dd0bd27a51e4b155dab3c1279b638 | [
"reading = ReadingsPerm.objects.filter(readings_id=self, username=healthcare, perm_value__in=[2, 3])\nif reading.count() == 0:\n return False\nelse:\n return True",
"if self.patient_id == patient:\n return True\nelse:\n return False"
] | <|body_start_0|>
reading = ReadingsPerm.objects.filter(readings_id=self, username=healthcare, perm_value__in=[2, 3])
if reading.count() == 0:
return False
else:
return True
<|end_body_0|>
<|body_start_1|>
if self.patient_id == patient:
return True
... | Readings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Readings:
def has_permission(self, healthcare):
"""Checks if a user has permissions to view the reading."""
<|body_0|>
def is_patient(self, patient):
"""Checks if the record belongs to the patient."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rea... | stack_v2_sparse_classes_36k_train_000634 | 12,031 | no_license | [
{
"docstring": "Checks if a user has permissions to view the reading.",
"name": "has_permission",
"signature": "def has_permission(self, healthcare)"
},
{
"docstring": "Checks if the record belongs to the patient.",
"name": "is_patient",
"signature": "def is_patient(self, patient)"
}
] | 2 | null | Implement the Python class `Readings` described below.
Class description:
Implement the Readings class.
Method signatures and docstrings:
- def has_permission(self, healthcare): Checks if a user has permissions to view the reading.
- def is_patient(self, patient): Checks if the record belongs to the patient. | Implement the Python class `Readings` described below.
Class description:
Implement the Readings class.
Method signatures and docstrings:
- def has_permission(self, healthcare): Checks if a user has permissions to view the reading.
- def is_patient(self, patient): Checks if the record belongs to the patient.
<|skele... | 685c2b9d40fb24ca1735352846a39fdf5d3728eb | <|skeleton|>
class Readings:
def has_permission(self, healthcare):
"""Checks if a user has permissions to view the reading."""
<|body_0|>
def is_patient(self, patient):
"""Checks if the record belongs to the patient."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Readings:
def has_permission(self, healthcare):
"""Checks if a user has permissions to view the reading."""
reading = ReadingsPerm.objects.filter(readings_id=self, username=healthcare, perm_value__in=[2, 3])
if reading.count() == 0:
return False
else:
re... | the_stack_v2_python_sparse | patientrecords/models.py | guekling/ifs4205team1 | train | 0 | |
dab168fd847f08b9b9dc729eed00f06d788312b3 | [
"if not value:\n return None\nvalue = value.strip().replace(',', '\\n')\nvalueByName = self._getIniParser().parseValueByNameMapping(value, valueTransformationFn=string.strip)\nreturn valueByName and netutils.createTcpEndpoint(valueByName.get('HOST') or '*', valueByName.get('PORT'), sap.PortTypeEnum.findByName(va... | <|body_start_0|>
if not value:
return None
value = value.strip().replace(',', '\n')
valueByName = self._getIniParser().parseValueByNameMapping(value, valueTransformationFn=string.strip)
return valueByName and netutils.createTcpEndpoint(valueByName.get('HOST') or '*', valueByN... | InstanceProfileParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceProfileParser:
def parseServerEndpoint(self, value):
"""Parse value of "icm/server_port" attribute in instance profile PROT=<protocol name>, PORT=<port or service name>[, TIMEOUT=<timeout>, PROCTIMEOUT=<proctimeout>, EXTBIND=1, HOST=<host name>, VCLIENT=<SSL Client Verification>]... | stack_v2_sparse_classes_36k_train_000635 | 12,962 | no_license | [
{
"docstring": "Parse value of \"icm/server_port\" attribute in instance profile PROT=<protocol name>, PORT=<port or service name>[, TIMEOUT=<timeout>, PROCTIMEOUT=<proctimeout>, EXTBIND=1, HOST=<host name>, VCLIENT=<SSL Client Verification>] Possible values for PROT are (http, https, smpt, route), route value ... | 4 | null | Implement the Python class `InstanceProfileParser` described below.
Class description:
Implement the InstanceProfileParser class.
Method signatures and docstrings:
- def parseServerEndpoint(self, value): Parse value of "icm/server_port" attribute in instance profile PROT=<protocol name>, PORT=<port or service name>[,... | Implement the Python class `InstanceProfileParser` described below.
Class description:
Implement the InstanceProfileParser class.
Method signatures and docstrings:
- def parseServerEndpoint(self, value): Parse value of "icm/server_port" attribute in instance profile PROT=<protocol name>, PORT=<port or service name>[,... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class InstanceProfileParser:
def parseServerEndpoint(self, value):
"""Parse value of "icm/server_port" attribute in instance profile PROT=<protocol name>, PORT=<port or service name>[, TIMEOUT=<timeout>, PROCTIMEOUT=<proctimeout>, EXTBIND=1, HOST=<host name>, VCLIENT=<SSL Client Verification>]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstanceProfileParser:
def parseServerEndpoint(self, value):
"""Parse value of "icm/server_port" attribute in instance profile PROT=<protocol name>, PORT=<port or service name>[, TIMEOUT=<timeout>, PROCTIMEOUT=<proctimeout>, EXTBIND=1, HOST=<host name>, VCLIENT=<SSL Client Verification>] Possible valu... | the_stack_v2_python_sparse | reference/ucmdb/discovery/sap_webdisp_discoverer.py | madmonkyang/cda-record | train | 0 | |
b6453361031f0b9ce581abe770960536889d98bf | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.notebook'.casefold():\n from .notebook i... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | OnenoteEntityHierarchyModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnenoteEntityHierarchyModel:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnenoteEntityHierarchyModel:
"""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 a... | stack_v2_sparse_classes_36k_train_000636 | 4,684 | 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: OnenoteEntityHierarchyModel",
"name": "create_from_discriminator_value",
"signature": "def create_from_discr... | 3 | stack_v2_sparse_classes_30k_train_015738 | Implement the Python class `OnenoteEntityHierarchyModel` described below.
Class description:
Implement the OnenoteEntityHierarchyModel class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnenoteEntityHierarchyModel: Creates a new instance of the appr... | Implement the Python class `OnenoteEntityHierarchyModel` described below.
Class description:
Implement the OnenoteEntityHierarchyModel class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnenoteEntityHierarchyModel: Creates a new instance of the appr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class OnenoteEntityHierarchyModel:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnenoteEntityHierarchyModel:
"""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 a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OnenoteEntityHierarchyModel:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnenoteEntityHierarchyModel:
"""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 ... | the_stack_v2_python_sparse | msgraph/generated/models/onenote_entity_hierarchy_model.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
8f41c3e4d62e2fca9a067b5e5575ae84d1d68497 | [
"unpacked = _split_curie(c.lstrip().rstrip())\nself.machine = unpacked[0]\nself.key = unpacked[1]",
"s = c.lstrip().rstrip()\nregex = '\\\\A\\\\[?[^\\\\[/]+/[^\\\\]]+\\\\]?\\\\Z'\npattern = re.compile(regex)\nif pattern.match(s):\n return True\nelse:\n return False"
] | <|body_start_0|>
unpacked = _split_curie(c.lstrip().rstrip())
self.machine = unpacked[0]
self.key = unpacked[1]
<|end_body_0|>
<|body_start_1|>
s = c.lstrip().rstrip()
regex = '\\A\\[?[^\\[/]+/[^\\]]+\\]?\\Z'
pattern = re.compile(regex)
if pattern.match(s):
... | Curie [machine/key], where the brackets are optional. | Curie | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Curie:
"""Curie [machine/key], where the brackets are optional."""
def __init__(self, c=''):
"""Init. :param c: curie string, allowing whitepsace on the left and right."""
<|body_0|>
def valid(cls, c=''):
"""Chack whether string contains a valid curie, allowing w... | stack_v2_sparse_classes_36k_train_000637 | 1,423 | permissive | [
{
"docstring": "Init. :param c: curie string, allowing whitepsace on the left and right.",
"name": "__init__",
"signature": "def __init__(self, c='')"
},
{
"docstring": "Chack whether string contains a valid curie, allowing whitepsace on the left and right. @param c: string with curie. :return: ... | 2 | null | Implement the Python class `Curie` described below.
Class description:
Curie [machine/key], where the brackets are optional.
Method signatures and docstrings:
- def __init__(self, c=''): Init. :param c: curie string, allowing whitepsace on the left and right.
- def valid(cls, c=''): Chack whether string contains a va... | Implement the Python class `Curie` described below.
Class description:
Curie [machine/key], where the brackets are optional.
Method signatures and docstrings:
- def __init__(self, c=''): Init. :param c: curie string, allowing whitepsace on the left and right.
- def valid(cls, c=''): Chack whether string contains a va... | ab8ca8a38bd47ecb1aa7ff90225f57e042aaad6e | <|skeleton|>
class Curie:
"""Curie [machine/key], where the brackets are optional."""
def __init__(self, c=''):
"""Init. :param c: curie string, allowing whitepsace on the left and right."""
<|body_0|>
def valid(cls, c=''):
"""Chack whether string contains a valid curie, allowing w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Curie:
"""Curie [machine/key], where the brackets are optional."""
def __init__(self, c=''):
"""Init. :param c: curie string, allowing whitepsace on the left and right."""
unpacked = _split_curie(c.lstrip().rstrip())
self.machine = unpacked[0]
self.key = unpacked[1]
d... | the_stack_v2_python_sparse | chconsole/connect/curie.py | mincode/chconsole | train | 0 |
ee34a45dfaf26346c0d07dad02df79e8308c93fc | [
"n = n_sersic\nx_red = self._x_reduced(x, y, n, R_sersic, center_x, center_y)\nb = self.b_n(n)\nhyper2f2_bx = util.hyper2F2_array(2 * n, 2 * n, 1 + 2 * n, 1 + 2 * n, -b * x_red)\nf_eff = np.exp(b) * R_sersic ** 2 / 2.0 * k_eff\nf_ = f_eff * x_red ** (2 * n) * hyper2f2_bx\nreturn f_",
"x_ = x - center_x\ny_ = y - ... | <|body_start_0|>
n = n_sersic
x_red = self._x_reduced(x, y, n, R_sersic, center_x, center_y)
b = self.b_n(n)
hyper2f2_bx = util.hyper2F2_array(2 * n, 2 * n, 1 + 2 * n, 1 + 2 * n, -b * x_red)
f_eff = np.exp(b) * R_sersic ** 2 / 2.0 * k_eff
f_ = f_eff * x_red ** (2 * n) * h... | this class contains functions to evaluate a Sersic mass profile: https://arxiv.org/pdf/astro-ph/0311559.pdf .. math:: \\kappa(R) = \\kappa_{\\rm eff} \\exp \\left[ -b_n (R/R_{\\rm Sersic})^{\\frac{1}{n}}\\right] with :math:`b_{n}\\approx 1.999n-0.327` Examples -------- Example for converting physical mass units into co... | Sersic | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sersic:
"""this class contains functions to evaluate a Sersic mass profile: https://arxiv.org/pdf/astro-ph/0311559.pdf .. math:: \\kappa(R) = \\kappa_{\\rm eff} \\exp \\left[ -b_n (R/R_{\\rm Sersic})^{\\frac{1}{n}}\\right] with :math:`b_{n}\\approx 1.999n-0.327` Examples -------- Example for conv... | stack_v2_sparse_classes_36k_train_000638 | 4,388 | permissive | [
{
"docstring": ":param x: x-coordinate :param y: y-coordinate :param n_sersic: Sersic index :param R_sersic: half light radius :param k_eff: convergence at half light radius :param center_x: x-center :param center_y: y-center :return:",
"name": "function",
"signature": "def function(self, x, y, n_sersic... | 3 | stack_v2_sparse_classes_30k_train_010358 | Implement the Python class `Sersic` described below.
Class description:
this class contains functions to evaluate a Sersic mass profile: https://arxiv.org/pdf/astro-ph/0311559.pdf .. math:: \\kappa(R) = \\kappa_{\\rm eff} \\exp \\left[ -b_n (R/R_{\\rm Sersic})^{\\frac{1}{n}}\\right] with :math:`b_{n}\\approx 1.999n-0.... | Implement the Python class `Sersic` described below.
Class description:
this class contains functions to evaluate a Sersic mass profile: https://arxiv.org/pdf/astro-ph/0311559.pdf .. math:: \\kappa(R) = \\kappa_{\\rm eff} \\exp \\left[ -b_n (R/R_{\\rm Sersic})^{\\frac{1}{n}}\\right] with :math:`b_{n}\\approx 1.999n-0.... | 73c9645f26f6983fe7961104075ebe8bf7a4b54c | <|skeleton|>
class Sersic:
"""this class contains functions to evaluate a Sersic mass profile: https://arxiv.org/pdf/astro-ph/0311559.pdf .. math:: \\kappa(R) = \\kappa_{\\rm eff} \\exp \\left[ -b_n (R/R_{\\rm Sersic})^{\\frac{1}{n}}\\right] with :math:`b_{n}\\approx 1.999n-0.327` Examples -------- Example for conv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Sersic:
"""this class contains functions to evaluate a Sersic mass profile: https://arxiv.org/pdf/astro-ph/0311559.pdf .. math:: \\kappa(R) = \\kappa_{\\rm eff} \\exp \\left[ -b_n (R/R_{\\rm Sersic})^{\\frac{1}{n}}\\right] with :math:`b_{n}\\approx 1.999n-0.327` Examples -------- Example for converting physic... | the_stack_v2_python_sparse | lenstronomy/LensModel/Profiles/sersic.py | lenstronomy/lenstronomy | train | 41 |
b8c586598f489e9ba8da712cab957bc3f96cfe35 | [
"from SaasSecurityEventCollector import fetch_events_from_saas_security\nmocker.patch.object(Client, 'http_request', side_effect=queue)\nevents, _ = fetch_events_from_saas_security(client=mock_client, max_fetch=max_fetch)\nassert expected_events.get('events') == events",
"import SaasSecurityEventCollector\nshould... | <|body_start_0|>
from SaasSecurityEventCollector import fetch_events_from_saas_security
mocker.patch.object(Client, 'http_request', side_effect=queue)
events, _ = fetch_events_from_saas_security(client=mock_client, max_fetch=max_fetch)
assert expected_events.get('events') == events
<|end... | TestFetchEvents | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFetchEvents:
def test_fetch_events(self, mocker, mock_client, max_fetch, queue, expected_events):
"""Given - a queue of responses to fetch events. - max fetch limit When - fetching events. Then - make sure the correct events are fetched according to the queue and max fetch. - make su... | stack_v2_sparse_classes_36k_train_000639 | 19,402 | permissive | [
{
"docstring": "Given - a queue of responses to fetch events. - max fetch limit When - fetching events. Then - make sure the correct events are fetched according to the queue and max fetch. - make sure in case max fetch is None that all available events will be fetched.",
"name": "test_fetch_events",
"s... | 5 | null | Implement the Python class `TestFetchEvents` described below.
Class description:
Implement the TestFetchEvents class.
Method signatures and docstrings:
- def test_fetch_events(self, mocker, mock_client, max_fetch, queue, expected_events): Given - a queue of responses to fetch events. - max fetch limit When - fetching... | Implement the Python class `TestFetchEvents` described below.
Class description:
Implement the TestFetchEvents class.
Method signatures and docstrings:
- def test_fetch_events(self, mocker, mock_client, max_fetch, queue, expected_events): Given - a queue of responses to fetch events. - max fetch limit When - fetching... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestFetchEvents:
def test_fetch_events(self, mocker, mock_client, max_fetch, queue, expected_events):
"""Given - a queue of responses to fetch events. - max fetch limit When - fetching events. Then - make sure the correct events are fetched according to the queue and max fetch. - make su... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFetchEvents:
def test_fetch_events(self, mocker, mock_client, max_fetch, queue, expected_events):
"""Given - a queue of responses to fetch events. - max fetch limit When - fetching events. Then - make sure the correct events are fetched according to the queue and max fetch. - make sure in case max... | the_stack_v2_python_sparse | Packs/PrismaSaasSecurity/Integrations/SaasSecurityEventCollector/SaasSecurityEventCollector_test.py | demisto/content | train | 1,023 | |
1d86915dd99b5f966aae576d9c26fe04beb74886 | [
"if not root:\n return\ntmp = [root]\nwhile tmp:\n node = tmp.pop()\n if node.left:\n tmp.append(node.left)\n if node.right:\n tmp.append(node.right)\n node.left, node.right = (node.right, node.left)\nreturn root",
"if not root:\n return\ntmp = root.left\nroot.left = self.mirrorTre... | <|body_start_0|>
if not root:
return
tmp = [root]
while tmp:
node = tmp.pop()
if node.left:
tmp.append(node.left)
if node.right:
tmp.append(node.right)
node.left, node.right = (node.right, node.left)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mirrorTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def mirrorTree2(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return
... | stack_v2_sparse_classes_36k_train_000640 | 1,035 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "mirrorTree",
"signature": "def mirrorTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "mirrorTree2",
"signature": "def mirrorTree2(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mirrorTree(self, root): :type root: TreeNode :rtype: TreeNode
- def mirrorTree2(self, root): :type root: TreeNode :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mirrorTree(self, root): :type root: TreeNode :rtype: TreeNode
- def mirrorTree2(self, root): :type root: TreeNode :rtype: TreeNode
<|skeleton|>
class Solution:
def mirr... | 38eec6f07fdc16658372490cd8c68dcb3d88a77f | <|skeleton|>
class Solution:
def mirrorTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def mirrorTree2(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mirrorTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
if not root:
return
tmp = [root]
while tmp:
node = tmp.pop()
if node.left:
tmp.append(node.left)
if node.right:
tmp.... | the_stack_v2_python_sparse | offer/27.py | gebijiaxiaowang/leetcode | train | 0 | |
fab49df87a4c1eb5de0a04b7712cd278f434e7ac | [
"super().__init__(**kwargs)\nif facility:\n try:\n self.facility = SYSLOG_FACILITY_MAP[facility]\n except KeyError:\n msg = 'An invalid syslog facility ({}) was specified.'.format(facility)\n self.logger.warning(msg)\n raise TypeError(msg)\nelse:\n self.facility = SYSLOG_FACILIT... | <|body_start_0|>
super().__init__(**kwargs)
if facility:
try:
self.facility = SYSLOG_FACILITY_MAP[facility]
except KeyError:
msg = 'An invalid syslog facility ({}) was specified.'.format(facility)
self.logger.warning(msg)
... | A wrapper for Syslog Notifications | NotifySyslog | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotifySyslog:
"""A wrapper for Syslog Notifications"""
def __init__(self, facility=None, log_pid=True, log_perror=False, **kwargs):
"""Initialize Syslog Object"""
<|body_0|>
def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs):
"""Perform Syslog ... | stack_v2_sparse_classes_36k_train_000641 | 10,822 | permissive | [
{
"docstring": "Initialize Syslog Object",
"name": "__init__",
"signature": "def __init__(self, facility=None, log_pid=True, log_perror=False, **kwargs)"
},
{
"docstring": "Perform Syslog Notification",
"name": "send",
"signature": "def send(self, body, title='', notify_type=NotifyType.I... | 4 | null | Implement the Python class `NotifySyslog` described below.
Class description:
A wrapper for Syslog Notifications
Method signatures and docstrings:
- def __init__(self, facility=None, log_pid=True, log_perror=False, **kwargs): Initialize Syslog Object
- def send(self, body, title='', notify_type=NotifyType.INFO, **kwa... | Implement the Python class `NotifySyslog` described below.
Class description:
A wrapper for Syslog Notifications
Method signatures and docstrings:
- def __init__(self, facility=None, log_pid=True, log_perror=False, **kwargs): Initialize Syslog Object
- def send(self, body, title='', notify_type=NotifyType.INFO, **kwa... | be3baed7e3d33bae973f1714df4ebbf65aa33f85 | <|skeleton|>
class NotifySyslog:
"""A wrapper for Syslog Notifications"""
def __init__(self, facility=None, log_pid=True, log_perror=False, **kwargs):
"""Initialize Syslog Object"""
<|body_0|>
def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs):
"""Perform Syslog ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotifySyslog:
"""A wrapper for Syslog Notifications"""
def __init__(self, facility=None, log_pid=True, log_perror=False, **kwargs):
"""Initialize Syslog Object"""
super().__init__(**kwargs)
if facility:
try:
self.facility = SYSLOG_FACILITY_MAP[facility]... | the_stack_v2_python_sparse | apprise/plugins/NotifySyslog.py | caronc/apprise | train | 8,426 |
a4bd136857769352d181965d0072472887e8c4bd | [
"self.batch_size = batch_size\nself.is_training = is_training\nself.latent_dim = latent_dim\nself.output_cells_dim = output_cells_dim\nself.var_scope = var_scope\nself.gen_layers = gen_layers\nself.output_lsn = output_lsn\nself.gen_cond_type = gen_cond_type\nself.clusters_no = clusters_no\nself.input_clusters = inp... | <|body_start_0|>
self.batch_size = batch_size
self.is_training = is_training
self.latent_dim = latent_dim
self.output_cells_dim = output_cells_dim
self.var_scope = var_scope
self.gen_layers = gen_layers
self.output_lsn = output_lsn
self.gen_cond_type = gen... | Generic class for the Generator network. | Generator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""Generic class for the Generator network."""
def __init__(self, fake_outputs, batch_size, latent_dim, output_cells_dim, var_scope, gen_layers, output_lsn, gen_cond_type=None, is_training=None, clusters_ratios=None, clusters_no=None, input_clusters=None, reuse=None):
"""D... | stack_v2_sparse_classes_36k_train_000642 | 29,633 | permissive | [
{
"docstring": "Default constructor. Parameters ---------- fake_outputs : Tensor Tensor holding the output of the generator. batch_size : int Batch size used during the training. latent_dim : int Dimension of the latent space used from which the input noise of the generator is sampled. output_cells_dim : int Di... | 3 | stack_v2_sparse_classes_30k_train_008405 | Implement the Python class `Generator` described below.
Class description:
Generic class for the Generator network.
Method signatures and docstrings:
- def __init__(self, fake_outputs, batch_size, latent_dim, output_cells_dim, var_scope, gen_layers, output_lsn, gen_cond_type=None, is_training=None, clusters_ratios=No... | Implement the Python class `Generator` described below.
Class description:
Generic class for the Generator network.
Method signatures and docstrings:
- def __init__(self, fake_outputs, batch_size, latent_dim, output_cells_dim, var_scope, gen_layers, output_lsn, gen_cond_type=None, is_training=None, clusters_ratios=No... | a06f8ccd6a071d57e591dacd6164c9f78987a794 | <|skeleton|>
class Generator:
"""Generic class for the Generator network."""
def __init__(self, fake_outputs, batch_size, latent_dim, output_cells_dim, var_scope, gen_layers, output_lsn, gen_cond_type=None, is_training=None, clusters_ratios=None, clusters_no=None, input_clusters=None, reuse=None):
"""D... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
"""Generic class for the Generator network."""
def __init__(self, fake_outputs, batch_size, latent_dim, output_cells_dim, var_scope, gen_layers, output_lsn, gen_cond_type=None, is_training=None, clusters_ratios=None, clusters_no=None, input_clusters=None, reuse=None):
"""Default constr... | the_stack_v2_python_sparse | estimators/utilities.py | imsb-uke/scGAN | train | 73 |
0122accf959081acb64d200093feee0f2bd3b16b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.printer'.casefold():\n from .printer imp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | PrinterBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrinterBase:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterBase:
"""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: Pr... | stack_v2_sparse_classes_36k_train_000643 | 5,587 | 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: PrinterBase",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(p... | 3 | stack_v2_sparse_classes_30k_train_007896 | Implement the Python class `PrinterBase` described below.
Class description:
Implement the PrinterBase class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterBase: Creates a new instance of the appropriate class based on discriminator value Args:... | Implement the Python class `PrinterBase` described below.
Class description:
Implement the PrinterBase class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterBase: Creates a new instance of the appropriate class based on discriminator value Args:... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class PrinterBase:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterBase:
"""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: Pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrinterBase:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterBase:
"""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: PrinterBase"""
... | the_stack_v2_python_sparse | msgraph/generated/models/printer_base.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3017b94c3ff2c21b446e881931f845e0f5b140ce | [
"def dist(p):\n return p[0] ** 2 + p[1] ** 2\n\ndef quick_select(arr, s, e, k, key=dist):\n if s == e:\n return s\n p = random.randint(s, e)\n arr[e], arr[p] = (arr[p], arr[e])\n v = key(arr[e])\n i = s\n j = e - 1\n while i <= j:\n if key(arr[i]) < v:\n i += 1\n ... | <|body_start_0|>
def dist(p):
return p[0] ** 2 + p[1] ** 2
def quick_select(arr, s, e, k, key=dist):
if s == e:
return s
p = random.randint(s, e)
arr[e], arr[p] = (arr[p], arr[e])
v = key(arr[e])
i = s
j... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
"""Quick selection TLE due to the worst case"""
<|body_0|>
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
"""Heap Time complexity: O(nlogk) Space complexity: O(... | stack_v2_sparse_classes_36k_train_000644 | 3,121 | no_license | [
{
"docstring": "Quick selection TLE due to the worst case",
"name": "kClosest",
"signature": "def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]"
},
{
"docstring": "Heap Time complexity: O(nlogk) Space complexity: O(k)",
"name": "kClosest",
"signature": "def kClosest(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: Quick selection TLE due to the worst case
- def kClosest(self, points: List[List[int]], k: int) -> List[Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: Quick selection TLE due to the worst case
- def kClosest(self, points: List[List[int]], k: int) -> List[Li... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
"""Quick selection TLE due to the worst case"""
<|body_0|>
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
"""Heap Time complexity: O(nlogk) Space complexity: O(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
"""Quick selection TLE due to the worst case"""
def dist(p):
return p[0] ** 2 + p[1] ** 2
def quick_select(arr, s, e, k, key=dist):
if s == e:
return s
... | the_stack_v2_python_sparse | leetcode/solved/1014_K_Closest_Points_to_Origin/solution.py | sungminoh/algorithms | train | 0 | |
a4b14a18fd976932c068529849f94666b7ad8d59 | [
"super(LoadRedshiftStep, self).__init__(**kwargs)\nself._output = self.create_pipeline_object(object_class=RedshiftNode, schedule=self.schedule, redshift_database=redshift_database, schema_name=schema, table_name=table)\nif avro:\n command_options = [\"FORMAT AS AVRO 'auto' TIMEFORMAT 'epochmillisecs' TRUNCATECO... | <|body_start_0|>
super(LoadRedshiftStep, self).__init__(**kwargs)
self._output = self.create_pipeline_object(object_class=RedshiftNode, schedule=self.schedule, redshift_database=redshift_database, schema_name=schema, table_name=table)
if avro:
command_options = ["FORMAT AS AVRO 'auto... | Load Redshift Step class that helps load data into redshift | LoadRedshiftStep | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadRedshiftStep:
"""Load Redshift Step class that helps load data into redshift"""
def __init__(self, schema, table, redshift_database, s3_path_precondition=None, insert_mode='TRUNCATE', delimiter='\t', max_errors=None, replace_invalid_char=None, compression=None, avro=None, additional_opti... | stack_v2_sparse_classes_36k_train_000645 | 3,978 | permissive | [
{
"docstring": "Constructor for the LoadRedshiftStep class Args: schema(str): schema from which table should be extracted table(path): table name for extract insert_mode(str): insert mode for redshift copy activity redshift_database(RedshiftDatabase): database to excute the query max_errors(int): Maximum number... | 2 | null | Implement the Python class `LoadRedshiftStep` described below.
Class description:
Load Redshift Step class that helps load data into redshift
Method signatures and docstrings:
- def __init__(self, schema, table, redshift_database, s3_path_precondition=None, insert_mode='TRUNCATE', delimiter='\t', max_errors=None, rep... | Implement the Python class `LoadRedshiftStep` described below.
Class description:
Load Redshift Step class that helps load data into redshift
Method signatures and docstrings:
- def __init__(self, schema, table, redshift_database, s3_path_precondition=None, insert_mode='TRUNCATE', delimiter='\t', max_errors=None, rep... | 797cb719e6c2abeda0751ada3339c72bfb19c8f2 | <|skeleton|>
class LoadRedshiftStep:
"""Load Redshift Step class that helps load data into redshift"""
def __init__(self, schema, table, redshift_database, s3_path_precondition=None, insert_mode='TRUNCATE', delimiter='\t', max_errors=None, replace_invalid_char=None, compression=None, avro=None, additional_opti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadRedshiftStep:
"""Load Redshift Step class that helps load data into redshift"""
def __init__(self, schema, table, redshift_database, s3_path_precondition=None, insert_mode='TRUNCATE', delimiter='\t', max_errors=None, replace_invalid_char=None, compression=None, avro=None, additional_options=None, **k... | the_stack_v2_python_sparse | dataduct/steps/load_redshift.py | EverFi/dataduct | train | 3 |
04b5fc5deb2d3f56de6edf4a4bd03dc87b3dae92 | [
"savefilenameH = None\nif len(args) < 1 or isinstance(args[0], str):\n if len(args) < 1:\n savefilename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/rcmodel_mode_jkz_ks_parsec_newlogg.sav')\n savefilenameH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/rcmode... | <|body_start_0|>
savefilenameH = None
if len(args) < 1 or isinstance(args[0], str):
if len(args) < 1:
savefilename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/rcmodel_mode_jkz_ks_parsec_newlogg.sav')
savefilenameH = os.path.join(os.path.d... | Class that holds the RC mean mag | rcdist | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class rcdist:
"""Class that holds the RC mean mag"""
def __init__(self, *args, **kwargs):
"""NAME: __init__ PURPOSE: initialize rcdist INPUT: Either: - file that holds a pickle - 2D-array [jk,Z], jks, Zs OUTPUT: object HISTORY: 2012-11-15 - Written - Bovy (IAS)"""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_000646 | 26,900 | permissive | [
{
"docstring": "NAME: __init__ PURPOSE: initialize rcdist INPUT: Either: - file that holds a pickle - 2D-array [jk,Z], jks, Zs OUTPUT: object HISTORY: 2012-11-15 - Written - Bovy (IAS)",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "NAME: __call__ PURP... | 2 | stack_v2_sparse_classes_30k_train_000247 | Implement the Python class `rcdist` described below.
Class description:
Class that holds the RC mean mag
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): NAME: __init__ PURPOSE: initialize rcdist INPUT: Either: - file that holds a pickle - 2D-array [jk,Z], jks, Zs OUTPUT: object HISTORY: 2012-... | Implement the Python class `rcdist` described below.
Class description:
Class that holds the RC mean mag
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): NAME: __init__ PURPOSE: initialize rcdist INPUT: Either: - file that holds a pickle - 2D-array [jk,Z], jks, Zs OUTPUT: object HISTORY: 2012-... | a4aac39fe52d1ca8ba8a790678e9b330f9462d49 | <|skeleton|>
class rcdist:
"""Class that holds the RC mean mag"""
def __init__(self, *args, **kwargs):
"""NAME: __init__ PURPOSE: initialize rcdist INPUT: Either: - file that holds a pickle - 2D-array [jk,Z], jks, Zs OUTPUT: object HISTORY: 2012-11-15 - Written - Bovy (IAS)"""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class rcdist:
"""Class that holds the RC mean mag"""
def __init__(self, *args, **kwargs):
"""NAME: __init__ PURPOSE: initialize rcdist INPUT: Either: - file that holds a pickle - 2D-array [jk,Z], jks, Zs OUTPUT: object HISTORY: 2012-11-15 - Written - Bovy (IAS)"""
savefilenameH = None
i... | the_stack_v2_python_sparse | apogee/samples/rc.py | jcbird/apogee | train | 1 |
6935dc59aa34a239d16476df23ff05ec16a72ac9 | [
"super(FactorizedReduce, self).__init__()\nassert C_out % 2 == 0\nself.relu = nn.ReLU(inplace=False)\nself.conv_1 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)\nself.conv_2 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)\nself.bn = nn.BatchNorm2d(C_out, affine=affine)",
"x = ... | <|body_start_0|>
super(FactorizedReduce, self).__init__()
assert C_out % 2 == 0
self.relu = nn.ReLU(inplace=False)
self.conv_1 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)
self.conv_2 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)
s... | Factorized reduce block. | FactorizedReduce | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactorizedReduce:
"""Factorized reduce block."""
def __init__(self, C_in, C_out, affine=True):
"""Construct FactorizedReduce class. :param C_in: input channel :param C_out: output channel :param affine: whether to use affine in BN"""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_36k_train_000647 | 5,408 | permissive | [
{
"docstring": "Construct FactorizedReduce class. :param C_in: input channel :param C_out: output channel :param affine: whether to use affine in BN",
"name": "__init__",
"signature": "def __init__(self, C_in, C_out, affine=True)"
},
{
"docstring": "Do an inference on FactorizedReduce. :param x:... | 2 | stack_v2_sparse_classes_30k_val_000032 | Implement the Python class `FactorizedReduce` described below.
Class description:
Factorized reduce block.
Method signatures and docstrings:
- def __init__(self, C_in, C_out, affine=True): Construct FactorizedReduce class. :param C_in: input channel :param C_out: output channel :param affine: whether to use affine in... | Implement the Python class `FactorizedReduce` described below.
Class description:
Factorized reduce block.
Method signatures and docstrings:
- def __init__(self, C_in, C_out, affine=True): Construct FactorizedReduce class. :param C_in: input channel :param C_out: output channel :param affine: whether to use affine in... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class FactorizedReduce:
"""Factorized reduce block."""
def __init__(self, C_in, C_out, affine=True):
"""Construct FactorizedReduce class. :param C_in: input channel :param C_out: output channel :param affine: whether to use affine in BN"""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FactorizedReduce:
"""Factorized reduce block."""
def __init__(self, C_in, C_out, affine=True):
"""Construct FactorizedReduce class. :param C_in: input channel :param C_out: output channel :param affine: whether to use affine in BN"""
super(FactorizedReduce, self).__init__()
assert... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/search_space/fine_grained_space/operators/functional.py | Huawei-Ascend/modelzoo | train | 1 |
d0ea156be19d778aa487b6f743da8395ca5d86b1 | [
"self.wt = weight\nself.cap = cap\nself.g = graph\nself.pathHeap = []\nself.pathList = []\nself.deletedEdges = set()\nself.deletedNodes = set()\nself.kPath = None\nif isinstance(graph, nx.Graph):\n if nx.is_directed(graph):\n self.tempG = nx.DiGraph(graph)\n else:\n self.tempG = nx.Graph(graph)\... | <|body_start_0|>
self.wt = weight
self.cap = cap
self.g = graph
self.pathHeap = []
self.pathList = []
self.deletedEdges = set()
self.deletedNodes = set()
self.kPath = None
if isinstance(graph, nx.Graph):
if nx.is_directed(graph):
... | This is a straight forward implementation of Yen's K shortest loopless path algorithm. No attempt has been made to perform any optimization that have been suggested in the literature. Our main goal was to have a functioning K-shortest path algorithm. This implementation should work for both undirected and directed grap... | YenKShortestPaths | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YenKShortestPaths:
"""This is a straight forward implementation of Yen's K shortest loopless path algorithm. No attempt has been made to perform any optimization that have been suggested in the literature. Our main goal was to have a functioning K-shortest path algorithm. This implementation shou... | stack_v2_sparse_classes_36k_train_000648 | 15,874 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, graph, weight='weight', cap='capacity')"
},
{
"docstring": "This function is called to initialize the k-shortest path algorithm. It also finds the shortest path in the network. You can use this function to restart... | 6 | null | Implement the Python class `YenKShortestPaths` described below.
Class description:
This is a straight forward implementation of Yen's K shortest loopless path algorithm. No attempt has been made to perform any optimization that have been suggested in the literature. Our main goal was to have a functioning K-shortest p... | Implement the Python class `YenKShortestPaths` described below.
Class description:
This is a straight forward implementation of Yen's K shortest loopless path algorithm. No attempt has been made to perform any optimization that have been suggested in the literature. Our main goal was to have a functioning K-shortest p... | e7a354137729fcc1f87e647efc8d91e5cd40c83d | <|skeleton|>
class YenKShortestPaths:
"""This is a straight forward implementation of Yen's K shortest loopless path algorithm. No attempt has been made to perform any optimization that have been suggested in the literature. Our main goal was to have a functioning K-shortest path algorithm. This implementation shou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YenKShortestPaths:
"""This is a straight forward implementation of Yen's K shortest loopless path algorithm. No attempt has been made to perform any optimization that have been suggested in the literature. Our main goal was to have a functioning K-shortest path algorithm. This implementation should work for b... | the_stack_v2_python_sparse | src/graphs/graph.py | zutshi/S3CAMR | train | 4 |
16097f513968b4b70008500419f3c1650220400d | [
"m = len(matrix)\nif m == 0:\n self.matrix = []\n return\nn = len(matrix[0])\nself.matrix = matrix\nself.m = m\nself.n = n\nself.data = [[0 for i in range(n + 1)] for j in range(m)]\nfor i in range(m):\n for j in range(n):\n self.data[i][j + 1] = self.data[i][j] + matrix[i][j]",
"t = val - self.ma... | <|body_start_0|>
m = len(matrix)
if m == 0:
self.matrix = []
return
n = len(matrix[0])
self.matrix = matrix
self.m = m
self.n = n
self.data = [[0 for i in range(n + 1)] for j in range(m)]
for i in range(m):
for j in rang... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
"""update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void"""
... | stack_v2_sparse_classes_36k_train_000649 | 1,547 | no_license | [
{
"docstring": "initialize your data structure here. :type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void",
"name": "update",
... | 3 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def update(self, row, col, val): update the element at matrix[row,col] to val. ... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def update(self, row, col, val): update the element at matrix[row,col] to val. ... | ef8c9422c481aa3c482933318c785ad28dd7703e | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
"""update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
m = len(matrix)
if m == 0:
self.matrix = []
return
n = len(matrix[0])
self.matrix = matrix
self.m = m
self.n = n
... | the_stack_v2_python_sparse | python/range_sum_query_2d_mutable.py | pzmrzy/LeetCode | train | 2 | |
29fe4ad0fc3759b4e4f82d309d7eab65eed83838 | [
"super().setUp()\nself.user = get_user_model().objects.create_user(username=self.username, password=self.password, email=self.email)\nself.group = Group.objects.create(name='my_test_group')\nself.user.groups.add(self.group)\nif self.superuser:\n self.user.is_superuser = True\nif self.is_staff:\n self.user.is_... | <|body_start_0|>
super().setUp()
self.user = get_user_model().objects.create_user(username=self.username, password=self.password, email=self.email)
self.group = Group.objects.create(name='my_test_group')
self.user.groups.add(self.group)
if self.superuser:
self.user.is... | Mixin to setup a user and login for tests. Use parameters to set username, password, email, roles and permissions. | UserMixin | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserMixin:
"""Mixin to setup a user and login for tests. Use parameters to set username, password, email, roles and permissions."""
def setUp(self):
"""Setup for all tests."""
<|body_0|>
def assignRole(self, role=None, assign_all: bool=False):
"""Set the user rol... | stack_v2_sparse_classes_36k_train_000650 | 7,955 | permissive | [
{
"docstring": "Setup for all tests.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Set the user roles for the registered user.",
"name": "assignRole",
"signature": "def assignRole(self, role=None, assign_all: bool=False)"
}
] | 2 | null | Implement the Python class `UserMixin` described below.
Class description:
Mixin to setup a user and login for tests. Use parameters to set username, password, email, roles and permissions.
Method signatures and docstrings:
- def setUp(self): Setup for all tests.
- def assignRole(self, role=None, assign_all: bool=Fal... | Implement the Python class `UserMixin` described below.
Class description:
Mixin to setup a user and login for tests. Use parameters to set username, password, email, roles and permissions.
Method signatures and docstrings:
- def setUp(self): Setup for all tests.
- def assignRole(self, role=None, assign_all: bool=Fal... | 5a08ef908dd5344b4433436a4679d122f7f99e41 | <|skeleton|>
class UserMixin:
"""Mixin to setup a user and login for tests. Use parameters to set username, password, email, roles and permissions."""
def setUp(self):
"""Setup for all tests."""
<|body_0|>
def assignRole(self, role=None, assign_all: bool=False):
"""Set the user rol... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserMixin:
"""Mixin to setup a user and login for tests. Use parameters to set username, password, email, roles and permissions."""
def setUp(self):
"""Setup for all tests."""
super().setUp()
self.user = get_user_model().objects.create_user(username=self.username, password=self.pa... | the_stack_v2_python_sparse | InvenTree/InvenTree/api_tester.py | onurtatli/InvenTree | train | 0 |
6da4425102b6b5847d98115febd4c17c7c8654bf | [
"if HAVE_PY26_SSL:\n self.sslobj = ssl.wrap_socket(self.sock)\n self.sslobj.do_handshake()\nelse:\n self.sslobj = socket.ssl(self.sock)",
"result = self.sslobj.read(n)\nwhile len(result) < n:\n s = self.sslobj.read(n - len(result))\n if not s:\n raise IOError('Socket closed')\n result += ... | <|body_start_0|>
if HAVE_PY26_SSL:
self.sslobj = ssl.wrap_socket(self.sock)
self.sslobj.do_handshake()
else:
self.sslobj = socket.ssl(self.sock)
<|end_body_0|>
<|body_start_1|>
result = self.sslobj.read(n)
while len(result) < n:
s = self.s... | Transport that works over SSL | SSLTransport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSLTransport:
"""Transport that works over SSL"""
def _setup_transport(self):
"""Wrap the socket in an SSL object, either the new Python 2.6 version, or the older Python 2.5 and lower version."""
<|body_0|>
def _read(self, n):
"""It seems that SSL Objects read() ... | stack_v2_sparse_classes_36k_train_000651 | 5,384 | permissive | [
{
"docstring": "Wrap the socket in an SSL object, either the new Python 2.6 version, or the older Python 2.5 and lower version.",
"name": "_setup_transport",
"signature": "def _setup_transport(self)"
},
{
"docstring": "It seems that SSL Objects read() method may not supply as much as you're aski... | 3 | stack_v2_sparse_classes_30k_train_011132 | Implement the Python class `SSLTransport` described below.
Class description:
Transport that works over SSL
Method signatures and docstrings:
- def _setup_transport(self): Wrap the socket in an SSL object, either the new Python 2.6 version, or the older Python 2.5 and lower version.
- def _read(self, n): It seems tha... | Implement the Python class `SSLTransport` described below.
Class description:
Transport that works over SSL
Method signatures and docstrings:
- def _setup_transport(self): Wrap the socket in an SSL object, either the new Python 2.6 version, or the older Python 2.5 and lower version.
- def _read(self, n): It seems tha... | 37444fb16b36743c439b0d6c3cac2347e0cc0a94 | <|skeleton|>
class SSLTransport:
"""Transport that works over SSL"""
def _setup_transport(self):
"""Wrap the socket in an SSL object, either the new Python 2.6 version, or the older Python 2.5 and lower version."""
<|body_0|>
def _read(self, n):
"""It seems that SSL Objects read() ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSLTransport:
"""Transport that works over SSL"""
def _setup_transport(self):
"""Wrap the socket in an SSL object, either the new Python 2.6 version, or the older Python 2.5 and lower version."""
if HAVE_PY26_SSL:
self.sslobj = ssl.wrap_socket(self.sock)
self.sslob... | the_stack_v2_python_sparse | vendor/amqplib/client_0_8/transport.py | bopopescu/cc-2 | train | 0 |
def6f2d5480019061dd29f5bc653655a6b3b179f | [
"Deviation.__init__(self, 'data', deviation, session, index=index)\nthumburl = deviation.xpath('.//span[@class=\"tt-fh-tc\"]//a[@class=\"thumb\"]/img/@src')[0]\nself.thumburl = re.sub('\\\\/200H', '', thumburl)\nparsedURL = urlparse(self.thumburl)\nself.thumb = basename(parsedURL[2])\nif page == None:\n page = s... | <|body_start_0|>
Deviation.__init__(self, 'data', deviation, session, index=index)
thumburl = deviation.xpath('.//span[@class="tt-fh-tc"]//a[@class="thumb"]/img/@src')[0]
self.thumburl = re.sub('\\/200H', '', thumburl)
parsedURL = urlparse(self.thumburl)
self.thumb = basename(par... | A single data deviation Holds the data for a single data deviation. This may be a swf file or actually just a collection of files/data. :var str thumb: The thumbnail preview is probaby more important for data deviations because their is no well defined way to map data (exg a zip file) to so pictorial representation ...... | Data | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Data:
"""A single data deviation Holds the data for a single data deviation. This may be a swf file or actually just a collection of files/data. :var str thumb: The thumbnail preview is probaby more important for data deviations because their is no well defined way to map data (exg a zip file) to... | stack_v2_sparse_classes_36k_train_000652 | 5,131 | permissive | [
{
"docstring": ":param lxml.etree.Element deviation: A div element from a collections page that contains basic meta data about the deviation. :param requests.Session session: An instance through which all remote requests should be made. :param lxml.etree.Element page: The deviations page. :param int index: Inde... | 4 | stack_v2_sparse_classes_30k_train_000861 | Implement the Python class `Data` described below.
Class description:
A single data deviation Holds the data for a single data deviation. This may be a swf file or actually just a collection of files/data. :var str thumb: The thumbnail preview is probaby more important for data deviations because their is no well defi... | Implement the Python class `Data` described below.
Class description:
A single data deviation Holds the data for a single data deviation. This may be a swf file or actually just a collection of files/data. :var str thumb: The thumbnail preview is probaby more important for data deviations because their is no well defi... | 5a2d71fc4c1c63d9479c7f57b0e5b335e2f664a3 | <|skeleton|>
class Data:
"""A single data deviation Holds the data for a single data deviation. This may be a swf file or actually just a collection of files/data. :var str thumb: The thumbnail preview is probaby more important for data deviations because their is no well defined way to map data (exg a zip file) to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Data:
"""A single data deviation Holds the data for a single data deviation. This may be a swf file or actually just a collection of files/data. :var str thumb: The thumbnail preview is probaby more important for data deviations because their is no well defined way to map data (exg a zip file) to so pictorial... | the_stack_v2_python_sparse | dadownloader/deviation/data.py | Galadirith/my-project-2 | train | 1 |
47afa865fbfd7f826f45eb85e06d5200a032fc48 | [
"ret = (yield http_get(route=path.WECHAT_ACCESS_TOKEN.format(appid, appsecret), timeout=5))\nif ret:\n raise gen.Return(ret)\nelse:\n raise gen.Return(ObjectDict())",
"access_token_res = (yield self.get_access_token(appid, appsecret))\nret = (yield http_get(route=path.WECHAT_USER_INFO.format(access_token_re... | <|body_start_0|>
ret = (yield http_get(route=path.WECHAT_ACCESS_TOKEN.format(appid, appsecret), timeout=5))
if ret:
raise gen.Return(ret)
else:
raise gen.Return(ObjectDict())
<|end_body_0|>
<|body_start_1|>
access_token_res = (yield self.get_access_token(appid, a... | 微信 Api服务 | WechatDataService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WechatDataService:
"""微信 Api服务"""
def get_access_token(self, appid, appsecret):
"""开发者模式,获得公众号 access_token :param appid: :param appsecret: :return json"""
<|body_0|>
def get_userinfo(self, openid, appid, appsecret):
"""获得微信用户信息 :param openid: :return:"""
... | stack_v2_sparse_classes_36k_train_000653 | 3,256 | no_license | [
{
"docstring": "开发者模式,获得公众号 access_token :param appid: :param appsecret: :return json",
"name": "get_access_token",
"signature": "def get_access_token(self, appid, appsecret)"
},
{
"docstring": "获得微信用户信息 :param openid: :return:",
"name": "get_userinfo",
"signature": "def get_userinfo(sel... | 5 | null | Implement the Python class `WechatDataService` described below.
Class description:
微信 Api服务
Method signatures and docstrings:
- def get_access_token(self, appid, appsecret): 开发者模式,获得公众号 access_token :param appid: :param appsecret: :return json
- def get_userinfo(self, openid, appid, appsecret): 获得微信用户信息 :param openid... | Implement the Python class `WechatDataService` described below.
Class description:
微信 Api服务
Method signatures and docstrings:
- def get_access_token(self, appid, appsecret): 开发者模式,获得公众号 access_token :param appid: :param appsecret: :return json
- def get_userinfo(self, openid, appid, appsecret): 获得微信用户信息 :param openid... | deced3892333f866525b46fa51ddbe0fa5ff8f58 | <|skeleton|>
class WechatDataService:
"""微信 Api服务"""
def get_access_token(self, appid, appsecret):
"""开发者模式,获得公众号 access_token :param appid: :param appsecret: :return json"""
<|body_0|>
def get_userinfo(self, openid, appid, appsecret):
"""获得微信用户信息 :param openid: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WechatDataService:
"""微信 Api服务"""
def get_access_token(self, appid, appsecret):
"""开发者模式,获得公众号 access_token :param appid: :param appsecret: :return json"""
ret = (yield http_get(route=path.WECHAT_ACCESS_TOKEN.format(appid, appsecret), timeout=5))
if ret:
raise gen.Retu... | the_stack_v2_python_sparse | service/data/wechat/wechat.py | cash2one/DL-BIKE | train | 0 |
ac4165fa3efd07d888b707c3e40ff4b22ffab97e | [
"intersectionMap = {}\nfor i in nums1:\n if intersectionMap.get(i) is None:\n intersectionMap[i] = 1\n else:\n intersectionMap[i] += 1\nintersectionLst = []\nfor i in nums2:\n if intersectionMap.get(i) is not None:\n intersectionLst.append(i)\n intersectionMap[i] -= 1\n i... | <|body_start_0|>
intersectionMap = {}
for i in nums1:
if intersectionMap.get(i) is None:
intersectionMap[i] = 1
else:
intersectionMap[i] += 1
intersectionLst = []
for i in nums2:
if intersectionMap.get(i) is not None:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersection2(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersection(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_000654 | 1,688 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersection2",
"signature": "def intersection2(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersection",
"signature": "def i... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersection2(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersection(self, nums1, nums2): :type nums1: List[int] :type nums2:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersection2(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersection(self, nums1, nums2): :type nums1: List[int] :type nums2:... | 483f0c93faca8ccaf038b77ebe2fa712f6b0c6bc | <|skeleton|>
class Solution:
def intersection2(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersection(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def intersection2(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
intersectionMap = {}
for i in nums1:
if intersectionMap.get(i) is None:
intersectionMap[i] = 1
else:
intersecti... | the_stack_v2_python_sparse | Algorithms and Data Structures Practice/LeetCode Questions/Easy/349. Intersection of 2 Arrays.py | harman666666/Algorithms-Data-Structures-and-Design | train | 3 | |
9b4d577dd6c701f7244999f91211e5d3bee2e9c1 | [
"self.input_k = 3\nself.input_arr = [1, 3, 5, 3, 1, 4]\nself.output = [[0, 2], [4, 5], [1, 3]]\nreturn (self.input_k, self.input_arr, self.output)",
"input_k, input_arr, proper_output = self.setUp()\noutput = TaskAssignment.taskAssignment(input_k, input_arr)\nself.assertEqual(output, proper_output)"
] | <|body_start_0|>
self.input_k = 3
self.input_arr = [1, 3, 5, 3, 1, 4]
self.output = [[0, 2], [4, 5], [1, 3]]
return (self.input_k, self.input_arr, self.output)
<|end_body_0|>
<|body_start_1|>
input_k, input_arr, proper_output = self.setUp()
output = TaskAssignment.taskAs... | Class with unittests for TaskAssignment.py | test_TaskAssignment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_TaskAssignment:
"""Class with unittests for TaskAssignment.py"""
def setUp(self):
"""SetUp matrix for tests."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_000655 | 933 | no_license | [
{
"docstring": "SetUp matrix for tests.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if returned output is as expected.",
"name": "test_ExpectedOutput",
"signature": "def test_ExpectedOutput(self)"
}
] | 2 | null | Implement the Python class `test_TaskAssignment` described below.
Class description:
Class with unittests for TaskAssignment.py
Method signatures and docstrings:
- def setUp(self): SetUp matrix for tests.
- def test_ExpectedOutput(self): Checks if returned output is as expected. | Implement the Python class `test_TaskAssignment` described below.
Class description:
Class with unittests for TaskAssignment.py
Method signatures and docstrings:
- def setUp(self): SetUp matrix for tests.
- def test_ExpectedOutput(self): Checks if returned output is as expected.
<|skeleton|>
class test_TaskAssignmen... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_TaskAssignment:
"""Class with unittests for TaskAssignment.py"""
def setUp(self):
"""SetUp matrix for tests."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_TaskAssignment:
"""Class with unittests for TaskAssignment.py"""
def setUp(self):
"""SetUp matrix for tests."""
self.input_k = 3
self.input_arr = [1, 3, 5, 3, 1, 4]
self.output = [[0, 2], [4, 5], [1, 3]]
return (self.input_k, self.input_arr, self.output)
... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Medium/TaskAssignment/test_TaskAssignment.py | JakubKazimierski/PythonPortfolio | train | 9 |
1d693cf05eef86ecae5edd7bf928cec01f854473 | [
"try:\n resource, authorized, user = view_utils.authorize(request, pk, needed_permission=ACTION_TO_AUTHORIZE.VIEW_RESOURCE, raises_exception=False)\nexcept NotFound as ex:\n return Response(str(ex), status=status.HTTP_404_NOT_FOUND)\nif not authorized:\n return Response('Insufficient permission', status=st... | <|body_start_0|>
try:
resource, authorized, user = view_utils.authorize(request, pk, needed_permission=ACTION_TO_AUTHORIZE.VIEW_RESOURCE, raises_exception=False)
except NotFound as ex:
return Response(str(ex), status=status.HTTP_404_NOT_FOUND)
if not authorized:
... | Manipulate resource folders in REST REST URL: hsapi/resource/{pk}/folders/{path}/ HTTP methods: GET, PUT, DELETE Returns HTTP 400, 403, 404 | ResourceFolders | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceFolders:
"""Manipulate resource folders in REST REST URL: hsapi/resource/{pk}/folders/{path}/ HTTP methods: GET, PUT, DELETE Returns HTTP 400, 403, 404"""
def get(self, request, pk, pathname):
"""list a given folder"""
<|body_0|>
def put(self, request, pk, pathna... | stack_v2_sparse_classes_36k_train_000656 | 4,699 | permissive | [
{
"docstring": "list a given folder",
"name": "get",
"signature": "def get(self, request, pk, pathname)"
},
{
"docstring": "create a given folder if not present and allowed",
"name": "put",
"signature": "def put(self, request, pk, pathname)"
},
{
"docstring": "Delete a folder.",
... | 3 | null | Implement the Python class `ResourceFolders` described below.
Class description:
Manipulate resource folders in REST REST URL: hsapi/resource/{pk}/folders/{path}/ HTTP methods: GET, PUT, DELETE Returns HTTP 400, 403, 404
Method signatures and docstrings:
- def get(self, request, pk, pathname): list a given folder
- d... | Implement the Python class `ResourceFolders` described below.
Class description:
Manipulate resource folders in REST REST URL: hsapi/resource/{pk}/folders/{path}/ HTTP methods: GET, PUT, DELETE Returns HTTP 400, 403, 404
Method signatures and docstrings:
- def get(self, request, pk, pathname): list a given folder
- d... | 69855813052243c702c9b0108d2eac3f4f1a768f | <|skeleton|>
class ResourceFolders:
"""Manipulate resource folders in REST REST URL: hsapi/resource/{pk}/folders/{path}/ HTTP methods: GET, PUT, DELETE Returns HTTP 400, 403, 404"""
def get(self, request, pk, pathname):
"""list a given folder"""
<|body_0|>
def put(self, request, pk, pathna... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourceFolders:
"""Manipulate resource folders in REST REST URL: hsapi/resource/{pk}/folders/{path}/ HTTP methods: GET, PUT, DELETE Returns HTTP 400, 403, 404"""
def get(self, request, pk, pathname):
"""list a given folder"""
try:
resource, authorized, user = view_utils.autho... | the_stack_v2_python_sparse | hs_core/views/resource_folder_rest_api.py | hydroshare/hydroshare | train | 207 |
ff9ddca5f5fcae922243d5a07ca737197b28eb38 | [
"self.horizontalAdvanceX = float(xmlElement.attributeDictionary['horiz-adv-x'])\nself.loops = []\nself.unitsPerEM = unitsPerEM\nxmlElement.attributeDictionary['fill'] = ''\nif 'd' not in xmlElement.attributeDictionary:\n return\nPathReader(self.loops, xmlElement, yAxisPointingUpward)",
"multiplierX = fontSize ... | <|body_start_0|>
self.horizontalAdvanceX = float(xmlElement.attributeDictionary['horiz-adv-x'])
self.loops = []
self.unitsPerEM = unitsPerEM
xmlElement.attributeDictionary['fill'] = ''
if 'd' not in xmlElement.attributeDictionary:
return
PathReader(self.loops,... | Class to handle a glyph. | Glyph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Glyph:
"""Class to handle a glyph."""
def __init__(self, unitsPerEM, xmlElement, yAxisPointingUpward):
"""Initialize."""
<|body_0|>
def getSizedAdvancedLoops(self, fontSize, horizontalAdvanceX, yAxisPointingUpward=True):
"""Get loops for font size, advanced horiz... | stack_v2_sparse_classes_36k_train_000657 | 39,231 | no_license | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, unitsPerEM, xmlElement, yAxisPointingUpward)"
},
{
"docstring": "Get loops for font size, advanced horizontally.",
"name": "getSizedAdvancedLoops",
"signature": "def getSizedAdvancedLoops(self, fontSize, h... | 2 | stack_v2_sparse_classes_30k_train_003805 | Implement the Python class `Glyph` described below.
Class description:
Class to handle a glyph.
Method signatures and docstrings:
- def __init__(self, unitsPerEM, xmlElement, yAxisPointingUpward): Initialize.
- def getSizedAdvancedLoops(self, fontSize, horizontalAdvanceX, yAxisPointingUpward=True): Get loops for font... | Implement the Python class `Glyph` described below.
Class description:
Class to handle a glyph.
Method signatures and docstrings:
- def __init__(self, unitsPerEM, xmlElement, yAxisPointingUpward): Initialize.
- def getSizedAdvancedLoops(self, fontSize, horizontalAdvanceX, yAxisPointingUpward=True): Get loops for font... | c1b00a76f1550df2cbb457248205159e51fd4308 | <|skeleton|>
class Glyph:
"""Class to handle a glyph."""
def __init__(self, unitsPerEM, xmlElement, yAxisPointingUpward):
"""Initialize."""
<|body_0|>
def getSizedAdvancedLoops(self, fontSize, horizontalAdvanceX, yAxisPointingUpward=True):
"""Get loops for font size, advanced horiz... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Glyph:
"""Class to handle a glyph."""
def __init__(self, unitsPerEM, xmlElement, yAxisPointingUpward):
"""Initialize."""
self.horizontalAdvanceX = float(xmlElement.attributeDictionary['horiz-adv-x'])
self.loops = []
self.unitsPerEM = unitsPerEM
xmlElement.attribute... | the_stack_v2_python_sparse | fabmetheus_utilities/svg_reader.py | amsler/skeinforge | train | 10 |
d57f5ee4d6f892265e44cc204116135cc1ff7e94 | [
"super(FieldBatchNormalization, self).__init__()\nself.bn = nn.BatchNorm1d(in_channel)\nself.in_channel = in_channel",
"points = in_feature[:, :, :3]\nfeature = in_feature[:, :, 3:]\nfeature = feature.permute(0, 2, 1)\nassert len(points.shape) == 3, 'The input point cloud should be batched!'\nassert len(feature.s... | <|body_start_0|>
super(FieldBatchNormalization, self).__init__()
self.bn = nn.BatchNorm1d(in_channel)
self.in_channel = in_channel
<|end_body_0|>
<|body_start_1|>
points = in_feature[:, :, :3]
feature = in_feature[:, :, 3:]
feature = feature.permute(0, 2, 1)
asse... | Field convolution layer. | FieldBatchNormalization | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FieldBatchNormalization:
"""Field convolution layer."""
def __init__(self, in_channel: int):
"""The initialization function. Args: in_channel: The number of input channels."""
<|body_0|>
def forward(self, in_feature: torch.Tensor):
"""The forward function. Args: ... | stack_v2_sparse_classes_36k_train_000658 | 1,846 | permissive | [
{
"docstring": "The initialization function. Args: in_channel: The number of input channels.",
"name": "__init__",
"signature": "def __init__(self, in_channel: int)"
},
{
"docstring": "The forward function. Args: in_feature: The input feature with the concatenation of the following two tensors. ... | 2 | stack_v2_sparse_classes_30k_train_019545 | Implement the Python class `FieldBatchNormalization` described below.
Class description:
Field convolution layer.
Method signatures and docstrings:
- def __init__(self, in_channel: int): The initialization function. Args: in_channel: The number of input channels.
- def forward(self, in_feature: torch.Tensor): The for... | Implement the Python class `FieldBatchNormalization` described below.
Class description:
Field convolution layer.
Method signatures and docstrings:
- def __init__(self, in_channel: int): The initialization function. Args: in_channel: The number of input channels.
- def forward(self, in_feature: torch.Tensor): The for... | ca88df568a6f2143dcb85d22c005fce4562a7523 | <|skeleton|>
class FieldBatchNormalization:
"""Field convolution layer."""
def __init__(self, in_channel: int):
"""The initialization function. Args: in_channel: The number of input channels."""
<|body_0|>
def forward(self, in_feature: torch.Tensor):
"""The forward function. Args: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FieldBatchNormalization:
"""Field convolution layer."""
def __init__(self, in_channel: int):
"""The initialization function. Args: in_channel: The number of input channels."""
super(FieldBatchNormalization, self).__init__()
self.bn = nn.BatchNorm1d(in_channel)
self.in_chan... | the_stack_v2_python_sparse | SDFConv/code/models/layers/sdf_bn.py | zshyang/FieldConvolution | train | 1 |
ab99cddba425a3374d3ffd2ccc0136f45df5b99d | [
"self.copy_recovery = copy_recovery\nself.datastore_entity = datastore_entity\nself.power_state_config = power_state_config\nself.rename_restored_object_param = rename_restored_object_param\nself.resource_entity = resource_entity\nself.restored_objects_network_config = restored_objects_network_config\nself.use_smb_... | <|body_start_0|>
self.copy_recovery = copy_recovery
self.datastore_entity = datastore_entity
self.power_state_config = power_state_config
self.rename_restored_object_param = rename_restored_object_param
self.resource_entity = resource_entity
self.restored_objects_network_... | Implementation of the 'RestoreHyperVVMParams' model. TODO: type description here. Attributes: copy_recovery (bool): Whether to perform copy recovery. datastore_entity (EntityProto): A datastore entity where the object's files should be restored to. This field is optional if object is being restored to its original pare... | RestoreHyperVVMParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreHyperVVMParams:
"""Implementation of the 'RestoreHyperVVMParams' model. TODO: type description here. Attributes: copy_recovery (bool): Whether to perform copy recovery. datastore_entity (EntityProto): A datastore entity where the object's files should be restored to. This field is optional... | stack_v2_sparse_classes_36k_train_000659 | 6,574 | permissive | [
{
"docstring": "Constructor for the RestoreHyperVVMParams class",
"name": "__init__",
"signature": "def __init__(self, copy_recovery=None, datastore_entity=None, power_state_config=None, rename_restored_object_param=None, resource_entity=None, restored_objects_network_config=None, use_smb_service=None, ... | 2 | null | Implement the Python class `RestoreHyperVVMParams` described below.
Class description:
Implementation of the 'RestoreHyperVVMParams' model. TODO: type description here. Attributes: copy_recovery (bool): Whether to perform copy recovery. datastore_entity (EntityProto): A datastore entity where the object's files should... | Implement the Python class `RestoreHyperVVMParams` described below.
Class description:
Implementation of the 'RestoreHyperVVMParams' model. TODO: type description here. Attributes: copy_recovery (bool): Whether to perform copy recovery. datastore_entity (EntityProto): A datastore entity where the object's files should... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreHyperVVMParams:
"""Implementation of the 'RestoreHyperVVMParams' model. TODO: type description here. Attributes: copy_recovery (bool): Whether to perform copy recovery. datastore_entity (EntityProto): A datastore entity where the object's files should be restored to. This field is optional... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoreHyperVVMParams:
"""Implementation of the 'RestoreHyperVVMParams' model. TODO: type description here. Attributes: copy_recovery (bool): Whether to perform copy recovery. datastore_entity (EntityProto): A datastore entity where the object's files should be restored to. This field is optional if object is... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_hyperv_vm_params.py | cohesity/management-sdk-python | train | 24 |
cf5a9c2ae802eab03e95c07333c1929a45337ad9 | [
"super().__init__()\nself.signal_gate_pad = nn.ConstantPad1d(padding=(kernels - 1, 0), value=0.0)\nself.signal_conv = nn.Conv1d(in_channels=residual_channels, out_channels=gate_channels, kernel_size=kernels, stride=1)\nself.gate_conv = nn.Conv1d(in_channels=residual_channels, out_channels=gate_channels, kernel_size... | <|body_start_0|>
super().__init__()
self.signal_gate_pad = nn.ConstantPad1d(padding=(kernels - 1, 0), value=0.0)
self.signal_conv = nn.Conv1d(in_channels=residual_channels, out_channels=gate_channels, kernel_size=kernels, stride=1)
self.gate_conv = nn.Conv1d(in_channels=residual_channels... | Блок с гейтом и остаточным соединением. | SubBlock | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubBlock:
"""Блок с гейтом и остаточным соединением."""
def __init__(self, kernels: int, gate_channels: int, residual_channels: int) -> None:
""":param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_channels: Количество каналов в signal и gate сверточных слоях.... | stack_v2_sparse_classes_36k_train_000660 | 13,064 | permissive | [
{
"docstring": ":param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_channels: Количество каналов в signal и gate сверточных слоях. :param residual_channels: Количество каналов на входе и по обходному пути.",
"name": "__init__",
"signature": "def __init__(self, kernels: int, gate... | 2 | null | Implement the Python class `SubBlock` described below.
Class description:
Блок с гейтом и остаточным соединением.
Method signatures and docstrings:
- def __init__(self, kernels: int, gate_channels: int, residual_channels: int) -> None: :param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_chann... | Implement the Python class `SubBlock` described below.
Class description:
Блок с гейтом и остаточным соединением.
Method signatures and docstrings:
- def __init__(self, kernels: int, gate_channels: int, residual_channels: int) -> None: :param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_chann... | 3a67544fd4c1bce39d67523799b76c9adfd03969 | <|skeleton|>
class SubBlock:
"""Блок с гейтом и остаточным соединением."""
def __init__(self, kernels: int, gate_channels: int, residual_channels: int) -> None:
""":param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_channels: Количество каналов в signal и gate сверточных слоях.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubBlock:
"""Блок с гейтом и остаточным соединением."""
def __init__(self, kernels: int, gate_channels: int, residual_channels: int) -> None:
""":param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_channels: Количество каналов в signal и gate сверточных слоях. :param resid... | the_stack_v2_python_sparse | poptimizer/dl/models/wave_net.py | tjlee/poptimizer | train | 0 |
63c7150a9bc25cfda9213649e598db626dd77d51 | [
"caller = Caller.Instance()\nif not caller.raw:\n return\nQtGui.QDialog.__init__(self)\nself.ui = Ui_ChannelSelectionDialog()\nself.ui.setupUi(self)\nself.ui.listWidgetChannels.clear()\nchannels = caller.raw.info['ch_names']\nfor channel in channels:\n item = QListWidgetItem(channel)\n self.ui.listWidgetCh... | <|body_start_0|>
caller = Caller.Instance()
if not caller.raw:
return
QtGui.QDialog.__init__(self)
self.ui = Ui_ChannelSelectionDialog()
self.ui.setupUi(self)
self.ui.listWidgetChannels.clear()
channels = caller.raw.info['ch_names']
for channel... | ChannelSelectionDialog | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelSelectionDialog:
def __init__(self, selChannels=[], caption=''):
"""A dialog for selecting bad channels by hand. parameters: selChannels - Used for checking channels. All the channels in this list are selected on startup."""
<|body_0|>
def accept(self, *args, **kwargs... | stack_v2_sparse_classes_36k_train_000661 | 1,656 | permissive | [
{
"docstring": "A dialog for selecting bad channels by hand. parameters: selChannels - Used for checking channels. All the channels in this list are selected on startup.",
"name": "__init__",
"signature": "def __init__(self, selChannels=[], caption='')"
},
{
"docstring": "Called when ok is click... | 2 | stack_v2_sparse_classes_30k_train_005132 | Implement the Python class `ChannelSelectionDialog` described below.
Class description:
Implement the ChannelSelectionDialog class.
Method signatures and docstrings:
- def __init__(self, selChannels=[], caption=''): A dialog for selecting bad channels by hand. parameters: selChannels - Used for checking channels. All... | Implement the Python class `ChannelSelectionDialog` described below.
Class description:
Implement the ChannelSelectionDialog class.
Method signatures and docstrings:
- def __init__(self, selChannels=[], caption=''): A dialog for selecting bad channels by hand. parameters: selChannels - Used for checking channels. All... | a7e812f27e33f9c43ac2e36c6b45a26a01530a06 | <|skeleton|>
class ChannelSelectionDialog:
def __init__(self, selChannels=[], caption=''):
"""A dialog for selecting bad channels by hand. parameters: selChannels - Used for checking channels. All the channels in this list are selected on startup."""
<|body_0|>
def accept(self, *args, **kwargs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChannelSelectionDialog:
def __init__(self, selChannels=[], caption=''):
"""A dialog for selecting bad channels by hand. parameters: selChannels - Used for checking channels. All the channels in this list are selected on startup."""
caller = Caller.Instance()
if not caller.raw:
... | the_stack_v2_python_sparse | ui/channelSelectionDialog.py | jaeilepp/eggie | train | 0 | |
3e87e2d274064f2e2dfc735ef04b0a3810c7106e | [
"l = ('lion', 'tiger')\nres = self.r.sadd('animal1', *l)\nprint(res)\nres = self.r.smenmbers('animal1')\nprint(res)\nreturn res",
"res = self.r.srem('animal2', 'lion')\nprint(res)\nres = self.r.smenmbers('animal2')\nprint(res)\nreturn res",
"res = self.r.sinter('animal1', 'animal2')\nprint(res)\nreturn res",
... | <|body_start_0|>
l = ('lion', 'tiger')
res = self.r.sadd('animal1', *l)
print(res)
res = self.r.smenmbers('animal1')
print(res)
return res
<|end_body_0|>
<|body_start_1|>
res = self.r.srem('animal2', 'lion')
print(res)
res = self.r.smenmbers('anim... | TestSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSet:
def test_sadd(self):
"""sadd/srem -- 添加/删除数据"""
<|body_0|>
def test_srem(self):
"""sadd/srem -- 添加/删除数据"""
<|body_1|>
def test_sinter(self):
"""sinter -- 返回几个集合的并集"""
<|body_2|>
def test_sunion(self):
"""sinter -- 返回... | stack_v2_sparse_classes_36k_train_000662 | 3,577 | no_license | [
{
"docstring": "sadd/srem -- 添加/删除数据",
"name": "test_sadd",
"signature": "def test_sadd(self)"
},
{
"docstring": "sadd/srem -- 添加/删除数据",
"name": "test_srem",
"signature": "def test_srem(self)"
},
{
"docstring": "sinter -- 返回几个集合的并集",
"name": "test_sinter",
"signature": "d... | 4 | stack_v2_sparse_classes_30k_train_004947 | Implement the Python class `TestSet` described below.
Class description:
Implement the TestSet class.
Method signatures and docstrings:
- def test_sadd(self): sadd/srem -- 添加/删除数据
- def test_srem(self): sadd/srem -- 添加/删除数据
- def test_sinter(self): sinter -- 返回几个集合的并集
- def test_sunion(self): sinter -- 返回几个集合的交集 | Implement the Python class `TestSet` described below.
Class description:
Implement the TestSet class.
Method signatures and docstrings:
- def test_sadd(self): sadd/srem -- 添加/删除数据
- def test_srem(self): sadd/srem -- 添加/删除数据
- def test_sinter(self): sinter -- 返回几个集合的并集
- def test_sunion(self): sinter -- 返回几个集合的交集
<|s... | 9434557f8e6b85ff7fc8f4699b253b054910d869 | <|skeleton|>
class TestSet:
def test_sadd(self):
"""sadd/srem -- 添加/删除数据"""
<|body_0|>
def test_srem(self):
"""sadd/srem -- 添加/删除数据"""
<|body_1|>
def test_sinter(self):
"""sinter -- 返回几个集合的并集"""
<|body_2|>
def test_sunion(self):
"""sinter -- 返回... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSet:
def test_sadd(self):
"""sadd/srem -- 添加/删除数据"""
l = ('lion', 'tiger')
res = self.r.sadd('animal1', *l)
print(res)
res = self.r.smenmbers('animal1')
print(res)
return res
def test_srem(self):
"""sadd/srem -- 添加/删除数据"""
res = ... | the_stack_v2_python_sparse | SQL/test_redis.py | 0Monster0/Python | train | 1 | |
ecb87e24dc713f7467b42d098fd7bf717ef36a7f | [
"driver = instance.driver\nWebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_name(self.locator))\ndriver.find_element_by_name(self.locator).send_keys(value)",
"driver = instance.driver\nWebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_name(self.locator))\nelement = drive... | <|body_start_0|>
driver = instance.driver
WebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_name(self.locator))
driver.find_element_by_name(self.locator).send_keys(value)
<|end_body_0|>
<|body_start_1|>
driver = instance.driver
WebDriverWait(driver, 100).unt... | Used for base page | BasePageElement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasePageElement:
"""Used for base page"""
def __set__(self, instance, value):
"""sets text for element to be located"""
<|body_0|>
def __get__(self, instance, owner):
"""Get text out of element"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dri... | stack_v2_sparse_classes_36k_train_000663 | 764 | no_license | [
{
"docstring": "sets text for element to be located",
"name": "__set__",
"signature": "def __set__(self, instance, value)"
},
{
"docstring": "Get text out of element",
"name": "__get__",
"signature": "def __get__(self, instance, owner)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004724 | Implement the Python class `BasePageElement` described below.
Class description:
Used for base page
Method signatures and docstrings:
- def __set__(self, instance, value): sets text for element to be located
- def __get__(self, instance, owner): Get text out of element | Implement the Python class `BasePageElement` described below.
Class description:
Used for base page
Method signatures and docstrings:
- def __set__(self, instance, value): sets text for element to be located
- def __get__(self, instance, owner): Get text out of element
<|skeleton|>
class BasePageElement:
"""Used... | 4a0b3f6ef59ff49b36fd143cd867710619849bf4 | <|skeleton|>
class BasePageElement:
"""Used for base page"""
def __set__(self, instance, value):
"""sets text for element to be located"""
<|body_0|>
def __get__(self, instance, owner):
"""Get text out of element"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasePageElement:
"""Used for base page"""
def __set__(self, instance, value):
"""sets text for element to be located"""
driver = instance.driver
WebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_name(self.locator))
driver.find_element_by_name(self.loca... | the_stack_v2_python_sparse | PageObject/try1/element.py | smiroshnikov/telegramBotforMiningControl | train | 0 |
e53b88a283a5d842c8838222976b7a6ff70a74cf | [
"self.s = s\nself.res = []\nself.visited = [False for _ in range(len(s))]\nself.dfs(0, [])\nreturn list(self.res)",
"if len(path) == len(self.s):\n self.res.append(''.join(path))\n return\nrepeat = set()\nfor i in range(len(self.s)):\n if not self.visited[i] and self.s[i] not in repeat:\n repeat.a... | <|body_start_0|>
self.s = s
self.res = []
self.visited = [False for _ in range(len(s))]
self.dfs(0, [])
return list(self.res)
<|end_body_0|>
<|body_start_1|>
if len(path) == len(self.s):
self.res.append(''.join(path))
return
repeat = set()... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permutation(self, s):
"""Args: s: str Return: list[str]"""
<|body_0|>
def dfs(self, index, path):
"""Args: index: int path: list[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.s = s
self.res = []
self.visited... | stack_v2_sparse_classes_36k_train_000664 | 1,767 | no_license | [
{
"docstring": "Args: s: str Return: list[str]",
"name": "permutation",
"signature": "def permutation(self, s)"
},
{
"docstring": "Args: index: int path: list[str]",
"name": "dfs",
"signature": "def dfs(self, index, path)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permutation(self, s): Args: s: str Return: list[str]
- def dfs(self, index, path): Args: index: int path: list[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permutation(self, s): Args: s: str Return: list[str]
- def dfs(self, index, path): Args: index: int path: list[str]
<|skeleton|>
class Solution:
def permutation(self, s... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def permutation(self, s):
"""Args: s: str Return: list[str]"""
<|body_0|>
def dfs(self, index, path):
"""Args: index: int path: list[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def permutation(self, s):
"""Args: s: str Return: list[str]"""
self.s = s
self.res = []
self.visited = [False for _ in range(len(s))]
self.dfs(0, [])
return list(self.res)
def dfs(self, index, path):
"""Args: index: int path: list[str]"""
... | the_stack_v2_python_sparse | 剑指offer/剑指 Offer 38. 字符串的排列.py | AiZhanghan/Leetcode | train | 0 | |
f147fbc04b7afbce6f08e4ed838e05c75f6061fe | [
"if len(edges) == 0:\n return\nself.inPhotoTarget = aggregator((edge.incoming.photos_target for edge in edges))\nself.inPhotoOther = aggregator((edge.incoming.photos_other for edge in edges))\nself.inMutuals = aggregator((edge.incoming.mut_friends for edge in edges))\nif require_incoming:\n self.inPostLikes =... | <|body_start_0|>
if len(edges) == 0:
return
self.inPhotoTarget = aggregator((edge.incoming.photos_target for edge in edges))
self.inPhotoOther = aggregator((edge.incoming.photos_other for edge in edges))
self.inMutuals = aggregator((edge.incoming.mut_friends for edge in edges... | Edge aggregation, scoring and ranking. | EdgeAggregate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeAggregate:
"""Edge aggregation, scoring and ranking."""
def __init__(self, edges, aggregator=max, require_incoming=True, require_outgoing=True):
"""Apply the aggregator to the given Edges to initialize instance data. edges: sequence of Edges from a primary to all friends aggregat... | stack_v2_sparse_classes_36k_train_000665 | 33,126 | no_license | [
{
"docstring": "Apply the aggregator to the given Edges to initialize instance data. edges: sequence of Edges from a primary to all friends aggregator: a function over properties of Edges (default: max)",
"name": "__init__",
"signature": "def __init__(self, edges, aggregator=max, require_incoming=True, ... | 2 | stack_v2_sparse_classes_30k_train_010291 | Implement the Python class `EdgeAggregate` described below.
Class description:
Edge aggregation, scoring and ranking.
Method signatures and docstrings:
- def __init__(self, edges, aggregator=max, require_incoming=True, require_outgoing=True): Apply the aggregator to the given Edges to initialize instance data. edges:... | Implement the Python class `EdgeAggregate` described below.
Class description:
Edge aggregation, scoring and ranking.
Method signatures and docstrings:
- def __init__(self, edges, aggregator=max, require_incoming=True, require_outgoing=True): Apply the aggregator to the given Edges to initialize instance data. edges:... | bebd10d910c87dabc0680692684a3e551e92dd2a | <|skeleton|>
class EdgeAggregate:
"""Edge aggregation, scoring and ranking."""
def __init__(self, edges, aggregator=max, require_incoming=True, require_outgoing=True):
"""Apply the aggregator to the given Edges to initialize instance data. edges: sequence of Edges from a primary to all friends aggregat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdgeAggregate:
"""Edge aggregation, scoring and ranking."""
def __init__(self, edges, aggregator=max, require_incoming=True, require_outgoing=True):
"""Apply the aggregator to the given Edges to initialize instance data. edges: sequence of Edges from a primary to all friends aggregator: a functio... | the_stack_v2_python_sparse | targetshare/models/datastructs.py | edgeflip/edgeflip | train | 1 |
fa7d858f7fee681225a3beb988b0c75302557181 | [
"self.env.revert_snapshot('ready_with_3_slaves')\nself.prepare_plugin()\nself.helpers.create_cluster(name=self.__class__.__name__)\nself.activate_plugin()",
"self.check_run('deploy_influxdb_grafana')\nself.env.revert_snapshot('ready_with_3_slaves')\nself.prepare_plugin()\nself.helpers.create_cluster(name=self.__c... | <|body_start_0|>
self.env.revert_snapshot('ready_with_3_slaves')
self.prepare_plugin()
self.helpers.create_cluster(name=self.__class__.__name__)
self.activate_plugin()
<|end_body_0|>
<|body_start_1|>
self.check_run('deploy_influxdb_grafana')
self.env.revert_snapshot('rea... | Class for smoke testing the InfluxDB-Grafana plugin. | TestInfluxdbPlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestInfluxdbPlugin:
"""Class for smoke testing the InfluxDB-Grafana plugin."""
def install_influxdb_grafana(self):
"""Install InfluxDB-Grafana plugin and check it exists Scenario: 1. Upload the InfluxDB/Grafana plugin to the master node 2. Install the plugin 3. Create a cluster 4. Ch... | stack_v2_sparse_classes_36k_train_000666 | 5,396 | no_license | [
{
"docstring": "Install InfluxDB-Grafana plugin and check it exists Scenario: 1. Upload the InfluxDB/Grafana plugin to the master node 2. Install the plugin 3. Create a cluster 4. Check that the plugin can be enabled Duration 20m",
"name": "install_influxdb_grafana",
"signature": "def install_influxdb_g... | 5 | stack_v2_sparse_classes_30k_train_002520 | Implement the Python class `TestInfluxdbPlugin` described below.
Class description:
Class for smoke testing the InfluxDB-Grafana plugin.
Method signatures and docstrings:
- def install_influxdb_grafana(self): Install InfluxDB-Grafana plugin and check it exists Scenario: 1. Upload the InfluxDB/Grafana plugin to the ma... | Implement the Python class `TestInfluxdbPlugin` described below.
Class description:
Class for smoke testing the InfluxDB-Grafana plugin.
Method signatures and docstrings:
- def install_influxdb_grafana(self): Install InfluxDB-Grafana plugin and check it exists Scenario: 1. Upload the InfluxDB/Grafana plugin to the ma... | 179249df2d206eeabb3955c9dc8cb78cac3c36c6 | <|skeleton|>
class TestInfluxdbPlugin:
"""Class for smoke testing the InfluxDB-Grafana plugin."""
def install_influxdb_grafana(self):
"""Install InfluxDB-Grafana plugin and check it exists Scenario: 1. Upload the InfluxDB/Grafana plugin to the master node 2. Install the plugin 3. Create a cluster 4. Ch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestInfluxdbPlugin:
"""Class for smoke testing the InfluxDB-Grafana plugin."""
def install_influxdb_grafana(self):
"""Install InfluxDB-Grafana plugin and check it exists Scenario: 1. Upload the InfluxDB/Grafana plugin to the master node 2. Install the plugin 3. Create a cluster 4. Check that the ... | the_stack_v2_python_sparse | stacklight_tests/influxdb_grafana/test_smoke_bvt.py | rkhozinov/stacklight-integration-tests | train | 1 |
108db673777e156bd07c50fb431b71b4286fd2fd | [
"ManualTriggerEntity.__init__(self, hass, trigger_entity_config)\nRestEntity.__init__(self, coordinator, rest, config.get(CONF_RESOURCE_TEMPLATE), config[CONF_FORCE_UPDATE])\nself._previous_data = None\nself._value_template: Template | None = config.get(CONF_VALUE_TEMPLATE)\nif (value_template := self._value_templa... | <|body_start_0|>
ManualTriggerEntity.__init__(self, hass, trigger_entity_config)
RestEntity.__init__(self, coordinator, rest, config.get(CONF_RESOURCE_TEMPLATE), config[CONF_FORCE_UPDATE])
self._previous_data = None
self._value_template: Template | None = config.get(CONF_VALUE_TEMPLATE)
... | Representation of a REST binary sensor. | RestBinarySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestBinarySensor:
"""Representation of a REST binary sensor."""
def __init__(self, hass: HomeAssistant, coordinator: DataUpdateCoordinator[None] | None, rest: RestData, config: ConfigType, trigger_entity_config: ConfigType) -> None:
"""Initialize a REST binary sensor."""
<|bo... | stack_v2_sparse_classes_36k_train_000667 | 5,213 | permissive | [
{
"docstring": "Initialize a REST binary sensor.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, coordinator: DataUpdateCoordinator[None] | None, rest: RestData, config: ConfigType, trigger_entity_config: ConfigType) -> None"
},
{
"docstring": "Return if entity is ava... | 3 | stack_v2_sparse_classes_30k_train_006685 | Implement the Python class `RestBinarySensor` described below.
Class description:
Representation of a REST binary sensor.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, coordinator: DataUpdateCoordinator[None] | None, rest: RestData, config: ConfigType, trigger_entity_config: ConfigType) ... | Implement the Python class `RestBinarySensor` described below.
Class description:
Representation of a REST binary sensor.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, coordinator: DataUpdateCoordinator[None] | None, rest: RestData, config: ConfigType, trigger_entity_config: ConfigType) ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class RestBinarySensor:
"""Representation of a REST binary sensor."""
def __init__(self, hass: HomeAssistant, coordinator: DataUpdateCoordinator[None] | None, rest: RestData, config: ConfigType, trigger_entity_config: ConfigType) -> None:
"""Initialize a REST binary sensor."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestBinarySensor:
"""Representation of a REST binary sensor."""
def __init__(self, hass: HomeAssistant, coordinator: DataUpdateCoordinator[None] | None, rest: RestData, config: ConfigType, trigger_entity_config: ConfigType) -> None:
"""Initialize a REST binary sensor."""
ManualTriggerEnti... | the_stack_v2_python_sparse | homeassistant/components/rest/binary_sensor.py | home-assistant/core | train | 35,501 |
409220a3cf8b7ab8209f12d7ac382a7634617d34 | [
"super(MultiGLM, self).__init__()\nself.enc = encoder\nself.dec = decoder\nif p_latent is not None:\n if p_latent.name() == 'PointMass':\n p_latent = None\nself.latent = p_latent\nself.obs = p_targ\nself.__name__ = '%s_%s_%s_%s' % (self.enc.__class__.__name__, self.enc.ndim, self.enc.activation, self.obs.... | <|body_start_0|>
super(MultiGLM, self).__init__()
self.enc = encoder
self.dec = decoder
if p_latent is not None:
if p_latent.name() == 'PointMass':
p_latent = None
self.latent = p_latent
self.obs = p_targ
self.__name__ = '%s_%s_%s_%s' %... | A deep GLM model with multiple outputs | MultiGLM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiGLM:
"""A deep GLM model with multiple outputs"""
def __init__(self, encoder, decoder, p_targ, p_latent=None):
"""Parameters ---------- encoder : Pytorch Module Mapping from data (x) to code (z), a feedforward network. decoder : Pytorch Module Mapping from code (z) to the natura... | stack_v2_sparse_classes_36k_train_000668 | 45,005 | no_license | [
{
"docstring": "Parameters ---------- encoder : Pytorch Module Mapping from data (x) to code (z), a feedforward network. decoder : Pytorch Module Mapping from code (z) to the natural parameters of p_targ. Usually just a linear-nonlinear layer, e.g. linear-sigmoid for logistic regression. p_targ : DeepDistributi... | 3 | stack_v2_sparse_classes_30k_train_015540 | Implement the Python class `MultiGLM` described below.
Class description:
A deep GLM model with multiple outputs
Method signatures and docstrings:
- def __init__(self, encoder, decoder, p_targ, p_latent=None): Parameters ---------- encoder : Pytorch Module Mapping from data (x) to code (z), a feedforward network. dec... | Implement the Python class `MultiGLM` described below.
Class description:
A deep GLM model with multiple outputs
Method signatures and docstrings:
- def __init__(self, encoder, decoder, p_targ, p_latent=None): Parameters ---------- encoder : Pytorch Module Mapping from data (x) to code (z), a feedforward network. dec... | 1d4c76920d50729680305a4e877c30e2b782d9d7 | <|skeleton|>
class MultiGLM:
"""A deep GLM model with multiple outputs"""
def __init__(self, encoder, decoder, p_targ, p_latent=None):
"""Parameters ---------- encoder : Pytorch Module Mapping from data (x) to code (z), a feedforward network. decoder : Pytorch Module Mapping from code (z) to the natura... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiGLM:
"""A deep GLM model with multiple outputs"""
def __init__(self, encoder, decoder, p_targ, p_latent=None):
"""Parameters ---------- encoder : Pytorch Module Mapping from data (x) to code (z), a feedforward network. decoder : Pytorch Module Mapping from code (z) to the natural parameters ... | the_stack_v2_python_sparse | src/students.py | Kelarion/repler | train | 0 |
a0e07f0976ed8e531402bef2225018a53a930263 | [
"super().__init__()\nself.alpha = alpha\nself.loss = nn.CrossEntropyLoss(reduce=False)",
"num_target = (target > 0).type(torch.FloatTensor).sum()\nloss_stage1 = self.loss(pred_stage1, target)\nloss_stage2 = self.loss(pred_stage2, target)\nexponential_term_stage1 = (1 - F.softmax(pred_stage1, dim=1).max(dim=1)[0])... | <|body_start_0|>
super().__init__()
self.alpha = alpha
self.loss = nn.CrossEntropyLoss(reduce=False)
<|end_body_0|>
<|body_start_1|>
num_target = (target > 0).type(torch.FloatTensor).sum()
loss_stage1 = self.loss(pred_stage1, target)
loss_stage2 = self.loss(pred_stage2, ... | CELoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CELoss:
def __init__(self, alpha=2):
""":param alpha: focal loss中的指数项的次数"""
<|body_0|>
def forward(self, pred_stage1, pred_stage2, target):
""":param pred_stage1: (B, 14, 48, 256, 256) :param pred_stage2: (B, 14, 48, 256, 256) :param target: (B, 48, 256, 256)"""
... | stack_v2_sparse_classes_36k_train_000669 | 10,741 | no_license | [
{
"docstring": ":param alpha: focal loss中的指数项的次数",
"name": "__init__",
"signature": "def __init__(self, alpha=2)"
},
{
"docstring": ":param pred_stage1: (B, 14, 48, 256, 256) :param pred_stage2: (B, 14, 48, 256, 256) :param target: (B, 48, 256, 256)",
"name": "forward",
"signature": "def... | 2 | null | Implement the Python class `CELoss` described below.
Class description:
Implement the CELoss class.
Method signatures and docstrings:
- def __init__(self, alpha=2): :param alpha: focal loss中的指数项的次数
- def forward(self, pred_stage1, pred_stage2, target): :param pred_stage1: (B, 14, 48, 256, 256) :param pred_stage2: (B,... | Implement the Python class `CELoss` described below.
Class description:
Implement the CELoss class.
Method signatures and docstrings:
- def __init__(self, alpha=2): :param alpha: focal loss中的指数项的次数
- def forward(self, pred_stage1, pred_stage2, target): :param pred_stage1: (B, 14, 48, 256, 256) :param pred_stage2: (B,... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class CELoss:
def __init__(self, alpha=2):
""":param alpha: focal loss中的指数项的次数"""
<|body_0|>
def forward(self, pred_stage1, pred_stage2, target):
""":param pred_stage1: (B, 14, 48, 256, 256) :param pred_stage2: (B, 14, 48, 256, 256) :param target: (B, 48, 256, 256)"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CELoss:
def __init__(self, alpha=2):
""":param alpha: focal loss中的指数项的次数"""
super().__init__()
self.alpha = alpha
self.loss = nn.CrossEntropyLoss(reduce=False)
def forward(self, pred_stage1, pred_stage2, target):
""":param pred_stage1: (B, 14, 48, 256, 256) :param ... | the_stack_v2_python_sparse | generated/test_assassint2017_abdominal_multi_organ_segmentation.py | jansel/pytorch-jit-paritybench | train | 35 | |
ad0260d9cb598dfa772fc678b07a4d77905b965f | [
"StreamBase.__init__(self, default_ns, extra_ns, keepalive, owner)\nStreamTLSMixIn.__init__(self, tls_settings)\nStreamSASLMixIn.__init__(self, sasl_mechanisms)\nself.__logger = logging.getLogger('pyxmpp.Stream')",
"StreamBase._reset(self)\nself._reset_tls()\nself._reset_sasl()",
"features = StreamBase._make_st... | <|body_start_0|>
StreamBase.__init__(self, default_ns, extra_ns, keepalive, owner)
StreamTLSMixIn.__init__(self, tls_settings)
StreamSASLMixIn.__init__(self, sasl_mechanisms)
self.__logger = logging.getLogger('pyxmpp.Stream')
<|end_body_0|>
<|body_start_1|>
StreamBase._reset(sel... | Generic XMPP stream class. Responsible for establishing connection, parsing the stream, StartTLS encryption and SASL authentication negotiation and usage, dispatching received stanzas to apopriate handlers and sending application's stanzas. Whenever we say "stream" here we actually mean two streams (incoming and outgoi... | Stream | [
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stream:
"""Generic XMPP stream class. Responsible for establishing connection, parsing the stream, StartTLS encryption and SASL authentication negotiation and usage, dispatching received stanzas to apopriate handlers and sending application's stanzas. Whenever we say "stream" here we actually mea... | stack_v2_sparse_classes_36k_train_000670 | 4,703 | permissive | [
{
"docstring": "Initialize Stream object :Parameters: - `default_ns`: stream's default namespace (\"jabber:client\" for client, \"jabber:server\" for server, etc.) - `extra_ns`: sequence of extra namespace URIs to be defined for the stream. - `sasl_mechanisms`: sequence of SASL mechanisms allowed for authentica... | 5 | stack_v2_sparse_classes_30k_test_000813 | Implement the Python class `Stream` described below.
Class description:
Generic XMPP stream class. Responsible for establishing connection, parsing the stream, StartTLS encryption and SASL authentication negotiation and usage, dispatching received stanzas to apopriate handlers and sending application's stanzas. Whenev... | Implement the Python class `Stream` described below.
Class description:
Generic XMPP stream class. Responsible for establishing connection, parsing the stream, StartTLS encryption and SASL authentication negotiation and usage, dispatching received stanzas to apopriate handlers and sending application's stanzas. Whenev... | 16a62c7df1018a49eaa8151c0f8b881c7e252949 | <|skeleton|>
class Stream:
"""Generic XMPP stream class. Responsible for establishing connection, parsing the stream, StartTLS encryption and SASL authentication negotiation and usage, dispatching received stanzas to apopriate handlers and sending application's stanzas. Whenever we say "stream" here we actually mea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stream:
"""Generic XMPP stream class. Responsible for establishing connection, parsing the stream, StartTLS encryption and SASL authentication negotiation and usage, dispatching received stanzas to apopriate handlers and sending application's stanzas. Whenever we say "stream" here we actually mean two streams... | the_stack_v2_python_sparse | digsby/lib/pyxmpp/stream.py | niterain/digsby | train | 1 |
eb998f0229b179b89a7949bf16f72e9f2d1d575e | [
"if p and q:\n return p.val == q.val and self.isSameTree1(p.left, q.left) and self.isSameTree1(p.right, q.right)\nreturn p is q",
"if p and q:\n stack = []\n while p and q or stack:\n while p and q:\n stack.append((p, q))\n p = p.left\n q = q.left\n if (p or... | <|body_start_0|>
if p and q:
return p.val == q.val and self.isSameTree1(p.left, q.left) and self.isSameTree1(p.right, q.right)
return p is q
<|end_body_0|>
<|body_start_1|>
if p and q:
stack = []
while p and q or stack:
while p and q:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSameTree1(self, p: TreeNode, q: TreeNode) -> bool:
"""recursive :param p: :param q: :return:"""
<|body_0|>
def isSameTree2(self, p: TreeNode, q: TreeNode) -> bool:
"""iterative - my version :param p: :param q: :return:"""
<|body_1|>
def i... | stack_v2_sparse_classes_36k_train_000671 | 1,994 | no_license | [
{
"docstring": "recursive :param p: :param q: :return:",
"name": "isSameTree1",
"signature": "def isSameTree1(self, p: TreeNode, q: TreeNode) -> bool"
},
{
"docstring": "iterative - my version :param p: :param q: :return:",
"name": "isSameTree2",
"signature": "def isSameTree2(self, p: Tr... | 3 | stack_v2_sparse_classes_30k_train_002099 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree1(self, p: TreeNode, q: TreeNode) -> bool: recursive :param p: :param q: :return:
- def isSameTree2(self, p: TreeNode, q: TreeNode) -> bool: iterative - my version ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree1(self, p: TreeNode, q: TreeNode) -> bool: recursive :param p: :param q: :return:
- def isSameTree2(self, p: TreeNode, q: TreeNode) -> bool: iterative - my version ... | 25f2795b6e7f9f68833f2fddc6cc4f4d977121a6 | <|skeleton|>
class Solution:
def isSameTree1(self, p: TreeNode, q: TreeNode) -> bool:
"""recursive :param p: :param q: :return:"""
<|body_0|>
def isSameTree2(self, p: TreeNode, q: TreeNode) -> bool:
"""iterative - my version :param p: :param q: :return:"""
<|body_1|>
def i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSameTree1(self, p: TreeNode, q: TreeNode) -> bool:
"""recursive :param p: :param q: :return:"""
if p and q:
return p.val == q.val and self.isSameTree1(p.left, q.left) and self.isSameTree1(p.right, q.right)
return p is q
def isSameTree2(self, p: TreeNode... | the_stack_v2_python_sparse | 100.py | Darkxiete/leetcode_python | train | 0 | |
e2b58644482f3930460f4344ebcd5bef89894ae4 | [
"if not raw.startswith('[') and (not raw.endswith(']')):\n raise MultiplicityException('Incorrectly formatted: ' + raw)\nvalues = raw.strip('[]').split('..')\nif len(values) != 2:\n raise MultiplicityException('Incorrectly formatted: ' + raw)\nself.min = self._getCardinality(values[0])\nself.max = self._getCa... | <|body_start_0|>
if not raw.startswith('[') and (not raw.endswith(']')):
raise MultiplicityException('Incorrectly formatted: ' + raw)
values = raw.strip('[]').split('..')
if len(values) != 2:
raise MultiplicityException('Incorrectly formatted: ' + raw)
self.min = ... | Class to represent the multiplicty of a collection | Multiplicity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Multiplicity:
"""Class to represent the multiplicty of a collection"""
def __init__(self, raw):
"""Constructor @param raw: The raw multiplicty string e.g. [0..1]"""
<|body_0|>
def _getCardinality(self, value):
"""Get the cardinality from a string @return Cardinal... | stack_v2_sparse_classes_36k_train_000672 | 2,157 | permissive | [
{
"docstring": "Constructor @param raw: The raw multiplicty string e.g. [0..1]",
"name": "__init__",
"signature": "def __init__(self, raw)"
},
{
"docstring": "Get the cardinality from a string @return Cardinality: The cardinality",
"name": "_getCardinality",
"signature": "def _getCardina... | 2 | stack_v2_sparse_classes_30k_train_019422 | Implement the Python class `Multiplicity` described below.
Class description:
Class to represent the multiplicty of a collection
Method signatures and docstrings:
- def __init__(self, raw): Constructor @param raw: The raw multiplicty string e.g. [0..1]
- def _getCardinality(self, value): Get the cardinality from a st... | Implement the Python class `Multiplicity` described below.
Class description:
Class to represent the multiplicty of a collection
Method signatures and docstrings:
- def __init__(self, raw): Constructor @param raw: The raw multiplicty string e.g. [0..1]
- def _getCardinality(self, value): Get the cardinality from a st... | e831fc2a28beaaab3805f998df796d9c42b11633 | <|skeleton|>
class Multiplicity:
"""Class to represent the multiplicty of a collection"""
def __init__(self, raw):
"""Constructor @param raw: The raw multiplicty string e.g. [0..1]"""
<|body_0|>
def _getCardinality(self, value):
"""Get the cardinality from a string @return Cardinal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Multiplicity:
"""Class to represent the multiplicty of a collection"""
def __init__(self, raw):
"""Constructor @param raw: The raw multiplicty string e.g. [0..1]"""
if not raw.startswith('[') and (not raw.endswith(']')):
raise MultiplicityException('Incorrectly formatted: ' + ... | the_stack_v2_python_sparse | tools/codegen/OCCI/Collection.py | compatibleone/accords-platform | train | 7 |
9fda7f71ac723fe1e139e40f7bfa6fb3f376d4b2 | [
"self._check_mandatory_fields()\nself._set_parameters()\nsimulation_parameters = si.run_adaptive(self.args)\nreturn simulation_parameters",
"COMPULSORY_FLAGS = ['final_site', 'initial_site']\nfor flag in COMPULSORY_FLAGS:\n if getattr(self.args, flag) is None:\n raise ce.OutInError(f'flag {flag} must be... | <|body_start_0|>
self._check_mandatory_fields()
self._set_parameters()
simulation_parameters = si.run_adaptive(self.args)
return simulation_parameters
<|end_body_0|>
<|body_start_1|>
COMPULSORY_FLAGS = ['final_site', 'initial_site']
for flag in COMPULSORY_FLAGS:
... | OutInLauncher | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutInLauncher:
def run_outin_simulation(self) -> pv.ParametersBuilder:
"""Runs the whole OutIn workflow. Returns -------- simulation_parameters : pv.ParametersBuilder An object containing all simulation parameters."""
<|body_0|>
def _check_mandatory_fields(self):
"""... | stack_v2_sparse_classes_36k_train_000673 | 2,126 | permissive | [
{
"docstring": "Runs the whole OutIn workflow. Returns -------- simulation_parameters : pv.ParametersBuilder An object containing all simulation parameters.",
"name": "run_outin_simulation",
"signature": "def run_outin_simulation(self) -> pv.ParametersBuilder"
},
{
"docstring": "Checks if mandat... | 3 | null | Implement the Python class `OutInLauncher` described below.
Class description:
Implement the OutInLauncher class.
Method signatures and docstrings:
- def run_outin_simulation(self) -> pv.ParametersBuilder: Runs the whole OutIn workflow. Returns -------- simulation_parameters : pv.ParametersBuilder An object containin... | Implement the Python class `OutInLauncher` described below.
Class description:
Implement the OutInLauncher class.
Method signatures and docstrings:
- def run_outin_simulation(self) -> pv.ParametersBuilder: Runs the whole OutIn workflow. Returns -------- simulation_parameters : pv.ParametersBuilder An object containin... | 451c5b7e146f4d10ff76333bb36fd3f819a5dbfc | <|skeleton|>
class OutInLauncher:
def run_outin_simulation(self) -> pv.ParametersBuilder:
"""Runs the whole OutIn workflow. Returns -------- simulation_parameters : pv.ParametersBuilder An object containing all simulation parameters."""
<|body_0|>
def _check_mandatory_fields(self):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutInLauncher:
def run_outin_simulation(self) -> pv.ParametersBuilder:
"""Runs the whole OutIn workflow. Returns -------- simulation_parameters : pv.ParametersBuilder An object containing all simulation parameters."""
self._check_mandatory_fields()
self._set_parameters()
simula... | the_stack_v2_python_sparse | pele_platform/out_in/main.py | ignasipuch/pele_platform | train | 0 | |
f914ff17deb92f79ce71b0ce5ac98a472bf9cb82 | [
"url = reverse('admin:users_group_add')\nresp = self.client.get(url)\nself.assertEqual(resp.status_code, 200)\nself.assertTrue('adminform' in resp.context)",
"url = reverse('admin:users_group_add')\npost = {'name': 'somegroup', 'description': 'somedescription', 'roles-TOTAL_FORMS': 0, 'roles-INITIAL_FORMS': 0, 'r... | <|body_start_0|>
url = reverse('admin:users_group_add')
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
self.assertTrue('adminform' in resp.context)
<|end_body_0|>
<|body_start_1|>
url = reverse('admin:users_group_add')
post = {'name': 'somegroup', 'd... | Test the interaction with the group registration form used for requesting the registration of a new group in the testbed. | GroupFormTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupFormTestCase:
"""Test the interaction with the group registration form used for requesting the registration of a new group in the testbed."""
def test_add_form(self):
"""Test if the new group form is generated successfully"""
<|body_0|>
def test_create_no_resources(... | stack_v2_sparse_classes_36k_train_000674 | 15,044 | no_license | [
{
"docstring": "Test if the new group form is generated successfully",
"name": "test_add_form",
"signature": "def test_add_form(self)"
},
{
"docstring": "Test that a valid post for creating a new group is working properly without resource requests",
"name": "test_create_no_resources",
"s... | 5 | null | Implement the Python class `GroupFormTestCase` described below.
Class description:
Test the interaction with the group registration form used for requesting the registration of a new group in the testbed.
Method signatures and docstrings:
- def test_add_form(self): Test if the new group form is generated successfully... | Implement the Python class `GroupFormTestCase` described below.
Class description:
Test the interaction with the group registration form used for requesting the registration of a new group in the testbed.
Method signatures and docstrings:
- def test_add_form(self): Test if the new group form is generated successfully... | dd798dc9bd3321b17007ff131e7b1288a2cd3c36 | <|skeleton|>
class GroupFormTestCase:
"""Test the interaction with the group registration form used for requesting the registration of a new group in the testbed."""
def test_add_form(self):
"""Test if the new group form is generated successfully"""
<|body_0|>
def test_create_no_resources(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupFormTestCase:
"""Test the interaction with the group registration form used for requesting the registration of a new group in the testbed."""
def test_add_form(self):
"""Test if the new group form is generated successfully"""
url = reverse('admin:users_group_add')
resp = self... | the_stack_v2_python_sparse | controller/apps/users/tests.py | m00dy/vct-controller | train | 2 |
af57943a53ae7caef5d6a6938ae7fdb38c209392 | [
"self.res = []\nif n == 0:\n return self.res\nelse:\n self.generateParenthesisRecur(n, n, '')\n return self.res",
"if open == 0 and close == 0:\n self.res.append(curr)\nelif open != 0 and open <= close:\n self.generateParenthesisRecur(open - 1, close, curr + '(')\nelif close <= 0:\n return\nself... | <|body_start_0|>
self.res = []
if n == 0:
return self.res
else:
self.generateParenthesisRecur(n, n, '')
return self.res
<|end_body_0|>
<|body_start_1|>
if open == 0 and close == 0:
self.res.append(curr)
elif open != 0 and open <= c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesisRecur(self, open, close, curr):
""":type open: int :type close: int :type curr: str :rtype: void"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_000675 | 1,119 | no_license | [
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
},
{
"docstring": ":type open: int :type close: int :type curr: str :rtype: void",
"name": "generateParenthesisRecur",
"signature": "def generateParenthesisRecu... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
- def generateParenthesisRecur(self, open, close, curr): :type open: int :type close: int :type curr: str :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
- def generateParenthesisRecur(self, open, close, curr): :type open: int :type close: int :type curr: str :rtype:... | 8cda0518440488992d7e2c70cb8555ec7b34083f | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesisRecur(self, open, close, curr):
""":type open: int :type close: int :type curr: str :rtype: void"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
self.res = []
if n == 0:
return self.res
else:
self.generateParenthesisRecur(n, n, '')
return self.res
def generateParenthesisRecur(self, open, close, curr)... | the_stack_v2_python_sparse | 22/main.py | szhongren/leetcode | train | 0 | |
b2c3c54adf0bcc730a7a63812158c912e1cc16dd | [
"self._start_msg = start_msg\nself._end_msg = end_msg\nif total < 1:\n raise ValueError('The total number of items to count should begreater than 1.')\nself._total = int(total)\nif 0 < approx_percentage < 50:\n real_percentage = round(approx_percentage / 100.0 * self._total)\nelse:\n print('Bad value given... | <|body_start_0|>
self._start_msg = start_msg
self._end_msg = end_msg
if total < 1:
raise ValueError('The total number of items to count should begreater than 1.')
self._total = int(total)
if 0 < approx_percentage < 50:
real_percentage = round(approx_percen... | Write a progress bar to sys.stdout. Instantiate ProgressBar with the expected total number of iterations and then call the inc() method at the end of each iteration. Example: data = [i for i in range(100)] report_progress = ProgressBar(len(data)) for something in data: # Do processing. report_progress.inc() | ProgressBar | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgressBar:
"""Write a progress bar to sys.stdout. Instantiate ProgressBar with the expected total number of iterations and then call the inc() method at the end of each iteration. Example: data = [i for i in range(100)] report_progress = ProgressBar(len(data)) for something in data: # Do proces... | stack_v2_sparse_classes_36k_train_000676 | 3,780 | permissive | [
{
"docstring": "Initialize with a total size and the reporting interval as a percentage. Args: total (int): The total number of iterations expected. approx_percentage (int): The approximate intervals, as a percent, for updating the progress bar. The default is ten percent. start_msg (Unicode): An optional messa... | 4 | stack_v2_sparse_classes_30k_train_017897 | Implement the Python class `ProgressBar` described below.
Class description:
Write a progress bar to sys.stdout. Instantiate ProgressBar with the expected total number of iterations and then call the inc() method at the end of each iteration. Example: data = [i for i in range(100)] report_progress = ProgressBar(len(da... | Implement the Python class `ProgressBar` described below.
Class description:
Write a progress bar to sys.stdout. Instantiate ProgressBar with the expected total number of iterations and then call the inc() method at the end of each iteration. Example: data = [i for i in range(100)] report_progress = ProgressBar(len(da... | 287350c0049a10cee10654d093a1d06128f9d7aa | <|skeleton|>
class ProgressBar:
"""Write a progress bar to sys.stdout. Instantiate ProgressBar with the expected total number of iterations and then call the inc() method at the end of each iteration. Example: data = [i for i in range(100)] report_progress = ProgressBar(len(data)) for something in data: # Do proces... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProgressBar:
"""Write a progress bar to sys.stdout. Instantiate ProgressBar with the expected total number of iterations and then call the inc() method at the end of each iteration. Example: data = [i for i in range(100)] report_progress = ProgressBar(len(data)) for something in data: # Do processing. report_... | the_stack_v2_python_sparse | pdb/lib/progress_bar.py | shellydeforte/PDB | train | 1 |
53f7d1dfaeaff3b42532264f3aacec70e2b4f672 | [
"dims = [1 for _ in shape]\nself.shape = tuple(shape[-3:-1])\ndims[-2] = self.shape[-1]\nfull_width_half_maximum, acceleration = self.choose_acceleration()\nif not isinstance(full_width_half_maximum, list):\n full_width_half_maximum = [full_width_half_maximum] * 2\nself.full_width_half_maximum = full_width_half_... | <|body_start_0|>
dims = [1 for _ in shape]
self.shape = tuple(shape[-3:-1])
dims[-2] = self.shape[-1]
full_width_half_maximum, acceleration = self.choose_acceleration()
if not isinstance(full_width_half_maximum, list):
full_width_half_maximum = [full_width_half_maximu... | Creates a 1D sub-sampling mask of a given shape. For autocalibration purposes, data points near the k-space center will be fully sampled within an ellipse of which the half-axes will set to the set scale % of the fully sampled region. The remaining points will be sampled according to a Gaussian distribution. The center... | Gaussian1DMaskFunc | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gaussian1DMaskFunc:
"""Creates a 1D sub-sampling mask of a given shape. For autocalibration purposes, data points near the k-space center will be fully sampled within an ellipse of which the half-axes will set to the set scale % of the fully sampled region. The remaining points will be sampled ac... | stack_v2_sparse_classes_36k_train_000677 | 27,455 | permissive | [
{
"docstring": "Parameters ---------- shape: The shape of the mask to be created. The shape should have at least 3 dimensions. Samples are drawn along the second last dimension. seed: Seed for the random number generator. Setting the seed ensures the same mask is generated each time for the same shape. The rand... | 4 | null | Implement the Python class `Gaussian1DMaskFunc` described below.
Class description:
Creates a 1D sub-sampling mask of a given shape. For autocalibration purposes, data points near the k-space center will be fully sampled within an ellipse of which the half-axes will set to the set scale % of the fully sampled region. ... | Implement the Python class `Gaussian1DMaskFunc` described below.
Class description:
Creates a 1D sub-sampling mask of a given shape. For autocalibration purposes, data points near the k-space center will be fully sampled within an ellipse of which the half-axes will set to the set scale % of the fully sampled region. ... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class Gaussian1DMaskFunc:
"""Creates a 1D sub-sampling mask of a given shape. For autocalibration purposes, data points near the k-space center will be fully sampled within an ellipse of which the half-axes will set to the set scale % of the fully sampled region. The remaining points will be sampled ac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Gaussian1DMaskFunc:
"""Creates a 1D sub-sampling mask of a given shape. For autocalibration purposes, data points near the k-space center will be fully sampled within an ellipse of which the half-axes will set to the set scale % of the fully sampled region. The remaining points will be sampled according to a ... | the_stack_v2_python_sparse | mridc/collections/reconstruction/data/subsample.py | wdika/mridc | train | 40 |
58f3b45fac30f641fcad0fd8f9fc39eacd3187a1 | [
"super().__init__()\nself.ensemble_size = args.size_rm_ensemble\nassert self.ensemble_size >= 2\nfor ensemble_num in range(self.ensemble_size):\n setattr(self, 'layers{}'.format(ensemble_num), nn.Sequential(nn.Linear(state_size + action_size, args.hid_units_rm), nn.ReLU(), nn.Dropout(args.p_dropout_rm), nn.Linea... | <|body_start_0|>
super().__init__()
self.ensemble_size = args.size_rm_ensemble
assert self.ensemble_size >= 2
for ensemble_num in range(self.ensemble_size):
setattr(self, 'layers{}'.format(ensemble_num), nn.Sequential(nn.Linear(state_size + action_size, args.hid_units_rm), nn... | Parameterises r_hat : states x actions -> real rewards Approximation of true reward, trained by supervised learning on preferences over trajectory segments as in Christiano et al. 2017 Ouput is an average of `args.size_rm_ensemble` networks TODO double check this is how Christiano actually implements it. | RewardModelEnsembleOld | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RewardModelEnsembleOld:
"""Parameterises r_hat : states x actions -> real rewards Approximation of true reward, trained by supervised learning on preferences over trajectory segments as in Christiano et al. 2017 Ouput is an average of `args.size_rm_ensemble` networks TODO double check this is how... | stack_v2_sparse_classes_36k_train_000678 | 30,496 | no_license | [
{
"docstring": "Feedforward NN with 2 hidden layers",
"name": "__init__",
"signature": "def __init__(self, state_size, action_size, args)"
},
{
"docstring": "Returns the average output from forward pass through each network in the ensemble.",
"name": "forward",
"signature": "def forward(... | 4 | stack_v2_sparse_classes_30k_train_019251 | Implement the Python class `RewardModelEnsembleOld` described below.
Class description:
Parameterises r_hat : states x actions -> real rewards Approximation of true reward, trained by supervised learning on preferences over trajectory segments as in Christiano et al. 2017 Ouput is an average of `args.size_rm_ensemble`... | Implement the Python class `RewardModelEnsembleOld` described below.
Class description:
Parameterises r_hat : states x actions -> real rewards Approximation of true reward, trained by supervised learning on preferences over trajectory segments as in Christiano et al. 2017 Ouput is an average of `args.size_rm_ensemble`... | baba7ffbbda9b1bbba9dc1d33df7857fa845c42e | <|skeleton|>
class RewardModelEnsembleOld:
"""Parameterises r_hat : states x actions -> real rewards Approximation of true reward, trained by supervised learning on preferences over trajectory segments as in Christiano et al. 2017 Ouput is an average of `args.size_rm_ensemble` networks TODO double check this is how... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RewardModelEnsembleOld:
"""Parameterises r_hat : states x actions -> real rewards Approximation of true reward, trained by supervised learning on preferences over trajectory segments as in Christiano et al. 2017 Ouput is an average of `args.size_rm_ensemble` networks TODO double check this is how Christiano a... | the_stack_v2_python_sparse | reward_learning.py | samsarana/active-reward-modelling | train | 0 |
c971cb1e0e7b9b07e6904e3d57f5607543dad4bc | [
"self.assertEqual(datetime.datetime(2013, 2, 14, 0, 0), inspector.extract_YYYYMMDD('rbspa_pre_ect-hope-L1_20130214_v1.0.0.cdf'))\nself.assertEqual(None, inspector.extract_YYYYMMDD('rbspa_pre_ect-hope-L1_20130231_v1.0.0.cdf'))\nself.assertEqual(None, inspector.extract_YYYYMMDD('rbspa_pre_ect-hope-L1_19520201_v1.0.0.... | <|body_start_0|>
self.assertEqual(datetime.datetime(2013, 2, 14, 0, 0), inspector.extract_YYYYMMDD('rbspa_pre_ect-hope-L1_20130214_v1.0.0.cdf'))
self.assertEqual(None, inspector.extract_YYYYMMDD('rbspa_pre_ect-hope-L1_20130231_v1.0.0.cdf'))
self.assertEqual(None, inspector.extract_YYYYMMDD('rbsp... | Tests of the inspector functions | InspectorFunctions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InspectorFunctions:
"""Tests of the inspector functions"""
def test_extract_YYYYMMDD(self):
"""extract_YYYYMMDD works"""
<|body_0|>
def test_extract_YYYYMM(self):
"""extract_YYYYMM works"""
<|body_1|>
def test_valid_YYYYMMDD(self):
"""valid_Y... | stack_v2_sparse_classes_36k_train_000679 | 7,654 | no_license | [
{
"docstring": "extract_YYYYMMDD works",
"name": "test_extract_YYYYMMDD",
"signature": "def test_extract_YYYYMMDD(self)"
},
{
"docstring": "extract_YYYYMM works",
"name": "test_extract_YYYYMM",
"signature": "def test_extract_YYYYMM(self)"
},
{
"docstring": "valid_YYYYMMDD works",... | 4 | null | Implement the Python class `InspectorFunctions` described below.
Class description:
Tests of the inspector functions
Method signatures and docstrings:
- def test_extract_YYYYMMDD(self): extract_YYYYMMDD works
- def test_extract_YYYYMM(self): extract_YYYYMM works
- def test_valid_YYYYMMDD(self): valid_YYYYMMDD works
-... | Implement the Python class `InspectorFunctions` described below.
Class description:
Tests of the inspector functions
Method signatures and docstrings:
- def test_extract_YYYYMMDD(self): extract_YYYYMMDD works
- def test_extract_YYYYMM(self): extract_YYYYMM works
- def test_valid_YYYYMMDD(self): valid_YYYYMMDD works
-... | a0bf5e682fb917bb707b4f66787b0ecb860efce1 | <|skeleton|>
class InspectorFunctions:
"""Tests of the inspector functions"""
def test_extract_YYYYMMDD(self):
"""extract_YYYYMMDD works"""
<|body_0|>
def test_extract_YYYYMM(self):
"""extract_YYYYMM works"""
<|body_1|>
def test_valid_YYYYMMDD(self):
"""valid_Y... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InspectorFunctions:
"""Tests of the inspector functions"""
def test_extract_YYYYMMDD(self):
"""extract_YYYYMMDD works"""
self.assertEqual(datetime.datetime(2013, 2, 14, 0, 0), inspector.extract_YYYYMMDD('rbspa_pre_ect-hope-L1_20130214_v1.0.0.cdf'))
self.assertEqual(None, inspector... | the_stack_v2_python_sparse | unit_tests/test_Inspector.py | spacepy/dbprocessing | train | 4 |
0ee75d1cb0c2ffda643eefceff4ee0609ba19433 | [
"if self.status == CONTENT_STATUS_PUBLISHED:\n return True\nreturn False",
"if self.link_menu == CONTENT_STATUS_PUBLISHED:\n return True\nreturn False",
"if self.type == EVENT_BLOCK_TYPE_CONTENT:\n return True\nreturn False",
"if self.type == EVENT_BLOCK_TYPE_PROGRAMATION:\n return True\nreturn Fa... | <|body_start_0|>
if self.status == CONTENT_STATUS_PUBLISHED:
return True
return False
<|end_body_0|>
<|body_start_1|>
if self.link_menu == CONTENT_STATUS_PUBLISHED:
return True
return False
<|end_body_1|>
<|body_start_2|>
if self.type == EVENT_BLOCK_TYPE... | Model de ligação dos blocos com Eventos | EventBlock | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventBlock:
"""Model de ligação dos blocos com Eventos"""
def is_published(self):
""":return: True se status == 2 (Publicado)"""
<|body_0|>
def show_link_menu(self):
""":return: True se status == 2 (Publicado)"""
<|body_1|>
def is_type_content(self):... | stack_v2_sparse_classes_36k_train_000680 | 14,093 | permissive | [
{
"docstring": ":return: True se status == 2 (Publicado)",
"name": "is_published",
"signature": "def is_published(self)"
},
{
"docstring": ":return: True se status == 2 (Publicado)",
"name": "show_link_menu",
"signature": "def show_link_menu(self)"
},
{
"docstring": ":return: Tru... | 4 | stack_v2_sparse_classes_30k_train_017044 | Implement the Python class `EventBlock` described below.
Class description:
Model de ligação dos blocos com Eventos
Method signatures and docstrings:
- def is_published(self): :return: True se status == 2 (Publicado)
- def show_link_menu(self): :return: True se status == 2 (Publicado)
- def is_type_content(self): :re... | Implement the Python class `EventBlock` described below.
Class description:
Model de ligação dos blocos com Eventos
Method signatures and docstrings:
- def is_published(self): :return: True se status == 2 (Publicado)
- def show_link_menu(self): :return: True se status == 2 (Publicado)
- def is_type_content(self): :re... | 14b6a7a47e75d6b6f8ca44fc0eb1cca500e0eecb | <|skeleton|>
class EventBlock:
"""Model de ligação dos blocos com Eventos"""
def is_published(self):
""":return: True se status == 2 (Publicado)"""
<|body_0|>
def show_link_menu(self):
""":return: True se status == 2 (Publicado)"""
<|body_1|>
def is_type_content(self):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventBlock:
"""Model de ligação dos blocos com Eventos"""
def is_published(self):
""":return: True se status == 2 (Publicado)"""
if self.status == CONTENT_STATUS_PUBLISHED:
return True
return False
def show_link_menu(self):
""":return: True se status == 2 ... | the_stack_v2_python_sparse | events/models.py | roberzguerra/rover | train | 2 |
483694a4fa3d2c44aa8260a9ef5f5787027ff8c6 | [
"from OpenGLContext import tests\nfrom OpenGLContext.tests.resources import test_vrml_set_txt\nbase = os.path.join(os.path.dirname(tests.__file__), 'wrls', '*.wrl')\npaths = glob.glob(base)\nfileMenu = glutCreateMenu(self.OnMenuLoad)\nfor path in paths:\n self.worldPaths.append(path)\n index = len(self.worldP... | <|body_start_0|>
from OpenGLContext import tests
from OpenGLContext.tests.resources import test_vrml_set_txt
base = os.path.join(os.path.dirname(tests.__file__), 'wrls', '*.wrl')
paths = glob.glob(base)
fileMenu = glutCreateMenu(self.OnMenuLoad)
for path in paths:
... | GLUT-specific VRML97-aware Testing Context | VRMLContext | [
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VRMLContext:
"""GLUT-specific VRML97-aware Testing Context"""
def createMenus(self):
"""Create pop-up menus for the VRML97 context"""
<|body_0|>
def OnMenuLoad(self, item):
"""React to a menu-load event"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_000681 | 1,838 | permissive | [
{
"docstring": "Create pop-up menus for the VRML97 context",
"name": "createMenus",
"signature": "def createMenus(self)"
},
{
"docstring": "React to a menu-load event",
"name": "OnMenuLoad",
"signature": "def OnMenuLoad(self, item)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013908 | Implement the Python class `VRMLContext` described below.
Class description:
GLUT-specific VRML97-aware Testing Context
Method signatures and docstrings:
- def createMenus(self): Create pop-up menus for the VRML97 context
- def OnMenuLoad(self, item): React to a menu-load event | Implement the Python class `VRMLContext` described below.
Class description:
GLUT-specific VRML97-aware Testing Context
Method signatures and docstrings:
- def createMenus(self): Create pop-up menus for the VRML97 context
- def OnMenuLoad(self, item): React to a menu-load event
<|skeleton|>
class VRMLContext:
""... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class VRMLContext:
"""GLUT-specific VRML97-aware Testing Context"""
def createMenus(self):
"""Create pop-up menus for the VRML97 context"""
<|body_0|>
def OnMenuLoad(self, item):
"""React to a menu-load event"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VRMLContext:
"""GLUT-specific VRML97-aware Testing Context"""
def createMenus(self):
"""Create pop-up menus for the VRML97 context"""
from OpenGLContext import tests
from OpenGLContext.tests.resources import test_vrml_set_txt
base = os.path.join(os.path.dirname(tests.__fil... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/glutvrmltestingcontext.py | alexus37/AugmentedRealityChess | train | 1 |
336e8389a38a99de63858c825c5e712b0868ccfd | [
"self.snake = collections.deque([(0, 0)])\nself.s = set([(0, 0)])\nself.width = width\nself.height = height\nself.food = food\nself.idx = 0",
"head_r, head_c = self.snake[0]\ntail = self.snake.pop()\nself.s.remove(tail)\nif direction == 'U':\n head_r -= 1\nelif direction == 'D':\n head_r += 1\nelif directio... | <|body_start_0|>
self.snake = collections.deque([(0, 0)])
self.s = set([(0, 0)])
self.width = width
self.height = height
self.food = food
self.idx = 0
<|end_body_0|>
<|body_start_1|>
head_r, head_c = self.snake[0]
tail = self.snake.pop()
self.s.re... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_36k_train_000682 | 2,074 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]",
... | 2 | null | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | fe79161211cc08c269cde9e1fdcfed27de11f2cb | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :... | the_stack_v2_python_sparse | MyLeetCode/python/Design Snake Game.py | ihuei801/leetcode | train | 0 | |
02055af1047f82e7b662c7dcc569fd8084496232 | [
"self.ndims = ndims\nself.W_init = W_init\nself.W0 = None\nif W_init == 'zeros':\n self.W0 = tf.zeros([self.ndims + 1, 1], dtype=tf.float64)\nelif W_init == 'ones':\n self.W0 = tf.ones([self.ndims + 1, 1], dtype=tf.float64)\nelif W_init == 'uniform':\n self.W0 = tf.random_uniform([self.ndims + 1, 1], 0, 1,... | <|body_start_0|>
self.ndims = ndims
self.W_init = W_init
self.W0 = None
if W_init == 'zeros':
self.W0 = tf.zeros([self.ndims + 1, 1], dtype=tf.float64)
elif W_init == 'ones':
self.W0 = tf.ones([self.ndims + 1, 1], dtype=tf.float64)
elif W_init == '... | LogisticModel_TF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogisticModel_TF:
def __init__(self, ndims, W_init='zeros'):
"""Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector, self.W, based on the method specified in W_init. We assume that the FIRST index of Weight is the bias t... | stack_v2_sparse_classes_36k_train_000683 | 4,070 | no_license | [
{
"docstring": "Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector, self.W, based on the method specified in W_init. We assume that the FIRST index of Weight is the bias term, Weight = [Bias, W1, W2, W3, ...] where Wi correspnds to each featur... | 3 | stack_v2_sparse_classes_30k_train_015578 | Implement the Python class `LogisticModel_TF` described below.
Class description:
Implement the LogisticModel_TF class.
Method signatures and docstrings:
- def __init__(self, ndims, W_init='zeros'): Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector... | Implement the Python class `LogisticModel_TF` described below.
Class description:
Implement the LogisticModel_TF class.
Method signatures and docstrings:
- def __init__(self, ndims, W_init='zeros'): Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector... | 7726edd466bc8986a50b1e13590c132065ccb64d | <|skeleton|>
class LogisticModel_TF:
def __init__(self, ndims, W_init='zeros'):
"""Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector, self.W, based on the method specified in W_init. We assume that the FIRST index of Weight is the bias t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogisticModel_TF:
def __init__(self, ndims, W_init='zeros'):
"""Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector, self.W, based on the method specified in W_init. We assume that the FIRST index of Weight is the bias term, Weight = ... | the_stack_v2_python_sparse | MachineProblems/3_BinaryClassification/mp3/codefromtf/logistic_model.py | namanUIUC/MachineLearning | train | 10 | |
dda4d6fdf84bc343cdbe94d0be98fc87c12a55ef | [
"assert verifiers, 'At least one verifier is required'\nif __debug__:\n for verifier in verifiers:\n assert isinstance(verifier, IVerifier), 'Invalid verifier %s' % verifier\nself.verifiers = verifiers",
"for verifier in self.verifiers:\n assert isinstance(verifier, IVerifier), 'Invalid verifier %s' ... | <|body_start_0|>
assert verifiers, 'At least one verifier is required'
if __debug__:
for verifier in verifiers:
assert isinstance(verifier, IVerifier), 'Invalid verifier %s' % verifier
self.verifiers = verifiers
<|end_body_0|>
<|body_start_1|>
for verifier in... | Implementation for a @see: IVerifier that aplies an 'and' operator between verifiers. | VerifierAnd | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerifierAnd:
"""Implementation for a @see: IVerifier that aplies an 'and' operator between verifiers."""
def __init__(self, *verifiers):
"""Construct the 'and' verifier. @param verifiers: arguments[IVerifier] The verifiers to apply the 'and' for."""
<|body_0|>
def prepar... | stack_v2_sparse_classes_36k_train_000684 | 15,633 | no_license | [
{
"docstring": "Construct the 'and' verifier. @param verifiers: arguments[IVerifier] The verifiers to apply the 'and' for.",
"name": "__init__",
"signature": "def __init__(self, *verifiers)"
},
{
"docstring": "@see: IVerifier.prepare",
"name": "prepare",
"signature": "def prepare(self, r... | 3 | null | Implement the Python class `VerifierAnd` described below.
Class description:
Implementation for a @see: IVerifier that aplies an 'and' operator between verifiers.
Method signatures and docstrings:
- def __init__(self, *verifiers): Construct the 'and' verifier. @param verifiers: arguments[IVerifier] The verifiers to a... | Implement the Python class `VerifierAnd` described below.
Class description:
Implementation for a @see: IVerifier that aplies an 'and' operator between verifiers.
Method signatures and docstrings:
- def __init__(self, *verifiers): Construct the 'and' verifier. @param verifiers: arguments[IVerifier] The verifiers to a... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class VerifierAnd:
"""Implementation for a @see: IVerifier that aplies an 'and' operator between verifiers."""
def __init__(self, *verifiers):
"""Construct the 'and' verifier. @param verifiers: arguments[IVerifier] The verifiers to apply the 'and' for."""
<|body_0|>
def prepar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VerifierAnd:
"""Implementation for a @see: IVerifier that aplies an 'and' operator between verifiers."""
def __init__(self, *verifiers):
"""Construct the 'and' verifier. @param verifiers: arguments[IVerifier] The verifiers to apply the 'and' for."""
assert verifiers, 'At least one verifie... | the_stack_v2_python_sparse | components/ally-core/ally/core/impl/definition.py | cristidomsa/Ally-Py | train | 0 |
c00fe289eb2b02751a4404bf79361e1a4a5837bc | [
"try:\n sport = self.kwargs['sport']\nexcept KeyError:\n sport = 'nba'\nsite_sport_manager = sports.classes.SiteSportManager()\ninjury_serializer_class = site_sport_manager.get_injury_serializer_class(sport)\nreturn injury_serializer_class",
"sport = self.kwargs['sport']\nsite_sport_manager = sports.classes... | <|body_start_0|>
try:
sport = self.kwargs['sport']
except KeyError:
sport = 'nba'
site_sport_manager = sports.classes.SiteSportManager()
injury_serializer_class = site_sport_manager.get_injury_serializer_class(sport)
return injury_serializer_class
<|end_bo... | Retrieve the contests which are relevant to the home page lobby. | LeagueInjuryAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeagueInjuryAPIView:
"""Retrieve the contests which are relevant to the home page lobby."""
def get_serializer_class(self):
"""override for having to set the self.serializer_class"""
<|body_0|>
def get_queryset(self):
"""Return a QuerySet from the LobbyContest mo... | stack_v2_sparse_classes_36k_train_000685 | 26,966 | no_license | [
{
"docstring": "override for having to set the self.serializer_class",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Return a QuerySet from the LobbyContest model.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
}
] | 2 | null | Implement the Python class `LeagueInjuryAPIView` described below.
Class description:
Retrieve the contests which are relevant to the home page lobby.
Method signatures and docstrings:
- def get_serializer_class(self): override for having to set the self.serializer_class
- def get_queryset(self): Return a QuerySet fro... | Implement the Python class `LeagueInjuryAPIView` described below.
Class description:
Retrieve the contests which are relevant to the home page lobby.
Method signatures and docstrings:
- def get_serializer_class(self): override for having to set the self.serializer_class
- def get_queryset(self): Return a QuerySet fro... | 4796fa9d88b56f80def011e2b043ce595bfce8c4 | <|skeleton|>
class LeagueInjuryAPIView:
"""Retrieve the contests which are relevant to the home page lobby."""
def get_serializer_class(self):
"""override for having to set the self.serializer_class"""
<|body_0|>
def get_queryset(self):
"""Return a QuerySet from the LobbyContest mo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LeagueInjuryAPIView:
"""Retrieve the contests which are relevant to the home page lobby."""
def get_serializer_class(self):
"""override for having to set the self.serializer_class"""
try:
sport = self.kwargs['sport']
except KeyError:
sport = 'nba'
s... | the_stack_v2_python_sparse | sports/views.py | nakamotohideyoshi/draftboard-web | train | 0 |
7f2871ad81c9da99a9dd494f9d4d693184b1d338 | [
"greater_dict = {}\nstack = []\nresult = []\nfor num in nums2:\n while len(stack) > 0 and stack[-1] < num:\n greater_dict[stack.pop(-1)] = num\n stack.append(num)\nwhile len(stack) > 0:\n greater_dict[stack.pop(-1)] = -1\nfor num in nums1:\n result.append(greater_dict[num])\nreturn result",
"re... | <|body_start_0|>
greater_dict = {}
stack = []
result = []
for num in nums2:
while len(stack) > 0 and stack[-1] < num:
greater_dict[stack.pop(-1)] = num
stack.append(num)
while len(stack) > 0:
greater_dict[stack.pop(-1)] = -1
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def next_greater_element(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 结果数组"""
<|body_0|>
def next_greater_element_2(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""获取比较大的数组 Args: nums1: ... | stack_v2_sparse_classes_36k_train_000686 | 3,320 | permissive | [
{
"docstring": "获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 结果数组",
"name": "next_greater_element",
"signature": "def next_greater_element(self, nums1: List[int], nums2: List[int]) -> List[int]"
},
{
"docstring": "获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 新数组",
"name": "next_greater_ele... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def next_greater_element(self, nums1: List[int], nums2: List[int]) -> List[int]: 获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 结果数组
- def next_greater_element_2(self, nums1: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def next_greater_element(self, nums1: List[int], nums2: List[int]) -> List[int]: 获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 结果数组
- def next_greater_element_2(self, nums1: List... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def next_greater_element(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 结果数组"""
<|body_0|>
def next_greater_element_2(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""获取比较大的数组 Args: nums1: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def next_greater_element(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""获取比较大的数组 Args: nums1: 数组1 nums2: 数组2 Returns: 结果数组"""
greater_dict = {}
stack = []
result = []
for num in nums2:
while len(stack) > 0 and stack[-1] < num:
... | the_stack_v2_python_sparse | src/leetcodepython/array/next_greater_element_496.py | zhangyu345293721/leetcode | train | 101 | |
b8b832569013798675759bc655a99921a8b03b4a | [
"print(1)\nif 'localhost:8000' == 'localhost:8000':\n from boost.models import EngageboostCompanies\n print(socket.gethostbyname(socket.gethostname()))\n host = socket.gethostbyname(socket.gethostname())\n user = EngageboostCompanies.objects.get(db_host=host)\n print(user.query)\nelse:\n from boos... | <|body_start_0|>
print(1)
if 'localhost:8000' == 'localhost:8000':
from boost.models import EngageboostCompanies
print(socket.gethostbyname(socket.gethostname()))
host = socket.gethostbyname(socket.gethostname())
user = EngageboostCompanies.objects.get(db_... | DatabaseRouter | [] | 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|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_000687 | 4,755 | no_license | [
{
"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... | 2 | null | 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... | 6b084547bed2af43a67bada313d68e56f4228f96 | <|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|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatabaseRouter:
def db_for_read(self, model, **hints):
""""Point all read operations to the specific database."""
print(1)
if 'localhost:8000' == 'localhost:8000':
from boost.models import EngageboostCompanies
print(socket.gethostbyname(socket.gethostname()))
... | the_stack_v2_python_sparse | settings/routers.py | obxlifco/Web-Picking-App-GoGrocery | train | 0 | |
edb1fdf69cc56d077585116e38f053c168f82b0c | [
"super(DMCM, self).__init__()\nself.conv_net = cfg.get_image_net(mode)\nself.sparse_net = cfg.get_genes_net(mode)\nself.conv_net.apply(_init_weights_xavier)",
"x1, x2 = x\ny1 = self.conv_net.forward(x1)\ny2 = self.sparse_net.forward(x2)\nreturn (y1, y2)"
] | <|body_start_0|>
super(DMCM, self).__init__()
self.conv_net = cfg.get_image_net(mode)
self.sparse_net = cfg.get_genes_net(mode)
self.conv_net.apply(_init_weights_xavier)
<|end_body_0|>
<|body_start_1|>
x1, x2 = x
y1 = self.conv_net.forward(x1)
y2 = self.sparse_ne... | DMCM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DMCM:
def __init__(self, mode, cfg):
"""Initialize model for Deep Multimodal Correlation Maximization."""
<|body_0|>
def forward(self, x):
"""Perform forward pass of images and associated signal through model. Output embeddings y1, y2."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_000688 | 1,803 | no_license | [
{
"docstring": "Initialize model for Deep Multimodal Correlation Maximization.",
"name": "__init__",
"signature": "def __init__(self, mode, cfg)"
},
{
"docstring": "Perform forward pass of images and associated signal through model. Output embeddings y1, y2.",
"name": "forward",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_014839 | Implement the Python class `DMCM` described below.
Class description:
Implement the DMCM class.
Method signatures and docstrings:
- def __init__(self, mode, cfg): Initialize model for Deep Multimodal Correlation Maximization.
- def forward(self, x): Perform forward pass of images and associated signal through model. ... | Implement the Python class `DMCM` described below.
Class description:
Implement the DMCM class.
Method signatures and docstrings:
- def __init__(self, mode, cfg): Initialize model for Deep Multimodal Correlation Maximization.
- def forward(self, x): Perform forward pass of images and associated signal through model. ... | 1b65fc0c3ec6b182907ba070e859c1d92fc98942 | <|skeleton|>
class DMCM:
def __init__(self, mode, cfg):
"""Initialize model for Deep Multimodal Correlation Maximization."""
<|body_0|>
def forward(self, x):
"""Perform forward pass of images and associated signal through model. Output embeddings y1, y2."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DMCM:
def __init__(self, mode, cfg):
"""Initialize model for Deep Multimodal Correlation Maximization."""
super(DMCM, self).__init__()
self.conv_net = cfg.get_image_net(mode)
self.sparse_net = cfg.get_genes_net(mode)
self.conv_net.apply(_init_weights_xavier)
def fo... | the_stack_v2_python_sparse | models/dmcm.py | KaiqianZhang/dpcca_v8 | train | 1 | |
dbd1966f12f478084828631a07659d29c6961a41 | [
"queryset = self.filter_queryset(self.get_queryset())\ndata = {'count': queryset.count()}\nreturn Response(data)",
"groups = request.query_params.getlist('group')\nif not groups:\n return Response({'detail': _('Missing group.')}, status.HTTP_400_BAD_REQUEST)\nif not set(groups).issubset(self.group_by_fields):\... | <|body_start_0|>
queryset = self.filter_queryset(self.get_queryset())
data = {'count': queryset.count()}
return Response(data)
<|end_body_0|>
<|body_start_1|>
groups = request.query_params.getlist('group')
if not groups:
return Response({'detail': _('Missing group.')... | Clients Profiles. | ProfileViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileViewSet:
"""Clients Profiles."""
def total(self, request, *args, **kwargs):
"""Get total number of clients profiles."""
<|body_0|>
def count(self, request, *args, **kwargs):
"""Count clients profiles by group."""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_000689 | 2,671 | permissive | [
{
"docstring": "Get total number of clients profiles.",
"name": "total",
"signature": "def total(self, request, *args, **kwargs)"
},
{
"docstring": "Count clients profiles by group.",
"name": "count",
"signature": "def count(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `ProfileViewSet` described below.
Class description:
Clients Profiles.
Method signatures and docstrings:
- def total(self, request, *args, **kwargs): Get total number of clients profiles.
- def count(self, request, *args, **kwargs): Count clients profiles by group. | Implement the Python class `ProfileViewSet` described below.
Class description:
Clients Profiles.
Method signatures and docstrings:
- def total(self, request, *args, **kwargs): Get total number of clients profiles.
- def count(self, request, *args, **kwargs): Count clients profiles by group.
<|skeleton|>
class Profi... | db7dfa7f89174be07d42bd469fd23c8553c0eff2 | <|skeleton|>
class ProfileViewSet:
"""Clients Profiles."""
def total(self, request, *args, **kwargs):
"""Get total number of clients profiles."""
<|body_0|>
def count(self, request, *args, **kwargs):
"""Count clients profiles by group."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileViewSet:
"""Clients Profiles."""
def total(self, request, *args, **kwargs):
"""Get total number of clients profiles."""
queryset = self.filter_queryset(self.get_queryset())
data = {'count': queryset.count()}
return Response(data)
def count(self, request, *args,... | the_stack_v2_python_sparse | hivs_clients/api/views.py | tehamalab/hivs | train | 0 |
f890657798f8bd65bd49c3c26d5124905ada60fa | [
"super(Graz, self).__init__(**kwargs)\nself.base_dir = base_dir\nself.data_id = identifier\nself.data_dir = base_dir\nself.trial_len = trail_len\nself.cue_interval = cue_interval\nself.trial_offset = trial_offset\nself.expected_freq = expected_freq\nself.matT = os.path.join(self.data_dir, '{id}T.mat'.format(id=self... | <|body_start_0|>
super(Graz, self).__init__(**kwargs)
self.base_dir = base_dir
self.data_id = identifier
self.data_dir = base_dir
self.trial_len = trail_len
self.cue_interval = cue_interval
self.trial_offset = trial_offset
self.expected_freq = expected_fre... | Graz dataset from BCNI2020 competition. http://bnci-horizon-2020.eu/database/data-sets | Graz | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graz:
"""Graz dataset from BCNI2020 competition. http://bnci-horizon-2020.eu/database/data-sets"""
def __init__(self, base_dir, identifier, trail_len, cue_interval, trial_offset, expected_freq, **kwargs):
"""Init Graz data specifics. trial_len, cue_interval, cue_offset and expected_f... | stack_v2_sparse_classes_36k_train_000690 | 6,110 | no_license | [
{
"docstring": "Init Graz data specifics. trial_len, cue_interval, cue_offset and expected_freq are expected depending on supporting literature.",
"name": "__init__",
"signature": "def __init__(self, base_dir, identifier, trail_len, cue_interval, trial_offset, expected_freq, **kwargs)"
},
{
"doc... | 2 | stack_v2_sparse_classes_30k_train_007006 | Implement the Python class `Graz` described below.
Class description:
Graz dataset from BCNI2020 competition. http://bnci-horizon-2020.eu/database/data-sets
Method signatures and docstrings:
- def __init__(self, base_dir, identifier, trail_len, cue_interval, trial_offset, expected_freq, **kwargs): Init Graz data spec... | Implement the Python class `Graz` described below.
Class description:
Graz dataset from BCNI2020 competition. http://bnci-horizon-2020.eu/database/data-sets
Method signatures and docstrings:
- def __init__(self, base_dir, identifier, trail_len, cue_interval, trial_offset, expected_freq, **kwargs): Init Graz data spec... | f3db33eb2e0f291f789aa8e4d947633623163781 | <|skeleton|>
class Graz:
"""Graz dataset from BCNI2020 competition. http://bnci-horizon-2020.eu/database/data-sets"""
def __init__(self, base_dir, identifier, trail_len, cue_interval, trial_offset, expected_freq, **kwargs):
"""Init Graz data specifics. trial_len, cue_interval, cue_offset and expected_f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Graz:
"""Graz dataset from BCNI2020 competition. http://bnci-horizon-2020.eu/database/data-sets"""
def __init__(self, base_dir, identifier, trail_len, cue_interval, trial_offset, expected_freq, **kwargs):
"""Init Graz data specifics. trial_len, cue_interval, cue_offset and expected_freq are expec... | the_stack_v2_python_sparse | utils/graz.py | eeshakumar/bci-incremental-learning | train | 0 |
53350caf95a171426d7a7f097d25bab754840907 | [
"for i in range(k):\n min_j = 0\n min_v = nums[0]\n for j in range(1, len(nums)):\n if nums[j] < min_v:\n min_v = nums[j]\n min_j = j\n nums[min_j] = -nums[min_j]\nreturn sum(nums)",
"nums = sorted(nums, key=abs, reverse=True)\nfor i in range(len(nums)):\n if nums[i] < ... | <|body_start_0|>
for i in range(k):
min_j = 0
min_v = nums[0]
for j in range(1, len(nums)):
if nums[j] < min_v:
min_v = nums[j]
min_j = j
nums[min_j] = -nums[min_j]
return sum(nums)
<|end_body_0|>
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestSumAfterKNegations0(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def largestSumAfterKNegations(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_000691 | 991 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "largestSumAfterKNegations0",
"signature": "def largestSumAfterKNegations0(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "largestSumAfterKNegations",
"signature": "def l... | 2 | stack_v2_sparse_classes_30k_train_001554 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestSumAfterKNegations0(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def largestSumAfterKNegations(self, nums, k): :type nums: List[int] :type k: int :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestSumAfterKNegations0(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def largestSumAfterKNegations(self, nums, k): :type nums: List[int] :type k: int :... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def largestSumAfterKNegations0(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def largestSumAfterKNegations(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestSumAfterKNegations0(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
for i in range(k):
min_j = 0
min_v = nums[0]
for j in range(1, len(nums)):
if nums[j] < min_v:
min_v = nums[j]
... | the_stack_v2_python_sparse | 1005.k-次取反后最大化的数组和.py | yangyuxiang1996/leetcode | train | 0 | |
4cfaadc222287c9f1dae83ff99d4dd7b28b5685f | [
"if not root:\n return\nstack = [root]\nwhile stack:\n l = len(stack)\n for i in range(l):\n cur = stack.pop(0)\n if i < l - 1:\n cur.next = stack[0]\n if cur.left:\n stack.append(cur.left)\n if cur.right:\n stack.append(cur.right)\nreturn",
"i... | <|body_start_0|>
if not root:
return
stack = [root]
while stack:
l = len(stack)
for i in range(l):
cur = stack.pop(0)
if i < l - 1:
cur.next = stack[0]
if cur.left:
stack.a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def connect(self, root):
"""层次遍历,连接每一层的节点 :param root: TreeLinkNode :return:"""
<|body_0|>
def connect2(self, root):
"""迭代 :param root: TreeLinkNode :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return
... | stack_v2_sparse_classes_36k_train_000692 | 2,535 | no_license | [
{
"docstring": "层次遍历,连接每一层的节点 :param root: TreeLinkNode :return:",
"name": "connect",
"signature": "def connect(self, root)"
},
{
"docstring": "迭代 :param root: TreeLinkNode :return:",
"name": "connect2",
"signature": "def connect2(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): 层次遍历,连接每一层的节点 :param root: TreeLinkNode :return:
- def connect2(self, root): 迭代 :param root: TreeLinkNode :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): 层次遍历,连接每一层的节点 :param root: TreeLinkNode :return:
- def connect2(self, root): 迭代 :param root: TreeLinkNode :return:
<|skeleton|>
class Solution:
def... | 4f2802d4773eddd2a2e06e61c51463056886b730 | <|skeleton|>
class Solution:
def connect(self, root):
"""层次遍历,连接每一层的节点 :param root: TreeLinkNode :return:"""
<|body_0|>
def connect2(self, root):
"""迭代 :param root: TreeLinkNode :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def connect(self, root):
"""层次遍历,连接每一层的节点 :param root: TreeLinkNode :return:"""
if not root:
return
stack = [root]
while stack:
l = len(stack)
for i in range(l):
cur = stack.pop(0)
if i < l - 1:
... | the_stack_v2_python_sparse | leetcode2/66_connect.py | Yara7L/python_algorithm | train | 0 | |
60ac777be2061c85c3a7594aeddbacd789211a47 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AndroidWorkProfileCompliancePolicy()",
"from .android_required_password_type import AndroidRequiredPasswordType\nfrom .device_compliance_policy import DeviceCompliancePolicy\nfrom .device_threat_protection_level import DeviceThreatProt... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AndroidWorkProfileCompliancePolicy()
<|end_body_0|>
<|body_start_1|>
from .android_required_password_type import AndroidRequiredPasswordType
from .device_compliance_policy import DeviceC... | This class contains compliance settings for Android Work Profile. | AndroidWorkProfileCompliancePolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AndroidWorkProfileCompliancePolicy:
"""This class contains compliance settings for Android Work Profile."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AndroidWorkProfileCompliancePolicy:
"""Creates a new instance of the appropriate class based on dis... | stack_v2_sparse_classes_36k_train_000693 | 10,288 | 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: AndroidWorkProfileCompliancePolicy",
"name": "create_from_discriminator_value",
"signature": "def create_fro... | 3 | stack_v2_sparse_classes_30k_train_011506 | Implement the Python class `AndroidWorkProfileCompliancePolicy` described below.
Class description:
This class contains compliance settings for Android Work Profile.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AndroidWorkProfileCompliancePolicy: Cre... | Implement the Python class `AndroidWorkProfileCompliancePolicy` described below.
Class description:
This class contains compliance settings for Android Work Profile.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AndroidWorkProfileCompliancePolicy: Cre... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AndroidWorkProfileCompliancePolicy:
"""This class contains compliance settings for Android Work Profile."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AndroidWorkProfileCompliancePolicy:
"""Creates a new instance of the appropriate class based on dis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AndroidWorkProfileCompliancePolicy:
"""This class contains compliance settings for Android Work Profile."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AndroidWorkProfileCompliancePolicy:
"""Creates a new instance of the appropriate class based on discriminator va... | the_stack_v2_python_sparse | msgraph/generated/models/android_work_profile_compliance_policy.py | microsoftgraph/msgraph-sdk-python | train | 135 |
809093e99504b513ff3e533745be845795310967 | [
"user = info.context.user\nif not user.is_authenticated or user is None:\n return User.objects.none()\nif user.is_admin or ('ADMIN' in user.auth_roles or 'DEV' in user.auth_roles):\n return User.objects.all()\nreturn [user]",
"user = info.context.user\nif not user.is_authenticated or user is None:\n rais... | <|body_start_0|>
user = info.context.user
if not user.is_authenticated or user is None:
return User.objects.none()
if user.is_admin or ('ADMIN' in user.auth_roles or 'DEV' in user.auth_roles):
return User.objects.all()
return [user]
<|end_body_0|>
<|body_start_1|... | Query | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Query:
def resolve_all_users(self, info, **kwargs):
"""If user is USER, only return that user If user is ADMIN, return all users If user is unauthed, return no users"""
<|body_0|>
def resolve_my_profile(self, info, **kwargs):
"""Return the user that is making the req... | stack_v2_sparse_classes_36k_train_000694 | 3,353 | permissive | [
{
"docstring": "If user is USER, only return that user If user is ADMIN, return all users If user is unauthed, return no users",
"name": "resolve_all_users",
"signature": "def resolve_all_users(self, info, **kwargs)"
},
{
"docstring": "Return the user that is making the request if they are valid... | 2 | stack_v2_sparse_classes_30k_train_002433 | Implement the Python class `Query` described below.
Class description:
Implement the Query class.
Method signatures and docstrings:
- def resolve_all_users(self, info, **kwargs): If user is USER, only return that user If user is ADMIN, return all users If user is unauthed, return no users
- def resolve_my_profile(sel... | Implement the Python class `Query` described below.
Class description:
Implement the Query class.
Method signatures and docstrings:
- def resolve_all_users(self, info, **kwargs): If user is USER, only return that user If user is ADMIN, return all users If user is unauthed, return no users
- def resolve_my_profile(sel... | 52831b2de2e0ce734d567289f3b10d720bce8a9e | <|skeleton|>
class Query:
def resolve_all_users(self, info, **kwargs):
"""If user is USER, only return that user If user is ADMIN, return all users If user is unauthed, return no users"""
<|body_0|>
def resolve_my_profile(self, info, **kwargs):
"""Return the user that is making the req... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Query:
def resolve_all_users(self, info, **kwargs):
"""If user is USER, only return that user If user is ADMIN, return all users If user is unauthed, return no users"""
user = info.context.user
if not user.is_authenticated or user is None:
return User.objects.none()
... | the_stack_v2_python_sparse | coordinator/graphql/users.py | kids-first/kf-api-release-coordinator | train | 2 | |
6b5de90e6a7c0f30c48cb6cf8f5258f4daf6f029 | [
"GPIO.setmode(GPIO.BCM)\nself.keypress_queue = Queue()\nself._row_pins = [22, 23, 24, 25]\nself._column_pins = [4, 5, 6, 13]\nself._matrix = [['1', '2', '3', 'A'], ['4', '5', '6', 'B'], ['7', '8', '9', 'C'], ['*', '0', '#', 'D']]\nfor col in self._column_pins:\n GPIO.setup(col, GPIO.OUT)\n GPIO.output(col, 1)... | <|body_start_0|>
GPIO.setmode(GPIO.BCM)
self.keypress_queue = Queue()
self._row_pins = [22, 23, 24, 25]
self._column_pins = [4, 5, 6, 13]
self._matrix = [['1', '2', '3', 'A'], ['4', '5', '6', 'B'], ['7', '8', '9', 'C'], ['*', '0', '#', 'D']]
for col in self._column_pins:
... | A class used to capture inputs from 4x4 membrane switch Attributes ---------- _row_pins: list[ints] A list of the pin used for inputs for the membrane switch _column_pins: list[ints] A list of the pins used for output columns _matrix: list[list[chars]] A representation of which each button represents on the membrane sw... | Keypad | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Keypad:
"""A class used to capture inputs from 4x4 membrane switch Attributes ---------- _row_pins: list[ints] A list of the pin used for inputs for the membrane switch _column_pins: list[ints] A list of the pins used for output columns _matrix: list[list[chars]] A representation of which each bu... | stack_v2_sparse_classes_36k_train_000695 | 3,606 | permissive | [
{
"docstring": "Initialization of the Keypad object. The only consideration is to make sure the thread is not started before the gpio pins are initialized.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Main processing to capture the keypress and put it into the queue... | 2 | stack_v2_sparse_classes_30k_train_002616 | Implement the Python class `Keypad` described below.
Class description:
A class used to capture inputs from 4x4 membrane switch Attributes ---------- _row_pins: list[ints] A list of the pin used for inputs for the membrane switch _column_pins: list[ints] A list of the pins used for output columns _matrix: list[list[ch... | Implement the Python class `Keypad` described below.
Class description:
A class used to capture inputs from 4x4 membrane switch Attributes ---------- _row_pins: list[ints] A list of the pin used for inputs for the membrane switch _column_pins: list[ints] A list of the pins used for output columns _matrix: list[list[ch... | bcc23ffeee68cad0a86d75995e6d335c24ed9f50 | <|skeleton|>
class Keypad:
"""A class used to capture inputs from 4x4 membrane switch Attributes ---------- _row_pins: list[ints] A list of the pin used for inputs for the membrane switch _column_pins: list[ints] A list of the pins used for output columns _matrix: list[list[chars]] A representation of which each bu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Keypad:
"""A class used to capture inputs from 4x4 membrane switch Attributes ---------- _row_pins: list[ints] A list of the pin used for inputs for the membrane switch _column_pins: list[ints] A list of the pins used for output columns _matrix: list[list[chars]] A representation of which each button represen... | the_stack_v2_python_sparse | code/keypad.py | AdamCorbinFAUPhD/CEN5035-Software-Engineering-Course-Project | train | 0 |
df78e9548770460872b397047f451255f69bf0a2 | [
"self.large = []\nself.small = []\nself.len_large = 0\nself.len_small = 0",
"if self.len_large == self.len_small:\n heappush(self.small, -heappushpop(self.large, num))\n self.len_small += 1\nelse:\n heappush(self.large, -heappushpop(self.small, -num))\n self.len_large += 1",
"if self.len_small == 0:... | <|body_start_0|>
self.large = []
self.small = []
self.len_large = 0
self.len_small = 0
<|end_body_0|>
<|body_start_1|>
if self.len_large == self.len_small:
heappush(self.small, -heappushpop(self.large, num))
self.len_small += 1
else:
h... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_000696 | 1,946 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | stack_v2_sparse_classes_30k_train_005340 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: void
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: void
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | a46b07adec6a8cb7e331e0b985d88cd34a3d5667 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
self.large = []
self.small = []
self.len_large = 0
self.len_small = 0
def addNum(self, num):
""":type num: int :rtype: void"""
if self.len_large == self.len_small:
... | the_stack_v2_python_sparse | 295_Find_Median_from_Data_Stream.py | ZDawang/leetcode | train | 8 | |
e0c7cdf2a0e61f20341632eb84be7f031633a20f | [
"extension_path = os.path.join(util.GetUnittestDataDir(), 'foo')\noptions = options_for_unittests.GetCopy()\nself.assertRaises(extension_to_load.ExtensionPathNonExistentException, lambda: extension_to_load.ExtensionToLoad(extension_path, options.browser_type))",
"extension_path = os.path.join(util.GetUnittestData... | <|body_start_0|>
extension_path = os.path.join(util.GetUnittestDataDir(), 'foo')
options = options_for_unittests.GetCopy()
self.assertRaises(extension_to_load.ExtensionPathNonExistentException, lambda: extension_to_load.ExtensionToLoad(extension_path, options.browser_type))
<|end_body_0|>
<|bod... | NonExistentExtensionTest | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NonExistentExtensionTest:
def testNonExistentExtensionPath(self):
"""Test that a non-existent extension path will raise an exception."""
<|body_0|>
def testExtensionNotLoaded(self):
"""Querying an extension that was not loaded will return None"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_000697 | 9,822 | permissive | [
{
"docstring": "Test that a non-existent extension path will raise an exception.",
"name": "testNonExistentExtensionPath",
"signature": "def testNonExistentExtensionPath(self)"
},
{
"docstring": "Querying an extension that was not loaded will return None",
"name": "testExtensionNotLoaded",
... | 2 | stack_v2_sparse_classes_30k_train_010987 | Implement the Python class `NonExistentExtensionTest` described below.
Class description:
Implement the NonExistentExtensionTest class.
Method signatures and docstrings:
- def testNonExistentExtensionPath(self): Test that a non-existent extension path will raise an exception.
- def testExtensionNotLoaded(self): Query... | Implement the Python class `NonExistentExtensionTest` described below.
Class description:
Implement the NonExistentExtensionTest class.
Method signatures and docstrings:
- def testNonExistentExtensionPath(self): Test that a non-existent extension path will raise an exception.
- def testExtensionNotLoaded(self): Query... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class NonExistentExtensionTest:
def testNonExistentExtensionPath(self):
"""Test that a non-existent extension path will raise an exception."""
<|body_0|>
def testExtensionNotLoaded(self):
"""Querying an extension that was not loaded will return None"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NonExistentExtensionTest:
def testNonExistentExtensionPath(self):
"""Test that a non-existent extension path will raise an exception."""
extension_path = os.path.join(util.GetUnittestDataDir(), 'foo')
options = options_for_unittests.GetCopy()
self.assertRaises(extension_to_load... | the_stack_v2_python_sparse | third_party/catapult/telemetry/telemetry/internal/browser/extension_unittest.py | metux/chromium-suckless | train | 5 | |
74b423b93468700106c28655b932f7d45879815a | [
"super(CommandFailedException, self).__init__()\nself.cmd = cmd\nself.cwd = cwd\nif cwd is None:\n self.cwd = os.getcwd()\nself.returncode = returncode\nself.stdout = stdout\nif stdout is None:\n self.stdout = ''\nself.stderr = stderr\nif stderr is None:\n self.stderr = ''",
"mess = 'The following comman... | <|body_start_0|>
super(CommandFailedException, self).__init__()
self.cmd = cmd
self.cwd = cwd
if cwd is None:
self.cwd = os.getcwd()
self.returncode = returncode
self.stdout = stdout
if stdout is None:
self.stdout = ''
self.stderr =... | Custom exception | CommandFailedException | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandFailedException:
"""Custom exception"""
def __init__(self, cmd, returncode, cwd=None, stdout=None, stderr=None):
"""CommandFailedException Init"""
<|body_0|>
def __str__(self):
"""CommandFailedException String Representation"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_000698 | 22,214 | permissive | [
{
"docstring": "CommandFailedException Init",
"name": "__init__",
"signature": "def __init__(self, cmd, returncode, cwd=None, stdout=None, stderr=None)"
},
{
"docstring": "CommandFailedException String Representation",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `CommandFailedException` described below.
Class description:
Custom exception
Method signatures and docstrings:
- def __init__(self, cmd, returncode, cwd=None, stdout=None, stderr=None): CommandFailedException Init
- def __str__(self): CommandFailedException String Representation | Implement the Python class `CommandFailedException` described below.
Class description:
Custom exception
Method signatures and docstrings:
- def __init__(self, cmd, returncode, cwd=None, stdout=None, stderr=None): CommandFailedException Init
- def __str__(self): CommandFailedException String Representation
<|skeleto... | efea6fa3744664348717fe5e8df708a3cf392072 | <|skeleton|>
class CommandFailedException:
"""Custom exception"""
def __init__(self, cmd, returncode, cwd=None, stdout=None, stderr=None):
"""CommandFailedException Init"""
<|body_0|>
def __str__(self):
"""CommandFailedException String Representation"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommandFailedException:
"""Custom exception"""
def __init__(self, cmd, returncode, cwd=None, stdout=None, stderr=None):
"""CommandFailedException Init"""
super(CommandFailedException, self).__init__()
self.cmd = cmd
self.cwd = cwd
if cwd is None:
self.c... | the_stack_v2_python_sparse | python/qisys/command.py | aldebaran/qibuild | train | 60 |
45670178a9cb2a818193688f7735b5055eafc8fd | [
"EasyFrame.__init__(self, title='Canvas Demo 1')\nself.colors = ('blue', 'green', 'red', 'yellow')\nself.canvas = self.addCanvas(row=0, column=0, width=300, height=150, background='gray')\nself.ovalButton = self.addButton(text='Draw oval', row=1, column=0, command=self.drawOval)",
"x = random.randint(0, 300)\ny =... | <|body_start_0|>
EasyFrame.__init__(self, title='Canvas Demo 1')
self.colors = ('blue', 'green', 'red', 'yellow')
self.canvas = self.addCanvas(row=0, column=0, width=300, height=150, background='gray')
self.ovalButton = self.addButton(text='Draw oval', row=1, column=0, command=self.drawO... | Draws filled ovals on a canvas. | CanvasDemo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanvasDemo:
"""Draws filled ovals on a canvas."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def drawOval(self):
"""Draws a filled oval at a random position."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
EasyFrame.__i... | stack_v2_sparse_classes_36k_train_000699 | 1,178 | no_license | [
{
"docstring": "Sets up the window and widgets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Draws a filled oval at a random position.",
"name": "drawOval",
"signature": "def drawOval(self)"
}
] | 2 | null | Implement the Python class `CanvasDemo` described below.
Class description:
Draws filled ovals on a canvas.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def drawOval(self): Draws a filled oval at a random position. | Implement the Python class `CanvasDemo` described below.
Class description:
Draws filled ovals on a canvas.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def drawOval(self): Draws a filled oval at a random position.
<|skeleton|>
class CanvasDemo:
"""Draws filled ovals ... | eca69d000dc77681a30734b073b2383c97ccc02e | <|skeleton|>
class CanvasDemo:
"""Draws filled ovals on a canvas."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def drawOval(self):
"""Draws a filled oval at a random position."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CanvasDemo:
"""Draws filled ovals on a canvas."""
def __init__(self):
"""Sets up the window and widgets."""
EasyFrame.__init__(self, title='Canvas Demo 1')
self.colors = ('blue', 'green', 'red', 'yellow')
self.canvas = self.addCanvas(row=0, column=0, width=300, height=150,... | the_stack_v2_python_sparse | gui/breezy/canvasdemo1.py | lforet/robomow | train | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.