blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0f9d3537c98abd7f653df332e74165224d9eaaf3 | [
"self.lock = asyncio.Lock()\nsession = aiohttp_client.async_get_clientsession(hass, verify_ssl=False)\nself.requester = AiohttpSessionRequester(session, with_sleep=True)\nself.upnp_factory = UpnpFactory(self.requester, non_strict=True)\nself.event_notifiers = {}\nself.event_notifier_refs = defaultdict(int)",
"LOG... | <|body_start_0|>
self.lock = asyncio.Lock()
session = aiohttp_client.async_get_clientsession(hass, verify_ssl=False)
self.requester = AiohttpSessionRequester(session, with_sleep=True)
self.upnp_factory = UpnpFactory(self.requester, non_strict=True)
self.event_notifiers = {}
... | Storage class for domain global data. | DlnaDmrData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DlnaDmrData:
"""Storage class for domain global data."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize global data."""
<|body_0|>
async def async_cleanup_event_notifiers(self, event: Event) -> None:
"""Clean up resources when Home Assistant is st... | stack_v2_sparse_classes_10k_train_000800 | 5,016 | permissive | [
{
"docstring": "Initialize global data.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant) -> None"
},
{
"docstring": "Clean up resources when Home Assistant is stopped.",
"name": "async_cleanup_event_notifiers",
"signature": "async def async_cleanup_event_notifi... | 4 | null | Implement the Python class `DlnaDmrData` described below.
Class description:
Storage class for domain global data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize global data.
- async def async_cleanup_event_notifiers(self, event: Event) -> None: Clean up resources when... | Implement the Python class `DlnaDmrData` described below.
Class description:
Storage class for domain global data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize global data.
- async def async_cleanup_event_notifiers(self, event: Event) -> None: Clean up resources when... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class DlnaDmrData:
"""Storage class for domain global data."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize global data."""
<|body_0|>
async def async_cleanup_event_notifiers(self, event: Event) -> None:
"""Clean up resources when Home Assistant is st... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DlnaDmrData:
"""Storage class for domain global data."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize global data."""
self.lock = asyncio.Lock()
session = aiohttp_client.async_get_clientsession(hass, verify_ssl=False)
self.requester = AiohttpSessionReques... | the_stack_v2_python_sparse | homeassistant/components/dlna_dmr/data.py | home-assistant/core | train | 35,501 |
b0885d3fa034851753d0eeb9698a7f22fb479700 | [
"if where_clause_type is WhereClauseTypes.Is:\n return '{}{}{} IS {}'.format('NOT ' if negation else '', table_name + '.' if table_name else '', column_name, values[0])\nelif where_clause_type is WhereClauseTypes.In:\n return '{}{}{} IN ({})'.format('NOT ' if negation else '', table_name + '.' if table_name e... | <|body_start_0|>
if where_clause_type is WhereClauseTypes.Is:
return '{}{}{} IS {}'.format('NOT ' if negation else '', table_name + '.' if table_name else '', column_name, values[0])
elif where_clause_type is WhereClauseTypes.In:
return '{}{}{} IN ({})'.format('NOT ' if negation ... | WhereClauseTypes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhereClauseTypes:
def get_string_for_single_clause(column_name, where_clause_type, values, table_name=None, negation=False):
"""Converts a given type and values to a where clause string that can be used in sql_provider queries. :param column_name: The column name that should be checked w... | stack_v2_sparse_classes_10k_train_000801 | 10,669 | permissive | [
{
"docstring": "Converts a given type and values to a where clause string that can be used in sql_provider queries. :param column_name: The column name that should be checked with the values. :type column_name: str :param where_clause_type: The type of the where clause. :type where_clause_type: WhereClauseTypes... | 2 | stack_v2_sparse_classes_30k_train_004281 | Implement the Python class `WhereClauseTypes` described below.
Class description:
Implement the WhereClauseTypes class.
Method signatures and docstrings:
- def get_string_for_single_clause(column_name, where_clause_type, values, table_name=None, negation=False): Converts a given type and values to a where clause stri... | Implement the Python class `WhereClauseTypes` described below.
Class description:
Implement the WhereClauseTypes class.
Method signatures and docstrings:
- def get_string_for_single_clause(column_name, where_clause_type, values, table_name=None, negation=False): Converts a given type and values to a where clause stri... | 09cecfb795cd9df33773a3095ff855d1c2eb396d | <|skeleton|>
class WhereClauseTypes:
def get_string_for_single_clause(column_name, where_clause_type, values, table_name=None, negation=False):
"""Converts a given type and values to a where clause string that can be used in sql_provider queries. :param column_name: The column name that should be checked w... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WhereClauseTypes:
def get_string_for_single_clause(column_name, where_clause_type, values, table_name=None, negation=False):
"""Converts a given type and values to a where clause string that can be used in sql_provider queries. :param column_name: The column name that should be checked with the values... | the_stack_v2_python_sparse | data_models/sql_provider/sql_interface_generic.py | imldresden/mcv-displaywall | train | 2 | |
e60364b51f045bc9254cc9b1ad0d7b9a90fb3113 | [
"if not already_authorized(request):\n response = self.wrap_json_response(code=ReturnCode.UNAUTHORIZED)\n return JsonResponse(response, safe=False)\nopen_id = request.session.get('open_id')\nuser = User.objects.get(open_id=open_id)\ndata = {}\ndata['open_id'] = user.open_id\ndata['focus'] = {}\ndata['focus'][... | <|body_start_0|>
if not already_authorized(request):
response = self.wrap_json_response(code=ReturnCode.UNAUTHORIZED)
return JsonResponse(response, safe=False)
open_id = request.session.get('open_id')
user = User.objects.get(open_id=open_id)
data = {}
data... | 关注的城市、股票和星座 | UserView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserView:
"""关注的城市、股票和星座"""
def get(self, request):
"""获取用户的数据"""
<|body_0|>
def post(self, request):
"""修改用户的数据"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not already_authorized(request):
response = self.wrap_json_response(c... | stack_v2_sparse_classes_10k_train_000802 | 5,687 | no_license | [
{
"docstring": "获取用户的数据",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "修改用户的数据",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002158 | Implement the Python class `UserView` described below.
Class description:
关注的城市、股票和星座
Method signatures and docstrings:
- def get(self, request): 获取用户的数据
- def post(self, request): 修改用户的数据 | Implement the Python class `UserView` described below.
Class description:
关注的城市、股票和星座
Method signatures and docstrings:
- def get(self, request): 获取用户的数据
- def post(self, request): 修改用户的数据
<|skeleton|>
class UserView:
"""关注的城市、股票和星座"""
def get(self, request):
"""获取用户的数据"""
<|body_0|>
de... | 9d0d27e6e29671bd5d38305dac828a61b01095cb | <|skeleton|>
class UserView:
"""关注的城市、股票和星座"""
def get(self, request):
"""获取用户的数据"""
<|body_0|>
def post(self, request):
"""修改用户的数据"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserView:
"""关注的城市、股票和星座"""
def get(self, request):
"""获取用户的数据"""
if not already_authorized(request):
response = self.wrap_json_response(code=ReturnCode.UNAUTHORIZED)
return JsonResponse(response, safe=False)
open_id = request.session.get('open_id')
... | the_stack_v2_python_sparse | backend_ch3_sec1/authorization/views.py | liuwenwen163/django_wx_mini_program | train | 0 |
3c58da696a26f28cf48bca9f77e455ec019e67f9 | [
"super(UnmanagedInstanceGroupMigration, self).__init__()\nself.instance_group = self.build_instance_group()\nself.instance_migration_handlers = []\nself.migration_status = MigrationStatus(0)",
"instance_group_helper = InstanceGroupHelper(self.compute, self.project, self.instance_group_name, self.region, self.zone... | <|body_start_0|>
super(UnmanagedInstanceGroupMigration, self).__init__()
self.instance_group = self.build_instance_group()
self.instance_migration_handlers = []
self.migration_status = MigrationStatus(0)
<|end_body_0|>
<|body_start_1|>
instance_group_helper = InstanceGroupHelper... | UnmanagedInstanceGroupMigration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnmanagedInstanceGroupMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target... | stack_v2_sparse_classes_10k_train_000803 | 6,427 | permissive | [
{
"docstring": "Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target network subnetwork_name: target subnetwork preserve_external_ip: whether to preserve instances' external IPs zone: zone of a zonal instance group region: region of regio... | 4 | stack_v2_sparse_classes_30k_train_002435 | Implement the Python class `UnmanagedInstanceGroupMigration` described below.
Class description:
Implement the UnmanagedInstanceGroupMigration class.
Method signatures and docstrings:
- def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name): Initia... | Implement the Python class `UnmanagedInstanceGroupMigration` described below.
Class description:
Implement the UnmanagedInstanceGroupMigration class.
Method signatures and docstrings:
- def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name): Initia... | 1132e44d696ab9da4d1079ebc3d32ed4382cdc28 | <|skeleton|>
class UnmanagedInstanceGroupMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UnmanagedInstanceGroupMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target network subne... | the_stack_v2_python_sparse | vm_network_migration/handlers/instance_group_migration/unmanaged_instance_group_migration.py | googleinterns/vm-network-migration | train | 1 | |
dd8b0561c406abc080fd88b4181c0584e39f0f10 | [
"import pyarrow as pa\nbatches = super(ArrowStreamUDFSerializer, self).load_stream(stream)\nfor batch in batches:\n struct = batch.column(0)\n yield [pa.RecordBatch.from_arrays(struct.flatten(), schema=pa.schema(struct.type))]",
"import pyarrow as pa\n\ndef wrap_and_init_stream():\n should_write_start_le... | <|body_start_0|>
import pyarrow as pa
batches = super(ArrowStreamUDFSerializer, self).load_stream(stream)
for batch in batches:
struct = batch.column(0)
yield [pa.RecordBatch.from_arrays(struct.flatten(), schema=pa.schema(struct.type))]
<|end_body_0|>
<|body_start_1|>
... | Same as :class:`ArrowStreamSerializer` but it flattens the struct to Arrow record batch for applying each function with the raw record arrow batch. See also `DataFrame.mapInArrow`. | ArrowStreamUDFSerializer | [
"BSD-3-Clause",
"CC0-1.0",
"CDDL-1.1",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"EPL-2.0",
"CDDL-1.0",
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown",... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArrowStreamUDFSerializer:
"""Same as :class:`ArrowStreamSerializer` but it flattens the struct to Arrow record batch for applying each function with the raw record arrow batch. See also `DataFrame.mapInArrow`."""
def load_stream(self, stream):
"""Flatten the struct into Arrow's recor... | stack_v2_sparse_classes_10k_train_000804 | 40,053 | permissive | [
{
"docstring": "Flatten the struct into Arrow's record batches.",
"name": "load_stream",
"signature": "def load_stream(self, stream)"
},
{
"docstring": "Override because Pandas UDFs require a START_ARROW_STREAM before the Arrow stream is sent. This should be sent after creating the first record ... | 2 | stack_v2_sparse_classes_30k_train_004468 | Implement the Python class `ArrowStreamUDFSerializer` described below.
Class description:
Same as :class:`ArrowStreamSerializer` but it flattens the struct to Arrow record batch for applying each function with the raw record arrow batch. See also `DataFrame.mapInArrow`.
Method signatures and docstrings:
- def load_st... | Implement the Python class `ArrowStreamUDFSerializer` described below.
Class description:
Same as :class:`ArrowStreamSerializer` but it flattens the struct to Arrow record batch for applying each function with the raw record arrow batch. See also `DataFrame.mapInArrow`.
Method signatures and docstrings:
- def load_st... | 60d8fc49bec5dae1b8cf39a0670cb640b430f520 | <|skeleton|>
class ArrowStreamUDFSerializer:
"""Same as :class:`ArrowStreamSerializer` but it flattens the struct to Arrow record batch for applying each function with the raw record arrow batch. See also `DataFrame.mapInArrow`."""
def load_stream(self, stream):
"""Flatten the struct into Arrow's recor... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ArrowStreamUDFSerializer:
"""Same as :class:`ArrowStreamSerializer` but it flattens the struct to Arrow record batch for applying each function with the raw record arrow batch. See also `DataFrame.mapInArrow`."""
def load_stream(self, stream):
"""Flatten the struct into Arrow's record batches."""... | the_stack_v2_python_sparse | python/pyspark/sql/pandas/serializers.py | apache/spark | train | 39,983 |
e6fcededbfd5e5af9392bc246fc7de3efdcfaff1 | [
"params = request.query_params\npage = int(params.get('page', 1))\npage_size = int(params.get('page_size', 10))\nkeyword = params.get('keyword')\ntotal_only = params.get('total_only')\nsort_by = request.data.get('sort_by')\nobj = Strategy.objects\nif keyword:\n obj = obj.filter(name__icontains=keyword)\ntotal_co... | <|body_start_0|>
params = request.query_params
page = int(params.get('page', 1))
page_size = int(params.get('page_size', 10))
keyword = params.get('keyword')
total_only = params.get('total_only')
sort_by = request.data.get('sort_by')
obj = Strategy.objects
... | StrategiesAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrategiesAPIView:
def get(request):
"""策略列表接口"""
<|body_0|>
def post(request):
"""策略创建接口"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
params = request.query_params
page = int(params.get('page', 1))
page_size = int(params.get('pag... | stack_v2_sparse_classes_10k_train_000805 | 9,461 | no_license | [
{
"docstring": "策略列表接口",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "策略创建接口",
"name": "post",
"signature": "def post(request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004672 | Implement the Python class `StrategiesAPIView` described below.
Class description:
Implement the StrategiesAPIView class.
Method signatures and docstrings:
- def get(request): 策略列表接口
- def post(request): 策略创建接口 | Implement the Python class `StrategiesAPIView` described below.
Class description:
Implement the StrategiesAPIView class.
Method signatures and docstrings:
- def get(request): 策略列表接口
- def post(request): 策略创建接口
<|skeleton|>
class StrategiesAPIView:
def get(request):
"""策略列表接口"""
<|body_0|>
... | bb85b52598d68956bde8756c8321ade7b8479ba7 | <|skeleton|>
class StrategiesAPIView:
def get(request):
"""策略列表接口"""
<|body_0|>
def post(request):
"""策略创建接口"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StrategiesAPIView:
def get(request):
"""策略列表接口"""
params = request.query_params
page = int(params.get('page', 1))
page_size = int(params.get('page_size', 10))
keyword = params.get('keyword')
total_only = params.get('total_only')
sort_by = request.data.ge... | the_stack_v2_python_sparse | curd_test/configure/views.py | huiiiuh/huihuiproject | train | 0 | |
2037e7c5693e1c0d3a05ed9229553eb3c3cd4a81 | [
"re_string = re.compile('[a-zA-Z0-9]')\nline = ''.join(re_string.findall(s)).lower()\nlenth = len(line)\nfor i in range(lenth // 2):\n if line[i] != line[lenth - i - 1]:\n print(line[i], i)\n return False\nreturn True",
"s = s.lower()\ncharacter = 'abcdefghijklmnopqrstuvwxyz0123456789'\nl = []\nf... | <|body_start_0|>
re_string = re.compile('[a-zA-Z0-9]')
line = ''.join(re_string.findall(s)).lower()
lenth = len(line)
for i in range(lenth // 2):
if line[i] != line[lenth - i - 1]:
print(line[i], i)
return False
return True
<|end_body_0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def other_isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
re_string = re.compile('[a-zA-Z0-9]')
line = ''.joi... | stack_v2_sparse_classes_10k_train_000806 | 1,062 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "other_isPalindrome",
"signature": "def other_isPalindrome(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s): :type s: str :rtype: bool
- def other_isPalindrome(self, s): :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s): :type s: str :rtype: bool
- def other_isPalindrome(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def isPalindrome(self, s):
... | d156c6a13c89727f80ed6244cae40574395ecf34 | <|skeleton|>
class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def other_isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
re_string = re.compile('[a-zA-Z0-9]')
line = ''.join(re_string.findall(s)).lower()
lenth = len(line)
for i in range(lenth // 2):
if line[i] != line[lenth - i - 1]:
print(lin... | the_stack_v2_python_sparse | easy/125.py | longhao54/leetcode | train | 0 | |
8e419dd4daffbd51e106252a8ad6b1d0425b18a9 | [
"response = self.client.get(reverse('polls:index'))\nself.assertEqual(response.status_code, 200)\nself.assertContains(response, 'No polls are available.')\nself.assertQuerysetEqual(response.context['latest_question_list'], [])",
"create_question(question_text='Past question.', days=-30)\nresponse = self.client.ge... | <|body_start_0|>
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'No polls are available.')
self.assertQuerysetEqual(response.context['latest_question_list'], [])
<|end_body_0|>
<|body_start_1|>
create_... | QuestionViewTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionViewTests:
def test_index_view_with_no_questions(self):
"""If no questions exist, an appropriate message should be displayed."""
<|body_0|>
def test_index_view_with_a_past_question(self):
"""Questions with a pub_date in the past should be displayed on the ind... | stack_v2_sparse_classes_10k_train_000807 | 12,478 | no_license | [
{
"docstring": "If no questions exist, an appropriate message should be displayed.",
"name": "test_index_view_with_no_questions",
"signature": "def test_index_view_with_no_questions(self)"
},
{
"docstring": "Questions with a pub_date in the past should be displayed on the index page",
"name"... | 5 | stack_v2_sparse_classes_30k_test_000282 | Implement the Python class `QuestionViewTests` described below.
Class description:
Implement the QuestionViewTests class.
Method signatures and docstrings:
- def test_index_view_with_no_questions(self): If no questions exist, an appropriate message should be displayed.
- def test_index_view_with_a_past_question(self)... | Implement the Python class `QuestionViewTests` described below.
Class description:
Implement the QuestionViewTests class.
Method signatures and docstrings:
- def test_index_view_with_no_questions(self): If no questions exist, an appropriate message should be displayed.
- def test_index_view_with_a_past_question(self)... | 43bca49c77eb16de7580e55f7418cdab92a9a596 | <|skeleton|>
class QuestionViewTests:
def test_index_view_with_no_questions(self):
"""If no questions exist, an appropriate message should be displayed."""
<|body_0|>
def test_index_view_with_a_past_question(self):
"""Questions with a pub_date in the past should be displayed on the ind... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QuestionViewTests:
def test_index_view_with_no_questions(self):
"""If no questions exist, an appropriate message should be displayed."""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'No polls are av... | the_stack_v2_python_sparse | sdd_project copy/labhelpers/tests.py | katrusso/LabHelpers | train | 0 | |
7ebda500248d54f5add0d09827042319d06ae3ac | [
"items = S3File.objects.all()\nfor item in items.all():\n item.delete()",
"try:\n return S3File.objects.get(pk=pk)\nexcept S3File.DoesNotExist:\n return None",
"pk_string = django_unsign(signed_pk)\npk = int_or_none(pk_string)\ntry:\n return self.get(pk=pk)\nexcept S3File.DoesNotExist:\n return N... | <|body_start_0|>
items = S3File.objects.all()
for item in items.all():
item.delete()
<|end_body_0|>
<|body_start_1|>
try:
return S3File.objects.get(pk=pk)
except S3File.DoesNotExist:
return None
<|end_body_1|>
<|body_start_2|>
pk_string = dja... | S3FileManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3FileManager:
def delete_all(self):
"""Utility function will delete all the S3 files in our system."""
<|body_0|>
def get_by_pk_or_none(self, pk):
"""Helper function which gets the S3File object by PK parameter or returns None result."""
<|body_1|>
def ... | stack_v2_sparse_classes_10k_train_000808 | 4,649 | permissive | [
{
"docstring": "Utility function will delete all the S3 files in our system.",
"name": "delete_all",
"signature": "def delete_all(self)"
},
{
"docstring": "Helper function which gets the S3File object by PK parameter or returns None result.",
"name": "get_by_pk_or_none",
"signature": "de... | 3 | null | Implement the Python class `S3FileManager` described below.
Class description:
Implement the S3FileManager class.
Method signatures and docstrings:
- def delete_all(self): Utility function will delete all the S3 files in our system.
- def get_by_pk_or_none(self, pk): Helper function which gets the S3File object by PK... | Implement the Python class `S3FileManager` described below.
Class description:
Implement the S3FileManager class.
Method signatures and docstrings:
- def delete_all(self): Utility function will delete all the S3 files in our system.
- def get_by_pk_or_none(self, pk): Helper function which gets the S3File object by PK... | 053973b5ff0b997c52bfaca8daf8e07db64a877c | <|skeleton|>
class S3FileManager:
def delete_all(self):
"""Utility function will delete all the S3 files in our system."""
<|body_0|>
def get_by_pk_or_none(self, pk):
"""Helper function which gets the S3File object by PK parameter or returns None result."""
<|body_1|>
def ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class S3FileManager:
def delete_all(self):
"""Utility function will delete all the S3 files in our system."""
items = S3File.objects.all()
for item in items.all():
item.delete()
def get_by_pk_or_none(self, pk):
"""Helper function which gets the S3File object by PK pa... | the_stack_v2_python_sparse | foundation_tenant/models/base/s3file.py | smegurus/smegurus-django | train | 1 | |
1f374bfc3ccd730f8b2e124827667f8d7fb376de | [
"result = []\nfor i in range(1, 5):\n result.append(i)\nreturn result",
"result = []\na = []\nfor i in range(1, 5):\n a.append(random.randint(1, 10))\nresult.append(a)\nreturn result"
] | <|body_start_0|>
result = []
for i in range(1, 5):
result.append(i)
return result
<|end_body_0|>
<|body_start_1|>
result = []
a = []
for i in range(1, 5):
a.append(random.randint(1, 10))
result.append(a)
return result
<|end_body_1|... | LineChartJSONView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineChartJSONView:
def get_labels(self):
"""Return 7 labels."""
<|body_0|>
def get_data(self):
"""Return 3 datasets to plot."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
for i in range(1, 5):
result.append(i)
... | stack_v2_sparse_classes_10k_train_000809 | 6,554 | no_license | [
{
"docstring": "Return 7 labels.",
"name": "get_labels",
"signature": "def get_labels(self)"
},
{
"docstring": "Return 3 datasets to plot.",
"name": "get_data",
"signature": "def get_data(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006945 | Implement the Python class `LineChartJSONView` described below.
Class description:
Implement the LineChartJSONView class.
Method signatures and docstrings:
- def get_labels(self): Return 7 labels.
- def get_data(self): Return 3 datasets to plot. | Implement the Python class `LineChartJSONView` described below.
Class description:
Implement the LineChartJSONView class.
Method signatures and docstrings:
- def get_labels(self): Return 7 labels.
- def get_data(self): Return 3 datasets to plot.
<|skeleton|>
class LineChartJSONView:
def get_labels(self):
... | f23b3a955a131fd0b4927321401cb5194f2fc574 | <|skeleton|>
class LineChartJSONView:
def get_labels(self):
"""Return 7 labels."""
<|body_0|>
def get_data(self):
"""Return 3 datasets to plot."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LineChartJSONView:
def get_labels(self):
"""Return 7 labels."""
result = []
for i in range(1, 5):
result.append(i)
return result
def get_data(self):
"""Return 3 datasets to plot."""
result = []
a = []
for i in range(1, 5):
... | the_stack_v2_python_sparse | si8device/views.py | AleksZ13ru/mysite | train | 0 | |
10be8057d3d11d8f107e408f0eef95af900a65a1 | [
"if not nums:\n return [None]\nn = len(nums)\nif n == 1:\n return [TreeNode(nums[0])]\ntns = []\nfor i in range(n):\n lefts = self.helper(nums[:i])\n rights = self.helper(nums[i + 1:])\n for l in lefts:\n for r in rights:\n root = TreeNode(nums[i])\n root.left = l\n ... | <|body_start_0|>
if not nums:
return [None]
n = len(nums)
if n == 1:
return [TreeNode(nums[0])]
tns = []
for i in range(n):
lefts = self.helper(nums[:i])
rights = self.helper(nums[i + 1:])
for l in lefts:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def helper(self, nums):
"""递归生成给定有序数组能组成的所有二叉搜索树 :param nums: :return:"""
<|body_0|>
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return [None]
... | stack_v2_sparse_classes_10k_train_000810 | 2,624 | no_license | [
{
"docstring": "递归生成给定有序数组能组成的所有二叉搜索树 :param nums: :return:",
"name": "helper",
"signature": "def helper(self, nums)"
},
{
"docstring": ":type n: int :rtype: List[TreeNode]",
"name": "generateTrees",
"signature": "def generateTrees(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004611 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, nums): 递归生成给定有序数组能组成的所有二叉搜索树 :param nums: :return:
- def generateTrees(self, n): :type n: int :rtype: List[TreeNode] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, nums): 递归生成给定有序数组能组成的所有二叉搜索树 :param nums: :return:
- def generateTrees(self, n): :type n: int :rtype: List[TreeNode]
<|skeleton|>
class Solution:
def helpe... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def helper(self, nums):
"""递归生成给定有序数组能组成的所有二叉搜索树 :param nums: :return:"""
<|body_0|>
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def helper(self, nums):
"""递归生成给定有序数组能组成的所有二叉搜索树 :param nums: :return:"""
if not nums:
return [None]
n = len(nums)
if n == 1:
return [TreeNode(nums[0])]
tns = []
for i in range(n):
lefts = self.helper(nums[:i])
... | the_stack_v2_python_sparse | 95_不同的二叉搜索树 II.py | lovehhf/LeetCode | train | 0 | |
15f9d452e064101b1fde0c39eefa8b647d11f618 | [
"silent_cfg_names_map = None\nif LooseVersion(self.version) < LooseVersion('2013_sp1'):\n silent_cfg_names_map = {'activation_name': ACTIVATION_NAME_2012, 'license_file_name': LICENSE_FILE_NAME_2012}\nsuper(EB_icc, self).install_step(silent_cfg_names_map=silent_cfg_names_map)",
"binprefix = 'bin/intel64'\nlibp... | <|body_start_0|>
silent_cfg_names_map = None
if LooseVersion(self.version) < LooseVersion('2013_sp1'):
silent_cfg_names_map = {'activation_name': ACTIVATION_NAME_2012, 'license_file_name': LICENSE_FILE_NAME_2012}
super(EB_icc, self).install_step(silent_cfg_names_map=silent_cfg_names_... | Support for installing icc - tested with 11.1.046 - will fail for all older versions (due to newer silent installer) | EB_icc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EB_icc:
"""Support for installing icc - tested with 11.1.046 - will fail for all older versions (due to newer silent installer)"""
def install_step(self):
"""Actual installation - create silent cfg file - execute command"""
<|body_0|>
def sanity_check_step(self):
... | stack_v2_sparse_classes_10k_train_000811 | 5,994 | no_license | [
{
"docstring": "Actual installation - create silent cfg file - execute command",
"name": "install_step",
"signature": "def install_step(self)"
},
{
"docstring": "Custom sanity check paths for icc.",
"name": "sanity_check_step",
"signature": "def sanity_check_step(self)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_002493 | Implement the Python class `EB_icc` described below.
Class description:
Support for installing icc - tested with 11.1.046 - will fail for all older versions (due to newer silent installer)
Method signatures and docstrings:
- def install_step(self): Actual installation - create silent cfg file - execute command
- def ... | Implement the Python class `EB_icc` described below.
Class description:
Support for installing icc - tested with 11.1.046 - will fail for all older versions (due to newer silent installer)
Method signatures and docstrings:
- def install_step(self): Actual installation - create silent cfg file - execute command
- def ... | 3c5434f9a4193fbe4cf8107327faadda83d798ae | <|skeleton|>
class EB_icc:
"""Support for installing icc - tested with 11.1.046 - will fail for all older versions (due to newer silent installer)"""
def install_step(self):
"""Actual installation - create silent cfg file - execute command"""
<|body_0|>
def sanity_check_step(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EB_icc:
"""Support for installing icc - tested with 11.1.046 - will fail for all older versions (due to newer silent installer)"""
def install_step(self):
"""Actual installation - create silent cfg file - execute command"""
silent_cfg_names_map = None
if LooseVersion(self.version)... | the_stack_v2_python_sparse | 1.11.1/easyblock/easyblocks/i/icc.py | lsuhpchelp/easybuild_smic | train | 0 |
95403b243f6285e44a78120a04ea480953f67d5d | [
"sum_1 = 0\nl = len(nums)\nnums = sorted(nums)\nfor i in range(l - 2):\n for j in range(i + 1, l - 1):\n k = nums[i] + nums[j]\n a = bisect.bisect_left(nums[j + 1:], k)\n sum_1 += a\n print(a, nums[i], nums[j], nums[j + 1:])\nreturn sum_1",
"sum_1 = 0\nl = len(nums)\nnums = sorted(n... | <|body_start_0|>
sum_1 = 0
l = len(nums)
nums = sorted(nums)
for i in range(l - 2):
for j in range(i + 1, l - 1):
k = nums[i] + nums[j]
a = bisect.bisect_left(nums[j + 1:], k)
sum_1 += a
print(a, nums[i], nums[j]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def triangleNumber(self, nums):
""":type nums: List[int] :rtype: int 2078ms"""
<|body_0|>
def triangleNumber_1(self, nums):
""":type nums: List[int] :rtype: int 315ms"""
<|body_1|>
def triangleNumber_2(self, nums):
""":type nums: List[i... | stack_v2_sparse_classes_10k_train_000812 | 2,014 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int 2078ms",
"name": "triangleNumber",
"signature": "def triangleNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int 315ms",
"name": "triangleNumber_1",
"signature": "def triangleNumber_1(self, nums)"
},
{
"docstr... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def triangleNumber(self, nums): :type nums: List[int] :rtype: int 2078ms
- def triangleNumber_1(self, nums): :type nums: List[int] :rtype: int 315ms
- def triangleNumber_2(self, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def triangleNumber(self, nums): :type nums: List[int] :rtype: int 2078ms
- def triangleNumber_1(self, nums): :type nums: List[int] :rtype: int 315ms
- def triangleNumber_2(self, ... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def triangleNumber(self, nums):
""":type nums: List[int] :rtype: int 2078ms"""
<|body_0|>
def triangleNumber_1(self, nums):
""":type nums: List[int] :rtype: int 315ms"""
<|body_1|>
def triangleNumber_2(self, nums):
""":type nums: List[i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def triangleNumber(self, nums):
""":type nums: List[int] :rtype: int 2078ms"""
sum_1 = 0
l = len(nums)
nums = sorted(nums)
for i in range(l - 2):
for j in range(i + 1, l - 1):
k = nums[i] + nums[j]
a = bisect.bisect_... | the_stack_v2_python_sparse | ValidTriangleNumber_MID_611.py | 953250587/leetcode-python | train | 2 | |
c2c5e005b3c3de4be0b46cac6045f476cfe468f5 | [
"passwd = data['password']\npasswd_conf = data['password_confirmation']\nif passwd != passwd_conf:\n raise serializers.ValidationError(\"Passwords don't match.\")\npassword_validation.validate_password(passwd)\ngeocode = geocoder.google(data['address'], key=settings.GOOGLE_API_KEY)\nif geocode:\n data['lat'],... | <|body_start_0|>
passwd = data['password']
passwd_conf = data['password_confirmation']
if passwd != passwd_conf:
raise serializers.ValidationError("Passwords don't match.")
password_validation.validate_password(passwd)
geocode = geocoder.google(data['address'], key=se... | User signup Serializer. Handle sign up data validation and user/type user creation. | UserSignupSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSignupSerializer:
"""User signup Serializer. Handle sign up data validation and user/type user creation."""
def validate(self, data):
"""Verify passwords match."""
<|body_0|>
def validate_availability(self, value):
"""Check if in the request only has only a u... | stack_v2_sparse_classes_10k_train_000813 | 7,359 | permissive | [
{
"docstring": "Verify passwords match.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Check if in the request only has only a unique combination between shift and day.",
"name": "validate_availability",
"signature": "def validate_availability(self, valu... | 3 | stack_v2_sparse_classes_30k_train_000389 | Implement the Python class `UserSignupSerializer` described below.
Class description:
User signup Serializer. Handle sign up data validation and user/type user creation.
Method signatures and docstrings:
- def validate(self, data): Verify passwords match.
- def validate_availability(self, value): Check if in the requ... | Implement the Python class `UserSignupSerializer` described below.
Class description:
User signup Serializer. Handle sign up data validation and user/type user creation.
Method signatures and docstrings:
- def validate(self, data): Verify passwords match.
- def validate_availability(self, value): Check if in the requ... | 5c37c6876ca13b5794ac44e0342b810426acbc76 | <|skeleton|>
class UserSignupSerializer:
"""User signup Serializer. Handle sign up data validation and user/type user creation."""
def validate(self, data):
"""Verify passwords match."""
<|body_0|>
def validate_availability(self, value):
"""Check if in the request only has only a u... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserSignupSerializer:
"""User signup Serializer. Handle sign up data validation and user/type user creation."""
def validate(self, data):
"""Verify passwords match."""
passwd = data['password']
passwd_conf = data['password_confirmation']
if passwd != passwd_conf:
... | the_stack_v2_python_sparse | hisitter/users/serializers/users.py | babysitter-finder/backend | train | 1 |
e19e224a20070ad32dd5d5b2a249421a3e3cdf25 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsWorkFromAnywhereDevicesSummary()",
"from .user_experience_analytics_autopilot_devices_summary import UserExperienceAnalyticsAutopilotDevicesSummary\nfrom .user_experience_analytics_cloud_identity_devices_summary ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsWorkFromAnywhereDevicesSummary()
<|end_body_0|>
<|body_start_1|>
from .user_experience_analytics_autopilot_devices_summary import UserExperienceAnalyticsAutopilotDevicesSu... | The user experience analytics Work From Anywhere metrics devices summary. | UserExperienceAnalyticsWorkFromAnywhereDevicesSummary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsWorkFromAnywhereDevicesSummary:
"""The user experience analytics Work From Anywhere metrics devices summary."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsWorkFromAnywhereDevicesSummary:
"""Creates a new ... | stack_v2_sparse_classes_10k_train_000814 | 9,487 | 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: UserExperienceAnalyticsWorkFromAnywhereDevicesSummary",
"name": "create_from_discriminator_value",
"signatur... | 3 | null | Implement the Python class `UserExperienceAnalyticsWorkFromAnywhereDevicesSummary` described below.
Class description:
The user experience analytics Work From Anywhere metrics devices summary.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperien... | Implement the Python class `UserExperienceAnalyticsWorkFromAnywhereDevicesSummary` described below.
Class description:
The user experience analytics Work From Anywhere metrics devices summary.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperien... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsWorkFromAnywhereDevicesSummary:
"""The user experience analytics Work From Anywhere metrics devices summary."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsWorkFromAnywhereDevicesSummary:
"""Creates a new ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserExperienceAnalyticsWorkFromAnywhereDevicesSummary:
"""The user experience analytics Work From Anywhere metrics devices summary."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsWorkFromAnywhereDevicesSummary:
"""Creates a new instance of t... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_work_from_anywhere_devices_summary.py | microsoftgraph/msgraph-sdk-python | train | 135 |
a7b47a5a44788ad09de86c3227d85f8ec52e2ce8 | [
"lexer_choices = [(lex[0], lex[0]) for lex in get_all_lexers()]\nwidgets = (TextInput(attrs=attrs), Select(attrs=attrs, choices=lexer_choices))\nsuper(LexersMappingWidget, self).__init__(widgets, attrs)",
"if value:\n return list(value)\nreturn [None, None]",
"key_lexer = [widget.value_from_datadict(data, fi... | <|body_start_0|>
lexer_choices = [(lex[0], lex[0]) for lex in get_all_lexers()]
widgets = (TextInput(attrs=attrs), Select(attrs=attrs, choices=lexer_choices))
super(LexersMappingWidget, self).__init__(widgets, attrs)
<|end_body_0|>
<|body_start_1|>
if value:
return list(valu... | A form widget for mapping a string to a Pygments Lexer class. This widget displays a text input with a drop-down list of Pygments Lexer names next to it. Version Added: 5.0 | LexersMappingWidget | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LexersMappingWidget:
"""A form widget for mapping a string to a Pygments Lexer class. This widget displays a text input with a drop-down list of Pygments Lexer names next to it. Version Added: 5.0"""
def __init__(self, attrs=None):
"""Initialize the LexersMappingWidget. Args: attrs (... | stack_v2_sparse_classes_10k_train_000815 | 16,804 | permissive | [
{
"docstring": "Initialize the LexersMappingWidget. Args: attrs (dict, optional): A dictionary containing HTML attributes to be set on the rendered widget.",
"name": "__init__",
"signature": "def __init__(self, attrs=None)"
},
{
"docstring": "Decompress the value into a list of values for each w... | 3 | null | Implement the Python class `LexersMappingWidget` described below.
Class description:
A form widget for mapping a string to a Pygments Lexer class. This widget displays a text input with a drop-down list of Pygments Lexer names next to it. Version Added: 5.0
Method signatures and docstrings:
- def __init__(self, attrs... | Implement the Python class `LexersMappingWidget` described below.
Class description:
A form widget for mapping a string to a Pygments Lexer class. This widget displays a text input with a drop-down list of Pygments Lexer names next to it. Version Added: 5.0
Method signatures and docstrings:
- def __init__(self, attrs... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class LexersMappingWidget:
"""A form widget for mapping a string to a Pygments Lexer class. This widget displays a text input with a drop-down list of Pygments Lexer names next to it. Version Added: 5.0"""
def __init__(self, attrs=None):
"""Initialize the LexersMappingWidget. Args: attrs (... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LexersMappingWidget:
"""A form widget for mapping a string to a Pygments Lexer class. This widget displays a text input with a drop-down list of Pygments Lexer names next to it. Version Added: 5.0"""
def __init__(self, attrs=None):
"""Initialize the LexersMappingWidget. Args: attrs (dict, optiona... | the_stack_v2_python_sparse | reviewboard/admin/form_widgets.py | reviewboard/reviewboard | train | 1,141 |
b42b1bdb5630119ac802d673c5bdbd5c91a18274 | [
"path_spec = database_file_entry.path_spec\nlocation = getattr(path_spec, 'location', None)\nif not path_spec or not location:\n return (None, None)\nlocation_wal = '{0:s}-wal'.format(location)\nfile_system = database_file_entry.GetFileSystem()\nwal_path_spec = path_spec_factory.Factory.NewPathSpec(file_system.t... | <|body_start_0|>
path_spec = database_file_entry.path_spec
location = getattr(path_spec, 'location', None)
if not path_spec or not location:
return (None, None)
location_wal = '{0:s}-wal'.format(location)
file_system = database_file_entry.GetFileSystem()
wal_p... | Parses SQLite database files. | SQLiteParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLiteParser:
"""Parses SQLite database files."""
def _OpenDatabaseWithWAL(self, parser_mediator, database_file_entry, database_file_object, filename):
"""Opens a database with its Write-Ahead Log (WAL) committed. Args: parser_mediator (ParserMediator): parser mediator. database_file... | stack_v2_sparse_classes_10k_train_000816 | 15,878 | permissive | [
{
"docstring": "Opens a database with its Write-Ahead Log (WAL) committed. Args: parser_mediator (ParserMediator): parser mediator. database_file_entry (dfvfs.FileEntry): file entry of the database. database_file_object (dfvfs.FileIO): file-like object of the database. filename (str): name of the database file ... | 4 | null | Implement the Python class `SQLiteParser` described below.
Class description:
Parses SQLite database files.
Method signatures and docstrings:
- def _OpenDatabaseWithWAL(self, parser_mediator, database_file_entry, database_file_object, filename): Opens a database with its Write-Ahead Log (WAL) committed. Args: parser_... | Implement the Python class `SQLiteParser` described below.
Class description:
Parses SQLite database files.
Method signatures and docstrings:
- def _OpenDatabaseWithWAL(self, parser_mediator, database_file_entry, database_file_object, filename): Opens a database with its Write-Ahead Log (WAL) committed. Args: parser_... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class SQLiteParser:
"""Parses SQLite database files."""
def _OpenDatabaseWithWAL(self, parser_mediator, database_file_entry, database_file_object, filename):
"""Opens a database with its Write-Ahead Log (WAL) committed. Args: parser_mediator (ParserMediator): parser mediator. database_file... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SQLiteParser:
"""Parses SQLite database files."""
def _OpenDatabaseWithWAL(self, parser_mediator, database_file_entry, database_file_object, filename):
"""Opens a database with its Write-Ahead Log (WAL) committed. Args: parser_mediator (ParserMediator): parser mediator. database_file_entry (dfvfs... | the_stack_v2_python_sparse | plaso/parsers/sqlite.py | log2timeline/plaso | train | 1,506 |
28b2e566f576a94370d8cb66b594a850c122ff39 | [
"self.lower_wave = lower_wave\nself.upper_wave = upper_wave\nself.window_width = window_width\nTes.__init__(self, lower_temp, upper_temp)",
"sam_radiance = measurement.sam.data.average_spectrum\nif measurement.dwr is None:\n dwr_radiance = np.zeros(len(sam_radiance))\nelse:\n dwr_radiance = measurement.dwr.... | <|body_start_0|>
self.lower_wave = lower_wave
self.upper_wave = upper_wave
self.window_width = window_width
Tes.__init__(self, lower_temp, upper_temp)
<|end_body_0|>
<|body_start_1|>
sam_radiance = measurement.sam.data.average_spectrum
if measurement.dwr is None:
... | A class that represents a moving window temperature emissivity separation object. Attributes: Inherited from Tes. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper wavelength of the window being examined. window_width - The width of the moving window. | MovingWindow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingWindow:
"""A class that represents a moving window temperature emissivity separation object. Attributes: Inherited from Tes. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper wavelength of the window being examined. window_width - The width of the moving... | stack_v2_sparse_classes_10k_train_000817 | 3,029 | no_license | [
{
"docstring": "MovingWindow instance constructor. Calls constructor for super class. Arguments: lower_temp - The minimum temperature in the range to be tested. upper_temp - The maximum temperature in the range to be tested. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper ... | 2 | stack_v2_sparse_classes_30k_train_001303 | Implement the Python class `MovingWindow` described below.
Class description:
A class that represents a moving window temperature emissivity separation object. Attributes: Inherited from Tes. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper wavelength of the window being examined.... | Implement the Python class `MovingWindow` described below.
Class description:
A class that represents a moving window temperature emissivity separation object. Attributes: Inherited from Tes. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper wavelength of the window being examined.... | 743167940f700374755ea273b90da66befae1ba4 | <|skeleton|>
class MovingWindow:
"""A class that represents a moving window temperature emissivity separation object. Attributes: Inherited from Tes. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper wavelength of the window being examined. window_width - The width of the moving... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MovingWindow:
"""A class that represents a moving window temperature emissivity separation object. Attributes: Inherited from Tes. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper wavelength of the window being examined. window_width - The width of the moving window."""
... | the_stack_v2_python_sparse | tes/models/tes_models/moving_window.py | max19951001/TES | train | 0 |
345ff216c2dd71d49a144762e47ffd2228a6ada8 | [
"if not self.request.body:\n return None\nbody = self.request.body.strip().decode(u'utf-8')\ntry:\n model = json.loads(body)\nexcept Exception:\n self.log.debug('Bad JSON: %r', body)\n self.log.error(\"Couldn't parse JSON\", exc_info=True)\n raise web.HTTPError(400, 'Invalid JSON in body of request')... | <|body_start_0|>
if not self.request.body:
return None
body = self.request.body.strip().decode(u'utf-8')
try:
model = json.loads(body)
except Exception:
self.log.debug('Bad JSON: %r', body)
self.log.error("Couldn't parse JSON", exc_info=Tru... | APIHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIHandler:
def get_json_body(self):
"""Return the body of the request as JSON data."""
<|body_0|>
def write_error(self, status_code, **kwargs):
"""Write JSON errors instead of HTML"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.request... | stack_v2_sparse_classes_10k_train_000818 | 1,619 | permissive | [
{
"docstring": "Return the body of the request as JSON data.",
"name": "get_json_body",
"signature": "def get_json_body(self)"
},
{
"docstring": "Write JSON errors instead of HTML",
"name": "write_error",
"signature": "def write_error(self, status_code, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007154 | Implement the Python class `APIHandler` described below.
Class description:
Implement the APIHandler class.
Method signatures and docstrings:
- def get_json_body(self): Return the body of the request as JSON data.
- def write_error(self, status_code, **kwargs): Write JSON errors instead of HTML | Implement the Python class `APIHandler` described below.
Class description:
Implement the APIHandler class.
Method signatures and docstrings:
- def get_json_body(self): Return the body of the request as JSON data.
- def write_error(self, status_code, **kwargs): Write JSON errors instead of HTML
<|skeleton|>
class AP... | e7f67bfc4f0cd8bd0ebbef013ea1526b340c253b | <|skeleton|>
class APIHandler:
def get_json_body(self):
"""Return the body of the request as JSON data."""
<|body_0|>
def write_error(self, status_code, **kwargs):
"""Write JSON errors instead of HTML"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class APIHandler:
def get_json_body(self):
"""Return the body of the request as JSON data."""
if not self.request.body:
return None
body = self.request.body.strip().decode(u'utf-8')
try:
model = json.loads(body)
except Exception:
self.log.d... | the_stack_v2_python_sparse | jupyterhub/apihandlers/base.py | rgbkrk/jupyterhub | train | 2 | |
9162fc337c7bb1d6afcc15c29d05e15bc5989ac6 | [
"super().__init__()\nself._path = path\nself._detect_change = detect_change\nself._data = None\nif initialize_data:\n self.validate_change()",
"old_data = self._data\nif not self.validate_file():\n return False\nreturn old_data != self._data if self._detect_change else True",
"if not self._path.exists():\... | <|body_start_0|>
super().__init__()
self._path = path
self._detect_change = detect_change
self._data = None
if initialize_data:
self.validate_change()
<|end_body_0|>
<|body_start_1|>
old_data = self._data
if not self.validate_file():
retur... | DefinitionValidator | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefinitionValidator:
def __init__(self, path: Path, detect_change: bool=True, initialize_data: bool=True) -> None:
"""Validator for JSON and YAML files. Calling validate_change() will return True if the definition is valid and has changes. Parameters ---------- path : Path Path to the de... | stack_v2_sparse_classes_10k_train_000819 | 2,590 | permissive | [
{
"docstring": "Validator for JSON and YAML files. Calling validate_change() will return True if the definition is valid and has changes. Parameters ---------- path : Path Path to the definition file detect_change : bool, optional validation will only be successful if there are changes between current and previ... | 3 | null | Implement the Python class `DefinitionValidator` described below.
Class description:
Implement the DefinitionValidator class.
Method signatures and docstrings:
- def __init__(self, path: Path, detect_change: bool=True, initialize_data: bool=True) -> None: Validator for JSON and YAML files. Calling validate_change() w... | Implement the Python class `DefinitionValidator` described below.
Class description:
Implement the DefinitionValidator class.
Method signatures and docstrings:
- def __init__(self, path: Path, detect_change: bool=True, initialize_data: bool=True) -> None: Validator for JSON and YAML files. Calling validate_change() w... | b297ff015f2b69d7c74059c2d42ece1c29ea73ee | <|skeleton|>
class DefinitionValidator:
def __init__(self, path: Path, detect_change: bool=True, initialize_data: bool=True) -> None:
"""Validator for JSON and YAML files. Calling validate_change() will return True if the definition is valid and has changes. Parameters ---------- path : Path Path to the de... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DefinitionValidator:
def __init__(self, path: Path, detect_change: bool=True, initialize_data: bool=True) -> None:
"""Validator for JSON and YAML files. Calling validate_change() will return True if the definition is valid and has changes. Parameters ---------- path : Path Path to the definition file ... | the_stack_v2_python_sparse | samcli/lib/utils/definition_validator.py | aws/aws-sam-cli | train | 1,402 | |
45ae6571a2b3e92331cd3fb3d3f593415333db9c | [
"is_np = isinstance(inputs, np.ndarray)\nif is_np:\n inputs = torch.tensor(inputs, dtype=torch.float32)\n_, indices = torch.max(inputs, 1)\nif is_np:\n return indices.numpy()\nreturn indices",
"serialized = transformer_pb.Layer()\nserialized.argmax_data.SetInParent()\nreturn serialized",
"if serialized.Wh... | <|body_start_0|>
is_np = isinstance(inputs, np.ndarray)
if is_np:
inputs = torch.tensor(inputs, dtype=torch.float32)
_, indices = torch.max(inputs, 1)
if is_np:
return indices.numpy()
return indices
<|end_body_0|>
<|body_start_1|>
serialized = tra... | Represents an ArgMax layer in a network. | ArgMaxLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgMaxLayer:
"""Represents an ArgMax layer in a network."""
def compute(self, inputs):
"""Returns ArgMax(inputs)."""
<|body_0|>
def serialize(self):
"""Serializes the layer for the transformer server."""
<|body_1|>
def deserialize(cls, serialized):
... | stack_v2_sparse_classes_10k_train_000820 | 1,038 | permissive | [
{
"docstring": "Returns ArgMax(inputs).",
"name": "compute",
"signature": "def compute(self, inputs)"
},
{
"docstring": "Serializes the layer for the transformer server.",
"name": "serialize",
"signature": "def serialize(self)"
},
{
"docstring": "Deserializes the layer from the P... | 3 | stack_v2_sparse_classes_30k_train_006792 | Implement the Python class `ArgMaxLayer` described below.
Class description:
Represents an ArgMax layer in a network.
Method signatures and docstrings:
- def compute(self, inputs): Returns ArgMax(inputs).
- def serialize(self): Serializes the layer for the transformer server.
- def deserialize(cls, serialized): Deser... | Implement the Python class `ArgMaxLayer` described below.
Class description:
Represents an ArgMax layer in a network.
Method signatures and docstrings:
- def compute(self, inputs): Returns ArgMax(inputs).
- def serialize(self): Serializes the layer for the transformer server.
- def deserialize(cls, serialized): Deser... | 19abf589e84ee67317134573054c648bb25c244d | <|skeleton|>
class ArgMaxLayer:
"""Represents an ArgMax layer in a network."""
def compute(self, inputs):
"""Returns ArgMax(inputs)."""
<|body_0|>
def serialize(self):
"""Serializes the layer for the transformer server."""
<|body_1|>
def deserialize(cls, serialized):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ArgMaxLayer:
"""Represents an ArgMax layer in a network."""
def compute(self, inputs):
"""Returns ArgMax(inputs)."""
is_np = isinstance(inputs, np.ndarray)
if is_np:
inputs = torch.tensor(inputs, dtype=torch.float32)
_, indices = torch.max(inputs, 1)
if... | the_stack_v2_python_sparse | pysyrenn/frontend/argmax_layer.py | 95616ARG/SyReNN | train | 38 |
5966fc65dc15b01fd857b743e91d49e4559a6bc3 | [
"self.responses = []\nself.path_basename = path_basename\nself.path_basename_len = len(path_basename)\nself.method = method\nself.success_response = success_response",
"assert path.startswith(self.path_basename), '%s does not start with %s' % (path, self.path_basename)\nif type(what) is int:\n code = what\n ... | <|body_start_0|>
self.responses = []
self.path_basename = path_basename
self.path_basename_len = len(path_basename)
self.method = method
self.success_response = success_response
<|end_body_0|>
<|body_start_1|>
assert path.startswith(self.path_basename), '%s does not star... | Stores a list of (typically error) responses for use in a L{MultiStatusResponse}. | ResponseQueue | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResponseQueue:
"""Stores a list of (typically error) responses for use in a L{MultiStatusResponse}."""
def __init__(self, path_basename, method, success_response):
"""@param path_basename: the base path for all responses to be added to the queue. All paths for responses added to the ... | stack_v2_sparse_classes_10k_train_000821 | 13,040 | permissive | [
{
"docstring": "@param path_basename: the base path for all responses to be added to the queue. All paths for responses added to the queue must start with C{path_basename}, which will be stripped from the beginning of each path to determine the response's URI. @param method: the name of the method generating th... | 3 | null | Implement the Python class `ResponseQueue` described below.
Class description:
Stores a list of (typically error) responses for use in a L{MultiStatusResponse}.
Method signatures and docstrings:
- def __init__(self, path_basename, method, success_response): @param path_basename: the base path for all responses to be ... | Implement the Python class `ResponseQueue` described below.
Class description:
Stores a list of (typically error) responses for use in a L{MultiStatusResponse}.
Method signatures and docstrings:
- def __init__(self, path_basename, method, success_response): @param path_basename: the base path for all responses to be ... | cb2962f1f1927f1e52ea405094fa3e7e180f23cb | <|skeleton|>
class ResponseQueue:
"""Stores a list of (typically error) responses for use in a L{MultiStatusResponse}."""
def __init__(self, path_basename, method, success_response):
"""@param path_basename: the base path for all responses to be added to the queue. All paths for responses added to the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResponseQueue:
"""Stores a list of (typically error) responses for use in a L{MultiStatusResponse}."""
def __init__(self, path_basename, method, success_response):
"""@param path_basename: the base path for all responses to be added to the queue. All paths for responses added to the queue must st... | the_stack_v2_python_sparse | txweb2/dav/http.py | ass-a2s/ccs-calendarserver | train | 2 |
9f894e08ff4ef54a9b8346171a857b123e3e2b02 | [
"max_1 = 0\nsets = set(nums)\nwhile sets:\n count = 1\n a = list(sets)[0]\n sets.remove(a)\n i = a - 1\n while sets and i in sets:\n sets.remove(i)\n count += 1\n i -= 1\n j = a + 1\n while sets and j in sets:\n sets.remove(j)\n count += 1\n j += 1\n ... | <|body_start_0|>
max_1 = 0
sets = set(nums)
while sets:
count = 1
a = list(sets)[0]
sets.remove(a)
i = a - 1
while sets and i in sets:
sets.remove(i)
count += 1
i -= 1
j = a + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int 39ms"""
<|body_0|>
def longestConsecutive_1(self, nums):
""":type nums: List[int] :rtype: int 35ms"""
<|body_1|>
def longestConsecutive_2(self, nums):
"""35ms :par... | stack_v2_sparse_classes_10k_train_000822 | 1,951 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int 39ms",
"name": "longestConsecutive",
"signature": "def longestConsecutive(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int 35ms",
"name": "longestConsecutive_1",
"signature": "def longestConsecutive_1(self, nums)"
},
... | 3 | stack_v2_sparse_classes_30k_train_005868 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int 39ms
- def longestConsecutive_1(self, nums): :type nums: List[int] :rtype: int 35ms
- def longestConsecutive... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int 39ms
- def longestConsecutive_1(self, nums): :type nums: List[int] :rtype: int 35ms
- def longestConsecutive... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int 39ms"""
<|body_0|>
def longestConsecutive_1(self, nums):
""":type nums: List[int] :rtype: int 35ms"""
<|body_1|>
def longestConsecutive_2(self, nums):
"""35ms :par... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int 39ms"""
max_1 = 0
sets = set(nums)
while sets:
count = 1
a = list(sets)[0]
sets.remove(a)
i = a - 1
while sets and i in sets:
... | the_stack_v2_python_sparse | LongestConsecutiveSequence_HARD_128.py | 953250587/leetcode-python | train | 2 | |
bb0b624d45c5420a3f3c2df5737b76e47d58a7a4 | [
"l_int = 0\nl_bytes = convert.int_2_bigend(l_int, 4)\nself.assertEqual(l_bytes, b'\\x00\\x00\\x00\\x00')",
"l_int = 0\nl_bytes = convert.int_2_bigend(l_int, 2)\nself.assertEqual(l_bytes, b'\\x00\\x00')",
"l_int = 15\nl_bytes = convert.int_2_bigend(l_int, 4)\nself.assertEqual(l_bytes, b'\\x00\\x00\\x00\\x0f')",
... | <|body_start_0|>
l_int = 0
l_bytes = convert.int_2_bigend(l_int, 4)
self.assertEqual(l_bytes, b'\x00\x00\x00\x00')
<|end_body_0|>
<|body_start_1|>
l_int = 0
l_bytes = convert.int_2_bigend(l_int, 2)
self.assertEqual(l_bytes, b'\x00\x00')
<|end_body_1|>
<|body_start_2|>
... | Test fetching big endian byte strings | D3_BigEnd | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class D3_BigEnd:
"""Test fetching big endian byte strings"""
def test_01_zero4(self):
"""Convert a datetime to Minutes"""
<|body_0|>
def test_02_zero2(self):
"""Convert a datetime to Minutes"""
<|body_1|>
def test_03_15_4(self):
"""Convert a dateti... | stack_v2_sparse_classes_10k_train_000823 | 6,756 | permissive | [
{
"docstring": "Convert a datetime to Minutes",
"name": "test_01_zero4",
"signature": "def test_01_zero4(self)"
},
{
"docstring": "Convert a datetime to Minutes",
"name": "test_02_zero2",
"signature": "def test_02_zero2(self)"
},
{
"docstring": "Convert a datetime to Minutes",
... | 6 | stack_v2_sparse_classes_30k_train_003925 | Implement the Python class `D3_BigEnd` described below.
Class description:
Test fetching big endian byte strings
Method signatures and docstrings:
- def test_01_zero4(self): Convert a datetime to Minutes
- def test_02_zero2(self): Convert a datetime to Minutes
- def test_03_15_4(self): Convert a datetime to Minutes
-... | Implement the Python class `D3_BigEnd` described below.
Class description:
Test fetching big endian byte strings
Method signatures and docstrings:
- def test_01_zero4(self): Convert a datetime to Minutes
- def test_02_zero2(self): Convert a datetime to Minutes
- def test_03_15_4(self): Convert a datetime to Minutes
-... | a100fc67761a22ae47ed6f21f3c9464e2de5d54f | <|skeleton|>
class D3_BigEnd:
"""Test fetching big endian byte strings"""
def test_01_zero4(self):
"""Convert a datetime to Minutes"""
<|body_0|>
def test_02_zero2(self):
"""Convert a datetime to Minutes"""
<|body_1|>
def test_03_15_4(self):
"""Convert a dateti... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class D3_BigEnd:
"""Test fetching big endian byte strings"""
def test_01_zero4(self):
"""Convert a datetime to Minutes"""
l_int = 0
l_bytes = convert.int_2_bigend(l_int, 4)
self.assertEqual(l_bytes, b'\x00\x00\x00\x00')
def test_02_zero2(self):
"""Convert a datetime... | the_stack_v2_python_sparse | Project/src/Modules/Core/Utilities/_test/test_convert.py | DBrianKimmel/PyHouse | train | 3 |
c652428851eb81eab8ea3fa740d3fb1f52b51bfc | [
"super(negative_sampling_loss, self).__init__()\nvocab_size, embedding_dim = word_vectors.size()\nself.embedding = nn.Embedding(vocab_size, embedding_dim)\nself.embedding.weight.data = word_vectors\nself.multinomial = AliasMultinomial(word_distribution)\nself.num_sampled = num_sampled\nself.embedding_dim = embeddin... | <|body_start_0|>
super(negative_sampling_loss, self).__init__()
vocab_size, embedding_dim = word_vectors.size()
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.embedding.weight.data = word_vectors
self.multinomial = AliasMultinomial(word_distribution)
self.n... | negative_sampling_loss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class negative_sampling_loss:
def __init__(self, word_vectors, word_distribution, num_sampled=10):
"""Arguments: word_vectors: A float tensor of shape [vocab_size, embedding_dim]. A word representation like, for example, word2vec or GloVe. word_distribution: A float tensor of shape [vocab_size... | stack_v2_sparse_classes_10k_train_000824 | 29,814 | no_license | [
{
"docstring": "Arguments: word_vectors: A float tensor of shape [vocab_size, embedding_dim]. A word representation like, for example, word2vec or GloVe. word_distribution: A float tensor of shape [vocab_size]. A distribution from which to sample negative words. num_sampled: An integer, number of negative words... | 2 | null | Implement the Python class `negative_sampling_loss` described below.
Class description:
Implement the negative_sampling_loss class.
Method signatures and docstrings:
- def __init__(self, word_vectors, word_distribution, num_sampled=10): Arguments: word_vectors: A float tensor of shape [vocab_size, embedding_dim]. A w... | Implement the Python class `negative_sampling_loss` described below.
Class description:
Implement the negative_sampling_loss class.
Method signatures and docstrings:
- def __init__(self, word_vectors, word_distribution, num_sampled=10): Arguments: word_vectors: A float tensor of shape [vocab_size, embedding_dim]. A w... | 82d3e9808073f2145b039ccf464c526cb85274e3 | <|skeleton|>
class negative_sampling_loss:
def __init__(self, word_vectors, word_distribution, num_sampled=10):
"""Arguments: word_vectors: A float tensor of shape [vocab_size, embedding_dim]. A word representation like, for example, word2vec or GloVe. word_distribution: A float tensor of shape [vocab_size... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class negative_sampling_loss:
def __init__(self, word_vectors, word_distribution, num_sampled=10):
"""Arguments: word_vectors: A float tensor of shape [vocab_size, embedding_dim]. A word representation like, for example, word2vec or GloVe. word_distribution: A float tensor of shape [vocab_size]. A distribut... | the_stack_v2_python_sparse | business/p201908/3507_750/lda2vec_model.py | Alvin2580du/alvin_py | train | 12 | |
98dd2b184bbfe2fcf26fa4d033ee2db1c859827f | [
"print('SnipcartHook:GET: Incoming get')\nprint(request.data)\ndata = {'body': 'ok'}\nreturn Response(data)",
"print('SnipcartHook:POST: Incoming post')\nprint(request.data['eventName'])\ntry:\n if request.data['eventName'] == 'order.completed':\n payment_gateway = 'snipcart'\n user = None\n ... | <|body_start_0|>
print('SnipcartHook:GET: Incoming get')
print(request.data)
data = {'body': 'ok'}
return Response(data)
<|end_body_0|>
<|body_start_1|>
print('SnipcartHook:POST: Incoming post')
print(request.data['eventName'])
try:
if request.data['e... | * Requires token authentication. | SnipcartHook | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnipcartHook:
"""* Requires token authentication."""
def get(self, request, format=None):
"""Docs"""
<|body_0|>
def post(self, request, format=None):
"""Docs"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
print('SnipcartHook:GET: Incoming get')... | stack_v2_sparse_classes_10k_train_000825 | 5,024 | no_license | [
{
"docstring": "Docs",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Docs",
"name": "post",
"signature": "def post(self, request, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004544 | Implement the Python class `SnipcartHook` described below.
Class description:
* Requires token authentication.
Method signatures and docstrings:
- def get(self, request, format=None): Docs
- def post(self, request, format=None): Docs | Implement the Python class `SnipcartHook` described below.
Class description:
* Requires token authentication.
Method signatures and docstrings:
- def get(self, request, format=None): Docs
- def post(self, request, format=None): Docs
<|skeleton|>
class SnipcartHook:
"""* Requires token authentication."""
de... | d1ba4723c0ee8774ed70b8a1d163d10b3dcef28e | <|skeleton|>
class SnipcartHook:
"""* Requires token authentication."""
def get(self, request, format=None):
"""Docs"""
<|body_0|>
def post(self, request, format=None):
"""Docs"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SnipcartHook:
"""* Requires token authentication."""
def get(self, request, format=None):
"""Docs"""
print('SnipcartHook:GET: Incoming get')
print(request.data)
data = {'body': 'ok'}
return Response(data)
def post(self, request, format=None):
"""Docs""... | the_stack_v2_python_sparse | meshhairline/app.py | LogicalAddress/meshhairline | train | 0 |
316cf0f9a0f5244c77ae5c4478424145a7421a84 | [
"self.dt = collections.defaultdict(list)\nfor i in range(len(arr)):\n self.dt[arr[i]].append(i)",
"if value not in self.dt:\n return 0\na = self.dt[value]\nreturn bisect.bisect_right(a, right) - bisect.bisect_left(a, left)"
] | <|body_start_0|>
self.dt = collections.defaultdict(list)
for i in range(len(arr)):
self.dt[arr[i]].append(i)
<|end_body_0|>
<|body_start_1|>
if value not in self.dt:
return 0
a = self.dt[value]
return bisect.bisect_right(a, right) - bisect.bisect_left(a, ... | RangeFreqQuery | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RangeFreqQuery:
def __init__(self, arr):
""":type arr: List[int] thought: a hashmap to store a value's (index), use a binary search for the ranged count a = [2,5,8] bisect.bisect_left(a,1) 0 bisect.bisect_left(a,3) 1 bisect.bisect_left(a,5) 1 bisect.bisect_left(a,6) 2 bisect.bisect_left(... | stack_v2_sparse_classes_10k_train_000826 | 2,667 | no_license | [
{
"docstring": ":type arr: List[int] thought: a hashmap to store a value's (index), use a binary search for the ranged count a = [2,5,8] bisect.bisect_left(a,1) 0 bisect.bisect_left(a,3) 1 bisect.bisect_left(a,5) 1 bisect.bisect_left(a,6) 2 bisect.bisect_left(a,8) 2 , lower range should bisect_left bisect.bisec... | 2 | stack_v2_sparse_classes_30k_train_002553 | Implement the Python class `RangeFreqQuery` described below.
Class description:
Implement the RangeFreqQuery class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int] thought: a hashmap to store a value's (index), use a binary search for the ranged count a = [2,5,8] bisect.bisect_left(a... | Implement the Python class `RangeFreqQuery` described below.
Class description:
Implement the RangeFreqQuery class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int] thought: a hashmap to store a value's (index), use a binary search for the ranged count a = [2,5,8] bisect.bisect_left(a... | 02726da394971ef02616a038dadc126c6ff260de | <|skeleton|>
class RangeFreqQuery:
def __init__(self, arr):
""":type arr: List[int] thought: a hashmap to store a value's (index), use a binary search for the ranged count a = [2,5,8] bisect.bisect_left(a,1) 0 bisect.bisect_left(a,3) 1 bisect.bisect_left(a,5) 1 bisect.bisect_left(a,6) 2 bisect.bisect_left(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RangeFreqQuery:
def __init__(self, arr):
""":type arr: List[int] thought: a hashmap to store a value's (index), use a binary search for the ranged count a = [2,5,8] bisect.bisect_left(a,1) 0 bisect.bisect_left(a,3) 1 bisect.bisect_left(a,5) 1 bisect.bisect_left(a,6) 2 bisect.bisect_left(a,8) 2 , lower... | the_stack_v2_python_sparse | design/N2080_RangeFrequencyQueries.py | zerghua/leetcode-python | train | 2 | |
d81eeb5957717858520517bfda383ed7a7717a04 | [
"table = HTML().table(border='1', klass=TABLE_ENV)\nheading = table.thead.tr\nheading.th('No')\nheading.th('Parameter')\nheading.th('Value')\ndetails = [('application', app.name), ('report time', strftime('%Y-%m-%d %H:%M:%S', gmtime())), ('host', app.ip), ('pid', app.pid), ('user', getpass.getuser()), ('os', app.ge... | <|body_start_0|>
table = HTML().table(border='1', klass=TABLE_ENV)
heading = table.thead.tr
heading.th('No')
heading.th('Parameter')
heading.th('Value')
details = [('application', app.name), ('report time', strftime('%Y-%m-%d %H:%M:%S', gmtime())), ('host', app.ip), ('pid... | Builds html report with details about profiling environment | EnvReportBuilder | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvReportBuilder:
"""Builds html report with details about profiling environment"""
def buildEnvironmentTable(app):
"""Builds a table with environment details :param app: an instance of xpedite app, to interact with target application"""
<|body_0|>
def buildCpuInfoTable(... | stack_v2_sparse_classes_10k_train_000827 | 4,154 | permissive | [
{
"docstring": "Builds a table with environment details :param app: an instance of xpedite app, to interact with target application",
"name": "buildEnvironmentTable",
"signature": "def buildEnvironmentTable(app)"
},
{
"docstring": "Builds a table with cpu info details :param app: an instance of ... | 3 | stack_v2_sparse_classes_30k_train_004997 | Implement the Python class `EnvReportBuilder` described below.
Class description:
Builds html report with details about profiling environment
Method signatures and docstrings:
- def buildEnvironmentTable(app): Builds a table with environment details :param app: an instance of xpedite app, to interact with target appl... | Implement the Python class `EnvReportBuilder` described below.
Class description:
Builds html report with details about profiling environment
Method signatures and docstrings:
- def buildEnvironmentTable(app): Builds a table with environment details :param app: an instance of xpedite app, to interact with target appl... | d6b67e98d4b640c98499a373425f1f009e5b9061 | <|skeleton|>
class EnvReportBuilder:
"""Builds html report with details about profiling environment"""
def buildEnvironmentTable(app):
"""Builds a table with environment details :param app: an instance of xpedite app, to interact with target application"""
<|body_0|>
def buildCpuInfoTable(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EnvReportBuilder:
"""Builds html report with details about profiling environment"""
def buildEnvironmentTable(app):
"""Builds a table with environment details :param app: an instance of xpedite app, to interact with target application"""
table = HTML().table(border='1', klass=TABLE_ENV)
... | the_stack_v2_python_sparse | scripts/lib/xpedite/report/env.py | dendisuhubdy/Xpedite | train | 1 |
85a384044dc73fa4202517f680d806dd78db5f80 | [
"cmd = 'python3 poll_http_endpoint.py --endpoint={endpoint} --max_retries={retries} --retry_interval={retry_interval} --timeout={timeout}'.format(endpoint=endpoint, retries=retries, retry_interval=retry_interval, timeout=timeout)\nif expected_response:\n cmd += ' --expected_response=%s' % expected_response\nif e... | <|body_start_0|>
cmd = 'python3 poll_http_endpoint.py --endpoint={endpoint} --max_retries={retries} --retry_interval={retry_interval} --timeout={timeout}'.format(endpoint=endpoint, retries=retries, retry_interval=retry_interval, timeout=timeout)
if expected_response:
cmd += ' --expected_resp... | Polls http endpoint. | HttpPoller | [
"Classpath-exception-2.0",
"BSD-3-Clause",
"AGPL-3.0-only",
"MIT",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpPoller:
"""Polls http endpoint."""
def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response):
"""Builds command for polling script."""
<|body_0|>
def Run(self, vm, endpoint, headers=(), retries=0, retry_in... | stack_v2_sparse_classes_10k_train_000828 | 3,784 | permissive | [
{
"docstring": "Builds command for polling script.",
"name": "_BuildCommand",
"signature": "def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response)"
},
{
"docstring": "Polls HTTP endpoint. Args: vm: VirtualMachine object. endpoint: ... | 2 | null | Implement the Python class `HttpPoller` described below.
Class description:
Polls http endpoint.
Method signatures and docstrings:
- def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response): Builds command for polling script.
- def Run(self, vm, endpoint,... | Implement the Python class `HttpPoller` described below.
Class description:
Polls http endpoint.
Method signatures and docstrings:
- def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response): Builds command for polling script.
- def Run(self, vm, endpoint,... | d0699f32998898757b036704fba39e5471641f01 | <|skeleton|>
class HttpPoller:
"""Polls http endpoint."""
def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response):
"""Builds command for polling script."""
<|body_0|>
def Run(self, vm, endpoint, headers=(), retries=0, retry_in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HttpPoller:
"""Polls http endpoint."""
def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response):
"""Builds command for polling script."""
cmd = 'python3 poll_http_endpoint.py --endpoint={endpoint} --max_retries={retries} --ret... | the_stack_v2_python_sparse | perfkitbenchmarker/linux_packages/http_poller.py | GoogleCloudPlatform/PerfKitBenchmarker | train | 1,923 |
14f229d21cf6ef1b3df5017db0273fd6874a0179 | [
"result = []\nif not root:\n return result\nqueue = collections.deque([root])\nwhile queue:\n root = queue.pop()\n if root:\n result.append(str(root.val))\n queue.appendleft(root.left)\n queue.appendleft(root.right)\n else:\n result.append('#')\nreturn ' '.join(result)",
"i... | <|body_start_0|>
result = []
if not root:
return result
queue = collections.deque([root])
while queue:
root = queue.pop()
if root:
result.append(str(root.val))
queue.appendleft(root.left)
queue.appendleft... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_000829 | 3,899 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
result = []
if not root:
return result
queue = collections.deque([root])
while queue:
root = queue.pop()
if root:
... | the_stack_v2_python_sparse | Python_leetcode/297_serialize_and_deserialize.py | xiangcao/Leetcode | train | 0 | |
8878bf1772e30bc79e2c67ec0c2157c0a24307b1 | [
"self.window = window\nworkspace = window.application.get_service(IWorkspace)\ncsp = ContainerSelectionPage(id='container_page', workspace=workspace)\nfwp = FilePage(id='file_page', csp=csp)\nself.pages = [csp, fwp]\nsuper(NewFileWizard, self).__init__(**traits)",
"csp = self.pages[0]\nfwp = self.pages[1]\nfile =... | <|body_start_0|>
self.window = window
workspace = window.application.get_service(IWorkspace)
csp = ContainerSelectionPage(id='container_page', workspace=workspace)
fwp = FilePage(id='file_page', csp=csp)
self.pages = [csp, fwp]
super(NewFileWizard, self).__init__(**traits... | A wizard for file creation. | NewFileWizard | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewFileWizard:
"""A wizard for file creation."""
def __init__(self, window, **traits):
"""Returns a NewFileWizard"""
<|body_0|>
def _finished_fired(self):
"""Performs the file resource creation if the wizard is finished successfully."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_10k_train_000830 | 7,361 | permissive | [
{
"docstring": "Returns a NewFileWizard",
"name": "__init__",
"signature": "def __init__(self, window, **traits)"
},
{
"docstring": "Performs the file resource creation if the wizard is finished successfully.",
"name": "_finished_fired",
"signature": "def _finished_fired(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000337 | Implement the Python class `NewFileWizard` described below.
Class description:
A wizard for file creation.
Method signatures and docstrings:
- def __init__(self, window, **traits): Returns a NewFileWizard
- def _finished_fired(self): Performs the file resource creation if the wizard is finished successfully. | Implement the Python class `NewFileWizard` described below.
Class description:
A wizard for file creation.
Method signatures and docstrings:
- def __init__(self, window, **traits): Returns a NewFileWizard
- def _finished_fired(self): Performs the file resource creation if the wizard is finished successfully.
<|skele... | e8fc0b2d6b9b08e60389fc4714a5cf51f628b57f | <|skeleton|>
class NewFileWizard:
"""A wizard for file creation."""
def __init__(self, window, **traits):
"""Returns a NewFileWizard"""
<|body_0|>
def _finished_fired(self):
"""Performs the file resource creation if the wizard is finished successfully."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NewFileWizard:
"""A wizard for file creation."""
def __init__(self, window, **traits):
"""Returns a NewFileWizard"""
self.window = window
workspace = window.application.get_service(IWorkspace)
csp = ContainerSelectionPage(id='container_page', workspace=workspace)
f... | the_stack_v2_python_sparse | puddle/python_editor/new_file_wizard.py | rwl/puddle | train | 2 |
236e095119e026f3d122a24d26c154997b812528 | [
"super(LCNN, self).__init__()\nmodules = [LCNNBlock(n_occupancy * n_neighbor_sites, n_features)]\nfor i in range(n_conv - 1):\n modules.append(LCNNBlock(n_features * n_neighbor_sites, n_features, n_permutation))\nself.LCNN_blocks = nn.Sequential(*modules)\nself.Atom_wise_Conv = Atom_Wise_Convolution(n_features, ... | <|body_start_0|>
super(LCNN, self).__init__()
modules = [LCNNBlock(n_occupancy * n_neighbor_sites, n_features)]
for i in range(n_conv - 1):
modules.append(LCNNBlock(n_features * n_neighbor_sites, n_features, n_permutation))
self.LCNN_blocks = nn.Sequential(*modules)
s... | The Lattice Convolution Neural Network (LCNN) This model takes lattice representation of Adsorbate Surface to predict coverage effects taking into consideration the adjacent elements interaction energies. The model follows the following steps [1] It performs n lattice convolution operations. For more details look at th... | LCNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LCNN:
"""The Lattice Convolution Neural Network (LCNN) This model takes lattice representation of Adsorbate Surface to predict coverage effects taking into consideration the adjacent elements interaction energies. The model follows the following steps [1] It performs n lattice convolution operati... | stack_v2_sparse_classes_10k_train_000831 | 18,579 | permissive | [
{
"docstring": "Parameters ---------- n_occupancy: int, default 3 number of possible occupancy n_neighbor_sites_list: int, default 19 Number of neighbors of each site. n_permutation: int, default 6 Diffrent permutations taken along diffrent directions. n_task: int, default 1 Number of tasks dropout_rate: float,... | 2 | stack_v2_sparse_classes_30k_train_004214 | Implement the Python class `LCNN` described below.
Class description:
The Lattice Convolution Neural Network (LCNN) This model takes lattice representation of Adsorbate Surface to predict coverage effects taking into consideration the adjacent elements interaction energies. The model follows the following steps [1] It... | Implement the Python class `LCNN` described below.
Class description:
The Lattice Convolution Neural Network (LCNN) This model takes lattice representation of Adsorbate Surface to predict coverage effects taking into consideration the adjacent elements interaction energies. The model follows the following steps [1] It... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class LCNN:
"""The Lattice Convolution Neural Network (LCNN) This model takes lattice representation of Adsorbate Surface to predict coverage effects taking into consideration the adjacent elements interaction energies. The model follows the following steps [1] It performs n lattice convolution operati... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LCNN:
"""The Lattice Convolution Neural Network (LCNN) This model takes lattice representation of Adsorbate Surface to predict coverage effects taking into consideration the adjacent elements interaction energies. The model follows the following steps [1] It performs n lattice convolution operations. For more... | the_stack_v2_python_sparse | deepchem/models/torch_models/lcnn.py | deepchem/deepchem | train | 4,876 |
d06726a20cb5bea540755b31d49512dfcff6be58 | [
"result = ''\ni = 0\nwhile i < len(number):\n count = 0\n last = number[i]\n while i < len(number) and number[i] == last:\n i += 1\n count += 1\n result += str(count) + last\nreturn result",
"number = '1'\nfor i in range(n - 1):\n number = self.next(number)\nreturn number"
] | <|body_start_0|>
result = ''
i = 0
while i < len(number):
count = 0
last = number[i]
while i < len(number) and number[i] == last:
i += 1
count += 1
result += str(count) + last
return result
<|end_body_0|>
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def next(self, number):
""">>> s = Solution() >>> s.next("1") '11' >>> s.next("11") '21' >>> s.next("21") '1211' >>> s.next('1211') '111221' >>> s.next('111221') '312211'"""
<|body_0|>
def countAndSay(self, n):
""":type n: int :rtype: str >>> s = Solution()... | stack_v2_sparse_classes_10k_train_000832 | 959 | no_license | [
{
"docstring": ">>> s = Solution() >>> s.next(\"1\") '11' >>> s.next(\"11\") '21' >>> s.next(\"21\") '1211' >>> s.next('1211') '111221' >>> s.next('111221') '312211'",
"name": "next",
"signature": "def next(self, number)"
},
{
"docstring": ":type n: int :rtype: str >>> s = Solution() >>> s.count... | 2 | stack_v2_sparse_classes_30k_train_006360 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def next(self, number): >>> s = Solution() >>> s.next("1") '11' >>> s.next("11") '21' >>> s.next("21") '1211' >>> s.next('1211') '111221' >>> s.next('111221') '312211'
- def coun... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def next(self, number): >>> s = Solution() >>> s.next("1") '11' >>> s.next("11") '21' >>> s.next("21") '1211' >>> s.next('1211') '111221' >>> s.next('111221') '312211'
- def coun... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def next(self, number):
""">>> s = Solution() >>> s.next("1") '11' >>> s.next("11") '21' >>> s.next("21") '1211' >>> s.next('1211') '111221' >>> s.next('111221') '312211'"""
<|body_0|>
def countAndSay(self, n):
""":type n: int :rtype: str >>> s = Solution()... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def next(self, number):
""">>> s = Solution() >>> s.next("1") '11' >>> s.next("11") '21' >>> s.next("21") '1211' >>> s.next('1211') '111221' >>> s.next('111221') '312211'"""
result = ''
i = 0
while i < len(number):
count = 0
last = number[i]
... | the_stack_v2_python_sparse | count_and_say.py | gsy/leetcode | train | 1 | |
7d2bf70a1736b50409a315ef6f4f601f3d63e250 | [
"x, z = self._process_cov_inputs(x, z)\nN = x.shape[0]\nM = z.shape[0]\nd = self.active_dims.size\nx = np.asarray(x)[:, self.active_dims].reshape((N, 1, d))\nz = np.asarray(z)[:, self.active_dims].reshape((1, M, d))\nif lengthscale is None:\n lengthscale = np.ones(d, dtype='d')\nelif isinstance(lengthscale, floa... | <|body_start_0|>
x, z = self._process_cov_inputs(x, z)
N = x.shape[0]
M = z.shape[0]
d = self.active_dims.size
x = np.asarray(x)[:, self.active_dims].reshape((N, 1, d))
z = np.asarray(z)[:, self.active_dims].reshape((1, M, d))
if lengthscale is None:
l... | base class for stationary kernels | Stationary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stationary:
"""base class for stationary kernels"""
def distances_squared(self, x, z=None, lengthscale=None):
"""Evaluate the distance between points squared. Inputs: x : array of shape (N, d) z : array of shape (M, d) (optional) Outputs: k : matrix of distances of shape shape (N, M)... | stack_v2_sparse_classes_10k_train_000833 | 9,047 | no_license | [
{
"docstring": "Evaluate the distance between points squared. Inputs: x : array of shape (N, d) z : array of shape (M, d) (optional) Outputs: k : matrix of distances of shape shape (N, M)",
"name": "distances_squared",
"signature": "def distances_squared(self, x, z=None, lengthscale=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_test_000219 | Implement the Python class `Stationary` described below.
Class description:
base class for stationary kernels
Method signatures and docstrings:
- def distances_squared(self, x, z=None, lengthscale=None): Evaluate the distance between points squared. Inputs: x : array of shape (N, d) z : array of shape (M, d) (optiona... | Implement the Python class `Stationary` described below.
Class description:
base class for stationary kernels
Method signatures and docstrings:
- def distances_squared(self, x, z=None, lengthscale=None): Evaluate the distance between points squared. Inputs: x : array of shape (N, d) z : array of shape (M, d) (optiona... | 1bed882b8a94ee58fd0bde6920ee85f81ffb77bb | <|skeleton|>
class Stationary:
"""base class for stationary kernels"""
def distances_squared(self, x, z=None, lengthscale=None):
"""Evaluate the distance between points squared. Inputs: x : array of shape (N, d) z : array of shape (M, d) (optional) Outputs: k : matrix of distances of shape shape (N, M)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Stationary:
"""base class for stationary kernels"""
def distances_squared(self, x, z=None, lengthscale=None):
"""Evaluate the distance between points squared. Inputs: x : array of shape (N, d) z : array of shape (M, d) (optional) Outputs: k : matrix of distances of shape shape (N, M)"""
x... | the_stack_v2_python_sparse | gp_grief/kern/stationary.py | scwolof/gp_grief | train | 2 |
eeb645ab00f85e64892190fc40e1e5d260caf40a | [
"self.indices = indices\nself.values = values\nself.axis = axis\nself.reduce = reduce\nself.types = types\nif paddle.device.is_compiled_with_cuda() is True:\n self.places = ['cpu', 'gpu:0']\nelse:\n self.places = ['cpu']",
"paddle.set_device(device)\npaddle.disable_static()\narr = paddle.to_tensor(self.arr,... | <|body_start_0|>
self.indices = indices
self.values = values
self.axis = axis
self.reduce = reduce
self.types = types
if paddle.device.is_compiled_with_cuda() is True:
self.places = ['cpu', 'gpu:0']
else:
self.places = ['cpu']
<|end_body_0|... | calculate put_along_axis api | PutAlongAxis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PutAlongAxis:
"""calculate put_along_axis api"""
def __init__(self, indices, values, axis, types, reduce='assign'):
"""init"""
<|body_0|>
def cal_dynamic(self, device, dtype):
"""dynamic calculate"""
<|body_1|>
def cal_static(self, device):
"... | stack_v2_sparse_classes_10k_train_000834 | 6,483 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, indices, values, axis, types, reduce='assign')"
},
{
"docstring": "dynamic calculate",
"name": "cal_dynamic",
"signature": "def cal_dynamic(self, device, dtype)"
},
{
"docstring": "static_calculate",
... | 4 | null | Implement the Python class `PutAlongAxis` described below.
Class description:
calculate put_along_axis api
Method signatures and docstrings:
- def __init__(self, indices, values, axis, types, reduce='assign'): init
- def cal_dynamic(self, device, dtype): dynamic calculate
- def cal_static(self, device): static_calcul... | Implement the Python class `PutAlongAxis` described below.
Class description:
calculate put_along_axis api
Method signatures and docstrings:
- def __init__(self, indices, values, axis, types, reduce='assign'): init
- def cal_dynamic(self, device, dtype): dynamic calculate
- def cal_static(self, device): static_calcul... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class PutAlongAxis:
"""calculate put_along_axis api"""
def __init__(self, indices, values, axis, types, reduce='assign'):
"""init"""
<|body_0|>
def cal_dynamic(self, device, dtype):
"""dynamic calculate"""
<|body_1|>
def cal_static(self, device):
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PutAlongAxis:
"""calculate put_along_axis api"""
def __init__(self, indices, values, axis, types, reduce='assign'):
"""init"""
self.indices = indices
self.values = values
self.axis = axis
self.reduce = reduce
self.types = types
if paddle.device.is_c... | the_stack_v2_python_sparse | framework/api/paddlebase/test_put_along_axis_.py | PaddlePaddle/PaddleTest | train | 42 |
873a7a1d658535c24f4ac6f2c37bfb47b326acb8 | [
"self.text_format = text_format\nself.justify: JustifyMethod = justify\nself.style = style\nself.markup = markup\nself.highlighter = highlighter\nself.overflow: Optional[OverflowMethod] = overflow\nself.width = width\nsuper().__init__()",
"_text = self.text_format.format(task=task)\nif self.markup:\n text = Te... | <|body_start_0|>
self.text_format = text_format
self.justify: JustifyMethod = justify
self.style = style
self.markup = markup
self.highlighter = highlighter
self.overflow: Optional[OverflowMethod] = overflow
self.width = width
super().__init__()
<|end_body... | Custom sized text column based on the Rich library. | SizedTextColumn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SizedTextColumn:
"""Custom sized text column based on the Rich library."""
def __init__(self, text_format: str, style: StyleType='none', justify: JustifyMethod='left', markup: bool=True, highlighter: Optional[Highlighter]=None, overflow: Optional[OverflowMethod]=None, width: int=20) -> None:... | stack_v2_sparse_classes_10k_train_000835 | 13,137 | permissive | [
{
"docstring": "A column containing text. ### Arguments - text_format: The format string to use for the text. - style: The style to use for the text. - justify: The justification to use for the text. - markup: Whether or not the text should be rendered as markup. - highlighter: A Highlighter to use for highligh... | 2 | stack_v2_sparse_classes_30k_train_006554 | Implement the Python class `SizedTextColumn` described below.
Class description:
Custom sized text column based on the Rich library.
Method signatures and docstrings:
- def __init__(self, text_format: str, style: StyleType='none', justify: JustifyMethod='left', markup: bool=True, highlighter: Optional[Highlighter]=No... | Implement the Python class `SizedTextColumn` described below.
Class description:
Custom sized text column based on the Rich library.
Method signatures and docstrings:
- def __init__(self, text_format: str, style: StyleType='none', justify: JustifyMethod='left', markup: bool=True, highlighter: Optional[Highlighter]=No... | 1924fbe6d5fdc4cd9132464f377fce150750730e | <|skeleton|>
class SizedTextColumn:
"""Custom sized text column based on the Rich library."""
def __init__(self, text_format: str, style: StyleType='none', justify: JustifyMethod='left', markup: bool=True, highlighter: Optional[Highlighter]=None, overflow: Optional[OverflowMethod]=None, width: int=20) -> None:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SizedTextColumn:
"""Custom sized text column based on the Rich library."""
def __init__(self, text_format: str, style: StyleType='none', justify: JustifyMethod='left', markup: bool=True, highlighter: Optional[Highlighter]=None, overflow: Optional[OverflowMethod]=None, width: int=20) -> None:
"""A... | the_stack_v2_python_sparse | spotdl/download/progress_handler.py | phcreery/spotify-downloader | train | 2 |
2e9a3a07b7d32bbe35ad945ef2f107fac83a362a | [
"source_map = defaultdict(lambda: 'USD')\ncost_models = CostModel.objects.all().values('uuid', 'currency').distinct()\ncm_to_currency = {row['uuid']: row['currency'] for row in cost_models}\nmapping = CostModelMap.objects.all().values('provider_uuid', 'cost_model_id')\nsource_map |= {row['provider_uuid']: cm_to_cur... | <|body_start_0|>
source_map = defaultdict(lambda: 'USD')
cost_models = CostModel.objects.all().values('uuid', 'currency').distinct()
cm_to_currency = {row['uuid']: row['currency'] for row in cost_models}
mapping = CostModelMap.objects.all().values('provider_uuid', 'cost_model_id')
... | OCP forecasting class. | OCPForecast | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OCPForecast:
"""OCP forecasting class."""
def source_to_currency_map(self):
"""OCP sources do not have costs associated, so we need to grab the base currency from the cost model, and create a mapping of source_uuid to currency. returns: dict: {source_uuid: currency}"""
<|body... | stack_v2_sparse_classes_10k_train_000836 | 26,653 | permissive | [
{
"docstring": "OCP sources do not have costs associated, so we need to grab the base currency from the cost model, and create a mapping of source_uuid to currency. returns: dict: {source_uuid: currency}",
"name": "source_to_currency_map",
"signature": "def source_to_currency_map(self)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_005429 | Implement the Python class `OCPForecast` described below.
Class description:
OCP forecasting class.
Method signatures and docstrings:
- def source_to_currency_map(self): OCP sources do not have costs associated, so we need to grab the base currency from the cost model, and create a mapping of source_uuid to currency.... | Implement the Python class `OCPForecast` described below.
Class description:
OCP forecasting class.
Method signatures and docstrings:
- def source_to_currency_map(self): OCP sources do not have costs associated, so we need to grab the base currency from the cost model, and create a mapping of source_uuid to currency.... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class OCPForecast:
"""OCP forecasting class."""
def source_to_currency_map(self):
"""OCP sources do not have costs associated, so we need to grab the base currency from the cost model, and create a mapping of source_uuid to currency. returns: dict: {source_uuid: currency}"""
<|body... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OCPForecast:
"""OCP forecasting class."""
def source_to_currency_map(self):
"""OCP sources do not have costs associated, so we need to grab the base currency from the cost model, and create a mapping of source_uuid to currency. returns: dict: {source_uuid: currency}"""
source_map = defaul... | the_stack_v2_python_sparse | koku/forecast/forecast.py | project-koku/koku | train | 225 |
1bb9db5eb0f6d75336bbc4809832f4967405ae92 | [
"try:\n release = Release.objects.get(organization_id=project.organization_id, projects=project, version=version)\nexcept Release.DoesNotExist:\n raise ResourceDoesNotExist\nreturn self.get_releasefile(request, release, file_id, check_permission_fn=lambda: has_download_permission(request, project))",
"try:\... | <|body_start_0|>
try:
release = Release.objects.get(organization_id=project.organization_id, projects=project, version=version)
except Release.DoesNotExist:
raise ResourceDoesNotExist
return self.get_releasefile(request, release, file_id, check_permission_fn=lambda: has_d... | ProjectReleaseFileDetailsEndpoint | [
"Apache-2.0",
"BUSL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectReleaseFileDetailsEndpoint:
def get(self, request: Request, project, version, file_id) -> Response:
"""Retrieve a Project Release's File ````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file,... | stack_v2_sparse_classes_10k_train_000837 | 10,538 | permissive | [
{
"docstring": "Retrieve a Project Release's File ````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file, just the associated metadata. :pparam string organization_slug: the slug of the organization the release belongs to. ... | 3 | stack_v2_sparse_classes_30k_train_005240 | Implement the Python class `ProjectReleaseFileDetailsEndpoint` described below.
Class description:
Implement the ProjectReleaseFileDetailsEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, project, version, file_id) -> Response: Retrieve a Project Release's File ``````````````````````... | Implement the Python class `ProjectReleaseFileDetailsEndpoint` described below.
Class description:
Implement the ProjectReleaseFileDetailsEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, project, version, file_id) -> Response: Retrieve a Project Release's File ``````````````````````... | d9dd4f382f96b5c4576b64cbf015db651556c18b | <|skeleton|>
class ProjectReleaseFileDetailsEndpoint:
def get(self, request: Request, project, version, file_id) -> Response:
"""Retrieve a Project Release's File ````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProjectReleaseFileDetailsEndpoint:
def get(self, request: Request, project, version, file_id) -> Response:
"""Retrieve a Project Release's File ````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file, just the asso... | the_stack_v2_python_sparse | src/sentry/api/endpoints/project_release_file_details.py | nagyist/sentry | train | 0 | |
cf360b3df06229fa5a122288dee32421a844311d | [
"super(UpConvBlock, self).__init__()\nself.upconv = UpConv2x2(in_channels)\nself.conv1 = conv3x3(in_channels, out_channels)\nself.conv2 = conv3x3(out_channels, out_channels)\nself.conv3 = conv3x3(out_channels, out_channels)\nself.norm = nn.BatchNorm2d(out_channels, track_running_stats=False)",
"xv = self.upconv(x... | <|body_start_0|>
super(UpConvBlock, self).__init__()
self.upconv = UpConv2x2(in_channels)
self.conv1 = conv3x3(in_channels, out_channels)
self.conv2 = conv3x3(out_channels, out_channels)
self.conv3 = conv3x3(out_channels, out_channels)
self.norm = nn.BatchNorm2d(out_chann... | UpConvBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpConvBlock:
def __init__(self, in_channels, out_channels):
"""Args: in_channels: number of channels in input (1st) feature map out_channels: number of channels in output feature maps"""
<|body_0|>
def forward(self, xh, xv):
"""Args: xh: torch Variable, activations f... | stack_v2_sparse_classes_10k_train_000838 | 6,249 | permissive | [
{
"docstring": "Args: in_channels: number of channels in input (1st) feature map out_channels: number of channels in output feature maps",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels)"
},
{
"docstring": "Args: xh: torch Variable, activations from same resolutio... | 2 | stack_v2_sparse_classes_30k_val_000018 | Implement the Python class `UpConvBlock` described below.
Class description:
Implement the UpConvBlock class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels): Args: in_channels: number of channels in input (1st) feature map out_channels: number of channels in output feature maps
- de... | Implement the Python class `UpConvBlock` described below.
Class description:
Implement the UpConvBlock class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels): Args: in_channels: number of channels in input (1st) feature map out_channels: number of channels in output feature maps
- de... | cae21c67316ed36529fdc2e470a105a9f847975c | <|skeleton|>
class UpConvBlock:
def __init__(self, in_channels, out_channels):
"""Args: in_channels: number of channels in input (1st) feature map out_channels: number of channels in output feature maps"""
<|body_0|>
def forward(self, xh, xv):
"""Args: xh: torch Variable, activations f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpConvBlock:
def __init__(self, in_channels, out_channels):
"""Args: in_channels: number of channels in input (1st) feature map out_channels: number of channels in output feature maps"""
super(UpConvBlock, self).__init__()
self.upconv = UpConv2x2(in_channels)
self.conv1 = conv3... | the_stack_v2_python_sparse | models/alex_fold_detector_norm_0130/architecture.py | seung-lab/SEAMLeSS | train | 7 | |
4b96b43b6f30a06ab9a55da59cbbe7a2d7287d13 | [
"super().__init__()\nself.urls = urls\nself.queue = queue\nself.username = username\nself.password = password\nself.max_retries = max_retries\nself.retry_delay = retry_delay\nself.ttl_in_seconds = ttl_in_seconds\nif self.urls is None or not isinstance(urls, List) or len(urls) == 0:\n raise ValueError('Invalid ur... | <|body_start_0|>
super().__init__()
self.urls = urls
self.queue = queue
self.username = username
self.password = password
self.max_retries = max_retries
self.retry_delay = retry_delay
self.ttl_in_seconds = ttl_in_seconds
if self.urls is None or not... | Proton implementation of a queue adaptor. | ProtonQueueAdaptor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtonQueueAdaptor:
"""Proton implementation of a queue adaptor."""
def __init__(self, urls: List[str], queue: str, username, password, max_retries=0, retry_delay=0, ttl_in_seconds=0) -> None:
"""Construct a Proton implementation of a :class:`QueueAdaptor <comms.queue_adaptor.QueueAd... | stack_v2_sparse_classes_10k_train_000839 | 10,709 | permissive | [
{
"docstring": "Construct a Proton implementation of a :class:`QueueAdaptor <comms.queue_adaptor.QueueAdaptor>`. The kwargs provided should contain the following information: * host: The host of the Message Queue to be interacted with. * username: The username to use to connect to the Message Queue. * password ... | 5 | null | Implement the Python class `ProtonQueueAdaptor` described below.
Class description:
Proton implementation of a queue adaptor.
Method signatures and docstrings:
- def __init__(self, urls: List[str], queue: str, username, password, max_retries=0, retry_delay=0, ttl_in_seconds=0) -> None: Construct a Proton implementati... | Implement the Python class `ProtonQueueAdaptor` described below.
Class description:
Proton implementation of a queue adaptor.
Method signatures and docstrings:
- def __init__(self, urls: List[str], queue: str, username, password, max_retries=0, retry_delay=0, ttl_in_seconds=0) -> None: Construct a Proton implementati... | 8420d9d4b800223bff6a648015679684f5aba38c | <|skeleton|>
class ProtonQueueAdaptor:
"""Proton implementation of a queue adaptor."""
def __init__(self, urls: List[str], queue: str, username, password, max_retries=0, retry_delay=0, ttl_in_seconds=0) -> None:
"""Construct a Proton implementation of a :class:`QueueAdaptor <comms.queue_adaptor.QueueAd... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProtonQueueAdaptor:
"""Proton implementation of a queue adaptor."""
def __init__(self, urls: List[str], queue: str, username, password, max_retries=0, retry_delay=0, ttl_in_seconds=0) -> None:
"""Construct a Proton implementation of a :class:`QueueAdaptor <comms.queue_adaptor.QueueAdaptor>`. The ... | the_stack_v2_python_sparse | common/comms/proton_queue_adaptor.py | nhsconnect/integration-adaptors | train | 15 |
b7c021335237a360542601e7b8972b8b202480e3 | [
"leaves = []\nself.dfs(root, leaves)\nreturn leaves",
"if not node:\n return -1\nheight = 1 + max(self.dfs(node.left, leaves), self.dfs(node.right, leaves))\nif height >= len(leaves):\n leaves.append([])\nleaves[height].append(node.val)\nreturn height"
] | <|body_start_0|>
leaves = []
self.dfs(root, leaves)
return leaves
<|end_body_0|>
<|body_start_1|>
if not node:
return -1
height = 1 + max(self.dfs(node.left, leaves), self.dfs(node.right, leaves))
if height >= len(leaves):
leaves.append([])
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLeaves(self, root):
"""The key is 1. to find height of a tree 2. to maintain a leaves nested list The height of a node is the number of edges from the node to the deepest leaf. :type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def dfs(self, node, l... | stack_v2_sparse_classes_10k_train_000840 | 999 | permissive | [
{
"docstring": "The key is 1. to find height of a tree 2. to maintain a leaves nested list The height of a node is the number of edges from the node to the deepest leaf. :type root: TreeNode :rtype: List[List[int]]",
"name": "findLeaves",
"signature": "def findLeaves(self, root)"
},
{
"docstring... | 2 | stack_v2_sparse_classes_30k_train_002966 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLeaves(self, root): The key is 1. to find height of a tree 2. to maintain a leaves nested list The height of a node is the number of edges from the node to the deepest le... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLeaves(self, root): The key is 1. to find height of a tree 2. to maintain a leaves nested list The height of a node is the number of edges from the node to the deepest le... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def findLeaves(self, root):
"""The key is 1. to find height of a tree 2. to maintain a leaves nested list The height of a node is the number of edges from the node to the deepest leaf. :type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def dfs(self, node, l... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findLeaves(self, root):
"""The key is 1. to find height of a tree 2. to maintain a leaves nested list The height of a node is the number of edges from the node to the deepest leaf. :type root: TreeNode :rtype: List[List[int]]"""
leaves = []
self.dfs(root, leaves)
... | the_stack_v2_python_sparse | 366 Find Leaves of Binary Tree.py | Aminaba123/LeetCode | train | 1 | |
15c87d4742a17bab9f19927567f9cab6a21d1a45 | [
"header = {'typ': 'JWT', 'alg': 'HS256'}\nheader = json.dumps(header, separators=(',', ':')).encode('utf-8')\nheader = base64.urlsafe_b64encode(header).replace(b'=', b'')\np = json.dumps(data, separators=(',', ':')).encode('utf-8')\np = base64.urlsafe_b64encode(p).replace(b'=', b'')\nsecret_key = properties.get('se... | <|body_start_0|>
header = {'typ': 'JWT', 'alg': 'HS256'}
header = json.dumps(header, separators=(',', ':')).encode('utf-8')
header = base64.urlsafe_b64encode(header).replace(b'=', b'')
p = json.dumps(data, separators=(',', ':')).encode('utf-8')
p = base64.urlsafe_b64encode(p).rep... | JWT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JWT:
def encode(data):
"""JWT签名 :param data: :return:"""
<|body_0|>
def verify(access_token):
"""JWT验签 :param access_token: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
header = {'typ': 'JWT', 'alg': 'HS256'}
header = json.dumps(... | stack_v2_sparse_classes_10k_train_000841 | 2,016 | no_license | [
{
"docstring": "JWT签名 :param data: :return:",
"name": "encode",
"signature": "def encode(data)"
},
{
"docstring": "JWT验签 :param access_token: :return:",
"name": "verify",
"signature": "def verify(access_token)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004939 | Implement the Python class `JWT` described below.
Class description:
Implement the JWT class.
Method signatures and docstrings:
- def encode(data): JWT签名 :param data: :return:
- def verify(access_token): JWT验签 :param access_token: :return: | Implement the Python class `JWT` described below.
Class description:
Implement the JWT class.
Method signatures and docstrings:
- def encode(data): JWT签名 :param data: :return:
- def verify(access_token): JWT验签 :param access_token: :return:
<|skeleton|>
class JWT:
def encode(data):
"""JWT签名 :param data: ... | 6156ba7e3b87552b80fe20b886fa476d8fc4a277 | <|skeleton|>
class JWT:
def encode(data):
"""JWT签名 :param data: :return:"""
<|body_0|>
def verify(access_token):
"""JWT验签 :param access_token: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JWT:
def encode(data):
"""JWT签名 :param data: :return:"""
header = {'typ': 'JWT', 'alg': 'HS256'}
header = json.dumps(header, separators=(',', ':')).encode('utf-8')
header = base64.urlsafe_b64encode(header).replace(b'=', b'')
p = json.dumps(data, separators=(',', ':')).e... | the_stack_v2_python_sparse | tools/jwt.py | Duo-Shou-Store/DSSP | train | 0 | |
2d26ae887ff3bebbae5706a93293ced0f6631fa4 | [
"self.level = 0\nself.header = Node(MAX_LEVEL, None, None)\nself.size = 0",
"i = self.level - 1\nq = self.header\nwhile i >= 0:\n while q.forward[i] and q.forward[i].key <= key:\n if q.forward[i].key == key:\n return (q.forward[i].key, q.forward[1].value, i)\n q = q.forward[i]\n i -... | <|body_start_0|>
self.level = 0
self.header = Node(MAX_LEVEL, None, None)
self.size = 0
<|end_body_0|>
<|body_start_1|>
i = self.level - 1
q = self.header
while i >= 0:
while q.forward[i] and q.forward[i].key <= key:
if q.forward[i].key == key... | SkipList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkipList:
def __init__(self):
"""跳表初始化 层数为0 初始化头部节点"""
<|body_0|>
def search(self, key):
"""跳表搜索操作 :param key: 查找的关键字 :return: 节点的 key & value & 节点所在的层数(最高的层数)"""
<|body_1|>
def insert(self, key, value):
"""跳表插入操作 :param key: 节点索引值 :param value: ... | stack_v2_sparse_classes_10k_train_000842 | 2,899 | no_license | [
{
"docstring": "跳表初始化 层数为0 初始化头部节点",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "跳表搜索操作 :param key: 查找的关键字 :return: 节点的 key & value & 节点所在的层数(最高的层数)",
"name": "search",
"signature": "def search(self, key)"
},
{
"docstring": "跳表插入操作 :param key: 节点索引值 :... | 3 | stack_v2_sparse_classes_30k_train_003504 | Implement the Python class `SkipList` described below.
Class description:
Implement the SkipList class.
Method signatures and docstrings:
- def __init__(self): 跳表初始化 层数为0 初始化头部节点
- def search(self, key): 跳表搜索操作 :param key: 查找的关键字 :return: 节点的 key & value & 节点所在的层数(最高的层数)
- def insert(self, key, value): 跳表插入操作 :param ... | Implement the Python class `SkipList` described below.
Class description:
Implement the SkipList class.
Method signatures and docstrings:
- def __init__(self): 跳表初始化 层数为0 初始化头部节点
- def search(self, key): 跳表搜索操作 :param key: 查找的关键字 :return: 节点的 key & value & 节点所在的层数(最高的层数)
- def insert(self, key, value): 跳表插入操作 :param ... | 9030cbf726b384d05e634195b78f6789af612aa1 | <|skeleton|>
class SkipList:
def __init__(self):
"""跳表初始化 层数为0 初始化头部节点"""
<|body_0|>
def search(self, key):
"""跳表搜索操作 :param key: 查找的关键字 :return: 节点的 key & value & 节点所在的层数(最高的层数)"""
<|body_1|>
def insert(self, key, value):
"""跳表插入操作 :param key: 节点索引值 :param value: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SkipList:
def __init__(self):
"""跳表初始化 层数为0 初始化头部节点"""
self.level = 0
self.header = Node(MAX_LEVEL, None, None)
self.size = 0
def search(self, key):
"""跳表搜索操作 :param key: 查找的关键字 :return: 节点的 key & value & 节点所在的层数(最高的层数)"""
i = self.level - 1
q = sel... | the_stack_v2_python_sparse | data_struct/skiplist.py | houhailun/data_struct_alrhorithm | train | 1 | |
83ce793ab6370b162367585b8c071081bee388da | [
"self.database_id = database_id\nself.name = name\nself.open_mode = open_mode\nself.size_bytes = size_bytes",
"if dictionary is None:\n return None\ndatabase_id = dictionary.get('databaseId')\nname = dictionary.get('name')\nopen_mode = dictionary.get('openMode')\nsize_bytes = dictionary.get('sizeBytes')\nretur... | <|body_start_0|>
self.database_id = database_id
self.name = name
self.open_mode = open_mode
self.size_bytes = size_bytes
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
database_id = dictionary.get('databaseId')
name = dictionary.ge... | Implementation of the 'OraclePluggableDatabaseInfo' model. Specifies the informatiomn about the pluggable database. A Pluggabele Database(PDB) is a portable collection of schemas, schema objects, and nonschema objects that appears to an Oracle Net client as a non-CDB. Attributes: database_id (string): Specifies the ID ... | OraclePluggableDatabaseInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OraclePluggableDatabaseInfo:
"""Implementation of the 'OraclePluggableDatabaseInfo' model. Specifies the informatiomn about the pluggable database. A Pluggabele Database(PDB) is a portable collection of schemas, schema objects, and nonschema objects that appears to an Oracle Net client as a non-C... | stack_v2_sparse_classes_10k_train_000843 | 2,649 | permissive | [
{
"docstring": "Constructor for the OraclePluggableDatabaseInfo class",
"name": "__init__",
"signature": "def __init__(self, database_id=None, name=None, open_mode=None, size_bytes=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dict... | 2 | null | Implement the Python class `OraclePluggableDatabaseInfo` described below.
Class description:
Implementation of the 'OraclePluggableDatabaseInfo' model. Specifies the informatiomn about the pluggable database. A Pluggabele Database(PDB) is a portable collection of schemas, schema objects, and nonschema objects that app... | Implement the Python class `OraclePluggableDatabaseInfo` described below.
Class description:
Implementation of the 'OraclePluggableDatabaseInfo' model. Specifies the informatiomn about the pluggable database. A Pluggabele Database(PDB) is a portable collection of schemas, schema objects, and nonschema objects that app... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class OraclePluggableDatabaseInfo:
"""Implementation of the 'OraclePluggableDatabaseInfo' model. Specifies the informatiomn about the pluggable database. A Pluggabele Database(PDB) is a portable collection of schemas, schema objects, and nonschema objects that appears to an Oracle Net client as a non-C... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OraclePluggableDatabaseInfo:
"""Implementation of the 'OraclePluggableDatabaseInfo' model. Specifies the informatiomn about the pluggable database. A Pluggabele Database(PDB) is a portable collection of schemas, schema objects, and nonschema objects that appears to an Oracle Net client as a non-CDB. Attribute... | the_stack_v2_python_sparse | cohesity_management_sdk/models/oracle_pluggable_database_info.py | cohesity/management-sdk-python | train | 24 |
fff7b890da23348a6c8b6afa9e22bb9afec32872 | [
"article = ArticleInst.fetch(slug)\ncomment = request.data.get('comment', {})\nposted_comment = CommentAPIView.check_comment(id, article)\nserializer = self.serializer_class(data=comment)\nserializer.is_valid(raise_exception=True)\nstatus_ = status.HTTP_201_CREATED\ntry:\n CommentReply.objects.get(comment_to=pos... | <|body_start_0|>
article = ArticleInst.fetch(slug)
comment = request.data.get('comment', {})
posted_comment = CommentAPIView.check_comment(id, article)
serializer = self.serializer_class(data=comment)
serializer.is_valid(raise_exception=True)
status_ = status.HTTP_201_CRE... | Handles viweing of replies made to a comment and replying to an article comment | ReplyList | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReplyList:
"""Handles viweing of replies made to a comment and replying to an article comment"""
def post(self, request, slug, id):
"""Posts a reply to a comment"""
<|body_0|>
def get(self, request, slug, id):
"""Retrieves all replies to a comment of matching ID"... | stack_v2_sparse_classes_10k_train_000844 | 10,918 | permissive | [
{
"docstring": "Posts a reply to a comment",
"name": "post",
"signature": "def post(self, request, slug, id)"
},
{
"docstring": "Retrieves all replies to a comment of matching ID",
"name": "get",
"signature": "def get(self, request, slug, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004290 | Implement the Python class `ReplyList` described below.
Class description:
Handles viweing of replies made to a comment and replying to an article comment
Method signatures and docstrings:
- def post(self, request, slug, id): Posts a reply to a comment
- def get(self, request, slug, id): Retrieves all replies to a co... | Implement the Python class `ReplyList` described below.
Class description:
Handles viweing of replies made to a comment and replying to an article comment
Method signatures and docstrings:
- def post(self, request, slug, id): Posts a reply to a comment
- def get(self, request, slug, id): Retrieves all replies to a co... | b80ad485339dbb02b74d9b2093543bf8173d51de | <|skeleton|>
class ReplyList:
"""Handles viweing of replies made to a comment and replying to an article comment"""
def post(self, request, slug, id):
"""Posts a reply to a comment"""
<|body_0|>
def get(self, request, slug, id):
"""Retrieves all replies to a comment of matching ID"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReplyList:
"""Handles viweing of replies made to a comment and replying to an article comment"""
def post(self, request, slug, id):
"""Posts a reply to a comment"""
article = ArticleInst.fetch(slug)
comment = request.data.get('comment', {})
posted_comment = CommentAPIView.... | the_stack_v2_python_sparse | authors/apps/comments/views.py | deferral/ah-django | train | 1 |
cf7f8e5f4b2ab085e09fc485224662d5c0119e6d | [
"super(AdamLossScalingOptimizer, self).__init__(False, name)\nself.learning_rate = tf.cast(learning_rate, dtype=weights_dtype)\nself.loss_scaling = loss_scaling\nself.beta_1 = beta_1\nself.beta_2 = beta_2\nself.epsilon = epsilon",
"assignments = []\nfor grad, param in grads_and_vars:\n if grad is None or param... | <|body_start_0|>
super(AdamLossScalingOptimizer, self).__init__(False, name)
self.learning_rate = tf.cast(learning_rate, dtype=weights_dtype)
self.loss_scaling = loss_scaling
self.beta_1 = beta_1
self.beta_2 = beta_2
self.epsilon = epsilon
<|end_body_0|>
<|body_start_1|>... | A basic Adam optimizer that includes loss scaling. | AdamLossScalingOptimizer | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdamLossScalingOptimizer:
"""A basic Adam optimizer that includes loss scaling."""
def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-06, name='AdamLossScalingOptimizer', weights_dtype=tf.float16):
"""Constructs a AdamLossScalingOptimizer."""
... | stack_v2_sparse_classes_10k_train_000845 | 3,902 | permissive | [
{
"docstring": "Constructs a AdamLossScalingOptimizer.",
"name": "__init__",
"signature": "def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-06, name='AdamLossScalingOptimizer', weights_dtype=tf.float16)"
},
{
"docstring": "See base class.",
"name": "apply_... | 3 | stack_v2_sparse_classes_30k_train_002123 | Implement the Python class `AdamLossScalingOptimizer` described below.
Class description:
A basic Adam optimizer that includes loss scaling.
Method signatures and docstrings:
- def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-06, name='AdamLossScalingOptimizer', weights_dtype=tf.fl... | Implement the Python class `AdamLossScalingOptimizer` described below.
Class description:
A basic Adam optimizer that includes loss scaling.
Method signatures and docstrings:
- def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-06, name='AdamLossScalingOptimizer', weights_dtype=tf.fl... | 46d2b7687b829778369fc6328170a7b14761e5c6 | <|skeleton|>
class AdamLossScalingOptimizer:
"""A basic Adam optimizer that includes loss scaling."""
def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-06, name='AdamLossScalingOptimizer', weights_dtype=tf.float16):
"""Constructs a AdamLossScalingOptimizer."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdamLossScalingOptimizer:
"""A basic Adam optimizer that includes loss scaling."""
def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-06, name='AdamLossScalingOptimizer', weights_dtype=tf.float16):
"""Constructs a AdamLossScalingOptimizer."""
super(AdamLo... | the_stack_v2_python_sparse | applications/tensorflow/conformer/ipu_optimizer.py | payoto/graphcore_examples | train | 0 |
55d72c67ad38d7dae4f05c6d1cb7e56ae730e236 | [
"c0 = Coordinates()\nself.assertIsNot(c0, None)\nself.assertIsInstance(c0, Coordinates)",
"c0 = Coordinates([1])\nself.assertIsNot(c0, None)\nself.assertIsInstance(c0, Coordinates)\nc1 = Coordinates([1, 2, 3])\nself.assertIsNot(c1, None)\nself.assertIsInstance(c1, Coordinates)\nc2 = Coordinates('xyz')\nc3 = Coord... | <|body_start_0|>
c0 = Coordinates()
self.assertIsNot(c0, None)
self.assertIsInstance(c0, Coordinates)
<|end_body_0|>
<|body_start_1|>
c0 = Coordinates([1])
self.assertIsNot(c0, None)
self.assertIsInstance(c0, Coordinates)
c1 = Coordinates([1, 2, 3])
self.... | Test Coordinate class calls | TestConstructor_Coordinate | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConstructor_Coordinate:
"""Test Coordinate class calls"""
def test_none(self):
"""Calling Coordinates class with no key (kay = None)"""
<|body_0|>
def test_iterable(self):
"""Calling Coordinates class with key conaining simple types"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_000846 | 6,423 | permissive | [
{
"docstring": "Calling Coordinates class with no key (kay = None)",
"name": "test_none",
"signature": "def test_none(self)"
},
{
"docstring": "Calling Coordinates class with key conaining simple types",
"name": "test_iterable",
"signature": "def test_iterable(self)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_004319 | Implement the Python class `TestConstructor_Coordinate` described below.
Class description:
Test Coordinate class calls
Method signatures and docstrings:
- def test_none(self): Calling Coordinates class with no key (kay = None)
- def test_iterable(self): Calling Coordinates class with key conaining simple types
- def... | Implement the Python class `TestConstructor_Coordinate` described below.
Class description:
Test Coordinate class calls
Method signatures and docstrings:
- def test_none(self): Calling Coordinates class with no key (kay = None)
- def test_iterable(self): Calling Coordinates class with key conaining simple types
- def... | f9b00a39bc16aea4abac60c0dd0aab2acac5adcf | <|skeleton|>
class TestConstructor_Coordinate:
"""Test Coordinate class calls"""
def test_none(self):
"""Calling Coordinates class with no key (kay = None)"""
<|body_0|>
def test_iterable(self):
"""Calling Coordinates class with key conaining simple types"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestConstructor_Coordinate:
"""Test Coordinate class calls"""
def test_none(self):
"""Calling Coordinates class with no key (kay = None)"""
c0 = Coordinates()
self.assertIsNot(c0, None)
self.assertIsInstance(c0, Coordinates)
def test_iterable(self):
"""Calling... | the_stack_v2_python_sparse | _BACKUPS_v3/v3_1/LightPicture_Test.py | nagame/LightPicture | train | 0 |
16ed1c8825d10f9148d9f33084c8e49d67afbe07 | [
"@lru_cache(None)\ndef dfs(index: int) -> int:\n if index == n:\n return 0\n curMax, remain = (0, shelfWidth)\n res = INF\n for select in range(1, n - index + 1):\n width, height = books[index + select - 1]\n if width > remain:\n break\n curMax = max(curMax, height... | <|body_start_0|>
@lru_cache(None)
def dfs(index: int) -> int:
if index == n:
return 0
curMax, remain = (0, shelfWidth)
res = INF
for select in range(1, n - index + 1):
width, height = books[index + select - 1]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:
"""O(n^2) dfs[i]表示前i本书的高度之和最小值"""
<|body_0|>
def minHeightShelves2(self, books: List[List[int]], shelfWidth: int) -> int:
"""O(n^2) dp[i]表示前i本书的最小高度之和"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_10k_train_000847 | 2,367 | no_license | [
{
"docstring": "O(n^2) dfs[i]表示前i本书的高度之和最小值",
"name": "minHeightShelves",
"signature": "def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int"
},
{
"docstring": "O(n^2) dp[i]表示前i本书的最小高度之和",
"name": "minHeightShelves2",
"signature": "def minHeightShelves2(self, books:... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int: O(n^2) dfs[i]表示前i本书的高度之和最小值
- def minHeightShelves2(self, books: List[List[int]], shelfWidth: int) -> ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int: O(n^2) dfs[i]表示前i本书的高度之和最小值
- def minHeightShelves2(self, books: List[List[int]], shelfWidth: int) -> ... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:
"""O(n^2) dfs[i]表示前i本书的高度之和最小值"""
<|body_0|>
def minHeightShelves2(self, books: List[List[int]], shelfWidth: int) -> int:
"""O(n^2) dp[i]表示前i本书的最小高度之和"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:
"""O(n^2) dfs[i]表示前i本书的高度之和最小值"""
@lru_cache(None)
def dfs(index: int) -> int:
if index == n:
return 0
curMax, remain = (0, shelfWidth)
res = INF
... | the_stack_v2_python_sparse | 11_动态规划/经典题/dfs+cache/1105. 填充书架..py | 981377660LMT/algorithm-study | train | 225 | |
43dd73d0599f9af4f50a0e239c7c3fa6bb09e6c4 | [
"self._registry_client = registry_client\nself._policy_evaluator = policy_evaluator\nself._permission_calculator = PermissionCalculator(policy_evaluator)",
"logger.debug(f'Rules: {self._policy_evaluator._policy_collection.policies()}')\npermissions = self._permission_calculator.calculate_permissions(job)\nlogger.... | <|body_start_0|>
self._registry_client = registry_client
self._policy_evaluator = policy_evaluator
self._permission_calculator = PermissionCalculator(policy_evaluator)
<|end_body_0|>
<|body_start_1|>
logger.debug(f'Rules: {self._policy_evaluator._policy_collection.policies()}')
... | Plans workflow execution across sites in a DDM. | WorkflowPlanner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowPlanner:
"""Plans workflow execution across sites in a DDM."""
def __init__(self, registry_client: RegistryClient, policy_evaluator: PolicyEvaluator) -> None:
"""Create a WorkflowOrchestrator. Args: registry_client: RegistryClient to get sites from. policy_evaluator: PolicyEv... | stack_v2_sparse_classes_10k_train_000848 | 11,293 | permissive | [
{
"docstring": "Create a WorkflowOrchestrator. Args: registry_client: RegistryClient to get sites from. policy_evaluator: PolicyEvaluator to use for permissions.",
"name": "__init__",
"signature": "def __init__(self, registry_client: RegistryClient, policy_evaluator: PolicyEvaluator) -> None"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_000978 | Implement the Python class `WorkflowPlanner` described below.
Class description:
Plans workflow execution across sites in a DDM.
Method signatures and docstrings:
- def __init__(self, registry_client: RegistryClient, policy_evaluator: PolicyEvaluator) -> None: Create a WorkflowOrchestrator. Args: registry_client: Reg... | Implement the Python class `WorkflowPlanner` described below.
Class description:
Plans workflow execution across sites in a DDM.
Method signatures and docstrings:
- def __init__(self, registry_client: RegistryClient, policy_evaluator: PolicyEvaluator) -> None: Create a WorkflowOrchestrator. Args: registry_client: Reg... | 22f9533a506e039237227ca66faea5375cce5fcb | <|skeleton|>
class WorkflowPlanner:
"""Plans workflow execution across sites in a DDM."""
def __init__(self, registry_client: RegistryClient, policy_evaluator: PolicyEvaluator) -> None:
"""Create a WorkflowOrchestrator. Args: registry_client: RegistryClient to get sites from. policy_evaluator: PolicyEv... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WorkflowPlanner:
"""Plans workflow execution across sites in a DDM."""
def __init__(self, registry_client: RegistryClient, policy_evaluator: PolicyEvaluator) -> None:
"""Create a WorkflowOrchestrator. Args: registry_client: RegistryClient to get sites from. policy_evaluator: PolicyEvaluator to us... | the_stack_v2_python_sparse | mahiru/components/orchestration.py | SecConNet/mahiru | train | 4 |
99a588fd1b3c8e7defae24d01c4ae7e08c5fb5c1 | [
"if num_pixels is None and quantile is None:\n raise ValueError('either num_pixels or quantile must be given')\nself.num_pixels: float = num_pixels\n'Number of pixels with highest values to set to one.'\nself.quantile: float = quantile\n'Quantile of pixels to set to one, rest is set to 0;\\n overridden by... | <|body_start_0|>
if num_pixels is None and quantile is None:
raise ValueError('either num_pixels or quantile must be given')
self.num_pixels: float = num_pixels
'Number of pixels with highest values to set to one.'
self.quantile: float = quantile
'Quantile of pixels t... | Set all but the given highest number of pixels / q-th quantile in an image to zero, rest to 1. Mind for RGB images: A pixel here means a pixel in one channel. | BinarizeByQuantile | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinarizeByQuantile:
"""Set all but the given highest number of pixels / q-th quantile in an image to zero, rest to 1. Mind for RGB images: A pixel here means a pixel in one channel."""
def __init__(self, quantile: float=None, num_pixels: int=None):
"""Init. :param quantile: quantile ... | stack_v2_sparse_classes_10k_train_000849 | 14,707 | permissive | [
{
"docstring": "Init. :param quantile: quantile of pixels to set to 1, rest is set to 0; overridden by ``num_pixels`` :param num_pixels: number of pixels with highest value to set to one, rest is set to 0",
"name": "__init__",
"signature": "def __init__(self, quantile: float=None, num_pixels: int=None)"... | 3 | stack_v2_sparse_classes_30k_train_002310 | Implement the Python class `BinarizeByQuantile` described below.
Class description:
Set all but the given highest number of pixels / q-th quantile in an image to zero, rest to 1. Mind for RGB images: A pixel here means a pixel in one channel.
Method signatures and docstrings:
- def __init__(self, quantile: float=None... | Implement the Python class `BinarizeByQuantile` described below.
Class description:
Set all but the given highest number of pixels / q-th quantile in an image to zero, rest to 1. Mind for RGB images: A pixel here means a pixel in one channel.
Method signatures and docstrings:
- def __init__(self, quantile: float=None... | 37b9fc83d7b14902dfe92e0c45071c150bcf3779 | <|skeleton|>
class BinarizeByQuantile:
"""Set all but the given highest number of pixels / q-th quantile in an image to zero, rest to 1. Mind for RGB images: A pixel here means a pixel in one channel."""
def __init__(self, quantile: float=None, num_pixels: int=None):
"""Init. :param quantile: quantile ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BinarizeByQuantile:
"""Set all but the given highest number of pixels / q-th quantile in an image to zero, rest to 1. Mind for RGB images: A pixel here means a pixel in one channel."""
def __init__(self, quantile: float=None, num_pixels: int=None):
"""Init. :param quantile: quantile of pixels to ... | the_stack_v2_python_sparse | hybrid_learning/datasets/transforms/image_transforms.py | JohnnyZhang917/hybrid_learning | train | 0 |
c1aa2c79ec02ea2569d041088936be373b090142 | [
"s.dingding = dingding\ns.match_pattern = d.get('MatchPattern', None)\ns.xmlrpc_recv_url = d['XmlRpcRecvUrl']\ns.recv_password = d.get('RecvPassword', None)",
"if s.xmlrpc_recv_url != subs.xmlrpc_recv_url:\n return False\nif s.recv_password != subs.recv_password:\n return False\nif not s.match_pattern:\n ... | <|body_start_0|>
s.dingding = dingding
s.match_pattern = d.get('MatchPattern', None)
s.xmlrpc_recv_url = d['XmlRpcRecvUrl']
s.recv_password = d.get('RecvPassword', None)
<|end_body_0|>
<|body_start_1|>
if s.xmlrpc_recv_url != subs.xmlrpc_recv_url:
return False
... | Unsubscription - augment an unsubscription dictionary | Unsubscription | [
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Unsubscription:
"""Unsubscription - augment an unsubscription dictionary"""
def __init__(s, d, dingding):
"""unsubscribe dict: * MatchPattern (*OPTIONAL*) - pattern to unsubscribe; if missing, unsubscribe ALL patterns * XmlRpcRecvUrl (REQUIRED) - XML-RPC URL of unsubscribing interfac... | stack_v2_sparse_classes_10k_train_000850 | 25,098 | permissive | [
{
"docstring": "unsubscribe dict: * MatchPattern (*OPTIONAL*) - pattern to unsubscribe; if missing, unsubscribe ALL patterns * XmlRpcRecvUrl (REQUIRED) - XML-RPC URL of unsubscribing interface * RecvPassword (OPTIONAL) - if there is a password associated with the receiver, put it here nothing else",
"name":... | 2 | stack_v2_sparse_classes_30k_train_007100 | Implement the Python class `Unsubscription` described below.
Class description:
Unsubscription - augment an unsubscription dictionary
Method signatures and docstrings:
- def __init__(s, d, dingding): unsubscribe dict: * MatchPattern (*OPTIONAL*) - pattern to unsubscribe; if missing, unsubscribe ALL patterns * XmlRpcR... | Implement the Python class `Unsubscription` described below.
Class description:
Unsubscription - augment an unsubscription dictionary
Method signatures and docstrings:
- def __init__(s, d, dingding): unsubscribe dict: * MatchPattern (*OPTIONAL*) - pattern to unsubscribe; if missing, unsubscribe ALL patterns * XmlRpcR... | da65d948b346d3f455e79168a8753b2b16d8fc5f | <|skeleton|>
class Unsubscription:
"""Unsubscription - augment an unsubscription dictionary"""
def __init__(s, d, dingding):
"""unsubscribe dict: * MatchPattern (*OPTIONAL*) - pattern to unsubscribe; if missing, unsubscribe ALL patterns * XmlRpcRecvUrl (REQUIRED) - XML-RPC URL of unsubscribing interfac... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Unsubscription:
"""Unsubscription - augment an unsubscription dictionary"""
def __init__(s, d, dingding):
"""unsubscribe dict: * MatchPattern (*OPTIONAL*) - pattern to unsubscribe; if missing, unsubscribe ALL patterns * XmlRpcRecvUrl (REQUIRED) - XML-RPC URL of unsubscribing interface * RecvPassw... | the_stack_v2_python_sparse | ancient/src/dingding/dingding.py | BackupTheBerlios/onebigsoup-svn | train | 0 |
5a67480a3dc085a3ccde932a0bb8a1585e4a596c | [
"self.act_f = activation\nself.dtype = dtype\nself.rnn_idx: np.ndarray = rnn_idx\nself.n_inputs: int = len(input_idx)\nself.n_hidden: int = len(hidden_idx)\nself.n_rnn: int = len(rnn_idx)\nself.n_outputs: int = len(output_idx)\nself.bs: int = batch_size\nrnn_map_temp = []\nfor i, m in enumerate(rnn_map):\n rnn_m... | <|body_start_0|>
self.act_f = activation
self.dtype = dtype
self.rnn_idx: np.ndarray = rnn_idx
self.n_inputs: int = len(input_idx)
self.n_hidden: int = len(hidden_idx)
self.n_rnn: int = len(rnn_idx)
self.n_outputs: int = len(output_idx)
self.bs: int = batc... | Custom representation of a feedforward network used by the genomes to make predictions. | FeedForwardNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedForwardNet:
"""Custom representation of a feedforward network used by the genomes to make predictions."""
def __init__(self, input_idx: np.ndarray, hidden_idx: np.ndarray, rnn_idx: np.ndarray, output_idx: np.ndarray, in2hid: tuple, in2out: tuple, hid2hid: tuple, hid2out: tuple, hidden_bi... | stack_v2_sparse_classes_10k_train_000851 | 16,851 | permissive | [
{
"docstring": "Create a simple feedforward network used as the control-mechanism for the drones. :param input_idx: Input indices (sensors) :param hidden_idx: Hidden simple-node indices (DefaultGeneNode) in the network :param rnn_idx: Hidden RNN-node indices (DefaultGeneNode) in the network :param output_idx: O... | 3 | stack_v2_sparse_classes_30k_train_002676 | Implement the Python class `FeedForwardNet` described below.
Class description:
Custom representation of a feedforward network used by the genomes to make predictions.
Method signatures and docstrings:
- def __init__(self, input_idx: np.ndarray, hidden_idx: np.ndarray, rnn_idx: np.ndarray, output_idx: np.ndarray, in2... | Implement the Python class `FeedForwardNet` described below.
Class description:
Custom representation of a feedforward network used by the genomes to make predictions.
Method signatures and docstrings:
- def __init__(self, input_idx: np.ndarray, hidden_idx: np.ndarray, rnn_idx: np.ndarray, output_idx: np.ndarray, in2... | 818a4ce941536611c0f1780f7c4a6238f0e1884e | <|skeleton|>
class FeedForwardNet:
"""Custom representation of a feedforward network used by the genomes to make predictions."""
def __init__(self, input_idx: np.ndarray, hidden_idx: np.ndarray, rnn_idx: np.ndarray, output_idx: np.ndarray, in2hid: tuple, in2out: tuple, hid2hid: tuple, hid2out: tuple, hidden_bi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeedForwardNet:
"""Custom representation of a feedforward network used by the genomes to make predictions."""
def __init__(self, input_idx: np.ndarray, hidden_idx: np.ndarray, rnn_idx: np.ndarray, output_idx: np.ndarray, in2hid: tuple, in2out: tuple, hid2hid: tuple, hid2out: tuple, hidden_biases: np.ndar... | the_stack_v2_python_sparse | population/utils/network_util/feed_forward_net.py | RubenPants/EvolvableRNN | train | 1 |
d1df998163385d3e3106ffdc620f2d659c647e17 | [
"device = self.device\nif hasattr(device.api, 'check_sensors'):\n data = await device.async_request(device.api.check_sensors)\n return self.normalize(data, self.coordinator.data)\nawait device.async_request(device.api.update)\nreturn {}",
"if data['temperature'] == -7:\n if previous_data is None or previ... | <|body_start_0|>
device = self.device
if hasattr(device.api, 'check_sensors'):
data = await device.async_request(device.api.check_sensors)
return self.normalize(data, self.coordinator.data)
await device.async_request(device.api.update)
return {}
<|end_body_0|>
<|... | Manages updates for Broadlink remotes. | BroadlinkRMUpdateManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BroadlinkRMUpdateManager:
"""Manages updates for Broadlink remotes."""
async def async_fetch_data(self):
"""Fetch data from the device."""
<|body_0|>
def normalize(data, previous_data):
"""Fix firmware issue. See https://github.com/home-assistant/core/issues/4210... | stack_v2_sparse_classes_10k_train_000852 | 6,174 | permissive | [
{
"docstring": "Fetch data from the device.",
"name": "async_fetch_data",
"signature": "async def async_fetch_data(self)"
},
{
"docstring": "Fix firmware issue. See https://github.com/home-assistant/core/issues/42100.",
"name": "normalize",
"signature": "def normalize(data, previous_data... | 2 | null | Implement the Python class `BroadlinkRMUpdateManager` described below.
Class description:
Manages updates for Broadlink remotes.
Method signatures and docstrings:
- async def async_fetch_data(self): Fetch data from the device.
- def normalize(data, previous_data): Fix firmware issue. See https://github.com/home-assis... | Implement the Python class `BroadlinkRMUpdateManager` described below.
Class description:
Manages updates for Broadlink remotes.
Method signatures and docstrings:
- async def async_fetch_data(self): Fetch data from the device.
- def normalize(data, previous_data): Fix firmware issue. See https://github.com/home-assis... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class BroadlinkRMUpdateManager:
"""Manages updates for Broadlink remotes."""
async def async_fetch_data(self):
"""Fetch data from the device."""
<|body_0|>
def normalize(data, previous_data):
"""Fix firmware issue. See https://github.com/home-assistant/core/issues/4210... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BroadlinkRMUpdateManager:
"""Manages updates for Broadlink remotes."""
async def async_fetch_data(self):
"""Fetch data from the device."""
device = self.device
if hasattr(device.api, 'check_sensors'):
data = await device.async_request(device.api.check_sensors)
... | the_stack_v2_python_sparse | homeassistant/components/broadlink/updater.py | home-assistant/core | train | 35,501 |
a67a7759a1fd7d8f4de0891e033b078c2fb0c7e9 | [
"self.gpu_id = gpu_id\nif self.gpu_id is not None and isinstance(self.gpu_id, int) and paddle.device.is_compiled_with_cuda():\n paddle.device.set_device('gpu:{}'.format(self.gpu_id))\nelse:\n paddle.device.set_device('cpu')\ncheckpoint = paddle.load(model_path)\nconfig = checkpoint['config']\nconfig['arch']['... | <|body_start_0|>
self.gpu_id = gpu_id
if self.gpu_id is not None and isinstance(self.gpu_id, int) and paddle.device.is_compiled_with_cuda():
paddle.device.set_device('gpu:{}'.format(self.gpu_id))
else:
paddle.device.set_device('cpu')
checkpoint = paddle.load(model... | PaddleModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaddleModel:
def __init__(self, model_path, post_p_thre=0.7, gpu_id=None):
"""初始化模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) :param gpu_id: 在哪一块gpu上运行"""
<|body_0|>
def predict(self, img_path: str, is_output_polygon=False, short_size: int=1024):
"""对传入的图像进行预测... | stack_v2_sparse_classes_10k_train_000853 | 6,575 | permissive | [
{
"docstring": "初始化模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) :param gpu_id: 在哪一块gpu上运行",
"name": "__init__",
"signature": "def __init__(self, model_path, post_p_thre=0.7, gpu_id=None)"
},
{
"docstring": "对传入的图像进行预测,支持图像地址,opecv 读取图片,偏慢 :param img_path: 图像地址 :param is_numpy: :return:",
... | 2 | null | Implement the Python class `PaddleModel` described below.
Class description:
Implement the PaddleModel class.
Method signatures and docstrings:
- def __init__(self, model_path, post_p_thre=0.7, gpu_id=None): 初始化模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) :param gpu_id: 在哪一块gpu上运行
- def predict(self, img_path:... | Implement the Python class `PaddleModel` described below.
Class description:
Implement the PaddleModel class.
Method signatures and docstrings:
- def __init__(self, model_path, post_p_thre=0.7, gpu_id=None): 初始化模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) :param gpu_id: 在哪一块gpu上运行
- def predict(self, img_path:... | 15963b0d242867a4cc4d76445626dc8965509b2f | <|skeleton|>
class PaddleModel:
def __init__(self, model_path, post_p_thre=0.7, gpu_id=None):
"""初始化模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) :param gpu_id: 在哪一块gpu上运行"""
<|body_0|>
def predict(self, img_path: str, is_output_polygon=False, short_size: int=1024):
"""对传入的图像进行预测... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PaddleModel:
def __init__(self, model_path, post_p_thre=0.7, gpu_id=None):
"""初始化模型 :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件) :param gpu_id: 在哪一块gpu上运行"""
self.gpu_id = gpu_id
if self.gpu_id is not None and isinstance(self.gpu_id, int) and paddle.device.is_compiled_with_cuda():
... | the_stack_v2_python_sparse | benchmark/PaddleOCR_DBNet/tools/predict.py | PaddlePaddle/PaddleOCR | train | 34,195 | |
e7c5b32e6c0b91e533bf934d84a897e199f16e0c | [
"self.shutdown()\nif self.state != PMAppType.HALTED:\n time.sleep(2)\n os.kill(self.processid, signal.SIGTERM)",
"stopcommand = os.path.join(pylabs.q.dirs.baseDir, 'control', self.name, 'stop.')\nif pylabs.q.platform.isUnix():\n stopcommand += 'py'\nelif pylabs.q.platform.isWindows():\n stopcommand +=... | <|body_start_0|>
self.shutdown()
if self.state != PMAppType.HALTED:
time.sleep(2)
os.kill(self.processid, signal.SIGTERM)
<|end_body_0|>
<|body_start_1|>
stopcommand = os.path.join(pylabs.q.dirs.baseDir, 'control', self.name, 'stop.')
if pylabs.q.platform.isUnix(... | PMApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PMApp:
def kill(self):
"""Attempts to stop a pylabs application gracefully Attempts to stop a pylabs application in a nice way, waits for two seconds. If the attempt fails, the application is killed the hard way."""
<|body_0|>
def shutdown(self):
"""Attempts to stop ... | stack_v2_sparse_classes_10k_train_000854 | 3,345 | no_license | [
{
"docstring": "Attempts to stop a pylabs application gracefully Attempts to stop a pylabs application in a nice way, waits for two seconds. If the attempt fails, the application is killed the hard way.",
"name": "kill",
"signature": "def kill(self)"
},
{
"docstring": "Attempts to stop a pylabs ... | 3 | null | Implement the Python class `PMApp` described below.
Class description:
Implement the PMApp class.
Method signatures and docstrings:
- def kill(self): Attempts to stop a pylabs application gracefully Attempts to stop a pylabs application in a nice way, waits for two seconds. If the attempt fails, the application is ki... | Implement the Python class `PMApp` described below.
Class description:
Implement the PMApp class.
Method signatures and docstrings:
- def kill(self): Attempts to stop a pylabs application gracefully Attempts to stop a pylabs application in a nice way, waits for two seconds. If the attempt fails, the application is ki... | 53d349fa6bee0ccead29afd6676979b44c109a61 | <|skeleton|>
class PMApp:
def kill(self):
"""Attempts to stop a pylabs application gracefully Attempts to stop a pylabs application in a nice way, waits for two seconds. If the attempt fails, the application is killed the hard way."""
<|body_0|>
def shutdown(self):
"""Attempts to stop ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PMApp:
def kill(self):
"""Attempts to stop a pylabs application gracefully Attempts to stop a pylabs application in a nice way, waits for two seconds. If the attempt fails, the application is killed the hard way."""
self.shutdown()
if self.state != PMAppType.HALTED:
time.sl... | the_stack_v2_python_sparse | core/apps/App.py | racktivity/ext-pylabs-core | train | 0 | |
f068a05ac79b3e12972bc2787e57ff4255d0ea92 | [
"self.mm = slt()\nself.urla = ParamsTest().selenium_url_sempreprod()\nself.url = f'{self.urla}scp/inventory/optlist'",
"driver = self.mm.sem_login()\nsleep(2)\ndriver.get(self.url)\nreturn driver"
] | <|body_start_0|>
self.mm = slt()
self.urla = ParamsTest().selenium_url_sempreprod()
self.url = f'{self.urla}scp/inventory/optlist'
<|end_body_0|>
<|body_start_1|>
driver = self.mm.sem_login()
sleep(2)
driver.get(self.url)
return driver
<|end_body_1|>
| SemOptList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SemOptList:
def __init__(self):
"""运营管理系统 供应链管理 库存管理 ----- 拣货单页面"""
<|body_0|>
def optlist(self):
"""定义driver"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.mm = slt()
self.urla = ParamsTest().selenium_url_sempreprod()
self.url... | stack_v2_sparse_classes_10k_train_000855 | 850 | no_license | [
{
"docstring": "运营管理系统 供应链管理 库存管理 ----- 拣货单页面",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "定义driver",
"name": "optlist",
"signature": "def optlist(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002622 | Implement the Python class `SemOptList` described below.
Class description:
Implement the SemOptList class.
Method signatures and docstrings:
- def __init__(self): 运营管理系统 供应链管理 库存管理 ----- 拣货单页面
- def optlist(self): 定义driver | Implement the Python class `SemOptList` described below.
Class description:
Implement the SemOptList class.
Method signatures and docstrings:
- def __init__(self): 运营管理系统 供应链管理 库存管理 ----- 拣货单页面
- def optlist(self): 定义driver
<|skeleton|>
class SemOptList:
def __init__(self):
"""运营管理系统 供应链管理 库存管理 ----- 拣货... | 97f9e4f286d017ee39ceeae0c730f1c4971499e7 | <|skeleton|>
class SemOptList:
def __init__(self):
"""运营管理系统 供应链管理 库存管理 ----- 拣货单页面"""
<|body_0|>
def optlist(self):
"""定义driver"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SemOptList:
def __init__(self):
"""运营管理系统 供应链管理 库存管理 ----- 拣货单页面"""
self.mm = slt()
self.urla = ParamsTest().selenium_url_sempreprod()
self.url = f'{self.urla}scp/inventory/optlist'
def optlist(self):
"""定义driver"""
driver = self.mm.sem_login()
slee... | the_stack_v2_python_sparse | setting/optlist/optlist.py | qq183727918/selenium_ui | train | 0 | |
1d79b8cbafa0d0ce513f5833a699b1bacf9b8feb | [
"if self.parent.ct is None:\n pn.state.notifications.warning('no CT found', duration=3000)\nelse:\n self.parent.ct = remove_ring_artifact(arrays=self.parent.ct, kernel_size=self.kernel_size, sub_division=self.sub_division, correction_range=self.correction_range)\n self.status = True\n pn.state.notificat... | <|body_start_0|>
if self.parent.ct is None:
pn.state.notifications.warning('no CT found', duration=3000)
else:
self.parent.ct = remove_ring_artifact(arrays=self.parent.ct, kernel_size=self.kernel_size, sub_division=self.sub_division, correction_range=self.correction_range)
... | Ring removal widget. widget of ring artifact removal filter from iMars3D, must have a parent widget with valid ct stack. | RemoveRingArtifact | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoveRingArtifact:
"""Ring removal widget. widget of ring artifact removal filter from iMars3D, must have a parent widget with valid ct stack."""
def apply(self):
"""Apply ring removal."""
<|body_0|>
def panel(self, width=200):
"""App card view."""
<|bod... | stack_v2_sparse_classes_10k_train_000856 | 2,746 | permissive | [
{
"docstring": "Apply ring removal.",
"name": "apply",
"signature": "def apply(self)"
},
{
"docstring": "App card view.",
"name": "panel",
"signature": "def panel(self, width=200)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002551 | Implement the Python class `RemoveRingArtifact` described below.
Class description:
Ring removal widget. widget of ring artifact removal filter from iMars3D, must have a parent widget with valid ct stack.
Method signatures and docstrings:
- def apply(self): Apply ring removal.
- def panel(self, width=200): App card v... | Implement the Python class `RemoveRingArtifact` described below.
Class description:
Ring removal widget. widget of ring artifact removal filter from iMars3D, must have a parent widget with valid ct stack.
Method signatures and docstrings:
- def apply(self): Apply ring removal.
- def panel(self, width=200): App card v... | 7c9dea7a3a7877af1bafdfb71da8fb018d5d828f | <|skeleton|>
class RemoveRingArtifact:
"""Ring removal widget. widget of ring artifact removal filter from iMars3D, must have a parent widget with valid ct stack."""
def apply(self):
"""Apply ring removal."""
<|body_0|>
def panel(self, width=200):
"""App card view."""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RemoveRingArtifact:
"""Ring removal widget. widget of ring artifact removal filter from iMars3D, must have a parent widget with valid ct stack."""
def apply(self):
"""Apply ring removal."""
if self.parent.ct is None:
pn.state.notifications.warning('no CT found', duration=3000)... | the_stack_v2_python_sparse | src/imars3d/ui/widgets/ring_removal.py | ornlneutronimaging/iMars3D | train | 3 |
9b09f6925ad2fda7f3f4ebbfd3f22dc9f9432627 | [
"super(TenorNetworkModule, self).__init__()\nself.setup_weights()\nself.init_parameters()",
"self.weight_matrix = torch.nn.Parameter(torch.Tensor(256, 256, 16))\nself.weight_matrix_block = torch.nn.Parameter(torch.Tensor(16, 2 * 256))\nself.bias = torch.nn.Parameter(torch.Tensor(16, 1))",
"torch.nn.init.xavier_... | <|body_start_0|>
super(TenorNetworkModule, self).__init__()
self.setup_weights()
self.init_parameters()
<|end_body_0|>
<|body_start_1|>
self.weight_matrix = torch.nn.Parameter(torch.Tensor(256, 256, 16))
self.weight_matrix_block = torch.nn.Parameter(torch.Tensor(16, 2 * 256))
... | SimGNN Tensor Network module to calculate similarity vector. | TenorNetworkModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenorNetworkModule:
"""SimGNN Tensor Network module to calculate similarity vector."""
def __init__(self):
""":param args: Arguments object."""
<|body_0|>
def setup_weights(self):
"""Defining weights."""
<|body_1|>
def init_parameters(self):
... | stack_v2_sparse_classes_10k_train_000857 | 4,926 | no_license | [
{
"docstring": ":param args: Arguments object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Defining weights.",
"name": "setup_weights",
"signature": "def setup_weights(self)"
},
{
"docstring": "Initializing weights.",
"name": "init_parameters",
... | 4 | stack_v2_sparse_classes_30k_val_000151 | Implement the Python class `TenorNetworkModule` described below.
Class description:
SimGNN Tensor Network module to calculate similarity vector.
Method signatures and docstrings:
- def __init__(self): :param args: Arguments object.
- def setup_weights(self): Defining weights.
- def init_parameters(self): Initializing... | Implement the Python class `TenorNetworkModule` described below.
Class description:
SimGNN Tensor Network module to calculate similarity vector.
Method signatures and docstrings:
- def __init__(self): :param args: Arguments object.
- def setup_weights(self): Defining weights.
- def init_parameters(self): Initializing... | 96b3cb5b392f08924ac0fd6df5eea2b6f680c1c8 | <|skeleton|>
class TenorNetworkModule:
"""SimGNN Tensor Network module to calculate similarity vector."""
def __init__(self):
""":param args: Arguments object."""
<|body_0|>
def setup_weights(self):
"""Defining weights."""
<|body_1|>
def init_parameters(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TenorNetworkModule:
"""SimGNN Tensor Network module to calculate similarity vector."""
def __init__(self):
""":param args: Arguments object."""
super(TenorNetworkModule, self).__init__()
self.setup_weights()
self.init_parameters()
def setup_weights(self):
"""D... | the_stack_v2_python_sparse | models/graph_similarity.py | GPNU-Frank/ABN_FER | train | 1 |
648ac173e5956499617ea380b2bca3aca584662a | [
"for i, val in enumerate(nums):\n other = target - val\n if other in nums[i + 1:]:\n return [i, nums.index(other, i + 1)]",
"dic = dict()\nfor i, val in enumerate(nums):\n other = target - val\n if other in dic:\n return [dic.get(other), i]\n dic[val] = i"
] | <|body_start_0|>
for i, val in enumerate(nums):
other = target - val
if other in nums[i + 1:]:
return [i, nums.index(other, i + 1)]
<|end_body_0|>
<|body_start_1|>
dic = dict()
for i, val in enumerate(nums):
other = target - val
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums: list, target: int) -> list:
"""在原列表中查找,如果找到补码,返回从i+1开始查找的索引。"""
<|body_0|>
def twoSum1(self, nums: list, target: int) -> list:
"""空间换时间:新建dict,存于dict中方便查找(Hash查找速度快)。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
f... | stack_v2_sparse_classes_10k_train_000858 | 1,336 | no_license | [
{
"docstring": "在原列表中查找,如果找到补码,返回从i+1开始查找的索引。",
"name": "twoSum",
"signature": "def twoSum(self, nums: list, target: int) -> list"
},
{
"docstring": "空间换时间:新建dict,存于dict中方便查找(Hash查找速度快)。",
"name": "twoSum1",
"signature": "def twoSum1(self, nums: list, target: int) -> list"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums: list, target: int) -> list: 在原列表中查找,如果找到补码,返回从i+1开始查找的索引。
- def twoSum1(self, nums: list, target: int) -> list: 空间换时间:新建dict,存于dict中方便查找(Hash查找速度快)。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums: list, target: int) -> list: 在原列表中查找,如果找到补码,返回从i+1开始查找的索引。
- def twoSum1(self, nums: list, target: int) -> list: 空间换时间:新建dict,存于dict中方便查找(Hash查找速度快)。
<|ske... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def twoSum(self, nums: list, target: int) -> list:
"""在原列表中查找,如果找到补码,返回从i+1开始查找的索引。"""
<|body_0|>
def twoSum1(self, nums: list, target: int) -> list:
"""空间换时间:新建dict,存于dict中方便查找(Hash查找速度快)。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums: list, target: int) -> list:
"""在原列表中查找,如果找到补码,返回从i+1开始查找的索引。"""
for i, val in enumerate(nums):
other = target - val
if other in nums[i + 1:]:
return [i, nums.index(other, i + 1)]
def twoSum1(self, nums: list, target:... | the_stack_v2_python_sparse | 001_two-sum.py | helloocc/algorithm | train | 1 | |
de56eabe2967d6f078fd6a5a396c1a68fb8d9956 | [
"Thread.__init__(self)\nself.global_var = global_var\nself.daemon = True",
"while True:\n time.sleep(2)\n if self.global_var['sequence']:\n if queue_manager.nb_seq_in_queue() != 0:\n queue_manager.set_current_thread()\n time.sleep(2)\n queue_manager.current_thread.sta... | <|body_start_0|>
Thread.__init__(self)
self.global_var = global_var
self.daemon = True
<|end_body_0|>
<|body_start_1|>
while True:
time.sleep(2)
if self.global_var['sequence']:
if queue_manager.nb_seq_in_queue() != 0:
queue_man... | Class daemon thread to manage Queue | SequenceManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceManager:
"""Class daemon thread to manage Queue"""
def __init__(self, global_var):
"""Constructor of SequenceManager :param global_var: global var of API"""
<|body_0|>
def run(self):
"""callback function of the thread this function manage the queue of the... | stack_v2_sparse_classes_10k_train_000859 | 1,008 | no_license | [
{
"docstring": "Constructor of SequenceManager :param global_var: global var of API",
"name": "__init__",
"signature": "def __init__(self, global_var)"
},
{
"docstring": "callback function of the thread this function manage the queue of the API :return: end of daemon thread",
"name": "run",
... | 2 | stack_v2_sparse_classes_30k_train_002687 | Implement the Python class `SequenceManager` described below.
Class description:
Class daemon thread to manage Queue
Method signatures and docstrings:
- def __init__(self, global_var): Constructor of SequenceManager :param global_var: global var of API
- def run(self): callback function of the thread this function ma... | Implement the Python class `SequenceManager` described below.
Class description:
Class daemon thread to manage Queue
Method signatures and docstrings:
- def __init__(self, global_var): Constructor of SequenceManager :param global_var: global var of API
- def run(self): callback function of the thread this function ma... | de1408317d5071b7e0c6b2fea6f281660115d728 | <|skeleton|>
class SequenceManager:
"""Class daemon thread to manage Queue"""
def __init__(self, global_var):
"""Constructor of SequenceManager :param global_var: global var of API"""
<|body_0|>
def run(self):
"""callback function of the thread this function manage the queue of the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SequenceManager:
"""Class daemon thread to manage Queue"""
def __init__(self, global_var):
"""Constructor of SequenceManager :param global_var: global var of API"""
Thread.__init__(self)
self.global_var = global_var
self.daemon = True
def run(self):
"""callbac... | the_stack_v2_python_sparse | api/package/sequence/sequence_manager.py | HE-Arc/Extrusion---web-interface | train | 4 |
e1f9a97d2ec1f236e39a894dd63ec7f9c3c3173a | [
"self.time_lapse_polygons = time_lapse_polygons\nself.raster_template = raster_template\nself.facility_id = facility_id\nself.from_break = from_break\nself.to_break = to_break\nself.scratch_folder = scratch_folder\nself._create_job_folder()\nself.scratch_gdb = None\nself.setup_logger('PercAccPoly')\nself.job_result... | <|body_start_0|>
self.time_lapse_polygons = time_lapse_polygons
self.raster_template = raster_template
self.facility_id = facility_id
self.from_break = from_break
self.to_break = to_break
self.scratch_folder = scratch_folder
self._create_job_folder()
self.... | Calculate percent access polygons for the designated facility, from break, to break combo. | ParallelCounter | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelCounter:
"""Calculate percent access polygons for the designated facility, from break, to break combo."""
def __init__(self, time_lapse_polygons, raster_template, facility_id, from_break, to_break, scratch_folder):
"""Initialize the parallel counter for the given inputs. Args... | stack_v2_sparse_classes_10k_train_000860 | 14,182 | permissive | [
{
"docstring": "Initialize the parallel counter for the given inputs. Args: time_lapse_polygons (feature class catalog path): Time lapse polygons raster_template (feature class catalog path): Raster-like polygons template facility_id (int): ID of the Service Area facility to select for processing this chunk fro... | 5 | stack_v2_sparse_classes_30k_train_005175 | Implement the Python class `ParallelCounter` described below.
Class description:
Calculate percent access polygons for the designated facility, from break, to break combo.
Method signatures and docstrings:
- def __init__(self, time_lapse_polygons, raster_template, facility_id, from_break, to_break, scratch_folder): I... | Implement the Python class `ParallelCounter` described below.
Class description:
Calculate percent access polygons for the designated facility, from break, to break combo.
Method signatures and docstrings:
- def __init__(self, time_lapse_polygons, raster_template, facility_id, from_break, to_break, scratch_folder): I... | 47cbc3de67a7b1bf9255e07e88cba7b051db0505 | <|skeleton|>
class ParallelCounter:
"""Calculate percent access polygons for the designated facility, from break, to break combo."""
def __init__(self, time_lapse_polygons, raster_template, facility_id, from_break, to_break, scratch_folder):
"""Initialize the parallel counter for the given inputs. Args... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ParallelCounter:
"""Calculate percent access polygons for the designated facility, from break, to break combo."""
def __init__(self, time_lapse_polygons, raster_template, facility_id, from_break, to_break, scratch_folder):
"""Initialize the parallel counter for the given inputs. Args: time_lapse_... | the_stack_v2_python_sparse | transit-network-analysis-tools/parallel_cpap.py | Esri/public-transit-tools | train | 155 |
6f91d47659a9ec242d4cb42f02a6de6f1b296116 | [
"table_object = Tag.query.get_or_404(int_id)\nform = TagForm(obj=table_object)\nflask.flash(f\"Please confirm deleting the tag '{table_object.name}'.\")\ntemplate_return = flask.render_template('confirm_deletion.html', form=form)\nreturn flask.Response(template_return, mimetype='text/html')",
"table_object = Tag.... | <|body_start_0|>
table_object = Tag.query.get_or_404(int_id)
form = TagForm(obj=table_object)
flask.flash(f"Please confirm deleting the tag '{table_object.name}'.")
template_return = flask.render_template('confirm_deletion.html', form=form)
return flask.Response(template_return, ... | DeleteTagResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteTagResource:
def get(self, int_id):
"""Args: int_id: Returns:"""
<|body_0|>
def post(self, int_id):
"""Args: int_id: Returns:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
table_object = Tag.query.get_or_404(int_id)
form = TagForm(ob... | stack_v2_sparse_classes_10k_train_000861 | 3,873 | no_license | [
{
"docstring": "Args: int_id: Returns:",
"name": "get",
"signature": "def get(self, int_id)"
},
{
"docstring": "Args: int_id: Returns:",
"name": "post",
"signature": "def post(self, int_id)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000279 | Implement the Python class `DeleteTagResource` described below.
Class description:
Implement the DeleteTagResource class.
Method signatures and docstrings:
- def get(self, int_id): Args: int_id: Returns:
- def post(self, int_id): Args: int_id: Returns: | Implement the Python class `DeleteTagResource` described below.
Class description:
Implement the DeleteTagResource class.
Method signatures and docstrings:
- def get(self, int_id): Args: int_id: Returns:
- def post(self, int_id): Args: int_id: Returns:
<|skeleton|>
class DeleteTagResource:
def get(self, int_id)... | 865403e3b1717226b25c9d64aeb4c35c7220e7e3 | <|skeleton|>
class DeleteTagResource:
def get(self, int_id):
"""Args: int_id: Returns:"""
<|body_0|>
def post(self, int_id):
"""Args: int_id: Returns:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeleteTagResource:
def get(self, int_id):
"""Args: int_id: Returns:"""
table_object = Tag.query.get_or_404(int_id)
form = TagForm(obj=table_object)
flask.flash(f"Please confirm deleting the tag '{table_object.name}'.")
template_return = flask.render_template('confirm_de... | the_stack_v2_python_sparse | things_organizer/web_app/tags/resources.py | yeyeto2788/Things-Organizer | train | 11 | |
cbd3c7bae1747db248f8c8e1b6bee3fb4ebbe10e | [
"from mmcv.ops import nms\nbatch_size, num_class, _ = scores.shape\nscore_threshold = float(score_threshold)\niou_threshold = float(iou_threshold)\nindices = []\nfor batch_id in range(batch_size):\n for cls_id in range(num_class):\n _boxes = boxes[batch_id, ...]\n _scores = scores[batch_id, cls_id,... | <|body_start_0|>
from mmcv.ops import nms
batch_size, num_class, _ = scores.shape
score_threshold = float(score_threshold)
iou_threshold = float(iou_threshold)
indices = []
for batch_id in range(batch_size):
for cls_id in range(num_class):
_box... | Create onnx::NonMaxSuppression op. NMS in mmcv only supports one class with no batch info. This class assists in exporting NMS of ONNX's definition. | ONNXNMSop | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ONNXNMSop:
"""Create onnx::NonMaxSuppression op. NMS in mmcv only supports one class with no batch info. This class assists in exporting NMS of ONNX's definition."""
def forward(ctx, boxes: Tensor, scores: Tensor, max_output_boxes_per_class: int, iou_threshold: float, score_threshold: float)... | stack_v2_sparse_classes_10k_train_000862 | 29,162 | permissive | [
{
"docstring": "Get NMS output indices. Args: ctx (Context): The context with meta information. boxes (Tensor): The bounding boxes of shape [N, num_boxes, 4]. scores (Tensor): The detection scores of shape [N, num_boxes, num_classes]. max_output_boxes_per_class (int): Maximum number of output boxes per class of... | 2 | stack_v2_sparse_classes_30k_train_003781 | Implement the Python class `ONNXNMSop` described below.
Class description:
Create onnx::NonMaxSuppression op. NMS in mmcv only supports one class with no batch info. This class assists in exporting NMS of ONNX's definition.
Method signatures and docstrings:
- def forward(ctx, boxes: Tensor, scores: Tensor, max_output... | Implement the Python class `ONNXNMSop` described below.
Class description:
Create onnx::NonMaxSuppression op. NMS in mmcv only supports one class with no batch info. This class assists in exporting NMS of ONNX's definition.
Method signatures and docstrings:
- def forward(ctx, boxes: Tensor, scores: Tensor, max_output... | 5479c8774f5b88d7ed9d399d4e305cb42cc2e73a | <|skeleton|>
class ONNXNMSop:
"""Create onnx::NonMaxSuppression op. NMS in mmcv only supports one class with no batch info. This class assists in exporting NMS of ONNX's definition."""
def forward(ctx, boxes: Tensor, scores: Tensor, max_output_boxes_per_class: int, iou_threshold: float, score_threshold: float)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ONNXNMSop:
"""Create onnx::NonMaxSuppression op. NMS in mmcv only supports one class with no batch info. This class assists in exporting NMS of ONNX's definition."""
def forward(ctx, boxes: Tensor, scores: Tensor, max_output_boxes_per_class: int, iou_threshold: float, score_threshold: float) -> Tensor:
... | the_stack_v2_python_sparse | mmdeploy/mmcv/ops/nms.py | open-mmlab/mmdeploy | train | 2,164 |
061f2259706d1d83f505c6bf28fa276351e1fc0a | [
"v = APIValidator()\ndraft_id = draft_id or deposition.get_default_draft_id()\nmetadata_schema = deposition.type.api_metadata_schema(draft_id)\nif metadata_schema:\n schema = self.input_schema.copy()\n schema['metadata'] = metadata_schema\nelse:\n schema = self.input_schema\nif not v.validate(request.json,... | <|body_start_0|>
v = APIValidator()
draft_id = draft_id or deposition.get_default_draft_id()
metadata_schema = deposition.type.api_metadata_schema(draft_id)
if metadata_schema:
schema = self.input_schema.copy()
schema['metadata'] = metadata_schema
else:
... | Mix-in class for validating and processing deposition input data. | InputProcessorMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputProcessorMixin:
"""Mix-in class for validating and processing deposition input data."""
def validate_input(self, deposition, draft_id=None):
"""Validate input data for creating and update a deposition."""
<|body_0|>
def process_input(self, deposition, draft_id=None)... | stack_v2_sparse_classes_10k_train_000863 | 19,789 | no_license | [
{
"docstring": "Validate input data for creating and update a deposition.",
"name": "validate_input",
"signature": "def validate_input(self, deposition, draft_id=None)"
},
{
"docstring": "Process input data.",
"name": "process_input",
"signature": "def process_input(self, deposition, dra... | 2 | stack_v2_sparse_classes_30k_val_000174 | Implement the Python class `InputProcessorMixin` described below.
Class description:
Mix-in class for validating and processing deposition input data.
Method signatures and docstrings:
- def validate_input(self, deposition, draft_id=None): Validate input data for creating and update a deposition.
- def process_input(... | Implement the Python class `InputProcessorMixin` described below.
Class description:
Mix-in class for validating and processing deposition input data.
Method signatures and docstrings:
- def validate_input(self, deposition, draft_id=None): Validate input data for creating and update a deposition.
- def process_input(... | e84cb33310506fcdab1dcdb1e8bd425d44435fbe | <|skeleton|>
class InputProcessorMixin:
"""Mix-in class for validating and processing deposition input data."""
def validate_input(self, deposition, draft_id=None):
"""Validate input data for creating and update a deposition."""
<|body_0|>
def process_input(self, deposition, draft_id=None)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InputProcessorMixin:
"""Mix-in class for validating and processing deposition input data."""
def validate_input(self, deposition, draft_id=None):
"""Validate input data for creating and update a deposition."""
v = APIValidator()
draft_id = draft_id or deposition.get_default_draft_... | the_stack_v2_python_sparse | lw_daap/modules/invenio_deposit/restful.py | groundnuty/lw-daap | train | 0 |
b857f4095cf36042baa38810ad2a0995c717e324 | [
"warnings.warn('SequentialWeaveGraph is deprecated. Will be removed in DeepChem 1.4.', DeprecationWarning)\nself.graph = tf.Graph()\nself.max_atoms = max_atoms\nself.n_atom_feat = n_atom_feat\nself.n_pair_feat = n_pair_feat\nwith self.graph.as_default():\n self.graph_topology = WeaveGraphTopology(self.max_atoms,... | <|body_start_0|>
warnings.warn('SequentialWeaveGraph is deprecated. Will be removed in DeepChem 1.4.', DeprecationWarning)
self.graph = tf.Graph()
self.max_atoms = max_atoms
self.n_atom_feat = n_atom_feat
self.n_pair_feat = n_pair_feat
with self.graph.as_default():
... | SequentialGraph for Weave models | SequentialWeaveGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequentialWeaveGraph:
"""SequentialGraph for Weave models"""
def __init__(self, max_atoms=50, n_atom_feat=75, n_pair_feat=14):
"""Parameters ---------- max_atoms: int, optional Maximum number of atoms in a molecule, should be defined based on dataset n_atom_feat: int, optional Number... | stack_v2_sparse_classes_10k_train_000864 | 11,824 | permissive | [
{
"docstring": "Parameters ---------- max_atoms: int, optional Maximum number of atoms in a molecule, should be defined based on dataset n_atom_feat: int, optional Number of features per atom. n_pair_feat: int, optional Number of features per pair of atoms.",
"name": "__init__",
"signature": "def __init... | 2 | null | Implement the Python class `SequentialWeaveGraph` described below.
Class description:
SequentialGraph for Weave models
Method signatures and docstrings:
- def __init__(self, max_atoms=50, n_atom_feat=75, n_pair_feat=14): Parameters ---------- max_atoms: int, optional Maximum number of atoms in a molecule, should be d... | Implement the Python class `SequentialWeaveGraph` described below.
Class description:
SequentialGraph for Weave models
Method signatures and docstrings:
- def __init__(self, max_atoms=50, n_atom_feat=75, n_pair_feat=14): Parameters ---------- max_atoms: int, optional Maximum number of atoms in a molecule, should be d... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class SequentialWeaveGraph:
"""SequentialGraph for Weave models"""
def __init__(self, max_atoms=50, n_atom_feat=75, n_pair_feat=14):
"""Parameters ---------- max_atoms: int, optional Maximum number of atoms in a molecule, should be defined based on dataset n_atom_feat: int, optional Number... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SequentialWeaveGraph:
"""SequentialGraph for Weave models"""
def __init__(self, max_atoms=50, n_atom_feat=75, n_pair_feat=14):
"""Parameters ---------- max_atoms: int, optional Maximum number of atoms in a molecule, should be defined based on dataset n_atom_feat: int, optional Number of features ... | the_stack_v2_python_sparse | contrib/one_shot_models/graph_models.py | deepchem/deepchem | train | 4,876 |
5934efc32892283e265d061925d72b82b3a82898 | [
"super().__init__(self.SCHEMA_NAME)\nself.redfish['@odata.type'] = self.get_odata_type()\nself.redfish['Name'] = network_set['name']\nself.redfish['Members@odata.count'] = len(network_set['networkUris'])\nself.redfish['Members'] = list()\nself._set_vlans_to_network_collection(endpoint, network_set['networkUris'])\n... | <|body_start_0|>
super().__init__(self.SCHEMA_NAME)
self.redfish['@odata.type'] = self.get_odata_type()
self.redfish['Name'] = network_set['name']
self.redfish['Members@odata.count'] = len(network_set['networkUris'])
self.redfish['Members'] = list()
self._set_vlans_to_net... | Creates a VLanNetworkInterfaceCollection Redfish dict Populates self.redfish with network set data retrieved from OneView | VLanNetworkInterfaceCollection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VLanNetworkInterfaceCollection:
"""Creates a VLanNetworkInterfaceCollection Redfish dict Populates self.redfish with network set data retrieved from OneView"""
def __init__(self, network_set, endpoint):
"""VLanNetworkInterfaceCollection constructor Populates self.redfish with Network... | stack_v2_sparse_classes_10k_train_000865 | 2,591 | permissive | [
{
"docstring": "VLanNetworkInterfaceCollection constructor Populates self.redfish with NetworkSet data retrieved from OneView. Args: network_set: Network Set dict from OneView endpoint: endpoint uri from original REST",
"name": "__init__",
"signature": "def __init__(self, network_set, endpoint)"
},
... | 2 | stack_v2_sparse_classes_30k_train_003420 | Implement the Python class `VLanNetworkInterfaceCollection` described below.
Class description:
Creates a VLanNetworkInterfaceCollection Redfish dict Populates self.redfish with network set data retrieved from OneView
Method signatures and docstrings:
- def __init__(self, network_set, endpoint): VLanNetworkInterfaceC... | Implement the Python class `VLanNetworkInterfaceCollection` described below.
Class description:
Creates a VLanNetworkInterfaceCollection Redfish dict Populates self.redfish with network set data retrieved from OneView
Method signatures and docstrings:
- def __init__(self, network_set, endpoint): VLanNetworkInterfaceC... | ffc86ea0a9e5d192ab6a2fe21c1717957b55d1da | <|skeleton|>
class VLanNetworkInterfaceCollection:
"""Creates a VLanNetworkInterfaceCollection Redfish dict Populates self.redfish with network set data retrieved from OneView"""
def __init__(self, network_set, endpoint):
"""VLanNetworkInterfaceCollection constructor Populates self.redfish with Network... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VLanNetworkInterfaceCollection:
"""Creates a VLanNetworkInterfaceCollection Redfish dict Populates self.redfish with network set data retrieved from OneView"""
def __init__(self, network_set, endpoint):
"""VLanNetworkInterfaceCollection constructor Populates self.redfish with NetworkSet data retr... | the_stack_v2_python_sparse | oneview_redfish_toolkit/api/vlan_network_interface_collection.py | shobhit-sinha/oneview-redfish-toolkit | train | 2 |
757de08854639016817e7589d3f65d5282b76581 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TemporaryAccessPassAuthenticationMethod()",
"from .authentication_method import AuthenticationMethod\nfrom .authentication_method import AuthenticationMethod\nfields: Dict[str, Callable[[Any], None]] = {'createdDateTime': lambda n: set... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TemporaryAccessPassAuthenticationMethod()
<|end_body_0|>
<|body_start_1|>
from .authentication_method import AuthenticationMethod
from .authentication_method import AuthenticationMethod
... | TemporaryAccessPassAuthenticationMethod | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemporaryAccessPassAuthenticationMethod:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethod:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read t... | stack_v2_sparse_classes_10k_train_000866 | 4,574 | 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: TemporaryAccessPassAuthenticationMethod",
"name": "create_from_discriminator_value",
"signature": "def creat... | 3 | null | Implement the Python class `TemporaryAccessPassAuthenticationMethod` described below.
Class description:
Implement the TemporaryAccessPassAuthenticationMethod class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethod... | Implement the Python class `TemporaryAccessPassAuthenticationMethod` described below.
Class description:
Implement the TemporaryAccessPassAuthenticationMethod class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethod... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TemporaryAccessPassAuthenticationMethod:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethod:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TemporaryAccessPassAuthenticationMethod:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethod:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminat... | the_stack_v2_python_sparse | msgraph/generated/models/temporary_access_pass_authentication_method.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
f615cf74412040847de5f243e9d488fb6440a8b0 | [
"self.new_inv_item = ['1', 'Knife Set', 10, 'n', 'n']\nself.new_furn_item = ['2', 'Couch', 25, 'y', 'Cloth', 'L']\nself.new_elec_item = ['3', 'Dryer', 100, 'n', 'y', 'Samsung', 12]",
"m.FULL_INVENTORY = {}\nwith patch('builtins.input', side_effect=self.new_inv_item):\n with patch('inventory_management.market_p... | <|body_start_0|>
self.new_inv_item = ['1', 'Knife Set', 10, 'n', 'n']
self.new_furn_item = ['2', 'Couch', 25, 'y', 'Cloth', 'L']
self.new_elec_item = ['3', 'Dryer', 100, 'n', 'y', 'Samsung', 12]
<|end_body_0|>
<|body_start_1|>
m.FULL_INVENTORY = {}
with patch('builtins.input', s... | Perform integration tests inventory_management package. | IntegrationTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntegrationTests:
"""Perform integration tests inventory_management package."""
def setUp(self):
"""Peform setup of tests."""
<|body_0|>
def test_integration(self):
"""Test all modules together."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
se... | stack_v2_sparse_classes_10k_train_000867 | 4,548 | no_license | [
{
"docstring": "Peform setup of tests.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test all modules together.",
"name": "test_integration",
"signature": "def test_integration(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000057 | Implement the Python class `IntegrationTests` described below.
Class description:
Perform integration tests inventory_management package.
Method signatures and docstrings:
- def setUp(self): Peform setup of tests.
- def test_integration(self): Test all modules together. | Implement the Python class `IntegrationTests` described below.
Class description:
Perform integration tests inventory_management package.
Method signatures and docstrings:
- def setUp(self): Peform setup of tests.
- def test_integration(self): Test all modules together.
<|skeleton|>
class IntegrationTests:
"""Pe... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class IntegrationTests:
"""Perform integration tests inventory_management package."""
def setUp(self):
"""Peform setup of tests."""
<|body_0|>
def test_integration(self):
"""Test all modules together."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IntegrationTests:
"""Perform integration tests inventory_management package."""
def setUp(self):
"""Peform setup of tests."""
self.new_inv_item = ['1', 'Knife Set', 10, 'n', 'n']
self.new_furn_item = ['2', 'Couch', 25, 'y', 'Cloth', 'L']
self.new_elec_item = ['3', 'Dryer',... | the_stack_v2_python_sparse | students/Reem_Alqaysi/Lesson_01/test_integration.py | JavaRod/SP_Python220B_2019 | train | 1 |
f3ea8c986fcefa31ee3e684132083cf896b1aea6 | [
"self.storage = storage\nself.email_sender = email_sender\nself.ses_client = ses_client",
"msg = MIMEMultipart('mixed')\nmsg['Subject'] = 'Work items'\nmsg['From'] = self.email_sender\nmsg['To'] = recipient\nmsg_body = MIMEMultipart('alternative')\ntextpart = MIMEText(text.encode(charset), 'plain', charset)\nhtml... | <|body_start_0|>
self.storage = storage
self.email_sender = email_sender
self.ses_client = ses_client
<|end_body_0|>
<|body_start_1|>
msg = MIMEMultipart('mixed')
msg['Subject'] = 'Work items'
msg['From'] = self.email_sender
msg['To'] = recipient
msg_body... | Encapsulates a report resource that gets work items from an Amazon Aurora Serverless database and uses Amazon SES to send emails about them. | Report | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Report:
"""Encapsulates a report resource that gets work items from an Amazon Aurora Serverless database and uses Amazon SES to send emails about them."""
def __init__(self, storage, email_sender, ses_client):
""":param storage: An object that manages moving data in and out of the un... | stack_v2_sparse_classes_10k_train_000868 | 5,653 | permissive | [
{
"docstring": ":param storage: An object that manages moving data in and out of the underlying database. :param email_sender: The email address from which the email report is sent. :param ses_client: A Boto3 Amazon SES client.",
"name": "__init__",
"signature": "def __init__(self, storage, email_sender... | 4 | null | Implement the Python class `Report` described below.
Class description:
Encapsulates a report resource that gets work items from an Amazon Aurora Serverless database and uses Amazon SES to send emails about them.
Method signatures and docstrings:
- def __init__(self, storage, email_sender, ses_client): :param storage... | Implement the Python class `Report` described below.
Class description:
Encapsulates a report resource that gets work items from an Amazon Aurora Serverless database and uses Amazon SES to send emails about them.
Method signatures and docstrings:
- def __init__(self, storage, email_sender, ses_client): :param storage... | dec41fb589043ac9d8667aac36fb88a53c3abe50 | <|skeleton|>
class Report:
"""Encapsulates a report resource that gets work items from an Amazon Aurora Serverless database and uses Amazon SES to send emails about them."""
def __init__(self, storage, email_sender, ses_client):
""":param storage: An object that manages moving data in and out of the un... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Report:
"""Encapsulates a report resource that gets work items from an Amazon Aurora Serverless database and uses Amazon SES to send emails about them."""
def __init__(self, storage, email_sender, ses_client):
""":param storage: An object that manages moving data in and out of the underlying data... | the_stack_v2_python_sparse | python/cross_service/aurora_item_tracker/report.py | awsdocs/aws-doc-sdk-examples | train | 8,240 |
f11fad5d26a3d7de11b0c8786cb45d46bbf3a547 | [
"self.hostname = ip\nself.username = username\nself.password = password\nself.port = port\nself.conn_timeout = conn_timeout\nself.key_filename = key_filename",
"_ssh = my_pxssh(ip=self.hostname, username=self.username, timeout=self.conn_timeout, maxread=5000, options={'StrictHostKeyChecking': 'no', 'UserKnownHost... | <|body_start_0|>
self.hostname = ip
self.username = username
self.password = password
self.port = port
self.conn_timeout = conn_timeout
self.key_filename = key_filename
<|end_body_0|>
<|body_start_1|>
_ssh = my_pxssh(ip=self.hostname, username=self.username, time... | PXSSH_Factory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PXSSH_Factory:
def __init__(self, ip, username, port, conn_timeout, password=None, key_filename=None):
""":param ip: 主机ip :param username: 登录用户名 :param port: 端口号 :param conn_timeout: 超时时间 :param password: 登录密码 :param key_filename: 登录密钥路径"""
<|body_0|>
def create(self, retry=... | stack_v2_sparse_classes_10k_train_000869 | 8,958 | no_license | [
{
"docstring": ":param ip: 主机ip :param username: 登录用户名 :param port: 端口号 :param conn_timeout: 超时时间 :param password: 登录密码 :param key_filename: 登录密钥路径",
"name": "__init__",
"signature": "def __init__(self, ip, username, port, conn_timeout, password=None, key_filename=None)"
},
{
"docstring": "创建pxs... | 2 | stack_v2_sparse_classes_30k_train_006017 | Implement the Python class `PXSSH_Factory` described below.
Class description:
Implement the PXSSH_Factory class.
Method signatures and docstrings:
- def __init__(self, ip, username, port, conn_timeout, password=None, key_filename=None): :param ip: 主机ip :param username: 登录用户名 :param port: 端口号 :param conn_timeout: 超时时... | Implement the Python class `PXSSH_Factory` described below.
Class description:
Implement the PXSSH_Factory class.
Method signatures and docstrings:
- def __init__(self, ip, username, port, conn_timeout, password=None, key_filename=None): :param ip: 主机ip :param username: 登录用户名 :param port: 端口号 :param conn_timeout: 超时时... | 9e66f5e62214e566528003d434ef2b74877419fd | <|skeleton|>
class PXSSH_Factory:
def __init__(self, ip, username, port, conn_timeout, password=None, key_filename=None):
""":param ip: 主机ip :param username: 登录用户名 :param port: 端口号 :param conn_timeout: 超时时间 :param password: 登录密码 :param key_filename: 登录密钥路径"""
<|body_0|>
def create(self, retry=... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PXSSH_Factory:
def __init__(self, ip, username, port, conn_timeout, password=None, key_filename=None):
""":param ip: 主机ip :param username: 登录用户名 :param port: 端口号 :param conn_timeout: 超时时间 :param password: 登录密码 :param key_filename: 登录密钥路径"""
self.hostname = ip
self.username = username
... | the_stack_v2_python_sparse | utils/deploy.py | seekplum/seekplum | train | 2 | |
18f813b87be221e42c42be4e66a5679c4e28c469 | [
"if not isinstance(op_types, (list, tuple)):\n op_types = [op_types]\nself._op_types = op_types",
"if not callable(f):\n raise TypeError('conversion_func must be callable.')\nfor op_type in self._op_types:\n _node_converter_registry.register(f, op_type)\nreturn f"
] | <|body_start_0|>
if not isinstance(op_types, (list, tuple)):
op_types = [op_types]
self._op_types = op_types
<|end_body_0|>
<|body_start_1|>
if not callable(f):
raise TypeError('conversion_func must be callable.')
for op_type in self._op_types:
_node_... | A decorator for registering the convertion function that converts the framework's op to NNDCT's op. For example: ```python @RegisterNodeConverter("Conv2D") def parse_conv2d(attrs): ... return op ``` The decorator argument `op_type` is the string type of an op which corresponds to the `NodeDef.op` field in the proto def... | RegisterNodeConverter | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSD-3-Clause-Open-MPI",
"LicenseRef-scancode-free-unknown",
"Libtool-exception",
"GCC-exception-3.1",
"LicenseRef-scancode-mit-old-style",
"OFL-1.1",
"JSON",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"ICU",
"LicenseRef-scancode-... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterNodeConverter:
"""A decorator for registering the convertion function that converts the framework's op to NNDCT's op. For example: ```python @RegisterNodeConverter("Conv2D") def parse_conv2d(attrs): ... return op ``` The decorator argument `op_type` is the string type of an op which corre... | stack_v2_sparse_classes_10k_train_000870 | 25,455 | permissive | [
{
"docstring": "Creates a new decorator with `op_type` as the Operation type. Args: op_type: The type of an framework operation. Raises: TypeError: If `op_type` is not string or `f` is not callable.",
"name": "__init__",
"signature": "def __init__(self, op_types)"
},
{
"docstring": "Registers th... | 2 | null | Implement the Python class `RegisterNodeConverter` described below.
Class description:
A decorator for registering the convertion function that converts the framework's op to NNDCT's op. For example: ```python @RegisterNodeConverter("Conv2D") def parse_conv2d(attrs): ... return op ``` The decorator argument `op_type` ... | Implement the Python class `RegisterNodeConverter` described below.
Class description:
A decorator for registering the convertion function that converts the framework's op to NNDCT's op. For example: ```python @RegisterNodeConverter("Conv2D") def parse_conv2d(attrs): ... return op ``` The decorator argument `op_type` ... | f74ddc6ed086ba949b791626638717e21505dba2 | <|skeleton|>
class RegisterNodeConverter:
"""A decorator for registering the convertion function that converts the framework's op to NNDCT's op. For example: ```python @RegisterNodeConverter("Conv2D") def parse_conv2d(attrs): ... return op ``` The decorator argument `op_type` is the string type of an op which corre... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RegisterNodeConverter:
"""A decorator for registering the convertion function that converts the framework's op to NNDCT's op. For example: ```python @RegisterNodeConverter("Conv2D") def parse_conv2d(attrs): ... return op ``` The decorator argument `op_type` is the string type of an op which corresponds to the... | the_stack_v2_python_sparse | src/vai_optimizer/tensorflow/tf_nndct/graph/converter.py | Xilinx/Vitis-AI | train | 1,283 |
a3030ea039e7a9a04d2835a27e76f01b312dbb94 | [
"query = session.query(GoldenHitCandidate.hit_id)\nassert query.count() > 0, 'No candidate golden hits'\nquery = query.order_by(GoldenHitCandidate.created_at.desc()).limit(n_lookback)\nquery = query.from_self()\nquery = query.outerjoin(GoldenHit, GoldenHitCandidate.hit_id == GoldenHit.hit_id)\nquery = query.group_b... | <|body_start_0|>
query = session.query(GoldenHitCandidate.hit_id)
assert query.count() > 0, 'No candidate golden hits'
query = query.order_by(GoldenHitCandidate.created_at.desc()).limit(n_lookback)
query = query.from_self()
query = query.outerjoin(GoldenHit, GoldenHitCandidate.hi... | Manager in charge of golden hits. | GoldenHitManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoldenHitManager:
"""Manager in charge of golden hits."""
def submit_golden_hits(n_hits, n_lookback):
"""Submit golden hits. Fetches the N_LOOKBACK hits most recently selected for golden submission and submits N_HITS of them, cycling through them as necessary, and prioritizing those ... | stack_v2_sparse_classes_10k_train_000871 | 2,356 | no_license | [
{
"docstring": "Submit golden hits. Fetches the N_LOOKBACK hits most recently selected for golden submission and submits N_HITS of them, cycling through them as necessary, and prioritizing those that have been submitted as golden the least number of times. Args: n_hits: Number of golden hits submissions. n_look... | 2 | stack_v2_sparse_classes_30k_train_003877 | Implement the Python class `GoldenHitManager` described below.
Class description:
Manager in charge of golden hits.
Method signatures and docstrings:
- def submit_golden_hits(n_hits, n_lookback): Submit golden hits. Fetches the N_LOOKBACK hits most recently selected for golden submission and submits N_HITS of them, c... | Implement the Python class `GoldenHitManager` described below.
Class description:
Manager in charge of golden hits.
Method signatures and docstrings:
- def submit_golden_hits(n_hits, n_lookback): Submit golden hits. Fetches the N_LOOKBACK hits most recently selected for golden submission and submits N_HITS of them, c... | 2f9c33c4e1a26b3e9e699210ac974047936f49e1 | <|skeleton|>
class GoldenHitManager:
"""Manager in charge of golden hits."""
def submit_golden_hits(n_hits, n_lookback):
"""Submit golden hits. Fetches the N_LOOKBACK hits most recently selected for golden submission and submits N_HITS of them, cycling through them as necessary, and prioritizing those ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GoldenHitManager:
"""Manager in charge of golden hits."""
def submit_golden_hits(n_hits, n_lookback):
"""Submit golden hits. Fetches the N_LOOKBACK hits most recently selected for golden submission and submits N_HITS of them, cycling through them as necessary, and prioritizing those that have bee... | the_stack_v2_python_sparse | affine/model/mturk/golden_hit_manager.py | winkash/image-classification | train | 0 |
8467dcdd46c26c027ca3888d2f2c2983aa9fe9d6 | [
"n = len(A)\nindices = sorted(range(n), key=lambda i: A[i])\nres = 0\npre = n\nfor i in indices:\n if i < pre:\n pre = i\n else:\n res = max(res, i - pre)\nreturn res",
"stack = []\nfor i, a in enumerate(A):\n if not stack or (stack and A[stack[-1]] > a):\n stack.append(i)\nres = 0\n... | <|body_start_0|>
n = len(A)
indices = sorted(range(n), key=lambda i: A[i])
res = 0
pre = n
for i in indices:
if i < pre:
pre = i
else:
res = max(res, i - pre)
return res
<|end_body_0|>
<|body_start_1|>
stack... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxWidthRamp1(self, A: List[int]) -> int:
"""求一个最长的上坡 索引排序 @param A: @return:"""
<|body_0|>
def maxWidthRamp2(self, A: List[int]) -> int:
"""单调栈 @param A: @return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(A)
indi... | stack_v2_sparse_classes_10k_train_000872 | 1,773 | no_license | [
{
"docstring": "求一个最长的上坡 索引排序 @param A: @return:",
"name": "maxWidthRamp1",
"signature": "def maxWidthRamp1(self, A: List[int]) -> int"
},
{
"docstring": "单调栈 @param A: @return:",
"name": "maxWidthRamp2",
"signature": "def maxWidthRamp2(self, A: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxWidthRamp1(self, A: List[int]) -> int: 求一个最长的上坡 索引排序 @param A: @return:
- def maxWidthRamp2(self, A: List[int]) -> int: 单调栈 @param A: @return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxWidthRamp1(self, A: List[int]) -> int: 求一个最长的上坡 索引排序 @param A: @return:
- def maxWidthRamp2(self, A: List[int]) -> int: 单调栈 @param A: @return:
<|skeleton|>
class Solution... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def maxWidthRamp1(self, A: List[int]) -> int:
"""求一个最长的上坡 索引排序 @param A: @return:"""
<|body_0|>
def maxWidthRamp2(self, A: List[int]) -> int:
"""单调栈 @param A: @return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxWidthRamp1(self, A: List[int]) -> int:
"""求一个最长的上坡 索引排序 @param A: @return:"""
n = len(A)
indices = sorted(range(n), key=lambda i: A[i])
res = 0
pre = n
for i in indices:
if i < pre:
pre = i
else:
... | the_stack_v2_python_sparse | LeetCode/栈/单调栈(Monotone Stack)/962. 最大宽度坡.py | yiming1012/MyLeetCode | train | 2 | |
c38961be6a51046ba1b3467ade6742179ee25dc2 | [
"content_parser = self.get(content_type)\nif not content_parser:\n raise UnsupportedContentType(f'No parser for `{content_type}`')\nreturn content_parser(fp)",
"if isinstance(content_types, str):\n content_types = (content_types,)\nfor content_type in content_types:\n self[content_type] = parser"
] | <|body_start_0|>
content_parser = self.get(content_type)
if not content_parser:
raise UnsupportedContentType(f'No parser for `{content_type}`')
return content_parser(fp)
<|end_body_0|>
<|body_start_1|>
if isinstance(content_types, str):
content_types = (content_t... | Registry of content type parsers. | ContentTypeParserRegistry | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentTypeParserRegistry:
"""Registry of content type parsers."""
def parse_file(self, fp, content_type: str) -> Dict[str, Any]:
"""Parse a file using the specified content type. :raises: UnsupportedContentType"""
<|body_0|>
def register(self, content_types: Union[str, ... | stack_v2_sparse_classes_10k_train_000873 | 2,441 | permissive | [
{
"docstring": "Parse a file using the specified content type. :raises: UnsupportedContentType",
"name": "parse_file",
"signature": "def parse_file(self, fp, content_type: str) -> Dict[str, Any]"
},
{
"docstring": "Register a content type parser.",
"name": "register",
"signature": "def r... | 2 | stack_v2_sparse_classes_30k_train_003334 | Implement the Python class `ContentTypeParserRegistry` described below.
Class description:
Registry of content type parsers.
Method signatures and docstrings:
- def parse_file(self, fp, content_type: str) -> Dict[str, Any]: Parse a file using the specified content type. :raises: UnsupportedContentType
- def register(... | Implement the Python class `ContentTypeParserRegistry` described below.
Class description:
Registry of content type parsers.
Method signatures and docstrings:
- def parse_file(self, fp, content_type: str) -> Dict[str, Any]: Parse a file using the specified content type. :raises: UnsupportedContentType
- def register(... | 1fa2651d8b42f6e28b0c33b2b4fd287affd3a88f | <|skeleton|>
class ContentTypeParserRegistry:
"""Registry of content type parsers."""
def parse_file(self, fp, content_type: str) -> Dict[str, Any]:
"""Parse a file using the specified content type. :raises: UnsupportedContentType"""
<|body_0|>
def register(self, content_types: Union[str, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ContentTypeParserRegistry:
"""Registry of content type parsers."""
def parse_file(self, fp, content_type: str) -> Dict[str, Any]:
"""Parse a file using the specified content type. :raises: UnsupportedContentType"""
content_parser = self.get(content_type)
if not content_parser:
... | the_stack_v2_python_sparse | pyapp/conf/loaders/content_types.py | gc-ss/pyapp | train | 0 |
a39b52fc67acb608709f1f240e28d2c48e34a1c6 | [
"if not root:\n return []\nstack, res = ([], [])\nstack.append(root)\nlevel = 0\nwhile stack:\n row, next_stack = ([], [])\n for node in stack:\n row.append(node.val)\n if node.left:\n next_stack.append(node.left)\n if node.right:\n next_stack.append(node.right)\n... | <|body_start_0|>
if not root:
return []
stack, res = ([], [])
stack.append(root)
level = 0
while stack:
row, next_stack = ([], [])
for node in stack:
row.append(node.val)
if node.left:
next_st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrderBottom(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrderBottom_reverse_102(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i... | stack_v2_sparse_classes_10k_train_000874 | 1,479 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrderBottom",
"signature": "def levelOrderBottom(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrderBottom_reverse_102",
"signature": "def levelOrderBottom_reverse_... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrderBottom_reverse_102(self, root): :type root: TreeNode :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrderBottom_reverse_102(self, root): :type root: TreeNode :rtype: List[List[int]]
<|ske... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def levelOrderBottom(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrderBottom_reverse_102(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrderBottom(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
if not root:
return []
stack, res = ([], [])
stack.append(root)
level = 0
while stack:
row, next_stack = ([], [])
for node in stack... | the_stack_v2_python_sparse | Algorithm/107_Binary_Tree_Level_Order_Traversal_II.py | Gi1ia/TechNoteBook | train | 7 | |
91bd2fc96977683de140f76944af0733510f0a17 | [
"super().__init__()\nself.gmm_size = gmm_size\nself.sample_size = sample_size\nself.input_slice = input_slice\nself.target_slice = target_slice\nself.stdout = stdout\nself.save_plots = save_plots\nos.makedirs(plot_dir, exist_ok=True)\nself.plot_dir = plot_dir",
"random.seed(datetime.now())\nsample_indexes = rando... | <|body_start_0|>
super().__init__()
self.gmm_size = gmm_size
self.sample_size = sample_size
self.input_slice = input_slice
self.target_slice = target_slice
self.stdout = stdout
self.save_plots = save_plots
os.makedirs(plot_dir, exist_ok=True)
self.... | DecypherAll | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecypherAll:
def __init__(self, gmm_size=1, sample_size=3, input_slice=lambda x: x[0:1], target_slice=lambda x: x[1:2], stdout=False, save_plots=True, plot_dir='plots'):
"""Class constructor that instantiates with a few vital settings in order to decypher the output :type target_slice: o... | stack_v2_sparse_classes_10k_train_000875 | 3,310 | permissive | [
{
"docstring": "Class constructor that instantiates with a few vital settings in order to decypher the output :type target_slice: object :param gmm_size: size as an integer of the gaussian mixture model :param sample_size: size as an integer of the number of samples to log :param stdout: boolean whether or not ... | 2 | stack_v2_sparse_classes_30k_train_002968 | Implement the Python class `DecypherAll` described below.
Class description:
Implement the DecypherAll class.
Method signatures and docstrings:
- def __init__(self, gmm_size=1, sample_size=3, input_slice=lambda x: x[0:1], target_slice=lambda x: x[1:2], stdout=False, save_plots=True, plot_dir='plots'): Class construct... | Implement the Python class `DecypherAll` described below.
Class description:
Implement the DecypherAll class.
Method signatures and docstrings:
- def __init__(self, gmm_size=1, sample_size=3, input_slice=lambda x: x[0:1], target_slice=lambda x: x[1:2], stdout=False, save_plots=True, plot_dir='plots'): Class construct... | 6ade84c0ac1197b21d189f905ec559505ca15159 | <|skeleton|>
class DecypherAll:
def __init__(self, gmm_size=1, sample_size=3, input_slice=lambda x: x[0:1], target_slice=lambda x: x[1:2], stdout=False, save_plots=True, plot_dir='plots'):
"""Class constructor that instantiates with a few vital settings in order to decypher the output :type target_slice: o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DecypherAll:
def __init__(self, gmm_size=1, sample_size=3, input_slice=lambda x: x[0:1], target_slice=lambda x: x[1:2], stdout=False, save_plots=True, plot_dir='plots'):
"""Class constructor that instantiates with a few vital settings in order to decypher the output :type target_slice: object :param g... | the_stack_v2_python_sparse | model/topoml_util/PyplotLogger.py | Empythy/geometry-learning | train | 0 | |
af788f1b33b24a6c2c3e80cb974c69b73c94106a | [
"role = request.get_json().get('role')\nmembership_status = request.get_json().get('status')\nnotify_user = request.get_json().get('notifyUser')\nupdated_fields_dict = {}\norigin = request.environ.get('HTTP_ORIGIN', 'localhost')\ntry:\n if role is not None:\n updated_role = MembershipService.get_membershi... | <|body_start_0|>
role = request.get_json().get('role')
membership_status = request.get_json().get('status')
notify_user = request.get_json().get('notifyUser')
updated_fields_dict = {}
origin = request.environ.get('HTTP_ORIGIN', 'localhost')
try:
if role is not... | Resource for managing a single membership record between an org and a user. | OrgMember | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrgMember:
"""Resource for managing a single membership record between an org and a user."""
def patch(org_id, membership_id):
"""Update a membership record with new member role."""
<|body_0|>
def delete(org_id, membership_id):
"""Mark a membership record as inac... | stack_v2_sparse_classes_10k_train_000876 | 30,185 | permissive | [
{
"docstring": "Update a membership record with new member role.",
"name": "patch",
"signature": "def patch(org_id, membership_id)"
},
{
"docstring": "Mark a membership record as inactive. Membership must match current user token.",
"name": "delete",
"signature": "def delete(org_id, memb... | 2 | null | Implement the Python class `OrgMember` described below.
Class description:
Resource for managing a single membership record between an org and a user.
Method signatures and docstrings:
- def patch(org_id, membership_id): Update a membership record with new member role.
- def delete(org_id, membership_id): Mark a memb... | Implement the Python class `OrgMember` described below.
Class description:
Resource for managing a single membership record between an org and a user.
Method signatures and docstrings:
- def patch(org_id, membership_id): Update a membership record with new member role.
- def delete(org_id, membership_id): Mark a memb... | 923cb8a3ee88dcbaf0fe800ca70022b3c13c1d01 | <|skeleton|>
class OrgMember:
"""Resource for managing a single membership record between an org and a user."""
def patch(org_id, membership_id):
"""Update a membership record with new member role."""
<|body_0|>
def delete(org_id, membership_id):
"""Mark a membership record as inac... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrgMember:
"""Resource for managing a single membership record between an org and a user."""
def patch(org_id, membership_id):
"""Update a membership record with new member role."""
role = request.get_json().get('role')
membership_status = request.get_json().get('status')
... | the_stack_v2_python_sparse | auth-api/src/auth_api/resources/org.py | bcgov/sbc-auth | train | 13 |
3a0d0d3fb727854130fe69e612ffd01064ed5c6c | [
"if timeout < 1:\n raise ValueError('Illegal timeout %s' % timeout)\nif interval < 1 or interval > timeout:\n raise ValueError('Illegal check interval %s' % interval)\nself.timeout = timeout\nself.interval = interval",
"if not resource:\n raise NoneReferenceError(\"resource to check can't be None!\")\nif... | <|body_start_0|>
if timeout < 1:
raise ValueError('Illegal timeout %s' % timeout)
if interval < 1 or interval > timeout:
raise ValueError('Illegal check interval %s' % interval)
self.timeout = timeout
self.interval = interval
<|end_body_0|>
<|body_start_1|>
... | check whether the given resource reaches the expected status within given period | SyncStateChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyncStateChecker:
"""check whether the given resource reaches the expected status within given period"""
def __init__(self, timeout=30, interval=5):
"""Initialization. :param timeout: the period in seconds when the check should stop. Default is 30 seconds. :param interval: the interv... | stack_v2_sparse_classes_10k_train_000877 | 2,236 | no_license | [
{
"docstring": "Initialization. :param timeout: the period in seconds when the check should stop. Default is 30 seconds. :param interval: the interval between 2 checks in second. Default is 5.",
"name": "__init__",
"signature": "def __init__(self, timeout=30, interval=5)"
},
{
"docstring": "Chec... | 2 | stack_v2_sparse_classes_30k_train_000144 | Implement the Python class `SyncStateChecker` described below.
Class description:
check whether the given resource reaches the expected status within given period
Method signatures and docstrings:
- def __init__(self, timeout=30, interval=5): Initialization. :param timeout: the period in seconds when the check should... | Implement the Python class `SyncStateChecker` described below.
Class description:
check whether the given resource reaches the expected status within given period
Method signatures and docstrings:
- def __init__(self, timeout=30, interval=5): Initialization. :param timeout: the period in seconds when the check should... | cde85988fa008c083afbeb980fa66960dbe3cb23 | <|skeleton|>
class SyncStateChecker:
"""check whether the given resource reaches the expected status within given period"""
def __init__(self, timeout=30, interval=5):
"""Initialization. :param timeout: the period in seconds when the check should stop. Default is 30 seconds. :param interval: the interv... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SyncStateChecker:
"""check whether the given resource reaches the expected status within given period"""
def __init__(self, timeout=30, interval=5):
"""Initialization. :param timeout: the period in seconds when the check should stop. Default is 30 seconds. :param interval: the interval between 2 ... | the_stack_v2_python_sparse | sedna/openstack/util.py | Jiakun/all_autotests | train | 0 |
1ea05c60d2612c9f7023a9f82d52e17347e0bf2c | [
"from enthought.tvtk.pipeline.browser import PipelineBrowser\nself.browser = PipelineBrowser()\nself.browser.show(parent=parent)\nreturn self.browser.ui.control",
"map(self._remove_scene, event.removed)\nmap(self._add_scene, event.added)\nreturn",
"self.browser.renwins.append(scene)\nself.browser.root_object.ap... | <|body_start_0|>
from enthought.tvtk.pipeline.browser import PipelineBrowser
self.browser = PipelineBrowser()
self.browser.show(parent=parent)
return self.browser.ui.control
<|end_body_0|>
<|body_start_1|>
map(self._remove_scene, event.removed)
map(self._add_scene, event... | The TVTK pipeline browser view. | BrowserView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrowserView:
"""The TVTK pipeline browser view."""
def create_control(self, parent):
"""Create the toolkit-specific control that represents the view."""
<|body_0|>
def _on_scenes_changed(self, event):
"""Dynamic trait change handler. This is called when scenes ar... | stack_v2_sparse_classes_10k_train_000878 | 3,017 | no_license | [
{
"docstring": "Create the toolkit-specific control that represents the view.",
"name": "create_control",
"signature": "def create_control(self, parent)"
},
{
"docstring": "Dynamic trait change handler. This is called when scenes are added/removed from the scene manager, it is used to add and re... | 4 | null | Implement the Python class `BrowserView` described below.
Class description:
The TVTK pipeline browser view.
Method signatures and docstrings:
- def create_control(self, parent): Create the toolkit-specific control that represents the view.
- def _on_scenes_changed(self, event): Dynamic trait change handler. This is ... | Implement the Python class `BrowserView` described below.
Class description:
The TVTK pipeline browser view.
Method signatures and docstrings:
- def create_control(self, parent): Create the toolkit-specific control that represents the view.
- def _on_scenes_changed(self, event): Dynamic trait change handler. This is ... | 5466f5858dbd2f1f082fa0d7417b57c8fb068fad | <|skeleton|>
class BrowserView:
"""The TVTK pipeline browser view."""
def create_control(self, parent):
"""Create the toolkit-specific control that represents the view."""
<|body_0|>
def _on_scenes_changed(self, event):
"""Dynamic trait change handler. This is called when scenes ar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BrowserView:
"""The TVTK pipeline browser view."""
def create_control(self, parent):
"""Create the toolkit-specific control that represents the view."""
from enthought.tvtk.pipeline.browser import PipelineBrowser
self.browser = PipelineBrowser()
self.browser.show(parent=pa... | the_stack_v2_python_sparse | maps/build/mayavi/enthought/tvtk/plugins/browser/browser_view.py | m-elhussieny/code | train | 0 |
b0d943f0dc540313444c75f4aca5fcdfa6815774 | [
"time.sleep(2)\nLoginPage(web_page).login(data['username'], data['password'])\nlogging.info('开始断言')\ntime.sleep(3)\ntry:\n assert LoginPage(web_page).login_success() == data['check']\n assert 1 == 1\n logging.info('登录成功')\nexcept:\n print('登录失败')\n common.save_screenShot(web_page, model_name='登录页面')\... | <|body_start_0|>
time.sleep(2)
LoginPage(web_page).login(data['username'], data['password'])
logging.info('开始断言')
time.sleep(3)
try:
assert LoginPage(web_page).login_success() == data['check']
assert 1 == 1
logging.info('登录成功')
except:
... | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
def test_login_success(self, data, web_page):
"""成功登录"""
<|body_0|>
def test_usernotin(self, data, web_page):
"""帐号不存在/密码少于6位,密码输入错误"""
<|body_1|>
def test_usernotin2(self, data, web_page):
"""手机号码为空"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_10k_train_000879 | 2,299 | no_license | [
{
"docstring": "成功登录",
"name": "test_login_success",
"signature": "def test_login_success(self, data, web_page)"
},
{
"docstring": "帐号不存在/密码少于6位,密码输入错误",
"name": "test_usernotin",
"signature": "def test_usernotin(self, data, web_page)"
},
{
"docstring": "手机号码为空",
"name": "tes... | 3 | stack_v2_sparse_classes_30k_train_005388 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login_success(self, data, web_page): 成功登录
- def test_usernotin(self, data, web_page): 帐号不存在/密码少于6位,密码输入错误
- def test_usernotin2(self, data, web_page): 手机号码为空 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login_success(self, data, web_page): 成功登录
- def test_usernotin(self, data, web_page): 帐号不存在/密码少于6位,密码输入错误
- def test_usernotin2(self, data, web_page): 手机号码为空
<|skelet... | b262c13e55a6e9eae1d4fa11d50b71814028261c | <|skeleton|>
class TestLogin:
def test_login_success(self, data, web_page):
"""成功登录"""
<|body_0|>
def test_usernotin(self, data, web_page):
"""帐号不存在/密码少于6位,密码输入错误"""
<|body_1|>
def test_usernotin2(self, data, web_page):
"""手机号码为空"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestLogin:
def test_login_success(self, data, web_page):
"""成功登录"""
time.sleep(2)
LoginPage(web_page).login(data['username'], data['password'])
logging.info('开始断言')
time.sleep(3)
try:
assert LoginPage(web_page).login_success() == data['check']
... | the_stack_v2_python_sparse | TestCase/test_C_web/test_login.py | xjx985426946/Test_UI | train | 0 | |
88000392ff7ed945a764d5d379e590379727bad8 | [
"super().__init__()\nself.unified_encoder = unified_encoder\nself.decoder = decoder\nself.output_layer = output_layer",
"enc_src, src_mask, src_inp = self.unified_encoder(*args)\nbatch_size, _, hid_dim = src_inp.shape\ndevice = src_inp.device\ntrg_inp = torch.cat((torch.zeros((batch_size, 1, hid_dim), device=devi... | <|body_start_0|>
super().__init__()
self.unified_encoder = unified_encoder
self.decoder = decoder
self.output_layer = output_layer
<|end_body_0|>
<|body_start_1|>
enc_src, src_mask, src_inp = self.unified_encoder(*args)
batch_size, _, hid_dim = src_inp.shape
devi... | TransformerAutoEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerAutoEncoder:
def __init__(self, unified_encoder, decoder, output_layer):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1|>
def run(self, y, seq_cat_data, seq_co... | stack_v2_sparse_classes_10k_train_000880 | 15,906 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, unified_encoder, decoder, output_layer)"
},
{
"docstring": "Run a forward pass of model over the data.",
"name": "forward",
"signature": "def forward(self, *args)"
},
{
"docstring... | 3 | stack_v2_sparse_classes_30k_train_005408 | Implement the Python class `TransformerAutoEncoder` described below.
Class description:
Implement the TransformerAutoEncoder class.
Method signatures and docstrings:
- def __init__(self, unified_encoder, decoder, output_layer): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over... | Implement the Python class `TransformerAutoEncoder` described below.
Class description:
Implement the TransformerAutoEncoder class.
Method signatures and docstrings:
- def __init__(self, unified_encoder, decoder, output_layer): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class TransformerAutoEncoder:
def __init__(self, unified_encoder, decoder, output_layer):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1|>
def run(self, y, seq_cat_data, seq_co... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TransformerAutoEncoder:
def __init__(self, unified_encoder, decoder, output_layer):
"""Initialize model with params."""
super().__init__()
self.unified_encoder = unified_encoder
self.decoder = decoder
self.output_layer = output_layer
def forward(self, *args):
... | the_stack_v2_python_sparse | caspr/models/model_wrapper.py | microsoft/CASPR | train | 29 | |
efdfd77feb771c8d8cc5f65aa9b027ee486c143d | [
"testName = 'meter_to_millimeter'\ntry:\n log.print_test_begin(testName)\n meters = 1\n millimeters = sc_Length.meter_to_millimeter(meters)\n self.assertEquals(millimeters, 1000)\n log.print_test_success(testName)\nexcept:\n log.print_test_failure(testName)\n self.fail(msg=testName[testName.rfi... | <|body_start_0|>
testName = 'meter_to_millimeter'
try:
log.print_test_begin(testName)
meters = 1
millimeters = sc_Length.meter_to_millimeter(meters)
self.assertEquals(millimeters, 1000)
log.print_test_success(testName)
except:
... | TestCalculations_length | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCalculations_length:
def meterToMillimeter(self):
"""Are meters correctly converted to millimeters?"""
<|body_0|>
def millimeterToMeter(self):
"""Are millimeters correctly converted to meters?"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test... | stack_v2_sparse_classes_10k_train_000881 | 2,102 | permissive | [
{
"docstring": "Are meters correctly converted to millimeters?",
"name": "meterToMillimeter",
"signature": "def meterToMillimeter(self)"
},
{
"docstring": "Are millimeters correctly converted to meters?",
"name": "millimeterToMeter",
"signature": "def millimeterToMeter(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005176 | Implement the Python class `TestCalculations_length` described below.
Class description:
Implement the TestCalculations_length class.
Method signatures and docstrings:
- def meterToMillimeter(self): Are meters correctly converted to millimeters?
- def millimeterToMeter(self): Are millimeters correctly converted to me... | Implement the Python class `TestCalculations_length` described below.
Class description:
Implement the TestCalculations_length class.
Method signatures and docstrings:
- def meterToMillimeter(self): Are meters correctly converted to millimeters?
- def millimeterToMeter(self): Are millimeters correctly converted to me... | 6a5bfbb459f5a1309fdace4e38b44e8274c497db | <|skeleton|>
class TestCalculations_length:
def meterToMillimeter(self):
"""Are meters correctly converted to millimeters?"""
<|body_0|>
def millimeterToMeter(self):
"""Are millimeters correctly converted to meters?"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestCalculations_length:
def meterToMillimeter(self):
"""Are meters correctly converted to millimeters?"""
testName = 'meter_to_millimeter'
try:
log.print_test_begin(testName)
meters = 1
millimeters = sc_Length.meter_to_millimeter(meters)
... | the_stack_v2_python_sparse | testCalculations/length.py | sativa/SPEED | train | 0 | |
f9244ce8cf0cb88bffeb9c890dc97da0fea29fe3 | [
"neg = (dividend < 0 or divisor < 0) and (not (dividend < 0 and divisor < 0))\nx, y = (abs(dividend), abs(divisor))\nzgen = range(y, x, y)\nzlen = len(zgen)\nif y > x:\n return 0\nif x == y:\n return -1 if neg else 1\nif zgen[-1] + y <= x:\n zlen += 1\nif neg:\n return 0 - zlen\nreturn min(max(-21474836... | <|body_start_0|>
neg = (dividend < 0 or divisor < 0) and (not (dividend < 0 and divisor < 0))
x, y = (abs(dividend), abs(divisor))
zgen = range(y, x, y)
zlen = len(zgen)
if y > x:
return 0
if x == y:
return -1 if neg else 1
if zgen[-1] + y ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def divide(self, dividend, divisor):
""":type dividend: int :type divisor: int :rtype: int"""
<|body_0|>
def divide_work(self, dividend, divisor):
""":type dividend: int :type divisor: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_10k_train_000882 | 2,372 | no_license | [
{
"docstring": ":type dividend: int :type divisor: int :rtype: int",
"name": "divide",
"signature": "def divide(self, dividend, divisor)"
},
{
"docstring": ":type dividend: int :type divisor: int :rtype: int",
"name": "divide_work",
"signature": "def divide_work(self, dividend, divisor)"... | 2 | stack_v2_sparse_classes_30k_train_003319 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def divide(self, dividend, divisor): :type dividend: int :type divisor: int :rtype: int
- def divide_work(self, dividend, divisor): :type dividend: int :type divisor: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def divide(self, dividend, divisor): :type dividend: int :type divisor: int :rtype: int
- def divide_work(self, dividend, divisor): :type dividend: int :type divisor: int :rtype:... | 3f0ffd519404165fd1a735441b212c801fd1ad1e | <|skeleton|>
class Solution:
def divide(self, dividend, divisor):
""":type dividend: int :type divisor: int :rtype: int"""
<|body_0|>
def divide_work(self, dividend, divisor):
""":type dividend: int :type divisor: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def divide(self, dividend, divisor):
""":type dividend: int :type divisor: int :rtype: int"""
neg = (dividend < 0 or divisor < 0) and (not (dividend < 0 and divisor < 0))
x, y = (abs(dividend), abs(divisor))
zgen = range(y, x, y)
zlen = len(zgen)
if y ... | the_stack_v2_python_sparse | Problems/0001_0099/0029_Divide_Two_Integers/project_Python3/Divide_Two_Integers.py | NobuyukiInoue/LeetCode | train | 0 | |
79aad45ef61218c8380c83007aadef65c25a546d | [
"self.viewport_name = viewport_name\nself.adhoc_media_pool_publisher = adhoc_media_pool_publisher\nself.media_type = media_type",
"adhoc_medias = self._extract_adhoc_media(data)\nlogger.info('Publishing AdhocMedias: %s' % adhoc_medias)\nself.adhoc_media_pool_publisher.publish(adhoc_medias)",
"medias = extract_f... | <|body_start_0|>
self.viewport_name = viewport_name
self.adhoc_media_pool_publisher = adhoc_media_pool_publisher
self.media_type = media_type
<|end_body_0|>
<|body_start_1|>
adhoc_medias = self._extract_adhoc_media(data)
logger.info('Publishing AdhocMedias: %s' % adhoc_medias)
... | Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on director messages and emits AdhocMedias messages via `mplayer_pool_publisher` | DirectorMediaBridge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectorMediaBridge:
"""Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on director messages and emits AdhocMedias mess... | stack_v2_sparse_classes_10k_train_000883 | 4,045 | permissive | [
{
"docstring": "MediaDirectorBridge should be configured per each viewport to properly translate director geometry to viewport geometry and provide separation and service granularity.",
"name": "__init__",
"signature": "def __init__(self, adhoc_media_pool_publisher, viewport_name, media_type='video')"
... | 5 | stack_v2_sparse_classes_30k_train_007232 | Implement the Python class `DirectorMediaBridge` described below.
Class description:
Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on direc... | Implement the Python class `DirectorMediaBridge` described below.
Class description:
Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on direc... | 90233b939bb4873c00a72e84ab3f8d1a776edee8 | <|skeleton|>
class DirectorMediaBridge:
"""Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on director messages and emits AdhocMedias mess... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DirectorMediaBridge:
"""Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on director messages and emits AdhocMedias messages via `mpl... | the_stack_v2_python_sparse | lg_media/src/lg_media/director_media_bridge.py | EndPointCorp/lg_ros_nodes | train | 18 |
cf09d86ec3eee51348ffaf79f42bb226cf91b885 | [
"if 'tune_embeds' not in config.keys():\n raise ValueError('config must define \"tune_embeds\".')\nsuper(TextModel, self).__init__(name, config)\nself.embeds = nn.Embedding(embed_mat.shape[0], embed_mat.shape[1])\nself.embeds.weight = nn.Parameter(torch.from_numpy(embed_mat), requires_grad=self.tune_embeds)",
... | <|body_start_0|>
if 'tune_embeds' not in config.keys():
raise ValueError('config must define "tune_embeds".')
super(TextModel, self).__init__(name, config)
self.embeds = nn.Embedding(embed_mat.shape[0], embed_mat.shape[1])
self.embeds.weight = nn.Parameter(torch.from_numpy(em... | Base text model. Extends base mode with embedding and lookup. Attributes: param_groups: List of dictionaries defining named parameter groups. embeds: torch.nn.Embedding. | TextModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextModel:
"""Base text model. Extends base mode with embedding and lookup. Attributes: param_groups: List of dictionaries defining named parameter groups. embeds: torch.nn.Embedding."""
def __init__(self, name, config, embed_mat):
"""Create a new TextModel. Expects config to have a ... | stack_v2_sparse_classes_10k_train_000884 | 5,995 | no_license | [
{
"docstring": "Create a new TextModel. Expects config to have a boolean \"tune_embeds\". Raises: ValueError: if \"tune_embeds\" not in config.",
"name": "__init__",
"signature": "def __init__(self, name, config, embed_mat)"
},
{
"docstring": "Embedding lookup. Args: ixs: numpy.ndarray of intege... | 2 | stack_v2_sparse_classes_30k_test_000355 | Implement the Python class `TextModel` described below.
Class description:
Base text model. Extends base mode with embedding and lookup. Attributes: param_groups: List of dictionaries defining named parameter groups. embeds: torch.nn.Embedding.
Method signatures and docstrings:
- def __init__(self, name, config, embe... | Implement the Python class `TextModel` described below.
Class description:
Base text model. Extends base mode with embedding and lookup. Attributes: param_groups: List of dictionaries defining named parameter groups. embeds: torch.nn.Embedding.
Method signatures and docstrings:
- def __init__(self, name, config, embe... | b35744011fcf6622cbd32481290b6d33bc46cd08 | <|skeleton|>
class TextModel:
"""Base text model. Extends base mode with embedding and lookup. Attributes: param_groups: List of dictionaries defining named parameter groups. embeds: torch.nn.Embedding."""
def __init__(self, name, config, embed_mat):
"""Create a new TextModel. Expects config to have a ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TextModel:
"""Base text model. Extends base mode with embedding and lookup. Attributes: param_groups: List of dictionaries defining named parameter groups. embeds: torch.nn.Embedding."""
def __init__(self, name, config, embed_mat):
"""Create a new TextModel. Expects config to have a boolean "tune... | the_stack_v2_python_sparse | ext/models.py | IKMLab/arct | train | 8 |
b42dd1c39c764de5bf8748cc1c6c64253337a8a9 | [
"diff_file_blink_h = ['some diff']\ndiff_file_chromium_h = ['another diff']\ndiff_file_test_expectations = ['more diff']\nmock_input_api = MockInputApi()\nmock_python_file = MockAffectedFile('file_blink.py', ['lint me'])\nmock_input_api.files = [MockAffectedFile('file_blink.h', diff_file_blink_h), MockAffectedFile(... | <|body_start_0|>
diff_file_blink_h = ['some diff']
diff_file_chromium_h = ['another diff']
diff_file_test_expectations = ['more diff']
mock_input_api = MockInputApi()
mock_python_file = MockAffectedFile('file_blink.py', ['lint me'])
mock_input_api.files = [MockAffectedFil... | PresubmitTest | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PresubmitTest:
def testCheckChangeOnUploadWithBlinkAndChromiumFiles(self, _, _run_tests, _get_pylint):
"""This verifies that CheckChangeOnUpload will only call check_blink_style.py on non-test files."""
<|body_0|>
def testCheckChangeOnUploadWithEmptyAffectedFileList(self, _)... | stack_v2_sparse_classes_10k_train_000885 | 10,881 | permissive | [
{
"docstring": "This verifies that CheckChangeOnUpload will only call check_blink_style.py on non-test files.",
"name": "testCheckChangeOnUploadWithBlinkAndChromiumFiles",
"signature": "def testCheckChangeOnUploadWithBlinkAndChromiumFiles(self, _, _run_tests, _get_pylint)"
},
{
"docstring": "Thi... | 5 | stack_v2_sparse_classes_30k_train_000644 | Implement the Python class `PresubmitTest` described below.
Class description:
Implement the PresubmitTest class.
Method signatures and docstrings:
- def testCheckChangeOnUploadWithBlinkAndChromiumFiles(self, _, _run_tests, _get_pylint): This verifies that CheckChangeOnUpload will only call check_blink_style.py on no... | Implement the Python class `PresubmitTest` described below.
Class description:
Implement the PresubmitTest class.
Method signatures and docstrings:
- def testCheckChangeOnUploadWithBlinkAndChromiumFiles(self, _, _run_tests, _get_pylint): This verifies that CheckChangeOnUpload will only call check_blink_style.py on no... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class PresubmitTest:
def testCheckChangeOnUploadWithBlinkAndChromiumFiles(self, _, _run_tests, _get_pylint):
"""This verifies that CheckChangeOnUpload will only call check_blink_style.py on non-test files."""
<|body_0|>
def testCheckChangeOnUploadWithEmptyAffectedFileList(self, _)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PresubmitTest:
def testCheckChangeOnUploadWithBlinkAndChromiumFiles(self, _, _run_tests, _get_pylint):
"""This verifies that CheckChangeOnUpload will only call check_blink_style.py on non-test files."""
diff_file_blink_h = ['some diff']
diff_file_chromium_h = ['another diff']
d... | the_stack_v2_python_sparse | third_party/blink/PRESUBMIT_test.py | chromium/chromium | train | 17,408 | |
ff93a18c697e6e0d64de601bcc9decf1326eeb9d | [
"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... | Service that handles processing/re-encoding of uploaded videos | UploadsServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadsServiceServicer:
"""Service that handles processing/re-encoding of uploaded videos"""
def GetUploadDestination(self, request, context):
"""Gets an upload destination for a user to upload a video"""
<|body_0|>
def MarkUploadComplete(self, request, context):
... | stack_v2_sparse_classes_10k_train_000886 | 3,536 | permissive | [
{
"docstring": "Gets an upload destination for a user to upload a video",
"name": "GetUploadDestination",
"signature": "def GetUploadDestination(self, request, context)"
},
{
"docstring": "Marks an upload as complete",
"name": "MarkUploadComplete",
"signature": "def MarkUploadComplete(se... | 3 | stack_v2_sparse_classes_30k_train_001748 | Implement the Python class `UploadsServiceServicer` described below.
Class description:
Service that handles processing/re-encoding of uploaded videos
Method signatures and docstrings:
- def GetUploadDestination(self, request, context): Gets an upload destination for a user to upload a video
- def MarkUploadComplete(... | Implement the Python class `UploadsServiceServicer` described below.
Class description:
Service that handles processing/re-encoding of uploaded videos
Method signatures and docstrings:
- def GetUploadDestination(self, request, context): Gets an upload destination for a user to upload a video
- def MarkUploadComplete(... | 55a610c97fd53c405edb2459c2722fc03857cb83 | <|skeleton|>
class UploadsServiceServicer:
"""Service that handles processing/re-encoding of uploaded videos"""
def GetUploadDestination(self, request, context):
"""Gets an upload destination for a user to upload a video"""
<|body_0|>
def MarkUploadComplete(self, request, context):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UploadsServiceServicer:
"""Service that handles processing/re-encoding of uploaded videos"""
def GetUploadDestination(self, request, context):
"""Gets an upload destination for a user to upload a video"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method ... | the_stack_v2_python_sparse | killrvideo/uploads/uploads_service_pb2_grpc.py | krzysztof-adamski/killrvideo-python | train | 0 |
286b58d160d6098874228f0de2eda41b674026c5 | [
"if model._meta.app_label == self.appname:\n return self.db_name\nreturn None",
"if model._meta.app_label == self.appname:\n return self.db_name\nreturn None",
"if obj1._meta.app_label == self.appname or obj2._meta.app_label == self.appname:\n return True\nreturn None",
"if app_label == self.appname:... | <|body_start_0|>
if model._meta.app_label == self.appname:
return self.db_name
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == self.appname:
return self.db_name
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta.app_label =... | Router | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Router:
def db_for_read(self, model, **hints):
"""Attempts to read self.appname models go to model.db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write self.appname models go to model.db."""
<|body_1|>
def allow_relation(self, o... | stack_v2_sparse_classes_10k_train_000887 | 1,715 | no_license | [
{
"docstring": "Attempts to read self.appname models go to model.db.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write self.appname models go to model.db.",
"name": "db_for_write",
"signature": "def db_for_write(self, model... | 4 | stack_v2_sparse_classes_30k_train_001053 | Implement the Python class `Router` described below.
Class description:
Implement the Router class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read self.appname models go to model.db.
- def db_for_write(self, model, **hints): Attempts to write self.appname models go to mode... | Implement the Python class `Router` described below.
Class description:
Implement the Router class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read self.appname models go to model.db.
- def db_for_write(self, model, **hints): Attempts to write self.appname models go to mode... | 7cf818076b67cf6d4e40192b6bbe7db547005c96 | <|skeleton|>
class Router:
def db_for_read(self, model, **hints):
"""Attempts to read self.appname models go to model.db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write self.appname models go to model.db."""
<|body_1|>
def allow_relation(self, o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Router:
def db_for_read(self, model, **hints):
"""Attempts to read self.appname models go to model.db."""
if model._meta.app_label == self.appname:
return self.db_name
return None
def db_for_write(self, model, **hints):
"""Attempts to write self.appname models ... | the_stack_v2_python_sparse | apps_cenco/db_local/router.py | robCastro/academica_cenco | train | 0 | |
5848cf562da9013ac09021dc63198d1b28e7268b | [
"self.id = id\nself.raw_policy_str = raw_policy_str\nself.statement_vec = statement_vec\nself.version = version",
"if dictionary is None:\n return None\nid = dictionary.get('id')\nraw_policy_str = dictionary.get('rawPolicyStr')\nstatement_vec = None\nif dictionary.get('statementVec') != None:\n statement_ve... | <|body_start_0|>
self.id = id
self.raw_policy_str = raw_policy_str
self.statement_vec = statement_vec
self.version = version
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
id = dictionary.get('id')
raw_policy_str = dictionary.get('... | Implementation of the 'BucketPolicy' model. TODO: type description here. Attributes: id (string): The identifier for the bucket policy. raw_policy_str (string): Raw JSON string of the stored policy. statement_vec (list of Statement): This field defines the statement to execute for each request. version (string): This f... | BucketPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BucketPolicy:
"""Implementation of the 'BucketPolicy' model. TODO: type description here. Attributes: id (string): The identifier for the bucket policy. raw_policy_str (string): Raw JSON string of the stored policy. statement_vec (list of Statement): This field defines the statement to execute fo... | stack_v2_sparse_classes_10k_train_000888 | 2,411 | permissive | [
{
"docstring": "Constructor for the BucketPolicy class",
"name": "__init__",
"signature": "def __init__(self, id=None, raw_policy_str=None, statement_vec=None, version=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary repres... | 2 | stack_v2_sparse_classes_30k_train_000329 | Implement the Python class `BucketPolicy` described below.
Class description:
Implementation of the 'BucketPolicy' model. TODO: type description here. Attributes: id (string): The identifier for the bucket policy. raw_policy_str (string): Raw JSON string of the stored policy. statement_vec (list of Statement): This fi... | Implement the Python class `BucketPolicy` described below.
Class description:
Implementation of the 'BucketPolicy' model. TODO: type description here. Attributes: id (string): The identifier for the bucket policy. raw_policy_str (string): Raw JSON string of the stored policy. statement_vec (list of Statement): This fi... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class BucketPolicy:
"""Implementation of the 'BucketPolicy' model. TODO: type description here. Attributes: id (string): The identifier for the bucket policy. raw_policy_str (string): Raw JSON string of the stored policy. statement_vec (list of Statement): This field defines the statement to execute fo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BucketPolicy:
"""Implementation of the 'BucketPolicy' model. TODO: type description here. Attributes: id (string): The identifier for the bucket policy. raw_policy_str (string): Raw JSON string of the stored policy. statement_vec (list of Statement): This field defines the statement to execute for each reques... | the_stack_v2_python_sparse | cohesity_management_sdk/models/bucket_policy.py | cohesity/management-sdk-python | train | 24 |
98a21ef74103c5afe58091994df806509c9aed4f | [
"self.z_start = z_start\nself.z_end = z_end\nself.gamma_boost = gamma_boost\nif m == 'all':\n self.modes = None\nelif isinstance(m, int):\n self.modes = [m]\nelif isinstance(m, list):\n self.modes = m\nelse:\n raise TypeError('m should be an int or a list of ints.')",
"if self.gamma_boost is None:\n ... | <|body_start_0|>
self.z_start = z_start
self.z_end = z_end
self.gamma_boost = gamma_boost
if m == 'all':
self.modes = None
elif isinstance(m, int):
self.modes = [m]
elif isinstance(m, list):
self.modes = m
else:
rais... | Mirror | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mirror:
def __init__(self, z_start, z_end, gamma_boost=None, m='all'):
"""Initialize a mirror. The mirror reflects the fields in the z direction, by setting the specified field modes to 0 in a thin slice orthogonal to z, at each timestep.s By default, all modes are zeroed. Parameters ---... | stack_v2_sparse_classes_10k_train_000889 | 3,295 | permissive | [
{
"docstring": "Initialize a mirror. The mirror reflects the fields in the z direction, by setting the specified field modes to 0 in a thin slice orthogonal to z, at each timestep.s By default, all modes are zeroed. Parameters ---------- z_start: float Start position of the mirror in the lab frame z_end: float ... | 2 | stack_v2_sparse_classes_30k_train_000915 | Implement the Python class `Mirror` described below.
Class description:
Implement the Mirror class.
Method signatures and docstrings:
- def __init__(self, z_start, z_end, gamma_boost=None, m='all'): Initialize a mirror. The mirror reflects the fields in the z direction, by setting the specified field modes to 0 in a ... | Implement the Python class `Mirror` described below.
Class description:
Implement the Mirror class.
Method signatures and docstrings:
- def __init__(self, z_start, z_end, gamma_boost=None, m='all'): Initialize a mirror. The mirror reflects the fields in the z direction, by setting the specified field modes to 0 in a ... | 5744598571eab40c4fb45cc3db21f346b69b1f37 | <|skeleton|>
class Mirror:
def __init__(self, z_start, z_end, gamma_boost=None, m='all'):
"""Initialize a mirror. The mirror reflects the fields in the z direction, by setting the specified field modes to 0 in a thin slice orthogonal to z, at each timestep.s By default, all modes are zeroed. Parameters ---... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Mirror:
def __init__(self, z_start, z_end, gamma_boost=None, m='all'):
"""Initialize a mirror. The mirror reflects the fields in the z direction, by setting the specified field modes to 0 in a thin slice orthogonal to z, at each timestep.s By default, all modes are zeroed. Parameters ---------- z_star... | the_stack_v2_python_sparse | fbpic/lpa_utils/mirrors.py | fbpic/fbpic | train | 163 | |
0e0e74307e8a63090893e1c80f9f9cd77eb1a9f9 | [
"self.default_branch_setting_func = kwargs.pop('branch_setting_func', lambda: ModuleStoreEnum.Branch.published_only)\nsuper().__init__(*args, **kwargs)\nself.thread_cache = threading.local()",
"previous_thread_branch_setting = getattr(self.thread_cache, 'branch_setting', None)\ntry:\n self.thread_cache.branch_... | <|body_start_0|>
self.default_branch_setting_func = kwargs.pop('branch_setting_func', lambda: ModuleStoreEnum.Branch.published_only)
super().__init__(*args, **kwargs)
self.thread_cache = threading.local()
<|end_body_0|>
<|body_start_1|>
previous_thread_branch_setting = getattr(self.thre... | A mixin to manage a module store's branch setting. The order of override is (from higher precedence to lower): 1. thread-specific setting temporarily set using the branch_setting contextmanager 2. the return value of the branch_setting_func passed into this mixin's init method 3. the default branch setting being Module... | BranchSettingMixin | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BranchSettingMixin:
"""A mixin to manage a module store's branch setting. The order of override is (from higher precedence to lower): 1. thread-specific setting temporarily set using the branch_setting contextmanager 2. the return value of the branch_setting_func passed into this mixin's init met... | stack_v2_sparse_classes_10k_train_000890 | 8,397 | permissive | [
{
"docstring": ":param branch_setting_func: a function that returns the default branch setting for this object. If not specified, ModuleStoreEnum.Branch.published_only is used as the default setting.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "A co... | 3 | stack_v2_sparse_classes_30k_train_006127 | Implement the Python class `BranchSettingMixin` described below.
Class description:
A mixin to manage a module store's branch setting. The order of override is (from higher precedence to lower): 1. thread-specific setting temporarily set using the branch_setting contextmanager 2. the return value of the branch_setting... | Implement the Python class `BranchSettingMixin` described below.
Class description:
A mixin to manage a module store's branch setting. The order of override is (from higher precedence to lower): 1. thread-specific setting temporarily set using the branch_setting contextmanager 2. the return value of the branch_setting... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class BranchSettingMixin:
"""A mixin to manage a module store's branch setting. The order of override is (from higher precedence to lower): 1. thread-specific setting temporarily set using the branch_setting contextmanager 2. the return value of the branch_setting_func passed into this mixin's init met... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BranchSettingMixin:
"""A mixin to manage a module store's branch setting. The order of override is (from higher precedence to lower): 1. thread-specific setting temporarily set using the branch_setting contextmanager 2. the return value of the branch_setting_func passed into this mixin's init method 3. the de... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/lib/xmodule/xmodule/modulestore/draft_and_published.py | luque/better-ways-of-thinking-about-software | train | 3 |
8443889d7c9b25c593b4fdd14bbcb8cae5e2e6f8 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DeviceComplianceActionItem()",
"from .device_compliance_action_type import DeviceComplianceActionType\nfrom .entity import Entity\nfrom .device_compliance_action_type import DeviceComplianceActionType\nfrom .entity import Entity\nfield... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DeviceComplianceActionItem()
<|end_body_0|>
<|body_start_1|>
from .device_compliance_action_type import DeviceComplianceActionType
from .entity import Entity
from .device_complia... | Scheduled Action Configuration | DeviceComplianceActionItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceComplianceActionItem:
"""Scheduled Action Configuration"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceActionItem:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node t... | stack_v2_sparse_classes_10k_train_000891 | 3,346 | 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: DeviceComplianceActionItem",
"name": "create_from_discriminator_value",
"signature": "def create_from_discri... | 3 | null | Implement the Python class `DeviceComplianceActionItem` described below.
Class description:
Scheduled Action Configuration
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceActionItem: Creates a new instance of the appropriate class based ... | Implement the Python class `DeviceComplianceActionItem` described below.
Class description:
Scheduled Action Configuration
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceActionItem: Creates a new instance of the appropriate class based ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DeviceComplianceActionItem:
"""Scheduled Action Configuration"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceActionItem:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeviceComplianceActionItem:
"""Scheduled Action Configuration"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceActionItem:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read... | the_stack_v2_python_sparse | msgraph/generated/models/device_compliance_action_item.py | microsoftgraph/msgraph-sdk-python | train | 135 |
aa81ee9a8e3e87e2be61d70693ecad0ba0351a21 | [
"dp, sm = ({0: -1}, 0)\nright, cnt = (-1, 0)\nfor i in range(len(nums)):\n sm += nums[i]\n if sm - target in dp:\n left = dp[sm - target]\n if right <= left:\n cnt += 1\n right = i\n dp[sm] = i\nreturn cnt",
"sm = [0]\nfor i in nums:\n sm.append(sm[-1] + i)\nm, righ... | <|body_start_0|>
dp, sm = ({0: -1}, 0)
right, cnt = (-1, 0)
for i in range(len(nums)):
sm += nums[i]
if sm - target in dp:
left = dp[sm - target]
if right <= left:
cnt += 1
right = i
dp[sm... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxNonOverlappingOnepass(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def maxNonOverlapping(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_000892 | 2,266 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "maxNonOverlappingOnepass",
"signature": "def maxNonOverlappingOnepass(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "maxNonOverlapping",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_001772 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxNonOverlappingOnepass(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def maxNonOverlapping(self, nums, target): :type nums: List[int] :type tar... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxNonOverlappingOnepass(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def maxNonOverlapping(self, nums, target): :type nums: List[int] :type tar... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def maxNonOverlappingOnepass(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def maxNonOverlapping(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxNonOverlappingOnepass(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
dp, sm = ({0: -1}, 0)
right, cnt = (-1, 0)
for i in range(len(nums)):
sm += nums[i]
if sm - target in dp:
left = dp[sm -... | the_stack_v2_python_sparse | M/MaximumNumberofNon-OverlappingSubarraysWithSumEqualsTarget.py | bssrdf/pyleet | train | 2 | |
04021339b4be3ae193900a1857477640ee228926 | [
"probabilities = []\nlist_theoretical_amplitude = []\nbest_algorithms = []\nconfigurations = []\nlist_number_calls_made = []\nfor eta_group in self._eta_groups:\n self._global_eta_group = eta_group\n result = self._compute_theoretical_best_configuration()\n best_algorithms.append(result['best_algorithm'])\... | <|body_start_0|>
probabilities = []
list_theoretical_amplitude = []
best_algorithms = []
configurations = []
list_number_calls_made = []
for eta_group in self._eta_groups:
self._global_eta_group = eta_group
result = self._compute_theoretical_best_c... | Representation of the theoretical One Shot Optimization | TheoreticalOneShotOptimization | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TheoreticalOneShotOptimization:
"""Representation of the theoretical One Shot Optimization"""
def compute_theoretical_optimal_results(self) -> TheoreticalOneShotOptimalConfigurations:
"""Finds out the theoretical optimal configuration for each pair of attenuation levels"""
<|... | stack_v2_sparse_classes_10k_train_000893 | 3,017 | permissive | [
{
"docstring": "Finds out the theoretical optimal configuration for each pair of attenuation levels",
"name": "compute_theoretical_optimal_results",
"signature": "def compute_theoretical_optimal_results(self) -> TheoreticalOneShotOptimalConfigurations"
},
{
"docstring": "Find out the theoretical... | 2 | stack_v2_sparse_classes_30k_train_000736 | Implement the Python class `TheoreticalOneShotOptimization` described below.
Class description:
Representation of the theoretical One Shot Optimization
Method signatures and docstrings:
- def compute_theoretical_optimal_results(self) -> TheoreticalOneShotOptimalConfigurations: Finds out the theoretical optimal config... | Implement the Python class `TheoreticalOneShotOptimization` described below.
Class description:
Representation of the theoretical One Shot Optimization
Method signatures and docstrings:
- def compute_theoretical_optimal_results(self) -> TheoreticalOneShotOptimalConfigurations: Finds out the theoretical optimal config... | ea37fca21fc4c8cf7ac6a39b3a6666e8a4fe5a19 | <|skeleton|>
class TheoreticalOneShotOptimization:
"""Representation of the theoretical One Shot Optimization"""
def compute_theoretical_optimal_results(self) -> TheoreticalOneShotOptimalConfigurations:
"""Finds out the theoretical optimal configuration for each pair of attenuation levels"""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TheoreticalOneShotOptimization:
"""Representation of the theoretical One Shot Optimization"""
def compute_theoretical_optimal_results(self) -> TheoreticalOneShotOptimalConfigurations:
"""Finds out the theoretical optimal configuration for each pair of attenuation levels"""
probabilities =... | the_stack_v2_python_sparse | qcd/optimizations/theoreticaloneshotoptimization.py | iamtxena/quantum-channel-discrimination | train | 0 |
2bc999e8f14c573c2c3b44bfaec1a05889999048 | [
"if not lists:\n return\nelif len(lists) == 1:\n return lists[0]\nmid = len(lists) // 2\nleft = self.mergeKLists(lists[:mid])\nright = self.mergeKLists(lists[mid:])\nreturn self.mergeTwoLists(left, right)",
"pre = ListNode(-1)\ncur = pre\nwhile l1 and l2:\n if l1.val <= l2.val:\n cur.next = l1\n ... | <|body_start_0|>
if not lists:
return
elif len(lists) == 1:
return lists[0]
mid = len(lists) // 2
left = self.mergeKLists(lists[:mid])
right = self.mergeKLists(lists[mid:])
return self.mergeTwoLists(left, right)
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not l... | stack_v2_sparse_classes_10k_train_000894 | 1,125 | permissive | [
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
<|skeleton|>... | eb58cd4f01d9b8006b7d1a725fc48910aad7f192 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
if not lists:
return
elif len(lists) == 1:
return lists[0]
mid = len(lists) // 2
left = self.mergeKLists(lists[:mid])
right = self.mergeKLists(list... | the_stack_v2_python_sparse | 1stRound/Hard/23-Merge K Sorted Lists/Merge2ListRecursion.py | ericchen12377/Leetcode-Algorithm-Python | train | 2 | |
22af5ebcea32d8d858a31947481f1d5e109e5280 | [
"super().__init__()\nself._registry = {}\nel = gremlin.event_handler.EventListener()\nel.joystick_event.connect(self._joystick_cb)",
"release_evt = physical_event.clone()\nrelease_evt.is_pressed = False\nif release_evt not in self._registry:\n self._registry[release_evt] = []\nself._registry[release_evt].appen... | <|body_start_0|>
super().__init__()
self._registry = {}
el = gremlin.event_handler.EventListener()
el.joystick_event.connect(self._joystick_cb)
<|end_body_0|>
<|body_start_1|>
release_evt = physical_event.clone()
release_evt.is_pressed = False
if release_evt not ... | Runs specified callback on release of an input. | OnReleaseExecutor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnReleaseExecutor:
"""Runs specified callback on release of an input."""
def __init__(self):
"""Creates a new instance."""
<|body_0|>
def register(self, callback, physical_event):
"""Register a callback to run for a particular event. :param callback the function ... | stack_v2_sparse_classes_10k_train_000895 | 2,935 | no_license | [
{
"docstring": "Creates a new instance.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Register a callback to run for a particular event. :param callback the function to run when the specified input is released :param physical_event the event describing the event on w... | 3 | stack_v2_sparse_classes_30k_test_000195 | Implement the Python class `OnReleaseExecutor` described below.
Class description:
Runs specified callback on release of an input.
Method signatures and docstrings:
- def __init__(self): Creates a new instance.
- def register(self, callback, physical_event): Register a callback to run for a particular event. :param c... | Implement the Python class `OnReleaseExecutor` described below.
Class description:
Runs specified callback on release of an input.
Method signatures and docstrings:
- def __init__(self): Creates a new instance.
- def register(self, callback, physical_event): Register a callback to run for a particular event. :param c... | 4788dd811f42b2654bdb00bb9f9e51f63a26abf0 | <|skeleton|>
class OnReleaseExecutor:
"""Runs specified callback on release of an input."""
def __init__(self):
"""Creates a new instance."""
<|body_0|>
def register(self, callback, physical_event):
"""Register a callback to run for a particular event. :param callback the function ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OnReleaseExecutor:
"""Runs specified callback on release of an input."""
def __init__(self):
"""Creates a new instance."""
super().__init__()
self._registry = {}
el = gremlin.event_handler.EventListener()
el.joystick_event.connect(self._joystick_cb)
def regist... | the_stack_v2_python_sparse | temporary_mode_switch.py | WhiteMagic/JoystickGremlinModules | train | 5 |
f0decf122472a64ffd9d04c9103a54fdca7bb422 | [
"self.name = cls_name\nif not config_path:\n self.working_dir = self.get_working_directory()\n config_path = os.path.join(self.working_dir, 'config.env.yml')\n if not os.path.isfile(config_path):\n config_path = os.path.join(self.working_dir, 'config.env.example.yml')\nself.config = Configurations.g... | <|body_start_0|>
self.name = cls_name
if not config_path:
self.working_dir = self.get_working_directory()
config_path = os.path.join(self.working_dir, 'config.env.yml')
if not os.path.isfile(config_path):
config_path = os.path.join(self.working_dir, 'c... | GetConfig decorator | GetConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetConfig:
"""GetConfig decorator"""
def __init__(self, cls_name: str, category: Union[str, None]=None, sub_category: Union[str, None]=None, config_path: Union[str, None]=None) -> None:
"""Check Settings File exists, Create Path, Get Configurations from file :param cls_name: Name of ... | stack_v2_sparse_classes_10k_train_000896 | 8,008 | permissive | [
{
"docstring": "Check Settings File exists, Create Path, Get Configurations from file :param cls_name: Name of Calling Class :param category: Configurations Category :param sub_category: Sub Configuration Category :param config_path: Absolute Path to custom configurations file",
"name": "__init__",
"sig... | 6 | stack_v2_sparse_classes_30k_train_003327 | Implement the Python class `GetConfig` described below.
Class description:
GetConfig decorator
Method signatures and docstrings:
- def __init__(self, cls_name: str, category: Union[str, None]=None, sub_category: Union[str, None]=None, config_path: Union[str, None]=None) -> None: Check Settings File exists, Create Pat... | Implement the Python class `GetConfig` described below.
Class description:
GetConfig decorator
Method signatures and docstrings:
- def __init__(self, cls_name: str, category: Union[str, None]=None, sub_category: Union[str, None]=None, config_path: Union[str, None]=None) -> None: Check Settings File exists, Create Pat... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class GetConfig:
"""GetConfig decorator"""
def __init__(self, cls_name: str, category: Union[str, None]=None, sub_category: Union[str, None]=None, config_path: Union[str, None]=None) -> None:
"""Check Settings File exists, Create Path, Get Configurations from file :param cls_name: Name of ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetConfig:
"""GetConfig decorator"""
def __init__(self, cls_name: str, category: Union[str, None]=None, sub_category: Union[str, None]=None, config_path: Union[str, None]=None) -> None:
"""Check Settings File exists, Create Path, Get Configurations from file :param cls_name: Name of Calling Class... | the_stack_v2_python_sparse | Analytics/settings/get_config_decorator.py | thanosbnt/SharingCitiesDashboard | train | 0 |
04e54ace2cb9f52486ec8f7881b1a7e5c7bc0ecc | [
"context = dict(form=UpLoadForm())\ncontext.update(setMenus())\nreturn render_template('webapp/datain.html', **context)",
"_value = int(request.json.get('value'))\ncontext = dict(form=UpLoadForm())\ncontext.update(setMenus())\ntemplate_name = 'webapp/form/register.html'\nreturn jsonify(body=render_template(templa... | <|body_start_0|>
context = dict(form=UpLoadForm())
context.update(setMenus())
return render_template('webapp/datain.html', **context)
<|end_body_0|>
<|body_start_1|>
_value = int(request.json.get('value'))
context = dict(form=UpLoadForm())
context.update(setMenus())
... | CDHChange | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CDHChange:
def get(self):
"""用于 列表翻页 的刷新 :return:"""
<|body_0|>
def post(self):
"""请求来自于:1)页面切换;2)定时器 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
context = dict(form=UpLoadForm())
context.update(setMenus())
return render... | stack_v2_sparse_classes_10k_train_000897 | 4,507 | no_license | [
{
"docstring": "用于 列表翻页 的刷新 :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "请求来自于:1)页面切换;2)定时器 :return:",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006094 | Implement the Python class `CDHChange` described below.
Class description:
Implement the CDHChange class.
Method signatures and docstrings:
- def get(self): 用于 列表翻页 的刷新 :return:
- def post(self): 请求来自于:1)页面切换;2)定时器 :return: | Implement the Python class `CDHChange` described below.
Class description:
Implement the CDHChange class.
Method signatures and docstrings:
- def get(self): 用于 列表翻页 的刷新 :return:
- def post(self): 请求来自于:1)页面切换;2)定时器 :return:
<|skeleton|>
class CDHChange:
def get(self):
"""用于 列表翻页 的刷新 :return:"""
... | f085ad50e52b6bbfd23d1afba2a7a86aae52e099 | <|skeleton|>
class CDHChange:
def get(self):
"""用于 列表翻页 的刷新 :return:"""
<|body_0|>
def post(self):
"""请求来自于:1)页面切换;2)定时器 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CDHChange:
def get(self):
"""用于 列表翻页 的刷新 :return:"""
context = dict(form=UpLoadForm())
context.update(setMenus())
return render_template('webapp/datain.html', **context)
def post(self):
"""请求来自于:1)页面切换;2)定时器 :return:"""
_value = int(request.json.get('value'... | the_stack_v2_python_sparse | nebula/portal/views/portal/hadoop/hadoop.py | shenwei0329/nebula | train | 1 | |
ddbee01c22db79de1eafcdb0a60bac9dd0b2489a | [
"action_space_dim = sum(action_space)\nself.action_space = action_space\nsuper(Actor, self).__init__()\nself.device = device\nconv_output_dim = 256 * 2 * 2\nself.conv_modules = nn.Sequential(nn.Conv2d(img_state_dim[-1], 32, kernel_size=5, stride=2, padding=2), nn.ReLU(), nn.BatchNorm2d(32), nn.Conv2d(32, 32, kernel... | <|body_start_0|>
action_space_dim = sum(action_space)
self.action_space = action_space
super(Actor, self).__init__()
self.device = device
conv_output_dim = 256 * 2 * 2
self.conv_modules = nn.Sequential(nn.Conv2d(img_state_dim[-1], 32, kernel_size=5, stride=2, padding=2), ... | Actor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Actor:
def __init__(self, img_state_dim, vect_state_len, action_space, device):
"""Create the actor network of the TD3 Algorithm. :param img_state_dim: Tuple Number of channels of the image input tensor at last place. (h,w,c) :param vect_state_len: Int Size of th semantic state input vec... | stack_v2_sparse_classes_10k_train_000898 | 3,370 | no_license | [
{
"docstring": "Create the actor network of the TD3 Algorithm. :param img_state_dim: Tuple Number of channels of the image input tensor at last place. (h,w,c) :param vect_state_len: Int Size of th semantic state input vector. :param action_space: Tupel of Ints Shape of the action space. E.g. for a combination o... | 2 | stack_v2_sparse_classes_30k_train_004174 | Implement the Python class `Actor` described below.
Class description:
Implement the Actor class.
Method signatures and docstrings:
- def __init__(self, img_state_dim, vect_state_len, action_space, device): Create the actor network of the TD3 Algorithm. :param img_state_dim: Tuple Number of channels of the image inpu... | Implement the Python class `Actor` described below.
Class description:
Implement the Actor class.
Method signatures and docstrings:
- def __init__(self, img_state_dim, vect_state_len, action_space, device): Create the actor network of the TD3 Algorithm. :param img_state_dim: Tuple Number of channels of the image inpu... | 8296c40c004f908d792ea8a496bcd16227ac81c1 | <|skeleton|>
class Actor:
def __init__(self, img_state_dim, vect_state_len, action_space, device):
"""Create the actor network of the TD3 Algorithm. :param img_state_dim: Tuple Number of channels of the image input tensor at last place. (h,w,c) :param vect_state_len: Int Size of th semantic state input vec... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Actor:
def __init__(self, img_state_dim, vect_state_len, action_space, device):
"""Create the actor network of the TD3 Algorithm. :param img_state_dim: Tuple Number of channels of the image input tensor at last place. (h,w,c) :param vect_state_len: Int Size of th semantic state input vector. :param ac... | the_stack_v2_python_sparse | src/agents/agent_smith_beta/td3_actor.py | leorychly/SC2-Game-AI | train | 0 | |
b62173335183be65b5f41cc1779a5b84b3e2cbfb | [
"super(C51DQN, self).__init__()\nobs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))\nif isinstance(obs_shape, int) or len(obs_shape) == 1:\n self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, activation=activation, norm_type=norm_type)\nelif len(obs_shape) == 3:\n self.encoder = ... | <|body_start_0|>
super(C51DQN, self).__init__()
obs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))
if isinstance(obs_shape, int) or len(obs_shape) == 1:
self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, activation=activation, norm_type=norm_type)
... | C51DQN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class C51DQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: int=64, head_layer_num: int=1, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optional[str]=None, v_min: Optiona... | stack_v2_sparse_classes_10k_train_000899 | 30,380 | permissive | [
{
"docstring": "Overview: Init the C51 Model according to input arguments. Arguments: - obs_shape (:obj:`Union[int, SequenceType]`): Observation's space. - action_shape (:obj:`Union[int, SequenceType]`): Action's space. - encoder_hidden_size_list (:obj:`SequenceType`): Collection of ``hidden_size`` to pass to `... | 2 | null | Implement the Python class `C51DQN` described below.
Class description:
Implement the C51DQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: int=64, head_... | Implement the Python class `C51DQN` described below.
Class description:
Implement the C51DQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: int=64, head_... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class C51DQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: int=64, head_layer_num: int=1, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optional[str]=None, v_min: Optiona... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class C51DQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: int=64, head_layer_num: int=1, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optional[str]=None, v_min: Optional[float]=-10, ... | the_stack_v2_python_sparse | ding/model/template/q_learning.py | shengxuesun/DI-engine | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.