blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
de3efcebc920dc64d643691da9107a990262a712 | [
"with open(path, encoding='utf-8') as json_data:\n data = json.load(json_data)\noutputdict = {}\nfor key, value in data.items():\n outputdict[key] = outputdict.get(key, []) + [value]\nreturn outputdict",
"dic = self.get_adict_local_history(self.path)\ndata_2 = dic['Areas you may have visited in the last two... | <|body_start_0|>
with open(path, encoding='utf-8') as json_data:
data = json.load(json_data)
outputdict = {}
for key, value in data.items():
outputdict[key] = outputdict.get(key, []) + [value]
return outputdict
<|end_body_0|>
<|body_start_1|>
dic = self.g... | SnapchatLocationLastTwoYears | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnapchatLocationLastTwoYears:
def get_adict_local_history(self, path):
"""The json file containing location history conained multiple kinds of information, this function returned a 'brut' dictionary from the json file"""
<|body_0|>
def read(self):
"""This function re... | stack_v2_sparse_classes_36k_train_014500 | 2,579 | permissive | [
{
"docstring": "The json file containing location history conained multiple kinds of information, this function returned a 'brut' dictionary from the json file",
"name": "get_adict_local_history",
"signature": "def get_adict_local_history(self, path)"
},
{
"docstring": "This function returns a d... | 2 | stack_v2_sparse_classes_30k_train_019200 | Implement the Python class `SnapchatLocationLastTwoYears` described below.
Class description:
Implement the SnapchatLocationLastTwoYears class.
Method signatures and docstrings:
- def get_adict_local_history(self, path): The json file containing location history conained multiple kinds of information, this function r... | Implement the Python class `SnapchatLocationLastTwoYears` described below.
Class description:
Implement the SnapchatLocationLastTwoYears class.
Method signatures and docstrings:
- def get_adict_local_history(self, path): The json file containing location history conained multiple kinds of information, this function r... | 179dd4f04713026656c0849916166fd1ed0d6f31 | <|skeleton|>
class SnapchatLocationLastTwoYears:
def get_adict_local_history(self, path):
"""The json file containing location history conained multiple kinds of information, this function returned a 'brut' dictionary from the json file"""
<|body_0|>
def read(self):
"""This function re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnapchatLocationLastTwoYears:
def get_adict_local_history(self, path):
"""The json file containing location history conained multiple kinds of information, this function returned a 'brut' dictionary from the json file"""
with open(path, encoding='utf-8') as json_data:
data = json.l... | the_stack_v2_python_sparse | Package/snapchat_sub_readers/location_last_two_years.py | AdrienCarthoblaz/Master-Thesis | train | 2 | |
2042473ac58e6837d57ab386b9a24b3cc0020c86 | [
"self.reporting_enabled = reporting_enabled\nself.collector_ip = collector_ip\nself.collector_port = collector_port",
"if dictionary is None:\n return None\nreporting_enabled = dictionary.get('reportingEnabled')\ncollector_ip = dictionary.get('collectorIp')\ncollector_port = dictionary.get('collectorPort')\nre... | <|body_start_0|>
self.reporting_enabled = reporting_enabled
self.collector_ip = collector_ip
self.collector_port = collector_port
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
reporting_enabled = dictionary.get('reportingEnabled')
collect... | Implementation of the 'updateNetworkNetflowSettings' model. TODO: type model description here. Attributes: reporting_enabled (bool): Boolean indicating whether NetFlow traffic reporting is enabled (true) or disabled (false). collector_ip (string): The IPv4 address of the NetFlow collector. collector_port (int): The por... | UpdateNetworkNetflowSettingsModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNetworkNetflowSettingsModel:
"""Implementation of the 'updateNetworkNetflowSettings' model. TODO: type model description here. Attributes: reporting_enabled (bool): Boolean indicating whether NetFlow traffic reporting is enabled (true) or disabled (false). collector_ip (string): The IPv4 ad... | stack_v2_sparse_classes_36k_train_014501 | 2,229 | permissive | [
{
"docstring": "Constructor for the UpdateNetworkNetflowSettingsModel class",
"name": "__init__",
"signature": "def __init__(self, reporting_enabled=None, collector_ip=None, collector_port=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary)... | 2 | stack_v2_sparse_classes_30k_train_006363 | Implement the Python class `UpdateNetworkNetflowSettingsModel` described below.
Class description:
Implementation of the 'updateNetworkNetflowSettings' model. TODO: type model description here. Attributes: reporting_enabled (bool): Boolean indicating whether NetFlow traffic reporting is enabled (true) or disabled (fal... | Implement the Python class `UpdateNetworkNetflowSettingsModel` described below.
Class description:
Implementation of the 'updateNetworkNetflowSettings' model. TODO: type model description here. Attributes: reporting_enabled (bool): Boolean indicating whether NetFlow traffic reporting is enabled (true) or disabled (fal... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateNetworkNetflowSettingsModel:
"""Implementation of the 'updateNetworkNetflowSettings' model. TODO: type model description here. Attributes: reporting_enabled (bool): Boolean indicating whether NetFlow traffic reporting is enabled (true) or disabled (false). collector_ip (string): The IPv4 ad... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateNetworkNetflowSettingsModel:
"""Implementation of the 'updateNetworkNetflowSettings' model. TODO: type model description here. Attributes: reporting_enabled (bool): Boolean indicating whether NetFlow traffic reporting is enabled (true) or disabled (false). collector_ip (string): The IPv4 address of the ... | the_stack_v2_python_sparse | meraki_sdk/models/update_network_netflow_settings_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
71a50726c1691449d7751d7488344857aaf49ab1 | [
"args_id = parse_id.parse_args()\nid = args_id.get('id')\nif id:\n admin = get_admin(id)\n data = {'status': RET.OK, 'data': object_to_json(admin)}\n return data\nargs = parse_page.parse_args()\npage = 1\npaginate = PAGINATE_NUM\nif args.get('page'):\n page = int(args.get('page'))\nif args.get('paginate... | <|body_start_0|>
args_id = parse_id.parse_args()
id = args_id.get('id')
if id:
admin = get_admin(id)
data = {'status': RET.OK, 'data': object_to_json(admin)}
return data
args = parse_page.parse_args()
page = 1
paginate = PAGINATE_NUM
... | AdminResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminResource:
def get(self):
"""获取用户信息"""
<|body_0|>
def post(self):
"""添加用户"""
<|body_1|>
def put(self):
"""重置密码"""
<|body_2|>
def delete(self):
"""删除用户"""
<|body_3|>
<|end_skeleton|>
<|body_start_0|>
args... | stack_v2_sparse_classes_36k_train_014502 | 11,703 | permissive | [
{
"docstring": "获取用户信息",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "添加用户",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "重置密码",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "删除用户",
"name": "delete",
"... | 4 | stack_v2_sparse_classes_30k_train_017871 | Implement the Python class `AdminResource` described below.
Class description:
Implement the AdminResource class.
Method signatures and docstrings:
- def get(self): 获取用户信息
- def post(self): 添加用户
- def put(self): 重置密码
- def delete(self): 删除用户 | Implement the Python class `AdminResource` described below.
Class description:
Implement the AdminResource class.
Method signatures and docstrings:
- def get(self): 获取用户信息
- def post(self): 添加用户
- def put(self): 重置密码
- def delete(self): 删除用户
<|skeleton|>
class AdminResource:
def get(self):
"""获取用户信息"""
... | 35ddd2946bf4c97806bb38057a7dc9d6fa97c118 | <|skeleton|>
class AdminResource:
def get(self):
"""获取用户信息"""
<|body_0|>
def post(self):
"""添加用户"""
<|body_1|>
def put(self):
"""重置密码"""
<|body_2|>
def delete(self):
"""删除用户"""
<|body_3|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdminResource:
def get(self):
"""获取用户信息"""
args_id = parse_id.parse_args()
id = args_id.get('id')
if id:
admin = get_admin(id)
data = {'status': RET.OK, 'data': object_to_json(admin)}
return data
args = parse_page.parse_args()
... | the_stack_v2_python_sparse | service/app/apis/admin/admin.py | xuannanxan/maitul-manage | train | 0 | |
9294803f85db4efc7ee59a7e204547cbc27dc2bc | [
"self.origin = origin\nself.comment = comment\nself.msgid = msgid\nself.msgstr = msgstr",
"if dictionary is None:\n return None\nmsgid = dictionary.get('msgid')\nmsgstr = dictionary.get('msgstr')\norigin = dictionary.get('origin')\ncomment = dictionary.get('comment')\nreturn cls(msgid, msgstr, origin, comment)... | <|body_start_0|>
self.origin = origin
self.comment = comment
self.msgid = msgid
self.msgstr = msgstr
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
msgid = dictionary.get('msgid')
msgstr = dictionary.get('msgstr')
origin = ... | Implementation of the 'Token Translation' model. TODO: type model description here. Attributes: origin (string): optional note of origin of token to be translated comment (string): optional comment for translators msgid (string): The token which will be translated msgstr (string): The locale's representation (translati... | TokenTranslation | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenTranslation:
"""Implementation of the 'Token Translation' model. TODO: type model description here. Attributes: origin (string): optional note of origin of token to be translated comment (string): optional comment for translators msgid (string): The token which will be translated msgstr (str... | stack_v2_sparse_classes_36k_train_014503 | 2,043 | permissive | [
{
"docstring": "Constructor for the TokenTranslation class",
"name": "__init__",
"signature": "def __init__(self, msgid=None, msgstr=None, origin=None, comment=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation... | 2 | stack_v2_sparse_classes_30k_train_016927 | Implement the Python class `TokenTranslation` described below.
Class description:
Implementation of the 'Token Translation' model. TODO: type model description here. Attributes: origin (string): optional note of origin of token to be translated comment (string): optional comment for translators msgid (string): The tok... | Implement the Python class `TokenTranslation` described below.
Class description:
Implementation of the 'Token Translation' model. TODO: type model description here. Attributes: origin (string): optional note of origin of token to be translated comment (string): optional comment for translators msgid (string): The tok... | 729e9391879e273545a4818558677b2e47261f08 | <|skeleton|>
class TokenTranslation:
"""Implementation of the 'Token Translation' model. TODO: type model description here. Attributes: origin (string): optional note of origin of token to be translated comment (string): optional comment for translators msgid (string): The token which will be translated msgstr (str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenTranslation:
"""Implementation of the 'Token Translation' model. TODO: type model description here. Attributes: origin (string): optional note of origin of token to be translated comment (string): optional comment for translators msgid (string): The token which will be translated msgstr (string): The loc... | the_stack_v2_python_sparse | sdk/python/v0.1-rc.4/opentelematicsapi/models/token_translation.py | nmfta-repo/nmfta-opentelematics-prototype | train | 2 |
ed1c7646e7c7881a3c1e54106d10b3a80bc28d18 | [
"sogouhao_search_consume = 0\ntry:\n for line in data:\n item = line[7].split(',')\n if len(item) >= 5:\n if item[5] == '108':\n sogouhao_search_consume += int(line[0])\nexcept IndexError as err:\n logging.error(err)\n sogouhao_search_consume = 0\nsogouhao_channel_co... | <|body_start_0|>
sogouhao_search_consume = 0
try:
for line in data:
item = line[7].split(',')
if len(item) >= 5:
if item[5] == '108':
sogouhao_search_consume += int(line[0])
except IndexError as err:
... | MonitorWSSogouHaoConsume | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonitorWSSogouHaoConsume:
def sogouhao_channel_search(cls, data):
"""搜狗号详情页消耗"""
<|body_0|>
def sogouhao_channel_back(cls, data):
"""搜狗号回流消耗"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sogouhao_search_consume = 0
try:
for lin... | stack_v2_sparse_classes_36k_train_014504 | 1,706 | no_license | [
{
"docstring": "搜狗号详情页消耗",
"name": "sogouhao_channel_search",
"signature": "def sogouhao_channel_search(cls, data)"
},
{
"docstring": "搜狗号回流消耗",
"name": "sogouhao_channel_back",
"signature": "def sogouhao_channel_back(cls, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010188 | Implement the Python class `MonitorWSSogouHaoConsume` described below.
Class description:
Implement the MonitorWSSogouHaoConsume class.
Method signatures and docstrings:
- def sogouhao_channel_search(cls, data): 搜狗号详情页消耗
- def sogouhao_channel_back(cls, data): 搜狗号回流消耗 | Implement the Python class `MonitorWSSogouHaoConsume` described below.
Class description:
Implement the MonitorWSSogouHaoConsume class.
Method signatures and docstrings:
- def sogouhao_channel_search(cls, data): 搜狗号详情页消耗
- def sogouhao_channel_back(cls, data): 搜狗号回流消耗
<|skeleton|>
class MonitorWSSogouHaoConsume:
... | a35ffc9fc869ac8cadb121c71daa0c977898f8d8 | <|skeleton|>
class MonitorWSSogouHaoConsume:
def sogouhao_channel_search(cls, data):
"""搜狗号详情页消耗"""
<|body_0|>
def sogouhao_channel_back(cls, data):
"""搜狗号回流消耗"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MonitorWSSogouHaoConsume:
def sogouhao_channel_search(cls, data):
"""搜狗号详情页消耗"""
sogouhao_search_consume = 0
try:
for line in data:
item = line[7].split(',')
if len(item) >= 5:
if item[5] == '108':
... | the_stack_v2_python_sparse | monitor_consume/monitor_consume_sogouhao.py | talentrobinho/prometheus_monitor_script | train | 0 | |
d811b972ce1779ca0045710083d210dedc0a61f8 | [
"self.check_xsrf_token(self.request_state)\ntry:\n tag_model.Tag.create(user_email=user.get_user_email(), name=request.tag.name, hidden=request.tag.hidden, color=request.tag.color, protect=request.tag.protect, description=request.tag.description)\nexcept datastore_errors.BadValueError as err:\n raise endpoint... | <|body_start_0|>
self.check_xsrf_token(self.request_state)
try:
tag_model.Tag.create(user_email=user.get_user_email(), name=request.tag.name, hidden=request.tag.hidden, color=request.tag.color, protect=request.tag.protect, description=request.tag.description)
except datastore_errors.... | This class is for the Tag API. | TagApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagApi:
"""This class is for the Tag API."""
def create(self, request):
"""Creates a new tag and inserts the instance into datastore."""
<|body_0|>
def destroy(self, request):
"""Destroys a tag and removes all references via _pre_delete_hook method."""
<|... | stack_v2_sparse_classes_36k_train_014505 | 5,591 | permissive | [
{
"docstring": "Creates a new tag and inserts the instance into datastore.",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Destroys a tag and removes all references via _pre_delete_hook method.",
"name": "destroy",
"signature": "def destroy(self, request)"... | 5 | stack_v2_sparse_classes_30k_train_020729 | Implement the Python class `TagApi` described below.
Class description:
This class is for the Tag API.
Method signatures and docstrings:
- def create(self, request): Creates a new tag and inserts the instance into datastore.
- def destroy(self, request): Destroys a tag and removes all references via _pre_delete_hook ... | Implement the Python class `TagApi` described below.
Class description:
This class is for the Tag API.
Method signatures and docstrings:
- def create(self, request): Creates a new tag and inserts the instance into datastore.
- def destroy(self, request): Destroys a tag and removes all references via _pre_delete_hook ... | 91753e47aff26d78978ebe7aca70f4a7cbf6a3d4 | <|skeleton|>
class TagApi:
"""This class is for the Tag API."""
def create(self, request):
"""Creates a new tag and inserts the instance into datastore."""
<|body_0|>
def destroy(self, request):
"""Destroys a tag and removes all references via _pre_delete_hook method."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TagApi:
"""This class is for the Tag API."""
def create(self, request):
"""Creates a new tag and inserts the instance into datastore."""
self.check_xsrf_token(self.request_state)
try:
tag_model.Tag.create(user_email=user.get_user_email(), name=request.tag.name, hidden=... | the_stack_v2_python_sparse | loaner/web_app/backend/api/tag_api.py | ryangugcloudca/loaner | train | 0 |
f022a1225df6737d780f37a9feb9fdbc0c4b3067 | [
"self.hass = hass\nself.api = api\nself.available = None",
"try:\n await self.hass.async_add_executor_job(self.api.auth)\nexcept BroadlinkException as err_msg:\n if self.available:\n self.available = False\n _LOGGER.warning('Disconnected from device at %s: %s', self.api.host[0], err_msg)\n ... | <|body_start_0|>
self.hass = hass
self.api = api
self.available = None
<|end_body_0|>
<|body_start_1|>
try:
await self.hass.async_add_executor_job(self.api.auth)
except BroadlinkException as err_msg:
if self.available:
self.available = Fal... | Manages a Broadlink device. | BroadlinkDevice | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BroadlinkDevice:
"""Manages a Broadlink device."""
def __init__(self, hass, api):
"""Initialize the device."""
<|body_0|>
async def async_connect(self):
"""Connect to the device."""
<|body_1|>
async def async_request(self, function, *args, **kwargs):... | stack_v2_sparse_classes_36k_train_014506 | 1,893 | permissive | [
{
"docstring": "Initialize the device.",
"name": "__init__",
"signature": "def __init__(self, hass, api)"
},
{
"docstring": "Connect to the device.",
"name": "async_connect",
"signature": "async def async_connect(self)"
},
{
"docstring": "Send a request to the device.",
"name... | 3 | null | Implement the Python class `BroadlinkDevice` described below.
Class description:
Manages a Broadlink device.
Method signatures and docstrings:
- def __init__(self, hass, api): Initialize the device.
- async def async_connect(self): Connect to the device.
- async def async_request(self, function, *args, **kwargs): Sen... | Implement the Python class `BroadlinkDevice` described below.
Class description:
Manages a Broadlink device.
Method signatures and docstrings:
- def __init__(self, hass, api): Initialize the device.
- async def async_connect(self): Connect to the device.
- async def async_request(self, function, *args, **kwargs): Sen... | ba55b4b8338a2dc0ba3f1d750efea49d86571291 | <|skeleton|>
class BroadlinkDevice:
"""Manages a Broadlink device."""
def __init__(self, hass, api):
"""Initialize the device."""
<|body_0|>
async def async_connect(self):
"""Connect to the device."""
<|body_1|>
async def async_request(self, function, *args, **kwargs):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BroadlinkDevice:
"""Manages a Broadlink device."""
def __init__(self, hass, api):
"""Initialize the device."""
self.hass = hass
self.api = api
self.available = None
async def async_connect(self):
"""Connect to the device."""
try:
await self... | the_stack_v2_python_sparse | homeassistant/components/broadlink/device.py | basnijholt/home-assistant | train | 5 |
8daee1e138557af68be00d3b7b47fb34b57bf654 | [
"analysis = Analysis.objects.get(id=analysis_id)\nwith transaction.atomic():\n property_view_ids = set(property_view_ids)\n property_views = PropertyView.objects.filter(id__in=property_view_ids, property__organization_id=analysis.organization_id)\n missing_property_views = property_view_ids - set(property_... | <|body_start_0|>
analysis = Analysis.objects.get(id=analysis_id)
with transaction.atomic():
property_view_ids = set(property_view_ids)
property_views = PropertyView.objects.filter(id__in=property_view_ids, property__organization_id=analysis.organization_id)
missing_pr... | The AnalysisPropertyView provides a "snapshot" of a property at the time an analysis was run. | AnalysisPropertyView | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalysisPropertyView:
"""The AnalysisPropertyView provides a "snapshot" of a property at the time an analysis was run."""
def batch_create(cls, analysis_id, property_view_ids):
"""Creates AnalysisPropertyViews from provided PropertyView IDs. The method returns a tuple, the first valu... | stack_v2_sparse_classes_36k_train_014507 | 5,119 | permissive | [
{
"docstring": "Creates AnalysisPropertyViews from provided PropertyView IDs. The method returns a tuple, the first value being a dictionary of the created AnalysisPropertyView IDs with the key as the original property_view_id, the second value being a list of BatchCreateErrors. Intended to be used when initial... | 2 | null | Implement the Python class `AnalysisPropertyView` described below.
Class description:
The AnalysisPropertyView provides a "snapshot" of a property at the time an analysis was run.
Method signatures and docstrings:
- def batch_create(cls, analysis_id, property_view_ids): Creates AnalysisPropertyViews from provided Pro... | Implement the Python class `AnalysisPropertyView` described below.
Class description:
The AnalysisPropertyView provides a "snapshot" of a property at the time an analysis was run.
Method signatures and docstrings:
- def batch_create(cls, analysis_id, property_view_ids): Creates AnalysisPropertyViews from provided Pro... | 680b6a2b45f3c568d779d8ac86553a0b08c384c8 | <|skeleton|>
class AnalysisPropertyView:
"""The AnalysisPropertyView provides a "snapshot" of a property at the time an analysis was run."""
def batch_create(cls, analysis_id, property_view_ids):
"""Creates AnalysisPropertyViews from provided PropertyView IDs. The method returns a tuple, the first valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnalysisPropertyView:
"""The AnalysisPropertyView provides a "snapshot" of a property at the time an analysis was run."""
def batch_create(cls, analysis_id, property_view_ids):
"""Creates AnalysisPropertyViews from provided PropertyView IDs. The method returns a tuple, the first value being a dic... | the_stack_v2_python_sparse | seed/models/analysis_property_views.py | SEED-platform/seed | train | 108 |
05ebbe5386164cad10948bb5ee01963dd33e2d17 | [
"tree_viewer = ResourceTreeViewer(parent=parent, input=self.workspace, selection_mode='single', show_root=False)\ntree_viewer.on_trait_change(self.on_selection_change, 'selection')\nreturn tree_viewer.control",
"if selections:\n selection = selections[0]\n if isinstance(selection, File):\n self.resou... | <|body_start_0|>
tree_viewer = ResourceTreeViewer(parent=parent, input=self.workspace, selection_mode='single', show_root=False)
tree_viewer.on_trait_change(self.on_selection_change, 'selection')
return tree_viewer.control
<|end_body_0|>
<|body_start_1|>
if selections:
selec... | Wizard page for resource selection. | ResourceSelectionPage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceSelectionPage:
"""Wizard page for resource selection."""
def create_page(self, parent):
"""Create the wizard page."""
<|body_0|>
def on_selection_change(self, selections):
"""Handles the tree viewer selections changing."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_014508 | 3,949 | permissive | [
{
"docstring": "Create the wizard page.",
"name": "create_page",
"signature": "def create_page(self, parent)"
},
{
"docstring": "Handles the tree viewer selections changing.",
"name": "on_selection_change",
"signature": "def on_selection_change(self, selections)"
}
] | 2 | null | Implement the Python class `ResourceSelectionPage` described below.
Class description:
Wizard page for resource selection.
Method signatures and docstrings:
- def create_page(self, parent): Create the wizard page.
- def on_selection_change(self, selections): Handles the tree viewer selections changing. | Implement the Python class `ResourceSelectionPage` described below.
Class description:
Wizard page for resource selection.
Method signatures and docstrings:
- def create_page(self, parent): Create the wizard page.
- def on_selection_change(self, selections): Handles the tree viewer selections changing.
<|skeleton|>
... | e8fc0b2d6b9b08e60389fc4714a5cf51f628b57f | <|skeleton|>
class ResourceSelectionPage:
"""Wizard page for resource selection."""
def create_page(self, parent):
"""Create the wizard page."""
<|body_0|>
def on_selection_change(self, selections):
"""Handles the tree viewer selections changing."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourceSelectionPage:
"""Wizard page for resource selection."""
def create_page(self, parent):
"""Create the wizard page."""
tree_viewer = ResourceTreeViewer(parent=parent, input=self.workspace, selection_mode='single', show_root=False)
tree_viewer.on_trait_change(self.on_selecti... | the_stack_v2_python_sparse | puddle/resource/wizard/resource_selection_page.py | rwl/puddle | train | 2 |
091d467cbc590c19ad42040d990747e9a34303eb | [
"self.screen_width = int(GetSystemMetrics(0) / 1.5)\nself.screen_height = int(GetSystemMetrics(1) / 1.5)\nself.bg_color = (230, 230, 230)\nself.ship_limit = 3\nself.bullet_width = 3\nself.bullet_height = 20\nself.ship_bullets_allowed = 5\nself.ship_bullet_color = (0, 0, 255)\nself.alien_bullet_color = (255, 0, 0)\n... | <|body_start_0|>
self.screen_width = int(GetSystemMetrics(0) / 1.5)
self.screen_height = int(GetSystemMetrics(1) / 1.5)
self.bg_color = (230, 230, 230)
self.ship_limit = 3
self.bullet_width = 3
self.bullet_height = 20
self.ship_bullets_allowed = 5
self.shi... | Stores all settings for Alien Invaders | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""Stores all settings for Alien Invaders"""
def __init__(self):
"""Initialize the games static settings"""
<|body_0|>
def initialize_dynamic_settings(self):
"""Initialize settings that change throughout the game"""
<|body_1|>
def increase_... | stack_v2_sparse_classes_36k_train_014509 | 1,990 | no_license | [
{
"docstring": "Initialize the games static settings",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Initialize settings that change throughout the game",
"name": "initialize_dynamic_settings",
"signature": "def initialize_dynamic_settings(self)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_006191 | Implement the Python class `Settings` described below.
Class description:
Stores all settings for Alien Invaders
Method signatures and docstrings:
- def __init__(self): Initialize the games static settings
- def initialize_dynamic_settings(self): Initialize settings that change throughout the game
- def increase_spee... | Implement the Python class `Settings` described below.
Class description:
Stores all settings for Alien Invaders
Method signatures and docstrings:
- def __init__(self): Initialize the games static settings
- def initialize_dynamic_settings(self): Initialize settings that change throughout the game
- def increase_spee... | f2cad90ba7f43485944e981612c74ebaf124d7eb | <|skeleton|>
class Settings:
"""Stores all settings for Alien Invaders"""
def __init__(self):
"""Initialize the games static settings"""
<|body_0|>
def initialize_dynamic_settings(self):
"""Initialize settings that change throughout the game"""
<|body_1|>
def increase_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Settings:
"""Stores all settings for Alien Invaders"""
def __init__(self):
"""Initialize the games static settings"""
self.screen_width = int(GetSystemMetrics(0) / 1.5)
self.screen_height = int(GetSystemMetrics(1) / 1.5)
self.bg_color = (230, 230, 230)
self.ship_li... | the_stack_v2_python_sparse | Space Invaders/settings.py | mattizatt140/Python | train | 0 |
627923ca1ac3413fff27cb3a8265d6c8440509f4 | [
"if not (segment := track.get_segment(track.sequences[-2])):\n return ''\nbandwidth = round((len(segment.init) + sum((len(part.data) for part in segment.parts))) * 8 / segment.duration * 1.2)\ncodecs = get_codec_string(segment.init)\nlines = ['#EXTM3U', f'#EXT-X-STREAM-INF:BANDWIDTH={bandwidth},CODECS=\"{codecs}... | <|body_start_0|>
if not (segment := track.get_segment(track.sequences[-2])):
return ''
bandwidth = round((len(segment.init) + sum((len(part.data) for part in segment.parts))) * 8 / segment.duration * 1.2)
codecs = get_codec_string(segment.init)
lines = ['#EXTM3U', f'#EXT-X-ST... | Stream view used only for Chromecast compatibility. | HlsMasterPlaylistView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HlsMasterPlaylistView:
"""Stream view used only for Chromecast compatibility."""
def render(track: StreamOutput) -> str:
"""Render M3U8 file."""
<|body_0|>
async def handle(self, request: web.Request, stream: Stream, sequence: str) -> web.Response:
"""Return m3u8... | stack_v2_sparse_classes_36k_train_014510 | 7,890 | permissive | [
{
"docstring": "Render M3U8 file.",
"name": "render",
"signature": "def render(track: StreamOutput) -> str"
},
{
"docstring": "Return m3u8 playlist.",
"name": "handle",
"signature": "async def handle(self, request: web.Request, stream: Stream, sequence: str) -> web.Response"
}
] | 2 | null | Implement the Python class `HlsMasterPlaylistView` described below.
Class description:
Stream view used only for Chromecast compatibility.
Method signatures and docstrings:
- def render(track: StreamOutput) -> str: Render M3U8 file.
- async def handle(self, request: web.Request, stream: Stream, sequence: str) -> web.... | Implement the Python class `HlsMasterPlaylistView` described below.
Class description:
Stream view used only for Chromecast compatibility.
Method signatures and docstrings:
- def render(track: StreamOutput) -> str: Render M3U8 file.
- async def handle(self, request: web.Request, stream: Stream, sequence: str) -> web.... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class HlsMasterPlaylistView:
"""Stream view used only for Chromecast compatibility."""
def render(track: StreamOutput) -> str:
"""Render M3U8 file."""
<|body_0|>
async def handle(self, request: web.Request, stream: Stream, sequence: str) -> web.Response:
"""Return m3u8... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HlsMasterPlaylistView:
"""Stream view used only for Chromecast compatibility."""
def render(track: StreamOutput) -> str:
"""Render M3U8 file."""
if not (segment := track.get_segment(track.sequences[-2])):
return ''
bandwidth = round((len(segment.init) + sum((len(part.d... | the_stack_v2_python_sparse | homeassistant/components/stream/hls.py | BenWoodford/home-assistant | train | 11 |
3c1d8af7ab082c2143946c618c25bd9a1fe9bc1a | [
"if not hasattr(self, '_zeval'):\n if self._args['evaluate_mc_at_zlens']:\n self._zeval = self.z\n else:\n self._zeval = self.z_infall\nreturn self._zeval",
"if not hasattr(self, '_params_physical'):\n [concentration, rt] = self.profile_args\n rhos, rs, r200 = self._lens_cosmo.NFW_params... | <|body_start_0|>
if not hasattr(self, '_zeval'):
if self._args['evaluate_mc_at_zlens']:
self._zeval = self.z
else:
self._zeval = self.z_infall
return self._zeval
<|end_body_0|>
<|body_start_1|>
if not hasattr(self, '_params_physical'):
... | Defines a truncated NFW halo that is a subhalo of the host dark matter halo | TNFWSubhalo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TNFWSubhalo:
"""Defines a truncated NFW halo that is a subhalo of the host dark matter halo"""
def z_eval(self):
"""Returns the redshift at which to evalate the concentration-mass relation"""
<|body_0|>
def params_physical(self):
"""See documentation in base clas... | stack_v2_sparse_classes_36k_train_014511 | 5,061 | permissive | [
{
"docstring": "Returns the redshift at which to evalate the concentration-mass relation",
"name": "z_eval",
"signature": "def z_eval(self)"
},
{
"docstring": "See documentation in base class (Halos/halo_base.py)",
"name": "params_physical",
"signature": "def params_physical(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_009076 | Implement the Python class `TNFWSubhalo` described below.
Class description:
Defines a truncated NFW halo that is a subhalo of the host dark matter halo
Method signatures and docstrings:
- def z_eval(self): Returns the redshift at which to evalate the concentration-mass relation
- def params_physical(self): See docum... | Implement the Python class `TNFWSubhalo` described below.
Class description:
Defines a truncated NFW halo that is a subhalo of the host dark matter halo
Method signatures and docstrings:
- def z_eval(self): Returns the redshift at which to evalate the concentration-mass relation
- def params_physical(self): See docum... | aac61ed4dd6bb9df1f8295760c6ec5f6099f8983 | <|skeleton|>
class TNFWSubhalo:
"""Defines a truncated NFW halo that is a subhalo of the host dark matter halo"""
def z_eval(self):
"""Returns the redshift at which to evalate the concentration-mass relation"""
<|body_0|>
def params_physical(self):
"""See documentation in base clas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TNFWSubhalo:
"""Defines a truncated NFW halo that is a subhalo of the host dark matter halo"""
def z_eval(self):
"""Returns the redshift at which to evalate the concentration-mass relation"""
if not hasattr(self, '_zeval'):
if self._args['evaluate_mc_at_zlens']:
... | the_stack_v2_python_sparse | pyHalo/Halos/HaloModels/TNFW.py | alexandres-lazar/pyHalo | train | 0 |
b0057acdc0e2755c710d7497fef4414b7a2a71dd | [
"self.svc_name = svc_name\nself.set_name = set_name\nself.min = int(min)\nself.max = int(max)\nself.isContinuous = True\nself.vals = None",
"self.isContinuous = False\nself.vals = [int(val) for val in vals]\nself.min = min(self.vals)\nself.max = max(self.vals)"
] | <|body_start_0|>
self.svc_name = svc_name
self.set_name = set_name
self.min = int(min)
self.max = int(max)
self.isContinuous = True
self.vals = None
<|end_body_0|>
<|body_start_1|>
self.isContinuous = False
self.vals = [int(val) for val in vals]
s... | a knob setting with max and min settings. It's the smallest unit for RAPID-C | Knob | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Knob:
"""a knob setting with max and min settings. It's the smallest unit for RAPID-C"""
def __init__(self, svc_name, set_name, min, max):
"""Initialization :param svc_name: name of service :param set_name: name of setting :param min: lower bound :param max: upper bound"""
<|... | stack_v2_sparse_classes_36k_train_014512 | 5,554 | no_license | [
{
"docstring": "Initialization :param svc_name: name of service :param set_name: name of setting :param min: lower bound :param max: upper bound",
"name": "__init__",
"signature": "def __init__(self, svc_name, set_name, min, max)"
},
{
"docstring": "Trasform to a knob with vals (discrete)",
... | 2 | stack_v2_sparse_classes_30k_train_004820 | Implement the Python class `Knob` described below.
Class description:
a knob setting with max and min settings. It's the smallest unit for RAPID-C
Method signatures and docstrings:
- def __init__(self, svc_name, set_name, min, max): Initialization :param svc_name: name of service :param set_name: name of setting :par... | Implement the Python class `Knob` described below.
Class description:
a knob setting with max and min settings. It's the smallest unit for RAPID-C
Method signatures and docstrings:
- def __init__(self, svc_name, set_name, min, max): Initialization :param svc_name: name of service :param set_name: name of setting :par... | 63b50cc32c6f647ea34b5512f48688149f949a3c | <|skeleton|>
class Knob:
"""a knob setting with max and min settings. It's the smallest unit for RAPID-C"""
def __init__(self, svc_name, set_name, min, max):
"""Initialization :param svc_name: name of service :param set_name: name of setting :param min: lower bound :param max: upper bound"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Knob:
"""a knob setting with max and min settings. It's the smallest unit for RAPID-C"""
def __init__(self, svc_name, set_name, min, max):
"""Initialization :param svc_name: name of service :param set_name: name of setting :param min: lower bound :param max: upper bound"""
self.svc_name =... | the_stack_v2_python_sparse | modelConstr/Rapids/Rapids_Classes/KDG.py | niuye8911/rapidlib-linux | train | 0 |
6d5e5b48cccb9100dc784e0cc4e0b4d1a6b2ecb9 | [
"other_photos = self.photograph.get_close_matches()\nif bool(other_photos):\n new_photo_tags = [PhotographTag(photograph=p, tag=self.tag, last_updated=timezone.now(), user_last_modified=self.user_last_modified) for p in other_photos]\n PhotographTag.objects.bulk_create(new_photo_tags, ignore_conflicts=True)\n... | <|body_start_0|>
other_photos = self.photograph.get_close_matches()
if bool(other_photos):
new_photo_tags = [PhotographTag(photograph=p, tag=self.tag, last_updated=timezone.now(), user_last_modified=self.user_last_modified) for p in other_photos]
PhotographTag.objects.bulk_create... | This through model will be the authoritative photograph/tag relationship through table, which allows tags to be added both through the dedicated TaggingTask/TaggingDecision workflows, as well as with arbitrary POST commands as needed. | PhotographTag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhotographTag:
"""This through model will be the authoritative photograph/tag relationship through table, which allows tags to be added both through the dedicated TaggingTask/TaggingDecision workflows, as well as with arbitrary POST commands as needed."""
def save(self, *args, **kwargs):
... | stack_v2_sparse_classes_36k_train_014513 | 6,107 | permissive | [
{
"docstring": "Any photos in a close match set with this one also get tagged",
"name": "save",
"signature": "def save(self, *args, **kwargs)"
},
{
"docstring": "Any photos in a close match set with this one also get untagged",
"name": "delete",
"signature": "def delete(self, *args, **kw... | 2 | null | Implement the Python class `PhotographTag` described below.
Class description:
This through model will be the authoritative photograph/tag relationship through table, which allows tags to be added both through the dedicated TaggingTask/TaggingDecision workflows, as well as with arbitrary POST commands as needed.
Meth... | Implement the Python class `PhotographTag` described below.
Class description:
This through model will be the authoritative photograph/tag relationship through table, which allows tags to be added both through the dedicated TaggingTask/TaggingDecision workflows, as well as with arbitrary POST commands as needed.
Meth... | c2c4bfbf2d5932dde1dde985d7b5c8786b9f2ab2 | <|skeleton|>
class PhotographTag:
"""This through model will be the authoritative photograph/tag relationship through table, which allows tags to be added both through the dedicated TaggingTask/TaggingDecision workflows, as well as with arbitrary POST commands as needed."""
def save(self, *args, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhotographTag:
"""This through model will be the authoritative photograph/tag relationship through table, which allows tags to be added both through the dedicated TaggingTask/TaggingDecision workflows, as well as with arbitrary POST commands as needed."""
def save(self, *args, **kwargs):
"""Any p... | the_stack_v2_python_sparse | rest/tagging/models.py | cmu-lib/campi | train | 13 |
e49f8b4b8a42f4d2a1848cb35511a9bf07a6f80a | [
"user_id = info.user_id\ndata = format_result(InfoAuthorize().query_auth_info(user_id))\nif data:\n data = [{k: '/aibus/' + v if k == 'take_photo' else v for k, v in auth.items()} for auth in data]\nreturn (ResponseCode.SUCCEED, '执行成功', data)",
"user_id = info.user_id\nauth_id = param.get('id')\ncreate_dt = da... | <|body_start_0|>
user_id = info.user_id
data = format_result(InfoAuthorize().query_auth_info(user_id))
if data:
data = [{k: '/aibus/' + v if k == 'take_photo' else v for k, v in auth.items()} for auth in data]
return (ResponseCode.SUCCEED, '执行成功', data)
<|end_body_0|>
<|body... | PickUpPersionService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PickUpPersionService:
def get_pick_up_persion(self, info):
"""获取授权人列表"""
<|body_0|>
def drop_pick_up_persion(self, info, param):
"""删除授权人"""
<|body_1|>
def add_pick_up_persion(self, info, param, auth_photo):
"""增加授权人"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_36k_train_014514 | 3,663 | no_license | [
{
"docstring": "获取授权人列表",
"name": "get_pick_up_persion",
"signature": "def get_pick_up_persion(self, info)"
},
{
"docstring": "删除授权人",
"name": "drop_pick_up_persion",
"signature": "def drop_pick_up_persion(self, info, param)"
},
{
"docstring": "增加授权人",
"name": "add_pick_up_pe... | 3 | stack_v2_sparse_classes_30k_train_008982 | Implement the Python class `PickUpPersionService` described below.
Class description:
Implement the PickUpPersionService class.
Method signatures and docstrings:
- def get_pick_up_persion(self, info): 获取授权人列表
- def drop_pick_up_persion(self, info, param): 删除授权人
- def add_pick_up_persion(self, info, param, auth_photo)... | Implement the Python class `PickUpPersionService` described below.
Class description:
Implement the PickUpPersionService class.
Method signatures and docstrings:
- def get_pick_up_persion(self, info): 获取授权人列表
- def drop_pick_up_persion(self, info, param): 删除授权人
- def add_pick_up_persion(self, info, param, auth_photo)... | a7cf5a0b6daa372ed860dc43d92c55fcde764eb9 | <|skeleton|>
class PickUpPersionService:
def get_pick_up_persion(self, info):
"""获取授权人列表"""
<|body_0|>
def drop_pick_up_persion(self, info, param):
"""删除授权人"""
<|body_1|>
def add_pick_up_persion(self, info, param, auth_photo):
"""增加授权人"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PickUpPersionService:
def get_pick_up_persion(self, info):
"""获取授权人列表"""
user_id = info.user_id
data = format_result(InfoAuthorize().query_auth_info(user_id))
if data:
data = [{k: '/aibus/' + v if k == 'take_photo' else v for k, v in auth.items()} for auth in data]
... | the_stack_v2_python_sparse | python_project/smart_schoolBus_project/app/sys/pick_up_persion/service.py | malqch/aibus | train | 0 | |
e7fa8588e965d12053a3dafa304b15c627cf58de | [
"if not head or not head.next:\n return head\np1 = head\np2 = head.next\ntemp = p2.next\np2.next = p1\np1.next = self.swapPairs_rec(temp)\nreturn p2",
"if not head:\n return None\nhead1 = head\nhead2 = head.next\nresult = head2\nwhile head1 and head2:\n head1.next = head2.next\n head2.next = head1\n ... | <|body_start_0|>
if not head or not head.next:
return head
p1 = head
p2 = head.next
temp = p2.next
p2.next = p1
p1.next = self.swapPairs_rec(temp)
return p2
<|end_body_0|>
<|body_start_1|>
if not head:
return None
head1 = h... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs_rec(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or not head.next:
... | stack_v2_sparse_classes_36k_train_014515 | 1,165 | permissive | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs_rec",
"signature": "def swapPairs_rec(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs",
"signature": "def swapPairs(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs_rec(self, head): :type head: ListNode :rtype: ListNode
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs_rec(self, head): :type head: ListNode :rtype: ListNode
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def swa... | 1ed22267156fb968671731c2e983b0e65f670750 | <|skeleton|>
class Solution:
def swapPairs_rec(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def swapPairs_rec(self, head):
""":type head: ListNode :rtype: ListNode"""
if not head or not head.next:
return head
p1 = head
p2 = head.next
temp = p2.next
p2.next = p1
p1.next = self.swapPairs_rec(temp)
return p2
def ... | the_stack_v2_python_sparse | leetcode/24.py | pingrunhuang/CodeChallenge | train | 0 | |
faf1accc4d8e99f5bfdb3715c761518e7bf244ea | [
"super(OverlayFrame, self).__init__(parent)\nself.setVisible(False)\nself.setAcceptDrops(True)",
"roundness = 10\nrect = self.rect()\nbgcolor = self.palette().color(QPalette.Background)\nalpha_bgcolor = QColor(50, 50, 50, 150)\npainter = QPainter()\npainter.begin(self)\npainter.save()\npainter.setRenderHint(QPain... | <|body_start_0|>
super(OverlayFrame, self).__init__(parent)
self.setVisible(False)
self.setAcceptDrops(True)
<|end_body_0|>
<|body_start_1|>
roundness = 10
rect = self.rect()
bgcolor = self.palette().color(QPalette.Background)
alpha_bgcolor = QColor(50, 50, 50, 1... | Creates a rounded rectangular translucent frame and accepts drops. | OverlayFrame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OverlayFrame:
"""Creates a rounded rectangular translucent frame and accepts drops."""
def __init__(self, parent):
"""Construct an OverlayFrame with the given Qt GUI parent."""
<|body_0|>
def paintEvent(self, event):
"""Display a translucent rounded rectangle."""... | stack_v2_sparse_classes_36k_train_014516 | 30,088 | no_license | [
{
"docstring": "Construct an OverlayFrame with the given Qt GUI parent.",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Display a translucent rounded rectangle.",
"name": "paintEvent",
"signature": "def paintEvent(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007043 | Implement the Python class `OverlayFrame` described below.
Class description:
Creates a rounded rectangular translucent frame and accepts drops.
Method signatures and docstrings:
- def __init__(self, parent): Construct an OverlayFrame with the given Qt GUI parent.
- def paintEvent(self, event): Display a translucent ... | Implement the Python class `OverlayFrame` described below.
Class description:
Creates a rounded rectangular translucent frame and accepts drops.
Method signatures and docstrings:
- def __init__(self, parent): Construct an OverlayFrame with the given Qt GUI parent.
- def paintEvent(self, event): Display a translucent ... | afa9c9547716909d806a0bd8165bfe896617ca7e | <|skeleton|>
class OverlayFrame:
"""Creates a rounded rectangular translucent frame and accepts drops."""
def __init__(self, parent):
"""Construct an OverlayFrame with the given Qt GUI parent."""
<|body_0|>
def paintEvent(self, event):
"""Display a translucent rounded rectangle."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OverlayFrame:
"""Creates a rounded rectangular translucent frame and accepts drops."""
def __init__(self, parent):
"""Construct an OverlayFrame with the given Qt GUI parent."""
super(OverlayFrame, self).__init__(parent)
self.setVisible(False)
self.setAcceptDrops(True)
... | the_stack_v2_python_sparse | boxfish/ModuleFrame.py | LLNL/boxfish | train | 4 |
c527450d8a2dbff05a637bdab37a6a4f0d5d819a | [
"super().__init__(coordinator, config)\nself.alert = alert\nself._attr_unique_id = f\"{config.entry_id}_{alert.replace(' ', '_')}\"\nself._attr_name = alert",
"for alert in self._client.alerts:\n if alert['name'] == self.alert:\n return alert['active']\nreturn None"
] | <|body_start_0|>
super().__init__(coordinator, config)
self.alert = alert
self._attr_unique_id = f"{config.entry_id}_{alert.replace(' ', '_')}"
self._attr_name = alert
<|end_body_0|>
<|body_start_1|>
for alert in self._client.alerts:
if alert['name'] == self.alert:
... | Represent a Venstar alert. | VenstarBinarySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VenstarBinarySensor:
"""Represent a Venstar alert."""
def __init__(self, coordinator, config, alert):
"""Initialize the alert."""
<|body_0|>
def is_on(self):
"""Return true if the binary sensor is on."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_014517 | 1,524 | permissive | [
{
"docstring": "Initialize the alert.",
"name": "__init__",
"signature": "def __init__(self, coordinator, config, alert)"
},
{
"docstring": "Return true if the binary sensor is on.",
"name": "is_on",
"signature": "def is_on(self)"
}
] | 2 | null | Implement the Python class `VenstarBinarySensor` described below.
Class description:
Represent a Venstar alert.
Method signatures and docstrings:
- def __init__(self, coordinator, config, alert): Initialize the alert.
- def is_on(self): Return true if the binary sensor is on. | Implement the Python class `VenstarBinarySensor` described below.
Class description:
Represent a Venstar alert.
Method signatures and docstrings:
- def __init__(self, coordinator, config, alert): Initialize the alert.
- def is_on(self): Return true if the binary sensor is on.
<|skeleton|>
class VenstarBinarySensor:
... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class VenstarBinarySensor:
"""Represent a Venstar alert."""
def __init__(self, coordinator, config, alert):
"""Initialize the alert."""
<|body_0|>
def is_on(self):
"""Return true if the binary sensor is on."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VenstarBinarySensor:
"""Represent a Venstar alert."""
def __init__(self, coordinator, config, alert):
"""Initialize the alert."""
super().__init__(coordinator, config)
self.alert = alert
self._attr_unique_id = f"{config.entry_id}_{alert.replace(' ', '_')}"
self._at... | the_stack_v2_python_sparse | homeassistant/components/venstar/binary_sensor.py | home-assistant/core | train | 35,501 |
420606abc10635d5a87b2b1bacb2bd19134ceb6b | [
"super().__init__()\nself._log_std_min = log_std_min\nself._log_std_max = log_std_max\nn1 = hidden_sizes['actor'][0]\nn2 = hidden_sizes['actor'][1]\nnet_0 = nn.Sequential(nn.Linear(obs_dim, n1), nn.ReLU())\nnet_1 = nn.Sequential(nn.Linear(n1, n2), nn.ReLU())\nself.net = nn.Sequential(net_0, net_1)\nself.mu_layer = ... | <|body_start_0|>
super().__init__()
self._log_std_min = log_std_min
self._log_std_max = log_std_max
n1 = hidden_sizes['actor'][0]
n2 = hidden_sizes['actor'][1]
net_0 = nn.Sequential(nn.Linear(obs_dim, n1), nn.ReLU())
net_1 = nn.Sequential(nn.Linear(n1, n2), nn.ReL... | The squashed gaussian actor network. Attributes: net (torch.nn.modules.container.Sequential): The input/hidden layers of the network. mu (torch.nn.modules.linear.Linear): The output layer which returns the mean of the actions. log_std_layer (torch.nn.modules.linear.Linear): The output layer which returns the log standa... | SquashedGaussianMLPActor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SquashedGaussianMLPActor:
"""The squashed gaussian actor network. Attributes: net (torch.nn.modules.container.Sequential): The input/hidden layers of the network. mu (torch.nn.modules.linear.Linear): The output layer which returns the mean of the actions. log_std_layer (torch.nn.modules.linear.Li... | stack_v2_sparse_classes_36k_train_014518 | 6,224 | no_license | [
{
"docstring": "Constructs all the necessary attributes for the Squashed Gaussian Actor object. Args: obs_dim (int): Dimension of the observation space. act_dim (int): Dimension of the action space. hidden_sizes (list): Sizes of the hidden layers. log_std_min (int, optional): The minimum log standard deviation.... | 2 | stack_v2_sparse_classes_30k_train_012455 | Implement the Python class `SquashedGaussianMLPActor` described below.
Class description:
The squashed gaussian actor network. Attributes: net (torch.nn.modules.container.Sequential): The input/hidden layers of the network. mu (torch.nn.modules.linear.Linear): The output layer which returns the mean of the actions. lo... | Implement the Python class `SquashedGaussianMLPActor` described below.
Class description:
The squashed gaussian actor network. Attributes: net (torch.nn.modules.container.Sequential): The input/hidden layers of the network. mu (torch.nn.modules.linear.Linear): The output layer which returns the mean of the actions. lo... | be30a3505e6abd9de74a88bc39456fa7e985f16f | <|skeleton|>
class SquashedGaussianMLPActor:
"""The squashed gaussian actor network. Attributes: net (torch.nn.modules.container.Sequential): The input/hidden layers of the network. mu (torch.nn.modules.linear.Linear): The output layer which returns the mean of the actions. log_std_layer (torch.nn.modules.linear.Li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SquashedGaussianMLPActor:
"""The squashed gaussian actor network. Attributes: net (torch.nn.modules.container.Sequential): The input/hidden layers of the network. mu (torch.nn.modules.linear.Linear): The output layer which returns the mean of the actions. log_std_layer (torch.nn.modules.linear.Linear): The ou... | the_stack_v2_python_sparse | LAC/pytorch_a.py | rickstaa/tf2-eager-vs-graph-grad-problem | train | 0 |
6b2a29f5ab7864e5e7739ca549e07087601edf21 | [
"n = len(graph)\ndfs_trace = []\nself.last = [None] * n\nto_visit = [(0, 0, None)]\nsucc = [0] * n\nwhile to_visit:\n level, node, father = to_visit[-1]\n self.last[node] = len(dfs_trace)\n dfs_trace.append((level, node))\n if succ[node] < len(graph[node]) and graph[node][succ[node]] == father:\n ... | <|body_start_0|>
n = len(graph)
dfs_trace = []
self.last = [None] * n
to_visit = [(0, 0, None)]
succ = [0] * n
while to_visit:
level, node, father = to_visit[-1]
self.last[node] = len(dfs_trace)
dfs_trace.append((level, node))
... | Lowest common ancestor data structure using a reduction to range minimum query | LowestCommonAncestorRMQ | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LowestCommonAncestorRMQ:
"""Lowest common ancestor data structure using a reduction to range minimum query"""
def __init__(self, graph):
"""builds the structure from a given tree :param graph: adjacency matrix of a tree :complexity: O(n log n), with n = len(graph)"""
<|body_0... | stack_v2_sparse_classes_36k_train_014519 | 3,713 | permissive | [
{
"docstring": "builds the structure from a given tree :param graph: adjacency matrix of a tree :complexity: O(n log n), with n = len(graph)",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": ":returns: the lowest common ancestor of u and v :complexity: O(log n)",
... | 2 | null | Implement the Python class `LowestCommonAncestorRMQ` described below.
Class description:
Lowest common ancestor data structure using a reduction to range minimum query
Method signatures and docstrings:
- def __init__(self, graph): builds the structure from a given tree :param graph: adjacency matrix of a tree :comple... | Implement the Python class `LowestCommonAncestorRMQ` described below.
Class description:
Lowest common ancestor data structure using a reduction to range minimum query
Method signatures and docstrings:
- def __init__(self, graph): builds the structure from a given tree :param graph: adjacency matrix of a tree :comple... | 634645707ebf2489356009a6f91f012b55b1ee39 | <|skeleton|>
class LowestCommonAncestorRMQ:
"""Lowest common ancestor data structure using a reduction to range minimum query"""
def __init__(self, graph):
"""builds the structure from a given tree :param graph: adjacency matrix of a tree :complexity: O(n log n), with n = len(graph)"""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LowestCommonAncestorRMQ:
"""Lowest common ancestor data structure using a reduction to range minimum query"""
def __init__(self, graph):
"""builds the structure from a given tree :param graph: adjacency matrix of a tree :complexity: O(n log n), with n = len(graph)"""
n = len(graph)
... | the_stack_v2_python_sparse | tryalgo/lowest_common_ancestor.py | jilljenn/tryalgo | train | 390 |
94bbc1267cb51ddbed5c530d554d05ac03de21cd | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | OuAppServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OuAppServiceServicer:
"""Missing associated documentation comment in .proto file."""
def ou_by_name(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def ou_by_id(self, request, context):
"""Missing associated docu... | stack_v2_sparse_classes_36k_train_014520 | 7,781 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "ou_by_name",
"signature": "def ou_by_name(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "ou_by_id",
"signature": "def ou_by_id(self, reques... | 4 | stack_v2_sparse_classes_30k_train_012664 | Implement the Python class `OuAppServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def ou_by_name(self, request, context): Missing associated documentation comment in .proto file.
- def ou_by_id(self, request, context): Mi... | Implement the Python class `OuAppServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def ou_by_name(self, request, context): Missing associated documentation comment in .proto file.
- def ou_by_id(self, request, context): Mi... | 55d36c068e26e13ee5bae5c033e2e17784c63feb | <|skeleton|>
class OuAppServiceServicer:
"""Missing associated documentation comment in .proto file."""
def ou_by_name(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def ou_by_id(self, request, context):
"""Missing associated docu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OuAppServiceServicer:
"""Missing associated documentation comment in .proto file."""
def ou_by_name(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!'... | the_stack_v2_python_sparse | src/resource/proto/_generated/identity/ou_app_service_pb2_grpc.py | arkanmgerges/cafm.identity | train | 0 |
022fb2f9a7f0f5aa9375428969e7cfdd0f387277 | [
"node = head\nwhile n and node:\n node = node.next\n n -= 1\nif n:\n return head\npp = None\np = head\nwhile node:\n node = node.next\n pp = p\n p = p.next\nif not pp:\n return p.next\npp.next = p.next\nreturn head",
"def length(node: ListNode):\n l = 0\n while node:\n l += 1\n ... | <|body_start_0|>
node = head
while n and node:
node = node.next
n -= 1
if n:
return head
pp = None
p = head
while node:
node = node.next
pp = p
p = p.next
if not pp:
return p.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""One pass using two pointers Time complexity: O(n) Space complexity: O(1)"""
<|body_0|>
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
"""10/16/2022 16:33... | stack_v2_sparse_classes_36k_train_014521 | 2,249 | no_license | [
{
"docstring": "One pass using two pointers Time complexity: O(n) Space complexity: O(1)",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode"
},
{
"docstring": "10/16/2022 16:33",
"name": "removeNthFromEnd",
"signature": "def removeN... | 2 | stack_v2_sparse_classes_30k_train_006017 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: One pass using two pointers Time complexity: O(n) Space complexity: O(1)
- def removeNthFromEnd(self, head: Option... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: One pass using two pointers Time complexity: O(n) Space complexity: O(1)
- def removeNthFromEnd(self, head: Option... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""One pass using two pointers Time complexity: O(n) Space complexity: O(1)"""
<|body_0|>
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
"""10/16/2022 16:33... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""One pass using two pointers Time complexity: O(n) Space complexity: O(1)"""
node = head
while n and node:
node = node.next
n -= 1
if n:
return head
pp = None... | the_stack_v2_python_sparse | leetcode/solved/19_Remove_nth_Node_From_End_of_List/solution.py | sungminoh/algorithms | train | 0 | |
f8c0799c5f0103e065b108b545a5e9e0e43afcd9 | [
"stations = []\ndata = requests.get('http://tunein.com/search/?query={0!s}'.format(quote(query)), headers=self.headers)\nsoup = BeautifulSoup(''.join(data.text), 'html.parser')\nfor element in soup.find_all(lambda tag: tag.name == 'a' and 'profile-link' in tag.get('class', []) and ('/radio/' in tag.get('href', ''))... | <|body_start_0|>
stations = []
data = requests.get('http://tunein.com/search/?query={0!s}'.format(quote(query)), headers=self.headers)
soup = BeautifulSoup(''.join(data.text), 'html.parser')
for element in soup.find_all(lambda tag: tag.name == 'a' and 'profile-link' in tag.get('class', [... | TuneIn client TODO: Move out requestor to voiceplay.utils | TuneInClient | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TuneInClient:
"""TuneIn client TODO: Move out requestor to voiceplay.utils"""
def search(self, query):
"""Run TuneIn search"""
<|body_0|>
def get_station_info(self, station_url):
"""Get station info (i.e. extract JS from HTML)"""
<|body_1|>
def extra... | stack_v2_sparse_classes_36k_train_014522 | 5,725 | permissive | [
{
"docstring": "Run TuneIn search",
"name": "search",
"signature": "def search(self, query)"
},
{
"docstring": "Get station info (i.e. extract JS from HTML)",
"name": "get_station_info",
"signature": "def get_station_info(self, station_url)"
},
{
"docstring": "Extract stream url ... | 5 | stack_v2_sparse_classes_30k_train_000246 | Implement the Python class `TuneInClient` described below.
Class description:
TuneIn client TODO: Move out requestor to voiceplay.utils
Method signatures and docstrings:
- def search(self, query): Run TuneIn search
- def get_station_info(self, station_url): Get station info (i.e. extract JS from HTML)
- def extract_s... | Implement the Python class `TuneInClient` described below.
Class description:
TuneIn client TODO: Move out requestor to voiceplay.utils
Method signatures and docstrings:
- def search(self, query): Run TuneIn search
- def get_station_info(self, station_url): Get station info (i.e. extract JS from HTML)
- def extract_s... | 3e35a25cfcf982a3871cf0d819bae4374ee31ecf | <|skeleton|>
class TuneInClient:
"""TuneIn client TODO: Move out requestor to voiceplay.utils"""
def search(self, query):
"""Run TuneIn search"""
<|body_0|>
def get_station_info(self, station_url):
"""Get station info (i.e. extract JS from HTML)"""
<|body_1|>
def extra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TuneInClient:
"""TuneIn client TODO: Move out requestor to voiceplay.utils"""
def search(self, query):
"""Run TuneIn search"""
stations = []
data = requests.get('http://tunein.com/search/?query={0!s}'.format(quote(query)), headers=self.headers)
soup = BeautifulSoup(''.join... | the_stack_v2_python_sparse | voiceplay/player/tasks/tunein.py | tb0hdan/voiceplay | train | 4 |
e1c351af5522685ba9458db6e12e8abf2ac16031 | [
"self.logger = logger\nself.script_type = script_type\nself.watcher = metadata_watcher.MetadataWatcher(logger=self.logger)",
"dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)\ndest_file.close()\ndest = dest_file.name\nself.logger.info('Downloading url from %s to %s using authentication token.',... | <|body_start_0|>
self.logger = logger
self.script_type = script_type
self.watcher = metadata_watcher.MetadataWatcher(logger=self.logger)
<|end_body_0|>
<|body_start_1|>
dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)
dest_file.close()
dest = dest_file... | A class for retrieving and storing user provided metadata scripts. | ScriptRetriever | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScriptRetriever:
"""A class for retrieving and storing user provided metadata scripts."""
def __init__(self, logger, script_type):
"""Constructor. Args: logger: logger object, used to write to SysLog and serial port. script_type: string, the metadata script type to run."""
<|... | stack_v2_sparse_classes_36k_train_014523 | 8,689 | permissive | [
{
"docstring": "Constructor. Args: logger: logger object, used to write to SysLog and serial port. script_type: string, the metadata script type to run.",
"name": "__init__",
"signature": "def __init__(self, logger, script_type)"
},
{
"docstring": "Download a Google Storage URL using an authenti... | 6 | stack_v2_sparse_classes_30k_train_015645 | Implement the Python class `ScriptRetriever` described below.
Class description:
A class for retrieving and storing user provided metadata scripts.
Method signatures and docstrings:
- def __init__(self, logger, script_type): Constructor. Args: logger: logger object, used to write to SysLog and serial port. script_typ... | Implement the Python class `ScriptRetriever` described below.
Class description:
A class for retrieving and storing user provided metadata scripts.
Method signatures and docstrings:
- def __init__(self, logger, script_type): Constructor. Args: logger: logger object, used to write to SysLog and serial port. script_typ... | cf4b33214f770da2299923a5fa73d3d95f66ec35 | <|skeleton|>
class ScriptRetriever:
"""A class for retrieving and storing user provided metadata scripts."""
def __init__(self, logger, script_type):
"""Constructor. Args: logger: logger object, used to write to SysLog and serial port. script_type: string, the metadata script type to run."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScriptRetriever:
"""A class for retrieving and storing user provided metadata scripts."""
def __init__(self, logger, script_type):
"""Constructor. Args: logger: logger object, used to write to SysLog and serial port. script_type: string, the metadata script type to run."""
self.logger = l... | the_stack_v2_python_sparse | packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py | GoogleCloudPlatform/compute-image-packages | train | 329 |
a7a935e17e4a551c4986fc4106fac8b74e866e63 | [
"create_hm_flow = linear_flow.Flow(constants.CREATE_HEALTH_MONITOR_FLOW)\ncreate_hm_flow.add(lifecycle_tasks.HealthMonitorToErrorOnRevertTask(requires=[constants.HEALTH_MON, constants.LISTENERS, constants.LOADBALANCER]))\ncreate_hm_flow.add(database_tasks.MarkHealthMonitorPendingCreateInDB(requires=constants.HEALTH... | <|body_start_0|>
create_hm_flow = linear_flow.Flow(constants.CREATE_HEALTH_MONITOR_FLOW)
create_hm_flow.add(lifecycle_tasks.HealthMonitorToErrorOnRevertTask(requires=[constants.HEALTH_MON, constants.LISTENERS, constants.LOADBALANCER]))
create_hm_flow.add(database_tasks.MarkHealthMonitorPendingCr... | HealthMonitorFlows | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HealthMonitorFlows:
def get_create_health_monitor_flow(self):
"""Create a flow to create a health monitor :returns: The flow for creating a health monitor"""
<|body_0|>
def get_delete_health_monitor_flow(self):
"""Create a flow to delete a health monitor :returns: Th... | stack_v2_sparse_classes_36k_train_014524 | 4,639 | permissive | [
{
"docstring": "Create a flow to create a health monitor :returns: The flow for creating a health monitor",
"name": "get_create_health_monitor_flow",
"signature": "def get_create_health_monitor_flow(self)"
},
{
"docstring": "Create a flow to delete a health monitor :returns: The flow for deletin... | 3 | stack_v2_sparse_classes_30k_train_008565 | Implement the Python class `HealthMonitorFlows` described below.
Class description:
Implement the HealthMonitorFlows class.
Method signatures and docstrings:
- def get_create_health_monitor_flow(self): Create a flow to create a health monitor :returns: The flow for creating a health monitor
- def get_delete_health_mo... | Implement the Python class `HealthMonitorFlows` described below.
Class description:
Implement the HealthMonitorFlows class.
Method signatures and docstrings:
- def get_create_health_monitor_flow(self): Create a flow to create a health monitor :returns: The flow for creating a health monitor
- def get_delete_health_mo... | 0426285a41464a5015494584f109eed35a0d44db | <|skeleton|>
class HealthMonitorFlows:
def get_create_health_monitor_flow(self):
"""Create a flow to create a health monitor :returns: The flow for creating a health monitor"""
<|body_0|>
def get_delete_health_monitor_flow(self):
"""Create a flow to delete a health monitor :returns: Th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HealthMonitorFlows:
def get_create_health_monitor_flow(self):
"""Create a flow to create a health monitor :returns: The flow for creating a health monitor"""
create_hm_flow = linear_flow.Flow(constants.CREATE_HEALTH_MONITOR_FLOW)
create_hm_flow.add(lifecycle_tasks.HealthMonitorToErrorO... | the_stack_v2_python_sparse | octavia/controller/worker/v2/flows/health_monitor_flows.py | openstack/octavia | train | 147 | |
04b1f7599c3db51cc0d3c3ba64029b3df9a8438e | [
"n = [i[:] for i in matrix]\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n m = len(matrix[0]) - 1 - i\n print(i, j, m)\n n[j][m] = matrix[i][j]\nreturn n",
"matrix.reverse()\nprint(matrix)\nfor i in range(len(matrix)):\n for j in range(i, len(matrix[0])):\n mat... | <|body_start_0|>
n = [i[:] for i in matrix]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
m = len(matrix[0]) - 1 - i
print(i, j, m)
n[j][m] = matrix[i][j]
return n
<|end_body_0|>
<|body_start_1|>
matrix.reverse()... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-... | stack_v2_sparse_classes_36k_train_014525 | 1,405 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "rotate2",
"signature": "def rotate2(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate2(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate1(self, matrix): :type matrix: List[List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate2(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate1(self, matrix): :type matrix: List[List... | f234bd7b62cb7bc2150faa764bf05a9095e19192 | <|skeleton|>
class Solution:
def rotate2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
n = [i[:] for i in matrix]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
m = len(matrix[0]) - 1 - i
... | the_stack_v2_python_sparse | alg/rotate_image.py | nyannko/leetcode-python | train | 0 | |
c62979dcac2975f695bb9a4a5dcdcc61745c04fe | [
"self.patch_message = message\nunion = data.union.get(True)\npack.pack_union_info(union, message)\nfor member in data.member_list.get_all(True):\n pack.pack_member_info(member, message.members.add())\nif enable_application:\n for application in data.application_list.get_all(True):\n if application.is_a... | <|body_start_0|>
self.patch_message = message
union = data.union.get(True)
pack.pack_union_info(union, message)
for member in data.member_list.get_all(True):
pack.pack_member_info(member, message.members.add())
if enable_application:
for application in dat... | 联盟信息填充 | UnionPatcher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnionPatcher:
"""联盟信息填充"""
def patch(self, message, data, user_id, now, enable_application=False):
"""填充联盟信息 message[protobuf UnionInfo] Args: message[protobuf UnionInfo] data[UnionData] user_id[int]: 玩家 user id now[int]: 时间戳 enable_application[bool]: 是否需要包含申请信息"""
<|body_0|>... | stack_v2_sparse_classes_36k_train_014526 | 3,922 | no_license | [
{
"docstring": "填充联盟信息 message[protobuf UnionInfo] Args: message[protobuf UnionInfo] data[UnionData] user_id[int]: 玩家 user id now[int]: 时间戳 enable_application[bool]: 是否需要包含申请信息",
"name": "patch",
"signature": "def patch(self, message, data, user_id, now, enable_application=False)"
},
{
"docstrin... | 3 | null | Implement the Python class `UnionPatcher` described below.
Class description:
联盟信息填充
Method signatures and docstrings:
- def patch(self, message, data, user_id, now, enable_application=False): 填充联盟信息 message[protobuf UnionInfo] Args: message[protobuf UnionInfo] data[UnionData] user_id[int]: 玩家 user id now[int]: 时间戳 e... | Implement the Python class `UnionPatcher` described below.
Class description:
联盟信息填充
Method signatures and docstrings:
- def patch(self, message, data, user_id, now, enable_application=False): 填充联盟信息 message[protobuf UnionInfo] Args: message[protobuf UnionInfo] data[UnionData] user_id[int]: 玩家 user id now[int]: 时间戳 e... | a16c872ba781855a8c891eff41e8e651cd565ebf | <|skeleton|>
class UnionPatcher:
"""联盟信息填充"""
def patch(self, message, data, user_id, now, enable_application=False):
"""填充联盟信息 message[protobuf UnionInfo] Args: message[protobuf UnionInfo] data[UnionData] user_id[int]: 玩家 user id now[int]: 时间戳 enable_application[bool]: 是否需要包含申请信息"""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnionPatcher:
"""联盟信息填充"""
def patch(self, message, data, user_id, now, enable_application=False):
"""填充联盟信息 message[protobuf UnionInfo] Args: message[protobuf UnionInfo] data[UnionData] user_id[int]: 玩家 user id now[int]: 时间戳 enable_application[bool]: 是否需要包含申请信息"""
self.patch_message = me... | the_stack_v2_python_sparse | gunion/union_patcher.py | daxingyou/test-2 | train | 0 |
dd652d73f620d43c586af21026428b0d24b7ca2d | [
"empty_result = [0] * len(coins)\nif amount == 0:\n return empty_result\nbest = [-1] * len(coins)\nfor idx, coin in enumerate(coins):\n if amount >= coin:\n tmp = self.changeCoin_rec(amount - coin, coins)\n tmp[idx] += 1\n if sum(best) < 0 or sum(tmp) < sum(best):\n best = tmp\... | <|body_start_0|>
empty_result = [0] * len(coins)
if amount == 0:
return empty_result
best = [-1] * len(coins)
for idx, coin in enumerate(coins):
if amount >= coin:
tmp = self.changeCoin_rec(amount - coin, coins)
tmp[idx] += 1
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def changeCoin_rec(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def changeCoin_dp(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
def coinChange(self, co... | stack_v2_sparse_classes_36k_train_014527 | 2,200 | permissive | [
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "changeCoin_rec",
"signature": "def changeCoin_rec(self, coins, amount)"
},
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "changeCoin_dp",
"signature": "def changeCoin_dp(self,... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def changeCoin_rec(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def changeCoin_dp(self, coins, amount): :type coins: List[int] :type amount: int :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def changeCoin_rec(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def changeCoin_dp(self, coins, amount): :type coins: List[int] :type amount: int :... | f462b66ae849f4332a4b150f206dd49c7519e83b | <|skeleton|>
class Solution:
def changeCoin_rec(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def changeCoin_dp(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
def coinChange(self, co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def changeCoin_rec(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
empty_result = [0] * len(coins)
if amount == 0:
return empty_result
best = [-1] * len(coins)
for idx, coin in enumerate(coins):
if amoun... | the_stack_v2_python_sparse | Practice/DP/Easy_Coin_Change.py | hooyao/Coding-Py3 | train | 0 | |
00f3b73a17f249a6cb3ac196ce9111290f2d5d1a | [
"data = {'igdb': request.data['game']['id'], 'name': request.data['game']['name'], 'slug': request.data['game']['slug'], 'cover_id': request.data['game']['coverId'], 'backdrop_id': request.data['game']['backdropId']}\ngame, _ = Game.objects.get_or_create(**data)\nuser = CustomUser.objects.get(id=request.user.id)\nr... | <|body_start_0|>
data = {'igdb': request.data['game']['id'], 'name': request.data['game']['name'], 'slug': request.data['game']['slug'], 'cover_id': request.data['game']['coverId'], 'backdrop_id': request.data['game']['backdropId']}
game, _ = Game.objects.get_or_create(**data)
user = CustomUser.... | Endpoint for the gaming journal. | JournalView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JournalView:
"""Endpoint for the gaming journal."""
def post(self, request, *args, **kwargs):
"""Creates a journal entry. Journal entries are tipycally created when a user finishes a game and wants to register that event in their profile. A journal entry must have a date, a user and ... | stack_v2_sparse_classes_36k_train_014528 | 15,728 | no_license | [
{
"docstring": "Creates a journal entry. Journal entries are tipycally created when a user finishes a game and wants to register that event in their profile. A journal entry must have a date, a user and a game. Args: game: game object with igdb id, name, slug, cover_id and backdrop_id date: the day you finished... | 2 | stack_v2_sparse_classes_30k_train_012655 | Implement the Python class `JournalView` described below.
Class description:
Endpoint for the gaming journal.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Creates a journal entry. Journal entries are tipycally created when a user finishes a game and wants to register that event in the... | Implement the Python class `JournalView` described below.
Class description:
Endpoint for the gaming journal.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Creates a journal entry. Journal entries are tipycally created when a user finishes a game and wants to register that event in the... | 7f7e44ca0dae3525394458c16b7093f90612524b | <|skeleton|>
class JournalView:
"""Endpoint for the gaming journal."""
def post(self, request, *args, **kwargs):
"""Creates a journal entry. Journal entries are tipycally created when a user finishes a game and wants to register that event in their profile. A journal entry must have a date, a user and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JournalView:
"""Endpoint for the gaming journal."""
def post(self, request, *args, **kwargs):
"""Creates a journal entry. Journal entries are tipycally created when a user finishes a game and wants to register that event in their profile. A journal entry must have a date, a user and a game. Args:... | the_stack_v2_python_sparse | backend/actions/views.py | RMalmberg/overworld | train | 3 |
5e8e15b12d569763695d09986a819c9b6a682a51 | [
"raytracer = Rangefinder()\nraytracer.add_photoreceptors([0], 0.01, 0.01)\nself.assertRaises(BVException, raytracer.render, RigidBodyState())",
"raytracer = Rangefinder()\nraytracer.set_map(example_world)\nself.assertRaises(BVException, raytracer.render, RigidBodyState())"
] | <|body_start_0|>
raytracer = Rangefinder()
raytracer.add_photoreceptors([0], 0.01, 0.01)
self.assertRaises(BVException, raytracer.render, RigidBodyState())
<|end_body_0|>
<|body_start_1|>
raytracer = Rangefinder()
raytracer.set_map(example_world)
self.assertRaises(BVExce... | ExampleNotset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleNotset:
def testInitWorld(self):
"""Make sure that there is an expection if world not passed"""
<|body_0|>
def testInitSensor(self):
"""Make sure that there is an expection if photoreceptors not defined"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_014529 | 5,320 | no_license | [
{
"docstring": "Make sure that there is an expection if world not passed",
"name": "testInitWorld",
"signature": "def testInitWorld(self)"
},
{
"docstring": "Make sure that there is an expection if photoreceptors not defined",
"name": "testInitSensor",
"signature": "def testInitSensor(se... | 2 | stack_v2_sparse_classes_30k_train_004405 | Implement the Python class `ExampleNotset` described below.
Class description:
Implement the ExampleNotset class.
Method signatures and docstrings:
- def testInitWorld(self): Make sure that there is an expection if world not passed
- def testInitSensor(self): Make sure that there is an expection if photoreceptors not... | Implement the Python class `ExampleNotset` described below.
Class description:
Implement the ExampleNotset class.
Method signatures and docstrings:
- def testInitWorld(self): Make sure that there is an expection if world not passed
- def testInitSensor(self): Make sure that there is an expection if photoreceptors not... | 2f1dace35ec9d5d72db1201231f655de4372a01e | <|skeleton|>
class ExampleNotset:
def testInitWorld(self):
"""Make sure that there is an expection if world not passed"""
<|body_0|>
def testInitSensor(self):
"""Make sure that there is an expection if photoreceptors not defined"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExampleNotset:
def testInitWorld(self):
"""Make sure that there is an expection if world not passed"""
raytracer = Rangefinder()
raytracer.add_photoreceptors([0], 0.01, 0.01)
self.assertRaises(BVException, raytracer.render, RigidBodyState())
def testInitSensor(self):
... | the_stack_v2_python_sparse | src/pybv/sensors/image_range_sensor_test.py | AndreaCensi/pybv | train | 0 | |
1c6315bf1ee497701ab03a0319aa9cf1024b13f0 | [
"url = '/dashboard/moorings/'\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.status_code, 302)",
"url = '/dashboard/moorings/'\nself.client.login(username=self.adminUN, password='pass')\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response... | <|body_start_0|>
url = '/dashboard/moorings/'
response = self.client.get(url, HTTP_HOST='website.domain')
self.assertEqual(response.status_code, 302)
<|end_body_0|>
<|body_start_1|>
url = '/dashboard/moorings/'
self.client.login(username=self.adminUN, password='pass')
re... | DashboardMooringsTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DashboardMooringsTestCase:
def test_not_logged_in(self):
"""Test that the dashboard moorings view will redirect whilst not logged in."""
<|body_0|>
def test_logged_in_admin(self):
"""Test that the dashboard moorings view will load whilst logged in as admin."""
... | stack_v2_sparse_classes_36k_train_014530 | 26,818 | permissive | [
{
"docstring": "Test that the dashboard moorings view will redirect whilst not logged in.",
"name": "test_not_logged_in",
"signature": "def test_not_logged_in(self)"
},
{
"docstring": "Test that the dashboard moorings view will load whilst logged in as admin.",
"name": "test_logged_in_admin"... | 3 | null | Implement the Python class `DashboardMooringsTestCase` described below.
Class description:
Implement the DashboardMooringsTestCase class.
Method signatures and docstrings:
- def test_not_logged_in(self): Test that the dashboard moorings view will redirect whilst not logged in.
- def test_logged_in_admin(self): Test t... | Implement the Python class `DashboardMooringsTestCase` described below.
Class description:
Implement the DashboardMooringsTestCase class.
Method signatures and docstrings:
- def test_not_logged_in(self): Test that the dashboard moorings view will redirect whilst not logged in.
- def test_logged_in_admin(self): Test t... | 37d2942efcbdaad072f7a06ac876a40e0f69f702 | <|skeleton|>
class DashboardMooringsTestCase:
def test_not_logged_in(self):
"""Test that the dashboard moorings view will redirect whilst not logged in."""
<|body_0|>
def test_logged_in_admin(self):
"""Test that the dashboard moorings view will load whilst logged in as admin."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DashboardMooringsTestCase:
def test_not_logged_in(self):
"""Test that the dashboard moorings view will redirect whilst not logged in."""
url = '/dashboard/moorings/'
response = self.client.get(url, HTTP_HOST='website.domain')
self.assertEqual(response.status_code, 302)
def... | the_stack_v2_python_sparse | mooring/test_views.py | dbca-wa/moorings | train | 0 | |
0e72c82cea4f418cfdb645802459f52230c4634f | [
"dict = {}\nfor index, value in enumerate(nums):\n dict[value] = index\nfor index, value in enumerate(nums):\n if target - value in dict and dict[target - value] != index:\n return (index, dict[target - value])",
"answer = []\nfor i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n ... | <|body_start_0|>
dict = {}
for index, value in enumerate(nums):
dict[value] = index
for index, value in enumerate(nums):
if target - value in dict and dict[target - value] != index:
return (index, dict[target - value])
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_hashtable(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_bruteforce(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_014531 | 904 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_hashtable",
"signature": "def twoSum_hashtable(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_bruteforce",
"signature": "def tw... | 2 | stack_v2_sparse_classes_30k_train_013401 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_hashtable(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum_bruteforce(self, nums, target): :type nums: List[int] :type targe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_hashtable(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum_bruteforce(self, nums, target): :type nums: List[int] :type targe... | 11d68f96c5a5689c141ee6395d1f453dfd3d5aeb | <|skeleton|>
class Solution:
def twoSum_hashtable(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_bruteforce(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum_hashtable(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
dict = {}
for index, value in enumerate(nums):
dict[value] = index
for index, value in enumerate(nums):
if target - value in dict and dict... | the_stack_v2_python_sparse | Leetcode/Python/0001_Two_sum.py | Modrisco/OJ-questions | train | 2 | |
0c4bfac3a661b17d4c373c5461d1bf0eca45e63a | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), name=name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password, name=name)\nuser.is_superuser = True\nuser.save(using=... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), name=name)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.c... | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k_train_014532 | 11,684 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, name, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_015413 | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | 1f39cbe46788fa1a6003a8c3a3307285c32cc392 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), na... | the_stack_v2_python_sparse | repository/models.py | thensnow/AwesomeCRM | train | 0 | |
9e4b32f0d1d7f37a522c9025a49a202c6b95a0f9 | [
"super().__init__(*args, **kwargs)\nself.game1 = Game()\nself.title('Double-or-nothing')\nself.geometry('360x160')\nself.resizable(width=False, height=False)\nself.__v_bet = tk.IntVar()\nself.__v_bet.set(1)\nself.__v_roll = tk.StringVar(value='Roll the dices')\nself.__result = tk.StringVar()\nself.__result.set(f'Th... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.game1 = Game()
self.title('Double-or-nothing')
self.geometry('360x160')
self.resizable(width=False, height=False)
self.__v_bet = tk.IntVar()
self.__v_bet.set(1)
self.__v_roll = tk.StringVar(value='Rol... | GUI and the reading of values happens in here | Dices | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dices:
"""GUI and the reading of values happens in here"""
def __init__(self, number=1, pot=100, bet=1, *args, **kwargs):
"""calls TK initializer Takes users bet"""
<|body_0|>
def __rollandcheck(self):
"""called when button is pressed, calls roll and then check a... | stack_v2_sparse_classes_36k_train_014533 | 4,856 | no_license | [
{
"docstring": "calls TK initializer Takes users bet",
"name": "__init__",
"signature": "def __init__(self, number=1, pot=100, bet=1, *args, **kwargs)"
},
{
"docstring": "called when button is pressed, calls roll and then check and shows result",
"name": "__rollandcheck",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_019839 | Implement the Python class `Dices` described below.
Class description:
GUI and the reading of values happens in here
Method signatures and docstrings:
- def __init__(self, number=1, pot=100, bet=1, *args, **kwargs): calls TK initializer Takes users bet
- def __rollandcheck(self): called when button is pressed, calls ... | Implement the Python class `Dices` described below.
Class description:
GUI and the reading of values happens in here
Method signatures and docstrings:
- def __init__(self, number=1, pot=100, bet=1, *args, **kwargs): calls TK initializer Takes users bet
- def __rollandcheck(self): called when button is pressed, calls ... | 2b3f2317673ffbb6352dd8c8a01e4fed18c2f6f2 | <|skeleton|>
class Dices:
"""GUI and the reading of values happens in here"""
def __init__(self, number=1, pot=100, bet=1, *args, **kwargs):
"""calls TK initializer Takes users bet"""
<|body_0|>
def __rollandcheck(self):
"""called when button is pressed, calls roll and then check a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dices:
"""GUI and the reading of values happens in here"""
def __init__(self, number=1, pot=100, bet=1, *args, **kwargs):
"""calls TK initializer Takes users bet"""
super().__init__(*args, **kwargs)
self.game1 = Game()
self.title('Double-or-nothing')
self.geometry(... | the_stack_v2_python_sparse | Object-oriented-programming/Dices-exercises/dices_0_3.py | nooraelina/school-work | train | 0 |
2b98b07b5dbe37ce0d46bba72a10d85c6526c08f | [
"super(SequenceEmbeddingCNN, self).__init__()\nself.kernel_size = kernel_size\nself.n_kernels = n_kernels\nself.n_layers = n_layers\nif dropout == True:\n self.dropout = nn.Dropout(0.3)\nelse:\n self.dropout = nn.Identity()\nif self.n_layers <= 0:\n raise ValueError(f'Number of layers n_layers must be > 0 ... | <|body_start_0|>
super(SequenceEmbeddingCNN, self).__init__()
self.kernel_size = kernel_size
self.n_kernels = n_kernels
self.n_layers = n_layers
if dropout == True:
self.dropout = nn.Dropout(0.3)
else:
self.dropout = nn.Identity()
if self.n... | SequenceEmbeddingCNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceEmbeddingCNN:
def __init__(self, n_input_features: int, kernel_size: int=4, n_kernels: int=32, n_layers: int=1, dropout=False):
"""Sequence embedding using 1D-CNN (`h()` in paper) See `deeprc/examples/` for examples. Parameters ---------- n_input_features : int Number of input fe... | stack_v2_sparse_classes_36k_train_014534 | 9,277 | no_license | [
{
"docstring": "Sequence embedding using 1D-CNN (`h()` in paper) See `deeprc/examples/` for examples. Parameters ---------- n_input_features : int Number of input features per sequence position kernel_size : int Size of 1D-CNN kernels n_kernels : int Number of 1D-CNN kernels in each layer n_layers : int Number ... | 2 | stack_v2_sparse_classes_30k_train_001647 | Implement the Python class `SequenceEmbeddingCNN` described below.
Class description:
Implement the SequenceEmbeddingCNN class.
Method signatures and docstrings:
- def __init__(self, n_input_features: int, kernel_size: int=4, n_kernels: int=32, n_layers: int=1, dropout=False): Sequence embedding using 1D-CNN (`h()` i... | Implement the Python class `SequenceEmbeddingCNN` described below.
Class description:
Implement the SequenceEmbeddingCNN class.
Method signatures and docstrings:
- def __init__(self, n_input_features: int, kernel_size: int=4, n_kernels: int=32, n_layers: int=1, dropout=False): Sequence embedding using 1D-CNN (`h()` i... | 8cf86c4f69a4673ee5045647b75f45eba5b09d9c | <|skeleton|>
class SequenceEmbeddingCNN:
def __init__(self, n_input_features: int, kernel_size: int=4, n_kernels: int=32, n_layers: int=1, dropout=False):
"""Sequence embedding using 1D-CNN (`h()` in paper) See `deeprc/examples/` for examples. Parameters ---------- n_input_features : int Number of input fe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceEmbeddingCNN:
def __init__(self, n_input_features: int, kernel_size: int=4, n_kernels: int=32, n_layers: int=1, dropout=False):
"""Sequence embedding using 1D-CNN (`h()` in paper) See `deeprc/examples/` for examples. Parameters ---------- n_input_features : int Number of input features per seq... | the_stack_v2_python_sparse | src/DeepRC_mod.py | richieYT-wan/DeepCAT_PyTorch | train | 0 | |
944b0633523b6e69d374d7a9c7a8fd20f93053ff | [
"if n == 0:\n return []\nnums = [i + 1 for i in range(n)]\nreturn self.generator(nums)",
"m = len(nums)\nif m == 0:\n return [None]\nif m == 1:\n root = TreeNode(nums[0])\n return [root]\nans = []\nfor i in range(m):\n v = nums[i]\n sub_l = self.generator(nums[:i])\n sub_r = self.generator(nu... | <|body_start_0|>
if n == 0:
return []
nums = [i + 1 for i in range(n)]
return self.generator(nums)
<|end_body_0|>
<|body_start_1|>
m = len(nums)
if m == 0:
return [None]
if m == 1:
root = TreeNode(nums[0])
return [root]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_0|>
def generator(self, nums):
"""assume nums is a sorted array"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0:
return []
nums = [i... | stack_v2_sparse_classes_36k_train_014535 | 3,712 | no_license | [
{
"docstring": ":type n: int :rtype: List[TreeNode]",
"name": "generateTrees",
"signature": "def generateTrees(self, n)"
},
{
"docstring": "assume nums is a sorted array",
"name": "generator",
"signature": "def generator(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateTrees(self, n): :type n: int :rtype: List[TreeNode]
- def generator(self, nums): assume nums is a sorted array | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateTrees(self, n): :type n: int :rtype: List[TreeNode]
- def generator(self, nums): assume nums is a sorted array
<|skeleton|>
class Solution:
def generateTrees(se... | e00cf94c5b86c8cca27e3bee69ad21e727b7679b | <|skeleton|>
class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_0|>
def generator(self, nums):
"""assume nums is a sorted array"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
if n == 0:
return []
nums = [i + 1 for i in range(n)]
return self.generator(nums)
def generator(self, nums):
"""assume nums is a sorted array"""
m = len(nums)
... | the_stack_v2_python_sparse | interview/prob95.py | binchen15/leet-python | train | 1 | |
50c3b31924573de7777f6e96b5155d4d6b34b160 | [
"self._map['l1'][Sentinel2TOA.id] = Sentinel2TOA\nself._map['l2'][Sentinel2SR.id] = Sentinel2SR\nself._map['l3'][Sentinel2NBAR.id] = Sentinel2NBAR",
"for drivers_by_level in self._map.values():\n for driver_name in drivers_by_level:\n if collection == driver_name:\n return drivers_by_level[dr... | <|body_start_0|>
self._map['l1'][Sentinel2TOA.id] = Sentinel2TOA
self._map['l2'][Sentinel2SR.id] = Sentinel2SR
self._map['l3'][Sentinel2NBAR.id] = Sentinel2NBAR
<|end_body_0|>
<|body_start_1|>
for drivers_by_level in self._map.values():
for driver_name in drivers_by_level:
... | Define a factory to identify a Sentinel product based on scene identifier. | SentinelFactory | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SentinelFactory:
"""Define a factory to identify a Sentinel product based on scene identifier."""
def register(self):
"""Initialize factory object."""
<|body_0|>
def get_from_collection(self, collection: str):
"""Retrieve the respective Sentinel driver from given... | stack_v2_sparse_classes_36k_train_014536 | 11,082 | permissive | [
{
"docstring": "Initialize factory object.",
"name": "register",
"signature": "def register(self)"
},
{
"docstring": "Retrieve the respective Sentinel driver from given collection.",
"name": "get_from_collection",
"signature": "def get_from_collection(self, collection: str)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_008874 | Implement the Python class `SentinelFactory` described below.
Class description:
Define a factory to identify a Sentinel product based on scene identifier.
Method signatures and docstrings:
- def register(self): Initialize factory object.
- def get_from_collection(self, collection: str): Retrieve the respective Senti... | Implement the Python class `SentinelFactory` described below.
Class description:
Define a factory to identify a Sentinel product based on scene identifier.
Method signatures and docstrings:
- def register(self): Initialize factory object.
- def get_from_collection(self, collection: str): Retrieve the respective Senti... | 62583f6c25bca79e7e1b5503bc6308298838c877 | <|skeleton|>
class SentinelFactory:
"""Define a factory to identify a Sentinel product based on scene identifier."""
def register(self):
"""Initialize factory object."""
<|body_0|>
def get_from_collection(self, collection: str):
"""Retrieve the respective Sentinel driver from given... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SentinelFactory:
"""Define a factory to identify a Sentinel product based on scene identifier."""
def register(self):
"""Initialize factory object."""
self._map['l1'][Sentinel2TOA.id] = Sentinel2TOA
self._map['l2'][Sentinel2SR.id] = Sentinel2SR
self._map['l3'][Sentinel2NBA... | the_stack_v2_python_sparse | bdc_collection_builder/collections/sentinel/utils.py | rodolfolotte/bdc-collection-builder | train | 0 |
d938a2e46f23fae5191ce54e862004232a143478 | [
"for i in range(len(arrays)):\n current_array = arrays[i]\n for i in range(len(current_array)):\n if not str(current_array[i]).isdigit():\n return False\nreturn True",
"for i in range(len(arrays)):\n current_array = arrays[i]\n for i in range(len(current_array)):\n if not str(... | <|body_start_0|>
for i in range(len(arrays)):
current_array = arrays[i]
for i in range(len(current_array)):
if not str(current_array[i]).isdigit():
return False
return True
<|end_body_0|>
<|body_start_1|>
for i in range(len(arrays)):
... | Validator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Validator:
def validate_custom_sorting_dataset(arrays):
"""Check if the arrays are valid for sorting :param arrays: (array of arrays) each array contains an array :return: Throw an exception if array isn't valid"""
<|body_0|>
def validate_custom_freq_dataset(arrays):
... | stack_v2_sparse_classes_36k_train_014537 | 1,814 | permissive | [
{
"docstring": "Check if the arrays are valid for sorting :param arrays: (array of arrays) each array contains an array :return: Throw an exception if array isn't valid",
"name": "validate_custom_sorting_dataset",
"signature": "def validate_custom_sorting_dataset(arrays)"
},
{
"docstring": "Chec... | 3 | stack_v2_sparse_classes_30k_train_007323 | Implement the Python class `Validator` described below.
Class description:
Implement the Validator class.
Method signatures and docstrings:
- def validate_custom_sorting_dataset(arrays): Check if the arrays are valid for sorting :param arrays: (array of arrays) each array contains an array :return: Throw an exception... | Implement the Python class `Validator` described below.
Class description:
Implement the Validator class.
Method signatures and docstrings:
- def validate_custom_sorting_dataset(arrays): Check if the arrays are valid for sorting :param arrays: (array of arrays) each array contains an array :return: Throw an exception... | beaa4b50d77079d260ae9783a250ea3b8bf0bae7 | <|skeleton|>
class Validator:
def validate_custom_sorting_dataset(arrays):
"""Check if the arrays are valid for sorting :param arrays: (array of arrays) each array contains an array :return: Throw an exception if array isn't valid"""
<|body_0|>
def validate_custom_freq_dataset(arrays):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Validator:
def validate_custom_sorting_dataset(arrays):
"""Check if the arrays are valid for sorting :param arrays: (array of arrays) each array contains an array :return: Throw an exception if array isn't valid"""
for i in range(len(arrays)):
current_array = arrays[i]
... | the_stack_v2_python_sparse | Session_1/dev/server/datasets_processing/validator.py | AhmedHani/acmASCIS-ML-Hack-2017 | train | 0 | |
6100f1a09996674b67a958a7026ada368ae699fb | [
"nn.Module.__init__(self)\nself.c = c\nself.eta = eta\nself.eps = eps",
"dist = torch.norm(self.c - input, p=2, dim=1)\nlosses = torch.where(semi_target == 0, dist ** 2, self.eta * (dist ** 2 + self.eps) ** semi_target.float())\nloss = torch.mean(losses)\nreturn loss"
] | <|body_start_0|>
nn.Module.__init__(self)
self.c = c
self.eta = eta
self.eps = eps
<|end_body_0|>
<|body_start_1|>
dist = torch.norm(self.c - input, p=2, dim=1)
losses = torch.where(semi_target == 0, dist ** 2, self.eta * (dist ** 2 + self.eps) ** semi_target.float())
... | Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019) | DeepSADLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepSADLoss:
"""Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019)"""
def __init__(self, c, eta, eps=1e-06):
"""Constructor of the DeepSAD loss. ---------- INPUT |---- c (torch.Tensor) the center of the hypersphere as a multidimensional vector. |---- eta (float) ... | stack_v2_sparse_classes_36k_train_014538 | 18,386 | permissive | [
{
"docstring": "Constructor of the DeepSAD loss. ---------- INPUT |---- c (torch.Tensor) the center of the hypersphere as a multidimensional vector. |---- eta (float) control the importance given to known or unknonw | samples. 1.0 gives equal weights, <1.0 gives more weight | to the unknown samples, >1.0 gives ... | 2 | stack_v2_sparse_classes_30k_train_018461 | Implement the Python class `DeepSADLoss` described below.
Class description:
Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019)
Method signatures and docstrings:
- def __init__(self, c, eta, eps=1e-06): Constructor of the DeepSAD loss. ---------- INPUT |---- c (torch.Tensor) the center of the hyp... | Implement the Python class `DeepSADLoss` described below.
Class description:
Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019)
Method signatures and docstrings:
- def __init__(self, c, eta, eps=1e-06): Constructor of the DeepSAD loss. ---------- INPUT |---- c (torch.Tensor) the center of the hyp... | 850b6195d6290a50eee865b4d5a66f5db5260e8f | <|skeleton|>
class DeepSADLoss:
"""Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019)"""
def __init__(self, c, eta, eps=1e-06):
"""Constructor of the DeepSAD loss. ---------- INPUT |---- c (torch.Tensor) the center of the hypersphere as a multidimensional vector. |---- eta (float) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepSADLoss:
"""Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019)"""
def __init__(self, c, eta, eps=1e-06):
"""Constructor of the DeepSAD loss. ---------- INPUT |---- c (torch.Tensor) the center of the hypersphere as a multidimensional vector. |---- eta (float) control the i... | the_stack_v2_python_sparse | Code/src/models/optim/CustomLosses.py | antoine-spahr/X-ray-Anomaly-Detection | train | 3 |
726dea38a7d3eed366ba4da38e7f407e99fba003 | [
"param = {'brand_image': 'flask-example/brand/image/'}\nif key not in param:\n return None\nreturn param[key]",
"path = Path.pathmedia(key)\nif path == None:\n return None\nreturn Environment.get_credential('APP_LOC') + '/public/' + path"
] | <|body_start_0|>
param = {'brand_image': 'flask-example/brand/image/'}
if key not in param:
return None
return param[key]
<|end_body_0|>
<|body_start_1|>
path = Path.pathmedia(key)
if path == None:
return None
return Environment.get_credential('AP... | Path | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Path:
def pathmedia(key):
"""this function for get path image :key string: :return string:"""
<|body_0|>
def fullpathmedia(key):
"""this function for get path image :key string: :return string:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
param =... | stack_v2_sparse_classes_36k_train_014539 | 718 | no_license | [
{
"docstring": "this function for get path image :key string: :return string:",
"name": "pathmedia",
"signature": "def pathmedia(key)"
},
{
"docstring": "this function for get path image :key string: :return string:",
"name": "fullpathmedia",
"signature": "def fullpathmedia(key)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000025 | Implement the Python class `Path` described below.
Class description:
Implement the Path class.
Method signatures and docstrings:
- def pathmedia(key): this function for get path image :key string: :return string:
- def fullpathmedia(key): this function for get path image :key string: :return string: | Implement the Python class `Path` described below.
Class description:
Implement the Path class.
Method signatures and docstrings:
- def pathmedia(key): this function for get path image :key string: :return string:
- def fullpathmedia(key): this function for get path image :key string: :return string:
<|skeleton|>
cl... | 4af89bd110ca305b952df15febe749bc9d0f6fe8 | <|skeleton|>
class Path:
def pathmedia(key):
"""this function for get path image :key string: :return string:"""
<|body_0|>
def fullpathmedia(key):
"""this function for get path image :key string: :return string:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Path:
def pathmedia(key):
"""this function for get path image :key string: :return string:"""
param = {'brand_image': 'flask-example/brand/image/'}
if key not in param:
return None
return param[key]
def fullpathmedia(key):
"""this function for get path ... | the_stack_v2_python_sparse | config/path.py | arywidiantara/Flask-Sqlalchemy | train | 0 | |
025736420a7250b9439a33beda0bc8520ce79214 | [
"err_msg, err_code = CommentResource._basic_checks(identifier, filing_id, request)\nif err_msg:\n return (jsonify(err_msg), err_code)\ncomments = db.session.query(Comment).filter(Comment.filing_id == filing_id)\nif comment_id:\n comment = comments.filter(Comment.id == comment_id).one_or_none()\n if not com... | <|body_start_0|>
err_msg, err_code = CommentResource._basic_checks(identifier, filing_id, request)
if err_msg:
return (jsonify(err_msg), err_code)
comments = db.session.query(Comment).filter(Comment.filing_id == filing_id)
if comment_id:
comment = comments.filter(... | Filings Comment service. | CommentResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentResource:
"""Filings Comment service."""
def get(identifier, filing_id, comment_id=None):
"""Return a JSON object with meta information about the Service."""
<|body_0|>
def post(identifier, filing_id):
"""Create a new comment for the filing."""
<|b... | stack_v2_sparse_classes_36k_train_014540 | 5,155 | permissive | [
{
"docstring": "Return a JSON object with meta information about the Service.",
"name": "get",
"signature": "def get(identifier, filing_id, comment_id=None)"
},
{
"docstring": "Create a new comment for the filing.",
"name": "post",
"signature": "def post(identifier, filing_id)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_004623 | Implement the Python class `CommentResource` described below.
Class description:
Filings Comment service.
Method signatures and docstrings:
- def get(identifier, filing_id, comment_id=None): Return a JSON object with meta information about the Service.
- def post(identifier, filing_id): Create a new comment for the f... | Implement the Python class `CommentResource` described below.
Class description:
Filings Comment service.
Method signatures and docstrings:
- def get(identifier, filing_id, comment_id=None): Return a JSON object with meta information about the Service.
- def post(identifier, filing_id): Create a new comment for the f... | d90f11a7b14411b02c07fe97d2c1fc31cd4a9b32 | <|skeleton|>
class CommentResource:
"""Filings Comment service."""
def get(identifier, filing_id, comment_id=None):
"""Return a JSON object with meta information about the Service."""
<|body_0|>
def post(identifier, filing_id):
"""Create a new comment for the filing."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentResource:
"""Filings Comment service."""
def get(identifier, filing_id, comment_id=None):
"""Return a JSON object with meta information about the Service."""
err_msg, err_code = CommentResource._basic_checks(identifier, filing_id, request)
if err_msg:
return (js... | the_stack_v2_python_sparse | legal-api/src/legal_api/resources/v1/business/filing_comments.py | bcgov/lear | train | 13 |
b4ca0346bf3820aaade607c0985853fd1d292705 | [
"zerosRow = []\nzerosCol = []\ni = 0\nwhile i < len(matrix):\n j = 0\n while j < len(matrix[i]):\n if matrix[i][j] == 0:\n zerosRow.append(i)\n zerosCol.append(j)\n j += 1\n i += 1\nprint(zerosCol)\nprint(zerosRow)\ni = 0\nwhile i < len(matrix):\n j = 0\n while j <... | <|body_start_0|>
zerosRow = []
zerosCol = []
i = 0
while i < len(matrix):
j = 0
while j < len(matrix[i]):
if matrix[i][j] == 0:
zerosRow.append(i)
zerosCol.append(j)
j += 1
i += 1
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matri... | stack_v2_sparse_classes_36k_train_014541 | 2,036 | permissive | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instea... | 2 | stack_v2_sparse_classes_30k_train_020761 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes1(self, matrix): :type matrix: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes1(self, matrix): :type matrix: List... | 3e2484d19e6845f0f93e78f7b447909bba3efadd | <|skeleton|>
class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
zerosRow = []
zerosCol = []
i = 0
while i < len(matrix):
j = 0
while j < len(matrix[i]):
... | the_stack_v2_python_sparse | explore_medium/array_and_string/SetZeroes.py | niefy/LeetCodeExam | train | 0 | |
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_36k_train_014542 | 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_017563 | 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_36k | 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 | |
b8dd9073c63e081ef5c2ed9395e7a19687e7ed67 | [
"wx.TreeCtrl.__init__(self, parent, text_id + 2000, pos=(0, 70), size=(100, 100), name='Source Browser', style=wx.TR_HIDE_ROOT | wx.TR_HAS_BUTTONS | wx.TR_HAS_VARIABLE_ROW_HEIGHT)\nself.parent = parent\nif TargetFile != '' and TargetFile != 'New Document':\n try:\n br_file = open(TargetFile, 'r')\n ... | <|body_start_0|>
wx.TreeCtrl.__init__(self, parent, text_id + 2000, pos=(0, 70), size=(100, 100), name='Source Browser', style=wx.TR_HIDE_ROOT | wx.TR_HAS_BUTTONS | wx.TR_HAS_VARIABLE_ROW_HEIGHT)
self.parent = parent
if TargetFile != '' and TargetFile != 'New Document':
try:
... | SrcBrowser Provides the necessary functions for collecting data and displays the date using a TreeCtrl. Used to display the classes and functions in the current file. | SrcBrowser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SrcBrowser:
"""SrcBrowser Provides the necessary functions for collecting data and displays the date using a TreeCtrl. Used to display the classes and functions in the current file."""
def __init__(self, TargetFile, nb, text_id, parent):
"""__init__ Initializes the TreeCtrl object, g... | stack_v2_sparse_classes_36k_train_014543 | 3,297 | no_license | [
{
"docstring": "__init__ Initializes the TreeCtrl object, gathers data and displays it in the TreeCtrl",
"name": "__init__",
"signature": "def __init__(self, TargetFile, nb, text_id, parent)"
},
{
"docstring": "RefreshTree Finds the current document, gathers data and displays it in the TreeCtrl.... | 3 | stack_v2_sparse_classes_30k_val_000815 | Implement the Python class `SrcBrowser` described below.
Class description:
SrcBrowser Provides the necessary functions for collecting data and displays the date using a TreeCtrl. Used to display the classes and functions in the current file.
Method signatures and docstrings:
- def __init__(self, TargetFile, nb, text... | Implement the Python class `SrcBrowser` described below.
Class description:
SrcBrowser Provides the necessary functions for collecting data and displays the date using a TreeCtrl. Used to display the classes and functions in the current file.
Method signatures and docstrings:
- def __init__(self, TargetFile, nb, text... | 3bcdbcc1b7a5ca57ab8d7913eac416b693ed8608 | <|skeleton|>
class SrcBrowser:
"""SrcBrowser Provides the necessary functions for collecting data and displays the date using a TreeCtrl. Used to display the classes and functions in the current file."""
def __init__(self, TargetFile, nb, text_id, parent):
"""__init__ Initializes the TreeCtrl object, g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SrcBrowser:
"""SrcBrowser Provides the necessary functions for collecting data and displays the date using a TreeCtrl. Used to display the classes and functions in the current file."""
def __init__(self, TargetFile, nb, text_id, parent):
"""__init__ Initializes the TreeCtrl object, gathers data a... | the_stack_v2_python_sparse | benchmarks/gecrit-code/bin/SourceBrowser.py | tomergreenwald/python-validator | train | 0 |
117f186bf483573d96e6ba3a351664693c211a67 | [
"self.nums = nums\nself.size = len(self.nums)\nself.k = k\nheapq.heapify(self.nums)\nwhile self.size > self.k:\n heapq.heappop(self.nums)\n self.size -= 1",
"if self.size < self.k:\n heapq.heappush(self.nums, val)\n self.size += 1\nelif val > self.nums[0]:\n heapq.heapreplace(self.nums, val)\nretur... | <|body_start_0|>
self.nums = nums
self.size = len(self.nums)
self.k = k
heapq.heapify(self.nums)
while self.size > self.k:
heapq.heappop(self.nums)
self.size -= 1
<|end_body_0|>
<|body_start_1|>
if self.size < self.k:
heapq.heappush(se... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.nums = nums
self.size = len(self.nums)
... | stack_v2_sparse_classes_36k_train_014544 | 2,773 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | null | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | dd0a1c92414e12d82053c3df981897e975063bb8 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.nums = nums
self.size = len(self.nums)
self.k = k
heapq.heapify(self.nums)
while self.size > self.k:
heapq.heappop(self.nums)
self.size -= 1
def a... | the_stack_v2_python_sparse | leetcode-gl-python/leetcodee-703-数据流中的第K大元素.py | ZX1209/gl-algorithm-practise | train | 0 | |
75510f50adcfbc81e7942916c7397b2afb03e646 | [
"options = super()._default_options()\noptions.plotter.set_figure_options(xlabel='Delay', ylabel='Normalized Projection on the Main Axis', xval_unit='s')\noptions.result_parameters = [curve.ParameterRepr('tau', 'T1', 's')]\noptions.normalization = True\nreturn options",
"amp = fit_data.ufloat_params['amp']\ntau =... | <|body_start_0|>
options = super()._default_options()
options.plotter.set_figure_options(xlabel='Delay', ylabel='Normalized Projection on the Main Axis', xval_unit='s')
options.result_parameters = [curve.ParameterRepr('tau', 'T1', 's')]
options.normalization = True
return options... | A class to analyze T1 experiments with kerneled data. | T1KerneledAnalysis | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class T1KerneledAnalysis:
"""A class to analyze T1 experiments with kerneled data."""
def _default_options(cls) -> Options:
"""Default analysis options."""
<|body_0|>
def _evaluate_quality(self, fit_data: curve.CurveFitResult) -> Union[str, None]:
"""Algorithmic criter... | stack_v2_sparse_classes_36k_train_014545 | 4,817 | permissive | [
{
"docstring": "Default analysis options.",
"name": "_default_options",
"signature": "def _default_options(cls) -> Options"
},
{
"docstring": "Algorithmic criteria for whether the fit is good or bad. A good fit has: - a reduced chi-squared lower than three - absolute amp is within [0.9, 1.1] - b... | 3 | null | Implement the Python class `T1KerneledAnalysis` described below.
Class description:
A class to analyze T1 experiments with kerneled data.
Method signatures and docstrings:
- def _default_options(cls) -> Options: Default analysis options.
- def _evaluate_quality(self, fit_data: curve.CurveFitResult) -> Union[str, None... | Implement the Python class `T1KerneledAnalysis` described below.
Class description:
A class to analyze T1 experiments with kerneled data.
Method signatures and docstrings:
- def _default_options(cls) -> Options: Default analysis options.
- def _evaluate_quality(self, fit_data: curve.CurveFitResult) -> Union[str, None... | a387675a3fe817cef05b968bbf3e05799a09aaae | <|skeleton|>
class T1KerneledAnalysis:
"""A class to analyze T1 experiments with kerneled data."""
def _default_options(cls) -> Options:
"""Default analysis options."""
<|body_0|>
def _evaluate_quality(self, fit_data: curve.CurveFitResult) -> Union[str, None]:
"""Algorithmic criter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class T1KerneledAnalysis:
"""A class to analyze T1 experiments with kerneled data."""
def _default_options(cls) -> Options:
"""Default analysis options."""
options = super()._default_options()
options.plotter.set_figure_options(xlabel='Delay', ylabel='Normalized Projection on the Main A... | the_stack_v2_python_sparse | qiskit_experiments/library/characterization/analysis/t1_analysis.py | oliverdial/qiskit-experiments | train | 0 |
12bf837484180e4f6f95526a5d072ae8ef009612 | [
"self.user_id = user_id\nself.user_info = user_info\nself.msg_info = msg_info\nself.text = text\nself.timestamp = timestamp\nself.user_interface = user_interface",
"user_interface = msg_dict['user_interface'] if 'user_interface' in msg_dict else None\nuser_id = msg_dict['user_id'] if 'user_id' in msg_dict else No... | <|body_start_0|>
self.user_id = user_id
self.user_info = user_info
self.msg_info = msg_info
self.text = text
self.timestamp = timestamp
self.user_interface = user_interface
<|end_body_0|>
<|body_start_1|>
user_interface = msg_dict['user_interface'] if 'user_inter... | Message | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Message:
def __init__(self, user_interface, user_id, user_info, msg_info, text, timestamp):
"""An object for input and output Message. Args: user_interface(str): The interface name used for this message (e.g., 'telegram') user_id(str or int): The user ID. user_info(dict): The dict contai... | stack_v2_sparse_classes_36k_train_014546 | 1,764 | permissive | [
{
"docstring": "An object for input and output Message. Args: user_interface(str): The interface name used for this message (e.g., 'telegram') user_id(str or int): The user ID. user_info(dict): The dict containing some more information about the user. msg_info(dict): The dict containing some more information ab... | 2 | stack_v2_sparse_classes_30k_train_001417 | Implement the Python class `Message` described below.
Class description:
Implement the Message class.
Method signatures and docstrings:
- def __init__(self, user_interface, user_id, user_info, msg_info, text, timestamp): An object for input and output Message. Args: user_interface(str): The interface name used for th... | Implement the Python class `Message` described below.
Class description:
Implement the Message class.
Method signatures and docstrings:
- def __init__(self, user_interface, user_id, user_info, msg_info, text, timestamp): An object for input and output Message. Args: user_interface(str): The interface name used for th... | f2f29d0dcb4d47a1f75e8add8501555486b5115f | <|skeleton|>
class Message:
def __init__(self, user_interface, user_id, user_info, msg_info, text, timestamp):
"""An object for input and output Message. Args: user_interface(str): The interface name used for this message (e.g., 'telegram') user_id(str or int): The user ID. user_info(dict): The dict contai... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Message:
def __init__(self, user_interface, user_id, user_info, msg_info, text, timestamp):
"""An object for input and output Message. Args: user_interface(str): The interface name used for this message (e.g., 'telegram') user_id(str or int): The user ID. user_info(dict): The dict containing some more... | the_stack_v2_python_sparse | macaw/core/interaction_handler/msg.py | hamed-zamani/macaw | train | 2 | |
c120acd5af964ec3df331bad4fdbd6ba6a8889a2 | [
"super(BertLayer, self).__init__()\nself.attention = BertAttention(config)\nself.is_decoder = config.is_decoder\nif self.is_decoder:\n self.crossattention = BertAttention(config)\nself.intermediate = BertIntermediate(config)\nself.output = BertOutput(config)",
"self_attention_outputs = self.attention(hidden_st... | <|body_start_0|>
super(BertLayer, self).__init__()
self.attention = BertAttention(config)
self.is_decoder = config.is_decoder
if self.is_decoder:
self.crossattention = BertAttention(config)
self.intermediate = BertIntermediate(config)
self.output = BertOutput(... | layer | BertLayer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertLayer:
"""layer"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None):
"""construct fun"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_014547 | 16,172 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "construct fun",
"name": "construct",
"signature": "def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None)"... | 2 | null | Implement the Python class `BertLayer` described below.
Class description:
layer
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None): construct fun | Implement the Python class `BertLayer` described below.
Class description:
layer
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None): construct fun
<|skeleton|>
clas... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class BertLayer:
"""layer"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None):
"""construct fun"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BertLayer:
"""layer"""
def __init__(self, config):
"""init fun"""
super(BertLayer, self).__init__()
self.attention = BertAttention(config)
self.is_decoder = config.is_decoder
if self.is_decoder:
self.crossattention = BertAttention(config)
self.i... | the_stack_v2_python_sparse | research/nlp/luke/src/luke/robert.py | mindspore-ai/models | train | 301 |
2359084c22a9704c96af5d7d58c5a961e34e0a72 | [
"username = self.txtUsername.get()\npassword = self.txtPassword.get()\nusers = SystemToolKit.readFile(Config.UserFile)\nfor j, i in enumerate(users):\n userHash = users[i]['Password']\n salt = users[i]['Salt']\n TestUsername = users[i]['Username']\n if self.checkPassword(userHash, password, salt) == Tru... | <|body_start_0|>
username = self.txtUsername.get()
password = self.txtPassword.get()
users = SystemToolKit.readFile(Config.UserFile)
for j, i in enumerate(users):
userHash = users[i]['Password']
salt = users[i]['Salt']
TestUsername = users[i]['Username... | Methods: CheckDetails Check Passwords Check Username | Login | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login:
"""Methods: CheckDetails Check Passwords Check Username"""
def checkDetails(self):
"""Searches though the User file for any accounts that can met the login requirements These are: Check Password returns true Check Username returns true If these tests are passed the system then... | stack_v2_sparse_classes_36k_train_014548 | 9,033 | no_license | [
{
"docstring": "Searches though the User file for any accounts that can met the login requirements These are: Check Password returns true Check Username returns true If these tests are passed the system then goes on to check if the email used to register the account has been confirmed if not the Confirm Email F... | 3 | stack_v2_sparse_classes_30k_train_004900 | Implement the Python class `Login` described below.
Class description:
Methods: CheckDetails Check Passwords Check Username
Method signatures and docstrings:
- def checkDetails(self): Searches though the User file for any accounts that can met the login requirements These are: Check Password returns true Check Userna... | Implement the Python class `Login` described below.
Class description:
Methods: CheckDetails Check Passwords Check Username
Method signatures and docstrings:
- def checkDetails(self): Searches though the User file for any accounts that can met the login requirements These are: Check Password returns true Check Userna... | 6420f365540d935906178691fbb5e46b6a31c6b5 | <|skeleton|>
class Login:
"""Methods: CheckDetails Check Passwords Check Username"""
def checkDetails(self):
"""Searches though the User file for any accounts that can met the login requirements These are: Check Password returns true Check Username returns true If these tests are passed the system then... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Login:
"""Methods: CheckDetails Check Passwords Check Username"""
def checkDetails(self):
"""Searches though the User file for any accounts that can met the login requirements These are: Check Password returns true Check Username returns true If these tests are passed the system then goes on to c... | the_stack_v2_python_sparse | Login.py | Lamppost122/Controlled-assessment-Final | train | 0 |
5d2f370d683940fbc8d0ebda5f3087c824c3d769 | [
"BISECT_LOG = 'git bisect start\\n# status: waiting for both good and bad commits\\n# good: [c1] Fake good commit\\ngit bisect good c1\\n# status: waiting for bad commit, 1 good commit known\\n# bad: [c2] Fake bad commit\\ngit bisect bad c2\\n# first bad commit: [c2] Fake bad commit\\n'\ngit = MockableGitController... | <|body_start_0|>
BISECT_LOG = 'git bisect start\n# status: waiting for both good and bad commits\n# good: [c1] Fake good commit\ngit bisect good c1\n# status: waiting for bad commit, 1 good commit known\n# bad: [c2] Fake bad commit\ngit bisect bad c2\n# first bad commit: [c2] Fake bad commit\n'
git = Mo... | TestBisectSession | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBisectSession:
def test_two_cached_only_fast(self):
"""Simple case with two cached commits and only the fast command."""
<|body_0|>
def test_only_fast(self):
"""Mix of cached and uncached with only the fast command."""
<|body_1|>
def test_fast_and_sl... | stack_v2_sparse_classes_36k_train_014549 | 13,456 | permissive | [
{
"docstring": "Simple case with two cached commits and only the fast command.",
"name": "test_two_cached_only_fast",
"signature": "def test_two_cached_only_fast(self)"
},
{
"docstring": "Mix of cached and uncached with only the fast command.",
"name": "test_only_fast",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_006077 | Implement the Python class `TestBisectSession` described below.
Class description:
Implement the TestBisectSession class.
Method signatures and docstrings:
- def test_two_cached_only_fast(self): Simple case with two cached commits and only the fast command.
- def test_only_fast(self): Mix of cached and uncached with ... | Implement the Python class `TestBisectSession` described below.
Class description:
Implement the TestBisectSession class.
Method signatures and docstrings:
- def test_two_cached_only_fast(self): Simple case with two cached commits and only the fast command.
- def test_only_fast(self): Mix of cached and uncached with ... | 51f6017b8425b14d5a4aa9abace8fe5a25ef08c8 | <|skeleton|>
class TestBisectSession:
def test_two_cached_only_fast(self):
"""Simple case with two cached commits and only the fast command."""
<|body_0|>
def test_only_fast(self):
"""Mix of cached and uncached with only the fast command."""
<|body_1|>
def test_fast_and_sl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestBisectSession:
def test_two_cached_only_fast(self):
"""Simple case with two cached commits and only the fast command."""
BISECT_LOG = 'git bisect start\n# status: waiting for both good and bad commits\n# good: [c1] Fake good commit\ngit bisect good c1\n# status: waiting for bad commit, 1 g... | the_stack_v2_python_sparse | util/fpga/bitstream_bisect_test.py | lowRISC/opentitan | train | 2,077 | |
93d715221b6b2099683f504a9b9410ad0867b280 | [
"if not len(s):\n return True\nif len(s) == 1:\n return False\nbracks = {'(': ')', '[': ']', '{': '}'}\nstack = []\nfor item in s:\n if item in bracks:\n stack.append(bracks[item])\n else:\n if not stack:\n return False\n if item == stack.pop():\n continue\n ... | <|body_start_0|>
if not len(s):
return True
if len(s) == 1:
return False
bracks = {'(': ')', '[': ']', '{': '}'}
stack = []
for item in s:
if item in bracks:
stack.append(bracks[item])
else:
if not st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isValid1(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not len(s):
return True
if len(s) == 1:
... | stack_v2_sparse_classes_36k_train_014550 | 1,676 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isValid",
"signature": "def isValid(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "isValid1",
"signature": "def isValid1(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006438 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid(self, s): :type s: str :rtype: bool
- def isValid1(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 isValid(self, s): :type s: str :rtype: bool
- def isValid1(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def isValid(self, s):
""":type s: st... | 715e301068432c12b35169728390b64a8d4f83a2 | <|skeleton|>
class Solution:
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isValid1(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isValid(self, s):
""":type s: str :rtype: bool"""
if not len(s):
return True
if len(s) == 1:
return False
bracks = {'(': ')', '[': ']', '{': '}'}
stack = []
for item in s:
if item in bracks:
stack... | the_stack_v2_python_sparse | codes_1-50/20_Valid_Parentheses.py | GuodongQi/LeetCode | train | 0 | |
31d22d6fd10462edcdce74955e293aff8be7b0a7 | [
"if len(nums) < 3:\n return []\nnums.sort()\nres = set()\nfor i, v in enumerate(nums[:-2]):\n if i >= 1 and v == nums[i - 1]:\n continue\n d = {}\n for x in nums[i + 1:]:\n if x not in d:\n d[-v - x] = 1\n else:\n res.add((v, -v - x, x))\nreturn list(res)",
"... | <|body_start_0|>
if len(nums) < 3:
return []
nums.sort()
res = set()
for i, v in enumerate(nums[:-2]):
if i >= 1 and v == nums[i - 1]:
continue
d = {}
for x in nums[i + 1:]:
if x not in d:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) < 3:
... | stack_v2_sparse_classes_36k_train_014551 | 1,354 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum2",
"signature": "def threeSum2(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solution:
... | f90526c9b073165b86b933cdf7d1dc496e68f2c6 | <|skeleton|>
class Solution:
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
if len(nums) < 3:
return []
nums.sort()
res = set()
for i, v in enumerate(nums[:-2]):
if i >= 1 and v == nums[i - 1]:
continue
d ... | the_stack_v2_python_sparse | star5/0015.py | mach8686devops/leetcode-100 | train | 0 | |
d4ab58c68de28b35e72a7c2a1c61603e502f909e | [
"genre = Genre.query.filter_by(id=id).first()\nif genre is None:\n return ({'message': 'Genre does not exist'}, 404)\nreturn genre_schema.dump(genre)",
"req = api.payload\ngenre = Genre.query.filter_by(id=id).first()\nif genre is None:\n return ({'message': 'Genre does not exist'}, 404)\ntry:\n edit_genr... | <|body_start_0|>
genre = Genre.query.filter_by(id=id).first()
if genre is None:
return ({'message': 'Genre does not exist'}, 404)
return genre_schema.dump(genre)
<|end_body_0|>
<|body_start_1|>
req = api.payload
genre = Genre.query.filter_by(id=id).first()
if... | SingleGenre | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleGenre:
def get(self, id):
"""Get Genre by id"""
<|body_0|>
def put(self, id):
"""Update a Genre"""
<|body_1|>
def delete(self, id):
"""Delete a Genre by id"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
genre = Genre.quer... | stack_v2_sparse_classes_36k_train_014552 | 3,163 | no_license | [
{
"docstring": "Get Genre by id",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Update a Genre",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "Delete a Genre by id",
"name": "delete",
"signature": "def delete(self, id)"
}
] | 3 | stack_v2_sparse_classes_30k_test_000052 | Implement the Python class `SingleGenre` described below.
Class description:
Implement the SingleGenre class.
Method signatures and docstrings:
- def get(self, id): Get Genre by id
- def put(self, id): Update a Genre
- def delete(self, id): Delete a Genre by id | Implement the Python class `SingleGenre` described below.
Class description:
Implement the SingleGenre class.
Method signatures and docstrings:
- def get(self, id): Get Genre by id
- def put(self, id): Update a Genre
- def delete(self, id): Delete a Genre by id
<|skeleton|>
class SingleGenre:
def get(self, id):... | ae78fff9888b0f68d9403d7f65cba086dabb3802 | <|skeleton|>
class SingleGenre:
def get(self, id):
"""Get Genre by id"""
<|body_0|>
def put(self, id):
"""Update a Genre"""
<|body_1|>
def delete(self, id):
"""Delete a Genre by id"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleGenre:
def get(self, id):
"""Get Genre by id"""
genre = Genre.query.filter_by(id=id).first()
if genre is None:
return ({'message': 'Genre does not exist'}, 404)
return genre_schema.dump(genre)
def put(self, id):
"""Update a Genre"""
req = ... | the_stack_v2_python_sparse | api/v1/genres.py | mythril-io/flask-api | train | 0 | |
6e8545e99737437088daffb5281a0ee34a0af047 | [
"self.image_size_height = 299\nself.image_size_width = 299\nself.num_channels = 3\nself.sess, self.logits = self.load_model(modelpath, model_file)\nself.x = self.sess.graph.get_tensor_by_name('x:0')",
"images_pre_processed = []\nfor a_image in imgs:\n a_image = np.expand_dims(a_image, axis=0)\n images_pre_p... | <|body_start_0|>
self.image_size_height = 299
self.image_size_width = 299
self.num_channels = 3
self.sess, self.logits = self.load_model(modelpath, model_file)
self.x = self.sess.graph.get_tensor_by_name('x:0')
<|end_body_0|>
<|body_start_1|>
images_pre_processed = []
... | Model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
def __init__(self, modelpath, model_file):
""":param modelpath: a string; absolute path to the model (excluding file name) :param model_file: a string; file name like .meta or .h5"""
<|body_0|>
def pre_process(imgs):
"""# The Model class must have a pre-proces... | stack_v2_sparse_classes_36k_train_014553 | 8,527 | no_license | [
{
"docstring": ":param modelpath: a string; absolute path to the model (excluding file name) :param model_file: a string; file name like .meta or .h5",
"name": "__init__",
"signature": "def __init__(self, modelpath, model_file)"
},
{
"docstring": "# The Model class must have a pre-process method... | 5 | stack_v2_sparse_classes_30k_train_001209 | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def __init__(self, modelpath, model_file): :param modelpath: a string; absolute path to the model (excluding file name) :param model_file: a string; file name like .meta or .h5
- def p... | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def __init__(self, modelpath, model_file): :param modelpath: a string; absolute path to the model (excluding file name) :param model_file: a string; file name like .meta or .h5
- def p... | ae4d8127eafa7f7e8b8109bb8e2ecec50183c364 | <|skeleton|>
class Model:
def __init__(self, modelpath, model_file):
""":param modelpath: a string; absolute path to the model (excluding file name) :param model_file: a string; file name like .meta or .h5"""
<|body_0|>
def pre_process(imgs):
"""# The Model class must have a pre-proces... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Model:
def __init__(self, modelpath, model_file):
""":param modelpath: a string; absolute path to the model (excluding file name) :param model_file: a string; file name like .meta or .h5"""
self.image_size_height = 299
self.image_size_width = 299
self.num_channels = 3
s... | the_stack_v2_python_sparse | userModel-inceptionV3.py | testingForTrust/tft | train | 0 | |
cf0f2f114ee9deb8eec21fe7036c1ce5e67ce614 | [
"import heapq\nself.low = []\nself.upp = []",
"if len(self.low) == 0 or num <= -self.low[0]:\n heapq.heappush(self.low, -num)\nelse:\n heapq.heappush(self.upp, num)\nif len(self.upp) == len(self.low) + 1:\n tmp = heapq.heappop(self.upp)\n heapq.heappush(self.low, -tmp)\nif len(self.low) == len(self.up... | <|body_start_0|>
import heapq
self.low = []
self.upp = []
<|end_body_0|>
<|body_start_1|>
if len(self.low) == 0 or num <= -self.low[0]:
heapq.heappush(self.low, -num)
else:
heapq.heappush(self.upp, num)
if len(self.upp) == len(self.low) + 1:
... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_014554 | 1,342 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: None",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | null | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | 6db9db1934bc0a8142124d8b56bf6c07bdf43d79 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
import heapq
self.low = []
self.upp = []
def addNum(self, num):
""":type num: int :rtype: None"""
if len(self.low) == 0 or num <= -self.low[0]:
heapq.heappush(self.low,... | the_stack_v2_python_sparse | PriorityQueue/0295_FindMedianFromDataStream_H.py | PFZ86/LeetcodePractice | train | 1 | |
1cc0a83392147b06631e69d6a56a2ace7e36c513 | [
"res = super(OnHold, self).default_get(fields)\nticket_id = self.env.context.get('active_id') or self.env.context.get('default_ticket_id')\nif ticket_id:\n ticket = self.env['flspticketsystem.ticket'].browse(ticket_id)\nif ticket.exists():\n if 'ticket_id' in fields:\n res['ticket_id'] = ticket.id\nres... | <|body_start_0|>
res = super(OnHold, self).default_get(fields)
ticket_id = self.env.context.get('active_id') or self.env.context.get('default_ticket_id')
if ticket_id:
ticket = self.env['flspticketsystem.ticket'].browse(ticket_id)
if ticket.exists():
if 'ticket_id... | Class_Name: OnHold Model_Name: flspticketsystem.onhold Purpose: To create a onhold model used in the wizard to put ticket on hold Date: Feb/3rd/Wednesday/2021 Author: Sami Byaruhanga | OnHold | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnHold:
"""Class_Name: OnHold Model_Name: flspticketsystem.onhold Purpose: To create a onhold model used in the wizard to put ticket on hold Date: Feb/3rd/Wednesday/2021 Author: Sami Byaruhanga"""
def default_get(self, fields):
"""Purpose: to get the default values from the ticket mo... | stack_v2_sparse_classes_36k_train_014555 | 3,998 | no_license | [
{
"docstring": "Purpose: to get the default values from the ticket model and load in the wizard",
"name": "default_get",
"signature": "def default_get(self, fields)"
},
{
"docstring": "Purpose: Button used in wizard put ticket onhold",
"name": "onhold",
"signature": "def onhold(self)"
... | 2 | null | Implement the Python class `OnHold` described below.
Class description:
Class_Name: OnHold Model_Name: flspticketsystem.onhold Purpose: To create a onhold model used in the wizard to put ticket on hold Date: Feb/3rd/Wednesday/2021 Author: Sami Byaruhanga
Method signatures and docstrings:
- def default_get(self, field... | Implement the Python class `OnHold` described below.
Class description:
Class_Name: OnHold Model_Name: flspticketsystem.onhold Purpose: To create a onhold model used in the wizard to put ticket on hold Date: Feb/3rd/Wednesday/2021 Author: Sami Byaruhanga
Method signatures and docstrings:
- def default_get(self, field... | 4a82cd5cfd1898c6da860cb68dff3a14e037bbad | <|skeleton|>
class OnHold:
"""Class_Name: OnHold Model_Name: flspticketsystem.onhold Purpose: To create a onhold model used in the wizard to put ticket on hold Date: Feb/3rd/Wednesday/2021 Author: Sami Byaruhanga"""
def default_get(self, fields):
"""Purpose: to get the default values from the ticket mo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OnHold:
"""Class_Name: OnHold Model_Name: flspticketsystem.onhold Purpose: To create a onhold model used in the wizard to put ticket on hold Date: Feb/3rd/Wednesday/2021 Author: Sami Byaruhanga"""
def default_get(self, fields):
"""Purpose: to get the default values from the ticket model and load ... | the_stack_v2_python_sparse | flsp_tktonhold/models/flsp_onhold.py | odoo-smg/firstlight | train | 3 |
9689eeca03569387815b68344597f6e1c00654f0 | [
"self.mtm = mtm\nself.rf = riskfreeRate\npReturns = AnnualReturn(self.mtm)\nself.portfolioReturn = pReturns.getValue()\nvolatility = Volatility(self.mtm.shift() / self.mtm - riskfreeRate)\nself.volatility = volatility.getValue()",
"improvement = (self.portfolioReturn - self.rf).fillna(0)\nvolatility = self.volati... | <|body_start_0|>
self.mtm = mtm
self.rf = riskfreeRate
pReturns = AnnualReturn(self.mtm)
self.portfolioReturn = pReturns.getValue()
volatility = Volatility(self.mtm.shift() / self.mtm - riskfreeRate)
self.volatility = volatility.getValue()
<|end_body_0|>
<|body_start_1|>... | Sharpe ratio of the data. | SharpeRatio | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharpeRatio:
"""Sharpe ratio of the data."""
def __init__(self, mtm, riskfreeRate):
"""Initialize a sharpe ratio calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in the format %Y%m%d; riskfreeRate : float risk-free interest... | stack_v2_sparse_classes_36k_train_014556 | 10,010 | permissive | [
{
"docstring": "Initialize a sharpe ratio calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in the format %Y%m%d; riskfreeRate : float risk-free interest rate.",
"name": "__init__",
"signature": "def __init__(self, mtm, riskfreeRate)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_006915 | Implement the Python class `SharpeRatio` described below.
Class description:
Sharpe ratio of the data.
Method signatures and docstrings:
- def __init__(self, mtm, riskfreeRate): Initialize a sharpe ratio calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in t... | Implement the Python class `SharpeRatio` described below.
Class description:
Sharpe ratio of the data.
Method signatures and docstrings:
- def __init__(self, mtm, riskfreeRate): Initialize a sharpe ratio calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in t... | 139d604177da3855503643e0fcfa87711ba7e588 | <|skeleton|>
class SharpeRatio:
"""Sharpe ratio of the data."""
def __init__(self, mtm, riskfreeRate):
"""Initialize a sharpe ratio calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in the format %Y%m%d; riskfreeRate : float risk-free interest... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SharpeRatio:
"""Sharpe ratio of the data."""
def __init__(self, mtm, riskfreeRate):
"""Initialize a sharpe ratio calculator. Parameters ---------- mtm : pandas.Series daily mark-to-market indexed by trading date as strings in the format %Y%m%d; riskfreeRate : float risk-free interest rate."""
... | the_stack_v2_python_sparse | analytics/riskMeasurement/riskMetric.py | WinQuant/arsenal | train | 0 |
9d44ee469cd9ef0273cce41298a72f0c4b580462 | [
"cache = get_cache(app_settings.PRICE_MONITOR_GRAPH_CACHE_NAME) if app_settings.PRICE_MONITOR_GRAPH_CACHE_NAME is not None else None\nsanitized_args = self.sanitize_allowed_args(renderer_context['request']) if 'request' in renderer_context else {}\ncache_key = self.create_cache_key(data, sanitized_args)\ncontent = ... | <|body_start_0|>
cache = get_cache(app_settings.PRICE_MONITOR_GRAPH_CACHE_NAME) if app_settings.PRICE_MONITOR_GRAPH_CACHE_NAME is not None else None
sanitized_args = self.sanitize_allowed_args(renderer_context['request']) if 'request' in renderer_context else {}
cache_key = self.create_cache_key... | A renderer to render charts as PNG for prices | PriceChartPNGRenderer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PriceChartPNGRenderer:
"""A renderer to render charts as PNG for prices"""
def render(self, data, accepted_media_type=None, renderer_context=None):
"""Renders `data` into serialized XML."""
<|body_0|>
def sanitize_allowed_args(self, request):
"""TODO: documentati... | stack_v2_sparse_classes_36k_train_014557 | 3,953 | permissive | [
{
"docstring": "Renders `data` into serialized XML.",
"name": "render",
"signature": "def render(self, data, accepted_media_type=None, renderer_context=None)"
},
{
"docstring": "TODO: documentation",
"name": "sanitize_allowed_args",
"signature": "def sanitize_allowed_args(self, request)"... | 4 | stack_v2_sparse_classes_30k_train_006388 | Implement the Python class `PriceChartPNGRenderer` described below.
Class description:
A renderer to render charts as PNG for prices
Method signatures and docstrings:
- def render(self, data, accepted_media_type=None, renderer_context=None): Renders `data` into serialized XML.
- def sanitize_allowed_args(self, reques... | Implement the Python class `PriceChartPNGRenderer` described below.
Class description:
A renderer to render charts as PNG for prices
Method signatures and docstrings:
- def render(self, data, accepted_media_type=None, renderer_context=None): Renders `data` into serialized XML.
- def sanitize_allowed_args(self, reques... | 5203e998bbea906cd88c1df7a6e55c89a0ec72a1 | <|skeleton|>
class PriceChartPNGRenderer:
"""A renderer to render charts as PNG for prices"""
def render(self, data, accepted_media_type=None, renderer_context=None):
"""Renders `data` into serialized XML."""
<|body_0|>
def sanitize_allowed_args(self, request):
"""TODO: documentati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PriceChartPNGRenderer:
"""A renderer to render charts as PNG for prices"""
def render(self, data, accepted_media_type=None, renderer_context=None):
"""Renders `data` into serialized XML."""
cache = get_cache(app_settings.PRICE_MONITOR_GRAPH_CACHE_NAME) if app_settings.PRICE_MONITOR_GRAPH_... | the_stack_v2_python_sparse | price_monitor/api/renderers/PriceChartPNGRenderer.py | teserak/django-amazon-price-monitor | train | 0 |
98bf45fc42191d2dda1bc092ef79ee7a213d185e | [
"self.a = nums\nself.to = range(0, len(nums))\nself.n = len(nums)",
"b = [0] * self.n\nfor i in xrange(self.n):\n b[self.to[i]] = self.a[i]\nself.a = b\nself.to = range(self.n)\nreturn self.a",
"for i in xrange(self.n - 1):\n pos = random.randint(i, self.n - 1)\n self.to[i], self.to[pos] = (self.to[pos... | <|body_start_0|>
self.a = nums
self.to = range(0, len(nums))
self.n = len(nums)
<|end_body_0|>
<|body_start_1|>
b = [0] * self.n
for i in xrange(self.n):
b[self.to[i]] = self.a[i]
self.a = b
self.to = range(self.n)
return self.a
<|end_body_1|>... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, nums):
""":type nums: List[int] :type size: int"""
<|body_0|>
def reset(self):
"""Resets the array to its original configuration and return it. :rtype: List[int]"""
<|body_1|>
def shuffle(self):
"""Returns a random sh... | stack_v2_sparse_classes_36k_train_014558 | 1,065 | no_license | [
{
"docstring": ":type nums: List[int] :type size: int",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "Resets the array to its original configuration and return it. :rtype: List[int]",
"name": "reset",
"signature": "def reset(self)"
},
{
"docstring... | 3 | stack_v2_sparse_classes_30k_train_010951 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int] :type size: int
- def reset(self): Resets the array to its original configuration and return it. :rtype: List[int]
- def shuffle(s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int] :type size: int
- def reset(self): Resets the array to its original configuration and return it. :rtype: List[int]
- def shuffle(s... | 58dcb51f183ac9bf5e825e8cd5c311852c231538 | <|skeleton|>
class Solution:
def __init__(self, nums):
""":type nums: List[int] :type size: int"""
<|body_0|>
def reset(self):
"""Resets the array to its original configuration and return it. :rtype: List[int]"""
<|body_1|>
def shuffle(self):
"""Returns a random sh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, nums):
""":type nums: List[int] :type size: int"""
self.a = nums
self.to = range(0, len(nums))
self.n = len(nums)
def reset(self):
"""Resets the array to its original configuration and return it. :rtype: List[int]"""
b = [0] * s... | the_stack_v2_python_sparse | 384 Shuffle an Array.py | jianminchen/LeetCode-30 | train | 0 | |
b35d9af19a45b67c05c09ddae2bfce92e2dd72f0 | [
"self.chol = cholesky_factor\nself.kmf = kmf\nself.nk = len(self.kmf.kpts)\nif naux is None:\n naux = cholesky_factor[0, 0].shape[0]\nself.naux = naux\nself.nao = cholesky_factor[0, 0].shape[-1]\nk_transfer_map = build_momentum_transfer_mapping(self.kmf.cell, self.kmf.kpts)\nself.k_transfer_map = k_transfer_map"... | <|body_start_0|>
self.chol = cholesky_factor
self.kmf = kmf
self.nk = len(self.kmf.kpts)
if naux is None:
naux = cholesky_factor[0, 0].shape[0]
self.naux = naux
self.nao = cholesky_factor[0, 0].shape[-1]
k_transfer_map = build_momentum_transfer_mapping... | SingleFactorization | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleFactorization:
def __init__(self, cholesky_factor: npt.NDArray, kmf: scf.HF, naux: int=None):
"""Class defining single-factorized ERIs. Args: cholesky_factor: Cholesky factor tensor that is [nkpts, nkpts, naux, nao, nao]. To see how to generate this see cholesky_from_df_ints kmf: p... | stack_v2_sparse_classes_36k_train_014559 | 4,487 | permissive | [
{
"docstring": "Class defining single-factorized ERIs. Args: cholesky_factor: Cholesky factor tensor that is [nkpts, nkpts, naux, nao, nao]. To see how to generate this see cholesky_from_df_ints kmf: pyscf k-object. Currently only used to obtain the number of k-points. Must have an attribute kpts which len(self... | 3 | stack_v2_sparse_classes_30k_train_019223 | Implement the Python class `SingleFactorization` described below.
Class description:
Implement the SingleFactorization class.
Method signatures and docstrings:
- def __init__(self, cholesky_factor: npt.NDArray, kmf: scf.HF, naux: int=None): Class defining single-factorized ERIs. Args: cholesky_factor: Cholesky factor... | Implement the Python class `SingleFactorization` described below.
Class description:
Implement the SingleFactorization class.
Method signatures and docstrings:
- def __init__(self, cholesky_factor: npt.NDArray, kmf: scf.HF, naux: int=None): Class defining single-factorized ERIs. Args: cholesky_factor: Cholesky factor... | 788481753c798a72c5cb3aa9f2aa9da3ce3190b0 | <|skeleton|>
class SingleFactorization:
def __init__(self, cholesky_factor: npt.NDArray, kmf: scf.HF, naux: int=None):
"""Class defining single-factorized ERIs. Args: cholesky_factor: Cholesky factor tensor that is [nkpts, nkpts, naux, nao, nao]. To see how to generate this see cholesky_from_df_ints kmf: p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleFactorization:
def __init__(self, cholesky_factor: npt.NDArray, kmf: scf.HF, naux: int=None):
"""Class defining single-factorized ERIs. Args: cholesky_factor: Cholesky factor tensor that is [nkpts, nkpts, naux, nao, nao]. To see how to generate this see cholesky_from_df_ints kmf: pyscf k-object.... | the_stack_v2_python_sparse | src/openfermion/resource_estimates/pbc/sf/sf_integrals.py | quantumlib/OpenFermion | train | 1,481 | |
7c34c1662c0e62da35a805dbb0ac6efa7ac5f12e | [
"self.w = INITIALIZERS[initializer](inputdim, units) if initializer else INITIALIZERS['random'](inputdim, units)\nself.regularizer = regularizer if regularizer else 'l'\nself.activation = activation\nself.dropout = dropout\nself.optimizer = None\nself.dz_dw = None\nself.dz_dx = None\nself.da_dz = None\nself.dr_dw =... | <|body_start_0|>
self.w = INITIALIZERS[initializer](inputdim, units) if initializer else INITIALIZERS['random'](inputdim, units)
self.regularizer = regularizer if regularizer else 'l'
self.activation = activation
self.dropout = dropout
self.optimizer = None
self.dz_dw = N... | Default dense layer class | DefaultDenseLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultDenseLayer:
"""Default dense layer class"""
def __init__(self, inputdim: int, units: int, activation: str, initializer: str=None, regularizer: str=None, dropout: float=None) -> None:
"""Initialize default dense layer Args: inputdim: number of input units units: number of units... | stack_v2_sparse_classes_36k_train_014560 | 5,858 | no_license | [
{
"docstring": "Initialize default dense layer Args: inputdim: number of input units units: number of units in layer activation: activation function string => should be a key of ACTIVATIONS initializer: weight initialization scheme => should be a key of INITIALIZERS regularizer: regularization method => should ... | 3 | stack_v2_sparse_classes_30k_train_015410 | Implement the Python class `DefaultDenseLayer` described below.
Class description:
Default dense layer class
Method signatures and docstrings:
- def __init__(self, inputdim: int, units: int, activation: str, initializer: str=None, regularizer: str=None, dropout: float=None) -> None: Initialize default dense layer Arg... | Implement the Python class `DefaultDenseLayer` described below.
Class description:
Default dense layer class
Method signatures and docstrings:
- def __init__(self, inputdim: int, units: int, activation: str, initializer: str=None, regularizer: str=None, dropout: float=None) -> None: Initialize default dense layer Arg... | 9e6d3846968597349eabda3eb07e70253baf4786 | <|skeleton|>
class DefaultDenseLayer:
"""Default dense layer class"""
def __init__(self, inputdim: int, units: int, activation: str, initializer: str=None, regularizer: str=None, dropout: float=None) -> None:
"""Initialize default dense layer Args: inputdim: number of input units units: number of units... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefaultDenseLayer:
"""Default dense layer class"""
def __init__(self, inputdim: int, units: int, activation: str, initializer: str=None, regularizer: str=None, dropout: float=None) -> None:
"""Initialize default dense layer Args: inputdim: number of input units units: number of units in layer act... | the_stack_v2_python_sparse | Packages/mlr/NN/Layer.py | akshat0123/MLReview | train | 0 |
aca3eb1aa6f11d6af1dfd68f80b269107c05560d | [
"v.theme.dark = self._dark_theme\nself.theme_name = 'dark' if self._dark_theme else 'light'\nsu.set_config('theme', self.theme_name)\nself.kwargs = DARK_THEME if self._dark_theme else LIGHT_THEME\nself.kwargs = new_colors or self.kwargs\ntheme = getattr(v.theme.themes, self.theme_name)\n[setattr(theme, color_name, ... | <|body_start_0|>
v.theme.dark = self._dark_theme
self.theme_name = 'dark' if self._dark_theme else 'light'
su.set_config('theme', self.theme_name)
self.kwargs = DARK_THEME if self._dark_theme else LIGHT_THEME
self.kwargs = new_colors or self.kwargs
theme = getattr(v.theme... | SepalColor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SepalColor:
def __init__(self, *_, **new_colors) -> None:
"""Custom simple name space to store and access to the sepal_ui colors and with a magic method to display theme. Args: **new_colors (optional): the new colors to set in hexadecimal as a dict (experimental)"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_014561 | 5,262 | permissive | [
{
"docstring": "Custom simple name space to store and access to the sepal_ui colors and with a magic method to display theme. Args: **new_colors (optional): the new colors to set in hexadecimal as a dict (experimental)",
"name": "__init__",
"signature": "def __init__(self, *_, **new_colors) -> None"
}... | 2 | stack_v2_sparse_classes_30k_train_019197 | Implement the Python class `SepalColor` described below.
Class description:
Implement the SepalColor class.
Method signatures and docstrings:
- def __init__(self, *_, **new_colors) -> None: Custom simple name space to store and access to the sepal_ui colors and with a magic method to display theme. Args: **new_colors... | Implement the Python class `SepalColor` described below.
Class description:
Implement the SepalColor class.
Method signatures and docstrings:
- def __init__(self, *_, **new_colors) -> None: Custom simple name space to store and access to the sepal_ui colors and with a magic method to display theme. Args: **new_colors... | b26c7d698659d5c5a2029d02fc94dcd9daf0df98 | <|skeleton|>
class SepalColor:
def __init__(self, *_, **new_colors) -> None:
"""Custom simple name space to store and access to the sepal_ui colors and with a magic method to display theme. Args: **new_colors (optional): the new colors to set in hexadecimal as a dict (experimental)"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SepalColor:
def __init__(self, *_, **new_colors) -> None:
"""Custom simple name space to store and access to the sepal_ui colors and with a magic method to display theme. Args: **new_colors (optional): the new colors to set in hexadecimal as a dict (experimental)"""
v.theme.dark = self._dark_t... | the_stack_v2_python_sparse | sepal_ui/frontend/styles.py | 12rambau/sepal_ui | train | 17 | |
fed072e6d6feb6da9ba096d866c6113ef7dca4ba | [
"address_data = validated_data.pop('address', None)\nif address_data:\n instance = super().create(validated_data)\n instance.set_address(**address_data)\n instance.save(update_fields=['address_id'])\n return instance\nreturn super().create(validated_data)",
"address_data = validated_data.pop('address'... | <|body_start_0|>
address_data = validated_data.pop('address', None)
if address_data:
instance = super().create(validated_data)
instance.set_address(**address_data)
instance.save(update_fields=['address_id'])
return instance
return super().create(va... | Nested Address Serializer Mixin. To be used on any serializer that needs to save address field in nested data. Note, the model of the serializer should have subclassed at least from :class:`address.models.AddressMixin`. | NestedAddressSerializerMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NestedAddressSerializerMixin:
"""Nested Address Serializer Mixin. To be used on any serializer that needs to save address field in nested data. Note, the model of the serializer should have subclassed at least from :class:`address.models.AddressMixin`."""
def create(self, validated_data):
... | stack_v2_sparse_classes_36k_train_014562 | 1,570 | no_license | [
{
"docstring": "Overriding create method to save the address data.",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Overriding update method to update the address data.",
"name": "update",
"signature": "def update(self, instance, validated_data)"
}... | 2 | null | Implement the Python class `NestedAddressSerializerMixin` described below.
Class description:
Nested Address Serializer Mixin. To be used on any serializer that needs to save address field in nested data. Note, the model of the serializer should have subclassed at least from :class:`address.models.AddressMixin`.
Meth... | Implement the Python class `NestedAddressSerializerMixin` described below.
Class description:
Nested Address Serializer Mixin. To be used on any serializer that needs to save address field in nested data. Note, the model of the serializer should have subclassed at least from :class:`address.models.AddressMixin`.
Meth... | fa794d08a3892f45e9e69fd226b53fb0bfa75145 | <|skeleton|>
class NestedAddressSerializerMixin:
"""Nested Address Serializer Mixin. To be used on any serializer that needs to save address field in nested data. Note, the model of the serializer should have subclassed at least from :class:`address.models.AddressMixin`."""
def create(self, validated_data):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NestedAddressSerializerMixin:
"""Nested Address Serializer Mixin. To be used on any serializer that needs to save address field in nested data. Note, the model of the serializer should have subclassed at least from :class:`address.models.AddressMixin`."""
def create(self, validated_data):
"""Over... | the_stack_v2_python_sparse | api/v1/address/serializers.py | NitinSatpal/mybill-server | train | 0 |
300684ac6049b6a2d169ff9ef6be34d9a6e02535 | [
"def rserialize(root, res):\n if not root:\n res += 'None,'\n else:\n res += str(root.val) + ','\n res = rserialize(root.left, res)\n res = rserialize(root.right, res)\n return res\nreturn rserialize(root, '')",
"def rdeserialize(datalist):\n if datalist[0] == 'None':\n ... | <|body_start_0|>
def rserialize(root, res):
if not root:
res += 'None,'
else:
res += str(root.val) + ','
res = rserialize(root.left, res)
res = rserialize(root.right, res)
return res
return rserialize(roo... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_014563 | 2,784 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_000320 | 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:... | 7a459e9742958e63be8886874904e5ab2489411a | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def rserialize(root, res):
if not root:
res += 'None,'
else:
res += str(root.val) + ','
res = rserialize(root.left... | the_stack_v2_python_sparse | Hard/297.py | Hellofafar/Leetcode | train | 6 | |
43a27f38ee70629ed5aa7de8bcacfda8c8146891 | [
"self.public_key_hash = public_key_hash\nself.ephemeral_public_key = ephemeral_public_key\nself.transaction_id = transaction_id",
"if dictionary is None:\n return None\nephemeral_public_key = dictionary.get('ephemeral_public_key')\npublic_key_hash = dictionary.get('public_key_hash')\ntransaction_id = dictionar... | <|body_start_0|>
self.public_key_hash = public_key_hash
self.ephemeral_public_key = ephemeral_public_key
self.transaction_id = transaction_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
ephemeral_public_key = dictionary.get('ephemeral_public_ke... | Implementation of the 'CreateApplePayHeaderRequest' model. The ApplePay header request Attributes: public_key_hash (string): SHA–256 hash, Base64 string codified ephemeral_public_key (string): X.509 encoded key bytes, Base64 encoded as a string transaction_id (string): Transaction identifier, generated on Device | CreateApplePayHeaderRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateApplePayHeaderRequest:
"""Implementation of the 'CreateApplePayHeaderRequest' model. The ApplePay header request Attributes: public_key_hash (string): SHA–256 hash, Base64 string codified ephemeral_public_key (string): X.509 encoded key bytes, Base64 encoded as a string transaction_id (stri... | stack_v2_sparse_classes_36k_train_014564 | 2,190 | permissive | [
{
"docstring": "Constructor for the CreateApplePayHeaderRequest class",
"name": "__init__",
"signature": "def __init__(self, ephemeral_public_key=None, public_key_hash=None, transaction_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary)... | 2 | stack_v2_sparse_classes_30k_train_005429 | Implement the Python class `CreateApplePayHeaderRequest` described below.
Class description:
Implementation of the 'CreateApplePayHeaderRequest' model. The ApplePay header request Attributes: public_key_hash (string): SHA–256 hash, Base64 string codified ephemeral_public_key (string): X.509 encoded key bytes, Base64 e... | Implement the Python class `CreateApplePayHeaderRequest` described below.
Class description:
Implementation of the 'CreateApplePayHeaderRequest' model. The ApplePay header request Attributes: public_key_hash (string): SHA–256 hash, Base64 string codified ephemeral_public_key (string): X.509 encoded key bytes, Base64 e... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class CreateApplePayHeaderRequest:
"""Implementation of the 'CreateApplePayHeaderRequest' model. The ApplePay header request Attributes: public_key_hash (string): SHA–256 hash, Base64 string codified ephemeral_public_key (string): X.509 encoded key bytes, Base64 encoded as a string transaction_id (stri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateApplePayHeaderRequest:
"""Implementation of the 'CreateApplePayHeaderRequest' model. The ApplePay header request Attributes: public_key_hash (string): SHA–256 hash, Base64 string codified ephemeral_public_key (string): X.509 encoded key bytes, Base64 encoded as a string transaction_id (string): Transact... | the_stack_v2_python_sparse | mundiapi/models/create_apple_pay_header_request.py | mundipagg/MundiAPI-PYTHON | train | 10 |
3d635d0a2deec98a68ddd3c67100abf97fa1c742 | [
"self.k = k\nself.nums = nums\nheapq.heapify(self.nums)\nwhile len(self.nums) > k:\n heapq.heappop(self.nums)",
"if len(self.nums) < self.k:\n heapq.heappush(self.nums, val)\nelif val > self.nums[0]:\n heapq.heapreplace(self.nums, val)\nreturn self.nums[0]"
] | <|body_start_0|>
self.k = k
self.nums = nums
heapq.heapify(self.nums)
while len(self.nums) > k:
heapq.heappop(self.nums)
<|end_body_0|>
<|body_start_1|>
if len(self.nums) < self.k:
heapq.heappush(self.nums, val)
elif val > self.nums[0]:
... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.nums = nums
heapq.heapify(... | stack_v2_sparse_classes_36k_train_014565 | 2,869 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020471 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | c615b40d65ada4914650e6192a1f7c1948abadce | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.nums = nums
heapq.heapify(self.nums)
while len(self.nums) > k:
heapq.heappop(self.nums)
def add(self, val):
""":type val: int :rtype: int"""
... | the_stack_v2_python_sparse | 703_Kth_Largest_Element_in_a_Stream.py | mxu007/leetcode | train | 0 | |
23400dc51cc2c2b438e4e7c396bda68e063069ff | [
"self.model = model\nself.device = device\ntry:\n target_module = _nested_getattr(model, target_module)\nexcept nn.modules.module.ModuleAttributeError:\n raise ValueError(f'`model` does not have a submodule {target_module}')\nself.extractor = ActivationExtractor()\ntarget_module.register_forward_hook(self.ext... | <|body_start_0|>
self.model = model
self.device = device
try:
target_module = _nested_getattr(model, target_module)
except nn.modules.module.ModuleAttributeError:
raise ValueError(f'`model` does not have a submodule {target_module}')
self.extractor = Activ... | ActivationOp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivationOp:
def __init__(self, model: nn.Module, target_module: str, device: int=None):
"""An Operation that runs a forward pass over each example in the dataset and stores model activations in a new column. Args: model (nn.Module): the torch model from which activations are extracted ... | stack_v2_sparse_classes_36k_train_014566 | 2,708 | permissive | [
{
"docstring": "An Operation that runs a forward pass over each example in the dataset and stores model activations in a new column. Args: model (nn.Module): the torch model from which activations are extracted target_module (str): the name of the submodule of `model` (i.e. an intermediate layer) that outputs t... | 2 | stack_v2_sparse_classes_30k_train_013665 | Implement the Python class `ActivationOp` described below.
Class description:
Implement the ActivationOp class.
Method signatures and docstrings:
- def __init__(self, model: nn.Module, target_module: str, device: int=None): An Operation that runs a forward pass over each example in the dataset and stores model activa... | Implement the Python class `ActivationOp` described below.
Class description:
Implement the ActivationOp class.
Method signatures and docstrings:
- def __init__(self, model: nn.Module, target_module: str, device: int=None): An Operation that runs a forward pass over each example in the dataset and stores model activa... | 8f844199b75420d2978f73b2535a2e3f83ca1836 | <|skeleton|>
class ActivationOp:
def __init__(self, model: nn.Module, target_module: str, device: int=None):
"""An Operation that runs a forward pass over each example in the dataset and stores model activations in a new column. Args: model (nn.Module): the torch model from which activations are extracted ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActivationOp:
def __init__(self, model: nn.Module, target_module: str, device: int=None):
"""An Operation that runs a forward pass over each example in the dataset and stores model activations in a new column. Args: model (nn.Module): the torch model from which activations are extracted target_module ... | the_stack_v2_python_sparse | robustnessgym/ops/activation.py | sushmit0109/robustness-gym | train | 0 | |
68e947a37066d7651e46c12d790c90490a96c602 | [
"if self.action in ['list']:\n permission_classes = [IsAuthenticated]\nelse:\n try:\n permission_classes = getattr(self, self.action).kwargs.get('permission_classes')\n except AttributeError:\n permission_classes = self.permission_classes\nreturn [permission() for permission in permission_cla... | <|body_start_0|>
if self.action in ['list']:
permission_classes = [IsAuthenticated]
else:
try:
permission_classes = getattr(self, self.action).kwargs.get('permission_classes')
except AttributeError:
permission_classes = self.permission_... | API endpoints for users. | UserViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserViewSet:
"""API endpoints for users."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions."""
<|body_0|>
def list(self, request, *args, *... | stack_v2_sparse_classes_36k_train_014567 | 6,127 | permissive | [
{
"docstring": "Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "This endpoint is intended to allow searc... | 4 | stack_v2_sparse_classes_30k_train_007168 | Implement the Python class `UserViewSet` described below.
Class description:
API endpoints for users.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions.
- ... | Implement the Python class `UserViewSet` described below.
Class description:
API endpoints for users.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions.
- ... | 22e4afa728a851bb4c2479fbb6f5944a75984b9b | <|skeleton|>
class UserViewSet:
"""API endpoints for users."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions."""
<|body_0|>
def list(self, request, *args, *... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserViewSet:
"""API endpoints for users."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions."""
if self.action in ['list']:
permission_classes = ... | the_stack_v2_python_sparse | src/backend/partaj/core/api/user.py | MTES-MCT/partaj | train | 4 |
9c65e59fb9e599af4d73de79e758e4c0032588e0 | [
"petition = self._petition(confirmation)\nmobile = petition.owner.relation_dict.get('mobile')\nif not mobile:\n raise ValueError('Missing mobile number')\nconfirmation.data['mobile'] = mobile\ndc_update(confirmation, expires=iso_now_offset(datetime.timedelta(minutes=5)))\nself.build_token(confirmation, petition)... | <|body_start_0|>
petition = self._petition(confirmation)
mobile = petition.owner.relation_dict.get('mobile')
if not mobile:
raise ValueError('Missing mobile number')
confirmation.data['mobile'] = mobile
dc_update(confirmation, expires=iso_now_offset(datetime.timedelta... | SMS confirmation handler for petitions | PetitionSMSHandler | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PetitionSMSHandler:
"""SMS confirmation handler for petitions"""
def _create(self, confirmation):
"""Send an SMS with the confirmation id"""
<|body_0|>
def _confirm(self, confirmation, petition=None):
"""Confirms the mobile number on the petition If the mobile nu... | stack_v2_sparse_classes_36k_train_014568 | 11,319 | permissive | [
{
"docstring": "Send an SMS with the confirmation id",
"name": "_create",
"signature": "def _create(self, confirmation)"
},
{
"docstring": "Confirms the mobile number on the petition If the mobile number on the owner relation matches the mobile number of this confirmation the mobile_trusted flag... | 2 | stack_v2_sparse_classes_30k_train_006212 | Implement the Python class `PetitionSMSHandler` described below.
Class description:
SMS confirmation handler for petitions
Method signatures and docstrings:
- def _create(self, confirmation): Send an SMS with the confirmation id
- def _confirm(self, confirmation, petition=None): Confirms the mobile number on the peti... | Implement the Python class `PetitionSMSHandler` described below.
Class description:
SMS confirmation handler for petitions
Method signatures and docstrings:
- def _create(self, confirmation): Send an SMS with the confirmation id
- def _confirm(self, confirmation, petition=None): Confirms the mobile number on the peti... | 680aadb1d9dd02e031b1902a4f9ef19440959465 | <|skeleton|>
class PetitionSMSHandler:
"""SMS confirmation handler for petitions"""
def _create(self, confirmation):
"""Send an SMS with the confirmation id"""
<|body_0|>
def _confirm(self, confirmation, petition=None):
"""Confirms the mobile number on the petition If the mobile nu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PetitionSMSHandler:
"""SMS confirmation handler for petitions"""
def _create(self, confirmation):
"""Send an SMS with the confirmation id"""
petition = self._petition(confirmation)
mobile = petition.owner.relation_dict.get('mobile')
if not mobile:
raise ValueEr... | the_stack_v2_python_sparse | src/iris/service/content/petition/confirmation.py | iris-dni/iris-service | train | 3 |
8a875df31b16c65dbb399c72c65a02b12049db5b | [
"if root is None:\n return True\nif abs(self.max_depth(root.left) - self.max_depth(root.right)) <= 1:\n return self.isBalanced(root.left) and self.isBalanced(root.right)\nelse:\n False",
"if root is None:\n return 0\nleft_length = self.max_depth(root.left)\nright_length = self.max_depth(root.right)\nr... | <|body_start_0|>
if root is None:
return True
if abs(self.max_depth(root.left) - self.max_depth(root.right)) <= 1:
return self.isBalanced(root.left) and self.isBalanced(root.right)
else:
False
<|end_body_0|>
<|body_start_1|>
if root is None:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def max_depth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
return True
... | stack_v2_sparse_classes_36k_train_014569 | 943 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isBalanced",
"signature": "def isBalanced(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "max_depth",
"signature": "def max_depth(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def max_depth(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def max_depth(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def isBalanced(self... | 772e047c4e1e9abf0d74b7dd539d684f216799b9 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def max_depth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
if root is None:
return True
if abs(self.max_depth(root.left) - self.max_depth(root.right)) <= 1:
return self.isBalanced(root.left) and self.isBalanced(root.right)
else:
... | the_stack_v2_python_sparse | code/BalancedBinaryTree.py | crl0636/Python | train | 1 | |
4763bebac4d86b4e61cbce3d297de04ebbcc7d01 | [
"self.domain_obj = domains.DiscreteNumericDomain([4, 5, 207.2, -2.3])\nself.points = [207.2, 5, -2.3]\nself.non_points = [5.4, -1.1, 'kky', None]",
"self.report('Testing if exception is raised for non numeric elements in a ' + 'discrete domain.')\nexception_raised = False\ntry:\n domains.DiscreteNumericDomain(... | <|body_start_0|>
self.domain_obj = domains.DiscreteNumericDomain([4, 5, 207.2, -2.3])
self.points = [207.2, 5, -2.3]
self.non_points = [5.4, -1.1, 'kky', None]
<|end_body_0|>
<|body_start_1|>
self.report('Testing if exception is raised for non numeric elements in a ' + 'discrete domain.... | Discrete Numeric Domain. | DiscreteNumericDomainTestCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscreteNumericDomainTestCase:
"""Discrete Numeric Domain."""
def _child_set_up(self):
"""Child set up."""
<|body_0|>
def test_non_numeric_discrete_domain(self):
"""Constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.domain_obj = d... | stack_v2_sparse_classes_36k_train_014570 | 5,755 | permissive | [
{
"docstring": "Child set up.",
"name": "_child_set_up",
"signature": "def _child_set_up(self)"
},
{
"docstring": "Constructor.",
"name": "test_non_numeric_discrete_domain",
"signature": "def test_non_numeric_discrete_domain(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012160 | Implement the Python class `DiscreteNumericDomainTestCase` described below.
Class description:
Discrete Numeric Domain.
Method signatures and docstrings:
- def _child_set_up(self): Child set up.
- def test_non_numeric_discrete_domain(self): Constructor. | Implement the Python class `DiscreteNumericDomainTestCase` described below.
Class description:
Discrete Numeric Domain.
Method signatures and docstrings:
- def _child_set_up(self): Child set up.
- def test_non_numeric_discrete_domain(self): Constructor.
<|skeleton|>
class DiscreteNumericDomainTestCase:
"""Discre... | 3eef7d30bcc2e56f2221a624bd8ec7f933f81e40 | <|skeleton|>
class DiscreteNumericDomainTestCase:
"""Discrete Numeric Domain."""
def _child_set_up(self):
"""Child set up."""
<|body_0|>
def test_non_numeric_discrete_domain(self):
"""Constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscreteNumericDomainTestCase:
"""Discrete Numeric Domain."""
def _child_set_up(self):
"""Child set up."""
self.domain_obj = domains.DiscreteNumericDomain([4, 5, 207.2, -2.3])
self.points = [207.2, 5, -2.3]
self.non_points = [5.4, -1.1, 'kky', None]
def test_non_numer... | the_stack_v2_python_sparse | dragonfly/exd/unittest_domains.py | dragonfly/dragonfly | train | 868 |
4f8119148d2f7aaf21781eaa0a6f462155d1f785 | [
"assert len(rpn_results_list) == len(batch_data_samples)\noutputs = unpack_gt_instances(batch_data_samples)\nbatch_gt_instances, batch_gt_instances_ignore, _ = outputs\nnum_imgs = len(batch_data_samples)\nsampling_results = []\nneg_label_weights = []\nfor i in range(num_imgs):\n rpn_results = rpn_results_list[i]... | <|body_start_0|>
assert len(rpn_results_list) == len(batch_data_samples)
outputs = unpack_gt_instances(batch_data_samples)
batch_gt_instances, batch_gt_instances_ignore, _ = outputs
num_imgs = len(batch_data_samples)
sampling_results = []
neg_label_weights = []
fo... | The RoI head for `Prime Sample Attention in Object Detection <https://arxiv.org/abs/1904.04821>`_. | PISARoIHead | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PISARoIHead:
"""The RoI head for `Prime Sample Attention in Object Detection <https://arxiv.org/abs/1904.04821>`_."""
def loss(self, x: Tuple[Tensor], rpn_results_list: InstanceList, batch_data_samples: List[DetDataSample]) -> dict:
"""Perform forward propagation and loss calculation... | stack_v2_sparse_classes_36k_train_014571 | 5,966 | permissive | [
{
"docstring": "Perform forward propagation and loss calculation of the detection roi on the features of the upstream network. Args: x (tuple[Tensor]): List of multi-level img features. rpn_results_list (list[:obj:`InstanceData`]): List of region proposals. batch_data_samples (list[:obj:`DetDataSample`]): The b... | 2 | null | Implement the Python class `PISARoIHead` described below.
Class description:
The RoI head for `Prime Sample Attention in Object Detection <https://arxiv.org/abs/1904.04821>`_.
Method signatures and docstrings:
- def loss(self, x: Tuple[Tensor], rpn_results_list: InstanceList, batch_data_samples: List[DetDataSample]) ... | Implement the Python class `PISARoIHead` described below.
Class description:
The RoI head for `Prime Sample Attention in Object Detection <https://arxiv.org/abs/1904.04821>`_.
Method signatures and docstrings:
- def loss(self, x: Tuple[Tensor], rpn_results_list: InstanceList, batch_data_samples: List[DetDataSample]) ... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class PISARoIHead:
"""The RoI head for `Prime Sample Attention in Object Detection <https://arxiv.org/abs/1904.04821>`_."""
def loss(self, x: Tuple[Tensor], rpn_results_list: InstanceList, batch_data_samples: List[DetDataSample]) -> dict:
"""Perform forward propagation and loss calculation... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PISARoIHead:
"""The RoI head for `Prime Sample Attention in Object Detection <https://arxiv.org/abs/1904.04821>`_."""
def loss(self, x: Tuple[Tensor], rpn_results_list: InstanceList, batch_data_samples: List[DetDataSample]) -> dict:
"""Perform forward propagation and loss calculation of the detec... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/roi_heads/pisa_roi_head.py | alldatacenter/alldata | train | 774 |
7f65df1744c71553f605286898749eb0e1510eae | [
"from torch.nn import ModuleList, AvgPool2d\nfrom pro_gan_pytorch.CustomLayers import DisGeneralConvBlock, ConDisFinalBlock\nsuper(ConditionalDiscriminator, self).__init__()\nassert feature_size != 0 and feature_size & feature_size - 1 == 0, 'latent size not a power of 2'\nif height >= 4:\n assert feature_size >... | <|body_start_0|>
from torch.nn import ModuleList, AvgPool2d
from pro_gan_pytorch.CustomLayers import DisGeneralConvBlock, ConDisFinalBlock
super(ConditionalDiscriminator, self).__init__()
assert feature_size != 0 and feature_size & feature_size - 1 == 0, 'latent size not a power of 2'
... | Discriminator of the GAN | ConditionalDiscriminator | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionalDiscriminator:
"""Discriminator of the GAN"""
def __init__(self, num_classes, height=7, feature_size=512, use_eql=True):
"""constructor for the class :param num_classes: number of classes for conditional discrimination :param height: total height of the discriminator (Must... | stack_v2_sparse_classes_36k_train_014572 | 10,883 | permissive | [
{
"docstring": "constructor for the class :param num_classes: number of classes for conditional discrimination :param height: total height of the discriminator (Must be equal to the Generator depth) :param feature_size: size of the deepest features extracted (Must be equal to Generator latent_size) :param use_e... | 2 | stack_v2_sparse_classes_30k_train_004570 | Implement the Python class `ConditionalDiscriminator` described below.
Class description:
Discriminator of the GAN
Method signatures and docstrings:
- def __init__(self, num_classes, height=7, feature_size=512, use_eql=True): constructor for the class :param num_classes: number of classes for conditional discriminati... | Implement the Python class `ConditionalDiscriminator` described below.
Class description:
Discriminator of the GAN
Method signatures and docstrings:
- def __init__(self, num_classes, height=7, feature_size=512, use_eql=True): constructor for the class :param num_classes: number of classes for conditional discriminati... | 30e7404924070f63b68e73f33f2b42ea8be22f65 | <|skeleton|>
class ConditionalDiscriminator:
"""Discriminator of the GAN"""
def __init__(self, num_classes, height=7, feature_size=512, use_eql=True):
"""constructor for the class :param num_classes: number of classes for conditional discrimination :param height: total height of the discriminator (Must... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionalDiscriminator:
"""Discriminator of the GAN"""
def __init__(self, num_classes, height=7, feature_size=512, use_eql=True):
"""constructor for the class :param num_classes: number of classes for conditional discrimination :param height: total height of the discriminator (Must be equal to ... | the_stack_v2_python_sparse | model/pggan/utils/Networks.py | TrendingTechnology/MTV-TSA | train | 0 |
32a68502dcef40c8efde77e22310f38b5fd2d2f6 | [
"data = self.get_json()\nif 'rfamp' not in data and 'lockloss' not in data:\n return self.error('Need to provide at least one of rfamp or lockloss measurement')\nwith self.Session() as session:\n event = session.scalars(EarthquakeEvent.select(session.user_or_token).where(EarthquakeEvent.event_id == earthquake... | <|body_start_0|>
data = self.get_json()
if 'rfamp' not in data and 'lockloss' not in data:
return self.error('Need to provide at least one of rfamp or lockloss measurement')
with self.Session() as session:
event = session.scalars(EarthquakeEvent.select(session.user_or_tok... | EarthquakeMeasurementHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EarthquakeMeasurementHandler:
async def post(self, earthquake_id, mma_detector_id):
"""--- description: Provide a ground velocity measurement for the earthquake. tags: - earthquakeevents parameters: - in: path name: earthquake_id required: true schema: type: string - in: path name: mma_d... | stack_v2_sparse_classes_36k_train_014573 | 28,208 | permissive | [
{
"docstring": "--- description: Provide a ground velocity measurement for the earthquake. tags: - earthquakeevents parameters: - in: path name: earthquake_id required: true schema: type: string - in: path name: mma_detector_id required: true schema: type: string responses: 200: content: application/json: schem... | 4 | stack_v2_sparse_classes_30k_train_014900 | Implement the Python class `EarthquakeMeasurementHandler` described below.
Class description:
Implement the EarthquakeMeasurementHandler class.
Method signatures and docstrings:
- async def post(self, earthquake_id, mma_detector_id): --- description: Provide a ground velocity measurement for the earthquake. tags: - e... | Implement the Python class `EarthquakeMeasurementHandler` described below.
Class description:
Implement the EarthquakeMeasurementHandler class.
Method signatures and docstrings:
- async def post(self, earthquake_id, mma_detector_id): --- description: Provide a ground velocity measurement for the earthquake. tags: - e... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class EarthquakeMeasurementHandler:
async def post(self, earthquake_id, mma_detector_id):
"""--- description: Provide a ground velocity measurement for the earthquake. tags: - earthquakeevents parameters: - in: path name: earthquake_id required: true schema: type: string - in: path name: mma_d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EarthquakeMeasurementHandler:
async def post(self, earthquake_id, mma_detector_id):
"""--- description: Provide a ground velocity measurement for the earthquake. tags: - earthquakeevents parameters: - in: path name: earthquake_id required: true schema: type: string - in: path name: mma_detector_id req... | the_stack_v2_python_sparse | skyportal/handlers/api/earthquake.py | skyportal/skyportal | train | 80 | |
f784e4744c05b9f94cc8f2e29442ffbc198dba39 | [
"user = User.objects.get(username=username)\nresponse = UserSchema().dump(user).data\nself.write(response)",
"self.verify_user_global_permission(USER_DELETE)\nuser = User.objects.get(username=username)\nuser.delete()\nself.set_status(204)",
"self.verify_user_global_permission(USER_UPDATE)\ntry:\n user_data =... | <|body_start_0|>
user = User.objects.get(username=username)
response = UserSchema().dump(user).data
self.write(response)
<|end_body_0|>
<|body_start_1|>
self.verify_user_global_permission(USER_DELETE)
user = User.objects.get(username=username)
user.delete()
self.... | UserAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAPI:
def get(self, username):
"""--- summary: Retrieve a specific User parameters: - name: username in: path required: true description: The username of the User type: string responses: 200: description: User with the given username schema: $ref: '#/definitions/User' 404: $ref: '#/de... | stack_v2_sparse_classes_36k_train_014574 | 6,509 | permissive | [
{
"docstring": "--- summary: Retrieve a specific User parameters: - name: username in: path required: true description: The username of the User type: string responses: 200: description: User with the given username schema: $ref: '#/definitions/User' 404: $ref: '#/definitions/404Error' 50x: $ref: '#/definitions... | 3 | stack_v2_sparse_classes_30k_train_013391 | Implement the Python class `UserAPI` described below.
Class description:
Implement the UserAPI class.
Method signatures and docstrings:
- def get(self, username): --- summary: Retrieve a specific User parameters: - name: username in: path required: true description: The username of the User type: string responses: 20... | Implement the Python class `UserAPI` described below.
Class description:
Implement the UserAPI class.
Method signatures and docstrings:
- def get(self, username): --- summary: Retrieve a specific User parameters: - name: username in: path required: true description: The username of the User type: string responses: 20... | a5fd2dcc2444409e243d3fdaa43d86695e5cb142 | <|skeleton|>
class UserAPI:
def get(self, username):
"""--- summary: Retrieve a specific User parameters: - name: username in: path required: true description: The username of the User type: string responses: 200: description: User with the given username schema: $ref: '#/definitions/User' 404: $ref: '#/de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserAPI:
def get(self, username):
"""--- summary: Retrieve a specific User parameters: - name: username in: path required: true description: The username of the User type: string responses: 200: description: User with the given username schema: $ref: '#/definitions/User' 404: $ref: '#/definitions/404E... | the_stack_v2_python_sparse | src/app/beer_garden/api/http/handlers/v1/user.py | beer-garden/beer-garden | train | 254 | |
8d0b9c75fa3fd01470a3c3cfa09c0bc22472084d | [
"dp = [float('inf')] * (amount + 1)\ndp[0] = 0\nfor coin in coins:\n for i in range(coin, amount + 1):\n dp[i] = min(dp[i], dp[i - coin] + 1)\nreturn dp[amount] if dp[amount] != float('inf') else -1",
"@functools.lru_cache(amount)\ndef memory_search(amount) -> int:\n if amount == 0:\n return 0... | <|body_start_0|>
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for i in range(coin, amount + 1):
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
<|end_body_0|>
<|body_start_1|>
@functools.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
"""动态规划(自底而上)"""
<|body_0|>
def coinChangeMemory(self, coins: List[int], amount: int) -> int:
"""记忆化回溯(自顶而上)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [float('inf')] * ... | stack_v2_sparse_classes_36k_train_014575 | 2,286 | no_license | [
{
"docstring": "动态规划(自底而上)",
"name": "coinChange",
"signature": "def coinChange(self, coins: List[int], amount: int) -> int"
},
{
"docstring": "记忆化回溯(自顶而上)",
"name": "coinChangeMemory",
"signature": "def coinChangeMemory(self, coins: List[int], amount: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_006063 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins: List[int], amount: int) -> int: 动态规划(自底而上)
- def coinChangeMemory(self, coins: List[int], amount: int) -> int: 记忆化回溯(自顶而上) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins: List[int], amount: int) -> int: 动态规划(自底而上)
- def coinChangeMemory(self, coins: List[int], amount: int) -> int: 记忆化回溯(自顶而上)
<|skeleton|>
class Solutio... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
"""动态规划(自底而上)"""
<|body_0|>
def coinChangeMemory(self, coins: List[int], amount: int) -> int:
"""记忆化回溯(自顶而上)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
"""动态规划(自底而上)"""
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for i in range(coin, amount + 1):
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[amount] if... | the_stack_v2_python_sparse | 322.零钱兑换/solution.py | QtTao/daily_leetcode | train | 0 | |
f7567c1aa357965ae781c491098554bbf05d8124 | [
"self.food = food[::-1]\nself.snake = collections.deque([[0, 0]])\nself.dim = [height, width]\nself.score = 0",
"dis = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}\nnext_pos = [self.snake[-1][0] + dis[direction][0], self.snake[-1][1] + dis[direction][1]]\nif not (0 <= next_pos[0] < self.dim[0] and 0 <= ... | <|body_start_0|>
self.food = food[::-1]
self.snake = collections.deque([[0, 0]])
self.dim = [height, width]
self.score = 0
<|end_body_0|>
<|body_start_1|>
dis = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}
next_pos = [self.snake[-1][0] + dis[direction][0], self... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_36k_train_014576 | 1,880 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]",
... | 2 | stack_v2_sparse_classes_30k_train_000057 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | c33559dc5e0bf6879bb3462ab65a9446a66d19f6 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :... | the_stack_v2_python_sparse | 353.py | htl1126/leetcode | train | 7 | |
9bf5fbee9c2ce1c7adabaf4b63c01471915272d4 | [
"if not s1 or not s2 or len(s1) != len(s2):\n return False\ns1, s2 = (list(s1), list(s2))\nreturn sort(s1) == sort(s2)",
"if not s1 or not s2 or len(s1) != len(s2):\n return False\ncounter1 = Counter(s1)\nfor ch in s2:\n if counter1.get(ch, -1) == -1:\n return False\n else:\n counter1[ch... | <|body_start_0|>
if not s1 or not s2 or len(s1) != len(s2):
return False
s1, s2 = (list(s1), list(s2))
return sort(s1) == sort(s2)
<|end_body_0|>
<|body_start_1|>
if not s1 or not s2 or len(s1) != len(s2):
return False
counter1 = Counter(s1)
for c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkPermutation_1(self, s1, s2):
"""sorting approach"""
<|body_0|>
def checkPermutation_2(self, s1, s2):
"""Counter approach (just as good as dict approach)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s1 or not s2 or len(s1... | stack_v2_sparse_classes_36k_train_014577 | 1,928 | no_license | [
{
"docstring": "sorting approach",
"name": "checkPermutation_1",
"signature": "def checkPermutation_1(self, s1, s2)"
},
{
"docstring": "Counter approach (just as good as dict approach)",
"name": "checkPermutation_2",
"signature": "def checkPermutation_2(self, s1, s2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkPermutation_1(self, s1, s2): sorting approach
- def checkPermutation_2(self, s1, s2): Counter approach (just as good as dict approach) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkPermutation_1(self, s1, s2): sorting approach
- def checkPermutation_2(self, s1, s2): Counter approach (just as good as dict approach)
<|skeleton|>
class Solution:
... | fb823ed86fb097f70d5b2e3173237ff828441310 | <|skeleton|>
class Solution:
def checkPermutation_1(self, s1, s2):
"""sorting approach"""
<|body_0|>
def checkPermutation_2(self, s1, s2):
"""Counter approach (just as good as dict approach)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def checkPermutation_1(self, s1, s2):
"""sorting approach"""
if not s1 or not s2 or len(s1) != len(s2):
return False
s1, s2 = (list(s1), list(s2))
return sort(s1) == sort(s2)
def checkPermutation_2(self, s1, s2):
"""Counter approach (just as g... | the_stack_v2_python_sparse | Archives/Cracking_Code_Interview/Old/01_Arrays_and_Strings/1.2_checkPermutation.py | jiinmoon/Algorithms_Review | train | 0 | |
0b4b9113fbb7bbf5084c3eb5939941f21c061014 | [
"self.source_vocab_size = source_vocab_size\nself.target_vocab_size = target_vocab_size\nself.source_vocab_name = 'vocab.source.%s' % self.source_vocab_size\nself.target_vocab_name = 'vocab.target.%s' % self.target_vocab_size\nif not isinstance(source_train_filenames, list):\n source_train_filenames = [source_tr... | <|body_start_0|>
self.source_vocab_size = source_vocab_size
self.target_vocab_size = target_vocab_size
self.source_vocab_name = 'vocab.source.%s' % self.source_vocab_size
self.target_vocab_name = 'vocab.target.%s' % self.target_vocab_size
if not isinstance(source_train_filenames,... | subword input | SubwordVocabProblem | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubwordVocabProblem:
"""subword input"""
def __init__(self, source_vocab_size=8000, target_vocab_size=8000, source_train_filenames='train.src', target_train_filenames='train.tgt', source_dev_filenames='dev.src', target_dev_filenames='dev.tgt', one_vocab=False):
""":param source_vocab... | stack_v2_sparse_classes_36k_train_014578 | 12,969 | permissive | [
{
"docstring": ":param source_vocab_size: :param target_vocab_size: :param source_train_filenames: :param target_train_filenames: :param source_dev_filenames: :param target_dev_filenames:",
"name": "__init__",
"signature": "def __init__(self, source_vocab_size=8000, target_vocab_size=8000, source_train_... | 3 | null | Implement the Python class `SubwordVocabProblem` described below.
Class description:
subword input
Method signatures and docstrings:
- def __init__(self, source_vocab_size=8000, target_vocab_size=8000, source_train_filenames='train.src', target_train_filenames='train.tgt', source_dev_filenames='dev.src', target_dev_f... | Implement the Python class `SubwordVocabProblem` described below.
Class description:
subword input
Method signatures and docstrings:
- def __init__(self, source_vocab_size=8000, target_vocab_size=8000, source_train_filenames='train.src', target_train_filenames='train.tgt', source_dev_filenames='dev.src', target_dev_f... | b8ec015fa9e16c0a879c619ee1f2aab8a393c7bd | <|skeleton|>
class SubwordVocabProblem:
"""subword input"""
def __init__(self, source_vocab_size=8000, target_vocab_size=8000, source_train_filenames='train.src', target_train_filenames='train.tgt', source_dev_filenames='dev.src', target_dev_filenames='dev.tgt', one_vocab=False):
""":param source_vocab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubwordVocabProblem:
"""subword input"""
def __init__(self, source_vocab_size=8000, target_vocab_size=8000, source_train_filenames='train.src', target_train_filenames='train.tgt', source_dev_filenames='dev.src', target_dev_filenames='dev.tgt', one_vocab=False):
""":param source_vocab_size: :param... | the_stack_v2_python_sparse | NLP/EMNLP2019-MAL/src/preprocess/problem.py | sserdoubleh/Research | train | 10 |
8d20f4a9c275b515ac04961662973dfb7330ef37 | [
"store = StoreModel.query.filter_by(id=store_id).first()\nif not store or not store:\n store_api.abort(404, \"Store {} doesn't exist\".format(store_id))\nreturn store.products",
"store = StoreModel.query.filter_by(id=store_id).first()\nif not store:\n store_api.abort(404, 'Store {} not found'.format(store_i... | <|body_start_0|>
store = StoreModel.query.filter_by(id=store_id).first()
if not store or not store:
store_api.abort(404, "Store {} doesn't exist".format(store_id))
return store.products
<|end_body_0|>
<|body_start_1|>
store = StoreModel.query.filter_by(id=store_id).first()
... | StoreStockList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoreStockList:
def get(self, store_id):
"""List all products given the store relation"""
<|body_0|>
def post(self, store_id):
"""Associate product to the given store with the intermediate table 'stocks'"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_014579 | 4,193 | no_license | [
{
"docstring": "List all products given the store relation",
"name": "get",
"signature": "def get(self, store_id)"
},
{
"docstring": "Associate product to the given store with the intermediate table 'stocks'",
"name": "post",
"signature": "def post(self, store_id)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000304 | Implement the Python class `StoreStockList` described below.
Class description:
Implement the StoreStockList class.
Method signatures and docstrings:
- def get(self, store_id): List all products given the store relation
- def post(self, store_id): Associate product to the given store with the intermediate table 'stoc... | Implement the Python class `StoreStockList` described below.
Class description:
Implement the StoreStockList class.
Method signatures and docstrings:
- def get(self, store_id): List all products given the store relation
- def post(self, store_id): Associate product to the given store with the intermediate table 'stoc... | f380164e92b70874042364ad4b5b20c5793d6921 | <|skeleton|>
class StoreStockList:
def get(self, store_id):
"""List all products given the store relation"""
<|body_0|>
def post(self, store_id):
"""Associate product to the given store with the intermediate table 'stocks'"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StoreStockList:
def get(self, store_id):
"""List all products given the store relation"""
store = StoreModel.query.filter_by(id=store_id).first()
if not store or not store:
store_api.abort(404, "Store {} doesn't exist".format(store_id))
return store.products
de... | the_stack_v2_python_sparse | project/app/main/controllers/store.py | ArielVilleda/docker-flask-postgres | train | 0 | |
56ef9c3dc71951a7aacce7117f10b88c0eb5c452 | [
"query_params = defaultdict(dict)\nquery_params['projection_type'] = projection_type.value\nquery_params['spin'] = spin.value\nif element:\n query_params['element'] = element.value\nif orbital:\n query_params['orbital'] = orbital.value\nif band_gap:\n query_params.update({'band_gap_min': band_gap[0], 'band... | <|body_start_0|>
query_params = defaultdict(dict)
query_params['projection_type'] = projection_type.value
query_params['spin'] = spin.value
if element:
query_params['element'] = element.value
if orbital:
query_params['orbital'] = orbital.value
if b... | DosRester | [
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-hdf5",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DosRester:
def search_dos_summary(self, projection_type: DOSProjectionType=DOSProjectionType.total, spin: Spin=Spin.up, element: Optional[Element]=None, orbital: Optional[OrbitalType]=None, band_gap: Optional[Tuple[float, float]]=None, efermi: Optional[Tuple[float, float]]=None, magnetic_orderin... | stack_v2_sparse_classes_36k_train_014580 | 14,062 | permissive | [
{
"docstring": "Query density of states summary data in electronic structure docs using a variety of search criteria. Arguments: projection_type (DOSProjectionType): Projection type of dos data. Default is the total dos. spin (Spin): Spin channel of dos data. If non spin-polarized data is stored in Spin.up elem... | 3 | stack_v2_sparse_classes_30k_train_013685 | Implement the Python class `DosRester` described below.
Class description:
Implement the DosRester class.
Method signatures and docstrings:
- def search_dos_summary(self, projection_type: DOSProjectionType=DOSProjectionType.total, spin: Spin=Spin.up, element: Optional[Element]=None, orbital: Optional[OrbitalType]=Non... | Implement the Python class `DosRester` described below.
Class description:
Implement the DosRester class.
Method signatures and docstrings:
- def search_dos_summary(self, projection_type: DOSProjectionType=DOSProjectionType.total, spin: Spin=Spin.up, element: Optional[Element]=None, orbital: Optional[OrbitalType]=Non... | e2dc71934baecd1a85621f7f7f6ff85f96cbd684 | <|skeleton|>
class DosRester:
def search_dos_summary(self, projection_type: DOSProjectionType=DOSProjectionType.total, spin: Spin=Spin.up, element: Optional[Element]=None, orbital: Optional[OrbitalType]=None, band_gap: Optional[Tuple[float, float]]=None, efermi: Optional[Tuple[float, float]]=None, magnetic_orderin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DosRester:
def search_dos_summary(self, projection_type: DOSProjectionType=DOSProjectionType.total, spin: Spin=Spin.up, element: Optional[Element]=None, orbital: Optional[OrbitalType]=None, band_gap: Optional[Tuple[float, float]]=None, efermi: Optional[Tuple[float, float]]=None, magnetic_ordering: Optional[Or... | the_stack_v2_python_sparse | src/mp_api/routes/electronic_structure/client.py | hhaoyan/api | train | 0 | |
cb7e9cc6efa898da9d2b1719b0de53383548af8d | [
"self.px = px\nself.py = py\nself.dpx = self.px.copy()\nself.dpxi = self.px.copy()",
"self.dpx = x - self.px\nre = 0.0\nfor i, v in enumerate(self.py):\n re += v * self.__li(i)\nreturn re",
"li_up = 1.0\nli_dn = 1.0\nself.dpxi = self.px[i] - self.px\nfor k, _ in enumerate(self.px):\n if k != i:\n l... | <|body_start_0|>
self.px = px
self.py = py
self.dpx = self.px.copy()
self.dpxi = self.px.copy()
<|end_body_0|>
<|body_start_1|>
self.dpx = x - self.px
re = 0.0
for i, v in enumerate(self.py):
re += v * self.__li(i)
return re
<|end_body_1|>
<|... | 多项式插值 使用Lagrange形式: fn(x) = sum(yi * li(x)), i = 0,1,2...,n li(x) = mul(x-xn) / mul(xi-xn), n = 0,1,2...i-1,i+1,...n | _PolynomialInterpolation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _PolynomialInterpolation:
"""多项式插值 使用Lagrange形式: fn(x) = sum(yi * li(x)), i = 0,1,2...,n li(x) = mul(x-xn) / mul(xi-xn), n = 0,1,2...i-1,i+1,...n"""
def __init__(self, px: np.ndarray, py: np.ndarray):
"""初始化 :Parameters: - px: 插值节点x值 - py: 插值节点y值"""
<|body_0|>
def __call... | stack_v2_sparse_classes_36k_train_014581 | 6,352 | no_license | [
{
"docstring": "初始化 :Parameters: - px: 插值节点x值 - py: 插值节点y值",
"name": "__init__",
"signature": "def __init__(self, px: np.ndarray, py: np.ndarray)"
},
{
"docstring": "函数调用重载 :Parameters: - x: 待求插值点 :Returns: 待求插值点的函数值",
"name": "__call__",
"signature": "def __call__(self, x: float)"
},
... | 3 | stack_v2_sparse_classes_30k_train_007488 | Implement the Python class `_PolynomialInterpolation` described below.
Class description:
多项式插值 使用Lagrange形式: fn(x) = sum(yi * li(x)), i = 0,1,2...,n li(x) = mul(x-xn) / mul(xi-xn), n = 0,1,2...i-1,i+1,...n
Method signatures and docstrings:
- def __init__(self, px: np.ndarray, py: np.ndarray): 初始化 :Parameters: - px: ... | Implement the Python class `_PolynomialInterpolation` described below.
Class description:
多项式插值 使用Lagrange形式: fn(x) = sum(yi * li(x)), i = 0,1,2...,n li(x) = mul(x-xn) / mul(xi-xn), n = 0,1,2...i-1,i+1,...n
Method signatures and docstrings:
- def __init__(self, px: np.ndarray, py: np.ndarray): 初始化 :Parameters: - px: ... | 5609be2f8317ae124b20050cbaaebe6a609ceef0 | <|skeleton|>
class _PolynomialInterpolation:
"""多项式插值 使用Lagrange形式: fn(x) = sum(yi * li(x)), i = 0,1,2...,n li(x) = mul(x-xn) / mul(xi-xn), n = 0,1,2...i-1,i+1,...n"""
def __init__(self, px: np.ndarray, py: np.ndarray):
"""初始化 :Parameters: - px: 插值节点x值 - py: 插值节点y值"""
<|body_0|>
def __call... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _PolynomialInterpolation:
"""多项式插值 使用Lagrange形式: fn(x) = sum(yi * li(x)), i = 0,1,2...,n li(x) = mul(x-xn) / mul(xi-xn), n = 0,1,2...i-1,i+1,...n"""
def __init__(self, px: np.ndarray, py: np.ndarray):
"""初始化 :Parameters: - px: 插值节点x值 - py: 插值节点y值"""
self.px = px
self.py = py
... | the_stack_v2_python_sparse | code/interpolation/interpolation.py | yehuohan/ln-misc | train | 1 |
c9a663c85bab3e44f79a3548d2329cc05a1271a0 | [
"filter_parser = reqparse.RequestParser(bundle_errors=True)\nfilter_parser.add_argument('last_pk', type=int, default=0, location='args')\nfilter_parser.add_argument('limit_num', type=int, default=20, location='args')\nfilter_parser_args = filter_parser.parse_args()\ndata = get_inventory_limit_rows_by_last_id(**filt... | <|body_start_0|>
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.add_argument('last_pk', type=int, default=0, location='args')
filter_parser.add_argument('limit_num', type=int, default=20, location='args')
filter_parser_args = filter_parser.parse_args()
d... | InventoryListResource | InventoryListResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InventoryListResource:
"""InventoryListResource"""
def get(self):
"""Example: curl http://0.0.0.0:5000/bearings/inventories curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2 :return:"""
<|body_0|>
def post(self):
"""Example: curl http://0.0.0.0:... | stack_v2_sparse_classes_36k_train_014582 | 5,543 | permissive | [
{
"docstring": "Example: curl http://0.0.0.0:5000/bearings/inventories curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2 :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Example: curl http://0.0.0.0:5000/bearings/inventories -H \"Content-Type: applicati... | 2 | stack_v2_sparse_classes_30k_train_016021 | Implement the Python class `InventoryListResource` described below.
Class description:
InventoryListResource
Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:5000/bearings/inventories curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2 :return:
- def post(self): Example:... | Implement the Python class `InventoryListResource` described below.
Class description:
InventoryListResource
Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:5000/bearings/inventories curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2 :return:
- def post(self): Example:... | 6ef54f3f7efbbaff6169e963dcf45ab25e11e593 | <|skeleton|>
class InventoryListResource:
"""InventoryListResource"""
def get(self):
"""Example: curl http://0.0.0.0:5000/bearings/inventories curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2 :return:"""
<|body_0|>
def post(self):
"""Example: curl http://0.0.0.0:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InventoryListResource:
"""InventoryListResource"""
def get(self):
"""Example: curl http://0.0.0.0:5000/bearings/inventories curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2 :return:"""
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.add_... | the_stack_v2_python_sparse | web_api/bearings/resources/inventory.py | zhanghe06/flask_restful | train | 2 |
fa34f75d24b39e1074f652928c5436c8fda5c4d9 | [
"assert 0.0 < pc < 1, 'Invalid crossover probability'\nassert 0.0 < pm < 1, 'Invalid mutation probability'\nassert len(population) % 2 == 0, 'Population size must be an even number'\nself.population = population\nself.tournament_size = tournament_size\nself.chromosome_length = chromosome_length\nself.pc = pc\nself.... | <|body_start_0|>
assert 0.0 < pc < 1, 'Invalid crossover probability'
assert 0.0 < pm < 1, 'Invalid mutation probability'
assert len(population) % 2 == 0, 'Population size must be an even number'
self.population = population
self.tournament_size = tournament_size
self.chr... | GAFP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GAFP:
def __init__(self, population, tournament_size=2, chromosome_length=10, pc=0.5, pm=0.1):
""":param population: Population where the selection operation occurs. :type population: list of labels :param tournament_size: Individual number in one tournament :type tournament_size: int :p... | stack_v2_sparse_classes_36k_train_014583 | 5,567 | no_license | [
{
"docstring": ":param population: Population where the selection operation occurs. :type population: list of labels :param tournament_size: Individual number in one tournament :type tournament_size: int :param chromosome_length: length of chromosome. :type chromosome_length: int :param pc: The probability of c... | 5 | stack_v2_sparse_classes_30k_train_018401 | Implement the Python class `GAFP` described below.
Class description:
Implement the GAFP class.
Method signatures and docstrings:
- def __init__(self, population, tournament_size=2, chromosome_length=10, pc=0.5, pm=0.1): :param population: Population where the selection operation occurs. :type population: list of lab... | Implement the Python class `GAFP` described below.
Class description:
Implement the GAFP class.
Method signatures and docstrings:
- def __init__(self, population, tournament_size=2, chromosome_length=10, pc=0.5, pm=0.1): :param population: Population where the selection operation occurs. :type population: list of lab... | baa26eebba6a2394d661cd4e13c1e7460e81d9dc | <|skeleton|>
class GAFP:
def __init__(self, population, tournament_size=2, chromosome_length=10, pc=0.5, pm=0.1):
""":param population: Population where the selection operation occurs. :type population: list of labels :param tournament_size: Individual number in one tournament :type tournament_size: int :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GAFP:
def __init__(self, population, tournament_size=2, chromosome_length=10, pc=0.5, pm=0.1):
""":param population: Population where the selection operation occurs. :type population: list of labels :param tournament_size: Individual number in one tournament :type tournament_size: int :param chromosom... | the_stack_v2_python_sparse | gafp.py | lunachy/ga | train | 1 | |
cb177c063f2ee4b9e2af39f62fab127f11bb8be2 | [
"state_dict = optimizer.state_dict()\nif self.coordinator.is_master():\n save_state_dict(state_dict, checkpoint, use_safetensors=False)",
"if os.path.isfile(checkpoint):\n logging.error(f'Provided path ({checkpoint}) should be a directory, not a file')\n return\nPath(checkpoint).mkdir(parents=True, exist... | <|body_start_0|>
state_dict = optimizer.state_dict()
if self.coordinator.is_master():
save_state_dict(state_dict, checkpoint, use_safetensors=False)
<|end_body_0|>
<|body_start_1|>
if os.path.isfile(checkpoint):
logging.error(f'Provided path ({checkpoint}) should be a di... | LowLevelZeroCheckpointIO | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LowLevelZeroCheckpointIO:
def save_unsharded_optimizer(self, optimizer: OptimizerWrapper, checkpoint: str, gather_dtensor: bool=False):
"""Save optimizer to checkpoint but only on master process. Args: optimizer (OptimizerWrapper): Optimizer to save state_dict checkpoint (str): Path to s... | stack_v2_sparse_classes_36k_train_014584 | 13,170 | permissive | [
{
"docstring": "Save optimizer to checkpoint but only on master process. Args: optimizer (OptimizerWrapper): Optimizer to save state_dict checkpoint (str): Path to save checkpoint gather_dtensor (bool): Whether to gather_dtensor, not used",
"name": "save_unsharded_optimizer",
"signature": "def save_unsh... | 3 | null | Implement the Python class `LowLevelZeroCheckpointIO` described below.
Class description:
Implement the LowLevelZeroCheckpointIO class.
Method signatures and docstrings:
- def save_unsharded_optimizer(self, optimizer: OptimizerWrapper, checkpoint: str, gather_dtensor: bool=False): Save optimizer to checkpoint but onl... | Implement the Python class `LowLevelZeroCheckpointIO` described below.
Class description:
Implement the LowLevelZeroCheckpointIO class.
Method signatures and docstrings:
- def save_unsharded_optimizer(self, optimizer: OptimizerWrapper, checkpoint: str, gather_dtensor: bool=False): Save optimizer to checkpoint but onl... | c7b60f75470f067d1342705708810a660eabd684 | <|skeleton|>
class LowLevelZeroCheckpointIO:
def save_unsharded_optimizer(self, optimizer: OptimizerWrapper, checkpoint: str, gather_dtensor: bool=False):
"""Save optimizer to checkpoint but only on master process. Args: optimizer (OptimizerWrapper): Optimizer to save state_dict checkpoint (str): Path to s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LowLevelZeroCheckpointIO:
def save_unsharded_optimizer(self, optimizer: OptimizerWrapper, checkpoint: str, gather_dtensor: bool=False):
"""Save optimizer to checkpoint but only on master process. Args: optimizer (OptimizerWrapper): Optimizer to save state_dict checkpoint (str): Path to save checkpoint... | the_stack_v2_python_sparse | colossalai/booster/plugin/low_level_zero_plugin.py | hpcaitech/ColossalAI | train | 32,044 | |
c37d0b40dd99513f41e5b0a0d8e4c43a8f4ed66a | [
"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!')"
] | <|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... | A set of methods for managing Redis backups. | BackupServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackupServiceServicer:
"""A set of methods for managing Redis backups."""
def Get(self, request, context):
"""Returns the specified Redis backup. To get the list of available Redis backups, make a [List] request."""
<|body_0|>
def List(self, request, context):
""... | stack_v2_sparse_classes_36k_train_014585 | 4,839 | permissive | [
{
"docstring": "Returns the specified Redis backup. To get the list of available Redis backups, make a [List] request.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Retrieves the list of Redis backups available for the specified folder.",
"name": "List",
... | 2 | null | Implement the Python class `BackupServiceServicer` described below.
Class description:
A set of methods for managing Redis backups.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified Redis backup. To get the list of available Redis backups, make a [List] request.
- def List(sel... | Implement the Python class `BackupServiceServicer` described below.
Class description:
A set of methods for managing Redis backups.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified Redis backup. To get the list of available Redis backups, make a [List] request.
- def List(sel... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class BackupServiceServicer:
"""A set of methods for managing Redis backups."""
def Get(self, request, context):
"""Returns the specified Redis backup. To get the list of available Redis backups, make a [List] request."""
<|body_0|>
def List(self, request, context):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BackupServiceServicer:
"""A set of methods for managing Redis backups."""
def Get(self, request, context):
"""Returns the specified Redis backup. To get the list of available Redis backups, make a [List] request."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_detai... | the_stack_v2_python_sparse | yandex/cloud/mdb/redis/v1/backup_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
808104b228bf51b7a09c669cb447770d18b3ea0a | [
"features = self.get_features(item)\np = 1\nfor feature in features:\n p *= self.weighted_prob(feature, category, self.f_prob)\nreturn p",
"cat_prob = self.cat_count(category) / self.total_count()\ndoc_prob = self.doc_prob(item, category)\nreturn doc_prob * cat_prob",
"probs = {}\nmax = 0.0\nfor category in ... | <|body_start_0|>
features = self.get_features(item)
p = 1
for feature in features:
p *= self.weighted_prob(feature, category, self.f_prob)
return p
<|end_body_0|>
<|body_start_1|>
cat_prob = self.cat_count(category) / self.total_count()
doc_prob = self.doc_pr... | NaiveBayes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NaiveBayes:
def doc_prob(self, item, category):
"""Extracts all the features from a supplied item and then multiplies all of their probabilities (belonging to a category) into one."""
<|body_0|>
def prob(self, item, category):
"""First, get the ratio of the supplied ... | stack_v2_sparse_classes_36k_train_014586 | 10,462 | no_license | [
{
"docstring": "Extracts all the features from a supplied item and then multiplies all of their probabilities (belonging to a category) into one.",
"name": "doc_prob",
"signature": "def doc_prob(self, item, category)"
},
{
"docstring": "First, get the ratio of the supplied category and total cat... | 3 | stack_v2_sparse_classes_30k_train_000059 | Implement the Python class `NaiveBayes` described below.
Class description:
Implement the NaiveBayes class.
Method signatures and docstrings:
- def doc_prob(self, item, category): Extracts all the features from a supplied item and then multiplies all of their probabilities (belonging to a category) into one.
- def pr... | Implement the Python class `NaiveBayes` described below.
Class description:
Implement the NaiveBayes class.
Method signatures and docstrings:
- def doc_prob(self, item, category): Extracts all the features from a supplied item and then multiplies all of their probabilities (belonging to a category) into one.
- def pr... | d13a7e692e11eb1b53643e01329faf52c5cd6586 | <|skeleton|>
class NaiveBayes:
def doc_prob(self, item, category):
"""Extracts all the features from a supplied item and then multiplies all of their probabilities (belonging to a category) into one."""
<|body_0|>
def prob(self, item, category):
"""First, get the ratio of the supplied ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NaiveBayes:
def doc_prob(self, item, category):
"""Extracts all the features from a supplied item and then multiplies all of their probabilities (belonging to a category) into one."""
features = self.get_features(item)
p = 1
for feature in features:
p *= self.weight... | the_stack_v2_python_sparse | chap6/docclass.py | nholtappels/collective_intelligence_examples | train | 0 | |
84e4a57279bf1764679d997f5d5595d82e331526 | [
"result = 1\ndp = [1] * len(nums)\nfor i in range(len(nums)):\n for j in range(i):\n if nums[i] > nums[j]:\n dp[i] = max(dp[i], dp[j] + 1)\n result = max(result, dp[i])\nreturn result",
"tails = []\nfor x in nums:\n if len(tails) == 0 or tails[-1] < x:\n tails.append(x)\n else... | <|body_start_0|>
result = 1
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
result = max(result, dp[i])
return result
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = 1
dp = [1] * len(nums)
... | stack_v2_sparse_classes_36k_train_014587 | 2,268 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "_lengthOfLIS",
"signature": "def _lengthOfLIS(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def _lengthOfL... | b7e3b02c50d54515e584cb18dff83109224245d0 | <|skeleton|>
class Solution:
def _lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
result = 1
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
result =... | the_stack_v2_python_sparse | Python/LeetCode/300_length_of_LIS.py | shouliang/Development | train | 0 | |
1a4a7e9e7ceab433b01cae7c2155beaa9aaf4ae7 | [
"if obj.objectName() == 'MainWindowWindow':\n return returnValue\nif obj == self.last:\n return returnValue\nelse:\n self.last = obj\nif isinstance(obj, PyQt5.QtWidgets.QTabBar):\n self.log.warning(f'Click Tab : [{obj.tabText(obj.currentIndex())}]')\nelif isinstance(obj, PyQt5.QtWidgets.QComboBox):\... | <|body_start_0|>
if obj.objectName() == 'MainWindowWindow':
return returnValue
if obj == self.last:
return returnValue
else:
self.last = obj
if isinstance(obj, PyQt5.QtWidgets.QTabBar):
self.log.warning(f'Click Tab : [{obj.tabText(obj.c... | MyApp implements a custom notify handler to log errors, when C++ classes and python wrapper in PyQt5 environment mismatch. mostly this relates to the situation when a C++ object is already deleted, but the python wrapper still exists. so far I know that's the only chance to log this issues. in addition it writes mouse ... | MyApp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyApp:
"""MyApp implements a custom notify handler to log errors, when C++ classes and python wrapper in PyQt5 environment mismatch. mostly this relates to the situation when a C++ object is already deleted, but the python wrapper still exists. so far I know that's the only chance to log this iss... | stack_v2_sparse_classes_36k_train_014588 | 16,165 | permissive | [
{
"docstring": ":param obj: :param returnValue: :return:",
"name": "handleButtons",
"signature": "def handleButtons(self, obj, returnValue)"
},
{
"docstring": ":param obj: :param event: :return:",
"name": "notify",
"signature": "def notify(self, obj, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017433 | Implement the Python class `MyApp` described below.
Class description:
MyApp implements a custom notify handler to log errors, when C++ classes and python wrapper in PyQt5 environment mismatch. mostly this relates to the situation when a C++ object is already deleted, but the python wrapper still exists. so far I know... | Implement the Python class `MyApp` described below.
Class description:
MyApp implements a custom notify handler to log errors, when C++ classes and python wrapper in PyQt5 environment mismatch. mostly this relates to the situation when a C++ object is already deleted, but the python wrapper still exists. so far I know... | c38c46050989a463f8e65b532b55c793f1ed9d15 | <|skeleton|>
class MyApp:
"""MyApp implements a custom notify handler to log errors, when C++ classes and python wrapper in PyQt5 environment mismatch. mostly this relates to the situation when a C++ object is already deleted, but the python wrapper still exists. so far I know that's the only chance to log this iss... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyApp:
"""MyApp implements a custom notify handler to log errors, when C++ classes and python wrapper in PyQt5 environment mismatch. mostly this relates to the situation when a C++ object is already deleted, but the python wrapper still exists. so far I know that's the only chance to log this issues. in addit... | the_stack_v2_python_sparse | mw4/loader.py | nickym998/MountWizzard4 | train | 0 |
fea4fa13cc7504695eb80870df399e2609bf7c82 | [
"if gradeid:\n params = {'vcode': vcode, 'action': 'list_classes_by_schoolgrade', 'gradeid': gradeid}\nelse:\n params = {'vcode': vcode, 'action': 'list_classes_by_schoolgrade'}\nrespDict = requests.get(URL, params=params).json()\npprint(respDict)\nreturn respDict",
"payload = {'vcode': vcode, 'action': 'ad... | <|body_start_0|>
if gradeid:
params = {'vcode': vcode, 'action': 'list_classes_by_schoolgrade', 'gradeid': gradeid}
else:
params = {'vcode': vcode, 'action': 'list_classes_by_schoolgrade'}
respDict = requests.get(URL, params=params).json()
pprint(respDict)
... | ClassManageResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassManageResource:
def list_classes_by_schoolgrade(self, gradeid=None):
"""根据年级id列出班级,若年级id未传入,则列出所有 :param gradeid:年级id :return: 返回dict形式的数据"""
<|body_0|>
def add_class(self, gradeid, name, studentlimit):
"""添加班级 :param gradeid:年级id :param name: 班级名次 :param studen... | stack_v2_sparse_classes_36k_train_014589 | 2,735 | no_license | [
{
"docstring": "根据年级id列出班级,若年级id未传入,则列出所有 :param gradeid:年级id :return: 返回dict形式的数据",
"name": "list_classes_by_schoolgrade",
"signature": "def list_classes_by_schoolgrade(self, gradeid=None)"
},
{
"docstring": "添加班级 :param gradeid:年级id :param name: 班级名次 :param studentlimit: 班级人数限制 :return: 返回dict... | 5 | null | Implement the Python class `ClassManageResource` described below.
Class description:
Implement the ClassManageResource class.
Method signatures and docstrings:
- def list_classes_by_schoolgrade(self, gradeid=None): 根据年级id列出班级,若年级id未传入,则列出所有 :param gradeid:年级id :return: 返回dict形式的数据
- def add_class(self, gradeid, name,... | Implement the Python class `ClassManageResource` described below.
Class description:
Implement the ClassManageResource class.
Method signatures and docstrings:
- def list_classes_by_schoolgrade(self, gradeid=None): 根据年级id列出班级,若年级id未传入,则列出所有 :param gradeid:年级id :return: 返回dict形式的数据
- def add_class(self, gradeid, name,... | 2c7049f0a70e2de922effc23d03e8b8fd995c67f | <|skeleton|>
class ClassManageResource:
def list_classes_by_schoolgrade(self, gradeid=None):
"""根据年级id列出班级,若年级id未传入,则列出所有 :param gradeid:年级id :return: 返回dict形式的数据"""
<|body_0|>
def add_class(self, gradeid, name, studentlimit):
"""添加班级 :param gradeid:年级id :param name: 班级名次 :param studen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassManageResource:
def list_classes_by_schoolgrade(self, gradeid=None):
"""根据年级id列出班级,若年级id未传入,则列出所有 :param gradeid:年级id :return: 返回dict形式的数据"""
if gradeid:
params = {'vcode': vcode, 'action': 'list_classes_by_schoolgrade', 'gradeid': gradeid}
else:
params = {... | the_stack_v2_python_sparse | ActualCombat/pylib/ClassManageResource.py | tangshenhong/PycharmProjects | train | 0 | |
b7eb5cf049fa9f88314bb40b397f22956dfee2c4 | [
"self.Wf = np.random.normal(size=(i + h, h))\nself.Wu = np.random.normal(size=(i + h, h))\nself.Wc = np.random.normal(size=(i + h, h))\nself.Wo = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bf = np.zeros((1, h))\nself.bu = np.zeros((1, h))\nself.bc = np.zeros((1, h))\nself.bo = ... | <|body_start_0|>
self.Wf = np.random.normal(size=(i + h, h))
self.Wu = np.random.normal(size=(i + h, h))
self.Wc = np.random.normal(size=(i + h, h))
self.Wo = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bf = np.zeros((1, h))
self... | LSTM cell | LSTMCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMCell:
"""LSTM cell"""
def __init__(self, i, h, o):
"""* The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros"""
<|body_0|>
def forward(self, h_prev, c_prev, x_t):
"""Returns: h_next, c_next, y"""
... | stack_v2_sparse_classes_36k_train_014590 | 1,441 | no_license | [
{
"docstring": "* The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "Returns: h_next, c_next, y",
"name": "forward",
"signature": "def forward... | 2 | stack_v2_sparse_classes_30k_train_019333 | Implement the Python class `LSTMCell` described below.
Class description:
LSTM cell
Method signatures and docstrings:
- def __init__(self, i, h, o): * The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros
- def forward(self, h_prev, c_prev, x_t): Returns: h_n... | Implement the Python class `LSTMCell` described below.
Class description:
LSTM cell
Method signatures and docstrings:
- def __init__(self, i, h, o): * The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros
- def forward(self, h_prev, c_prev, x_t): Returns: h_n... | 9ff78818c132d1233c11b8fc8fd469878b23b14e | <|skeleton|>
class LSTMCell:
"""LSTM cell"""
def __init__(self, i, h, o):
"""* The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros"""
<|body_0|>
def forward(self, h_prev, c_prev, x_t):
"""Returns: h_next, c_next, y"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSTMCell:
"""LSTM cell"""
def __init__(self, i, h, o):
"""* The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros"""
self.Wf = np.random.normal(size=(i + h, h))
self.Wu = np.random.normal(size=(i + h, h))
self.Wc =... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/3-lstm_cell.py | Nzparra/holbertonschool-machine_learning | train | 0 |
90c3fe5de5e014f36260d94e850e5cf3a5b679c5 | [
"producer = Producer()\nrecord_metadata = producer.send_message(TOPIC, URL, REGEX, TEST_DATA).get(timeout=5)\nassert record_metadata.topic == TOPIC, 'Stats should be sent properly to topic {}.'.format(TOPIC)",
"producer = Producer()\nwith pytest.raises(KafkaTimeoutError):\n producer.send_message('topic_not_exi... | <|body_start_0|>
producer = Producer()
record_metadata = producer.send_message(TOPIC, URL, REGEX, TEST_DATA).get(timeout=5)
assert record_metadata.topic == TOPIC, 'Stats should be sent properly to topic {}.'.format(TOPIC)
<|end_body_0|>
<|body_start_1|>
producer = Producer()
wit... | This is to Producer. | TestProducer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProducer:
"""This is to Producer."""
def test_send_message(self):
"""Verify producer should send message properly."""
<|body_0|>
def test_send_message_to_non_existing_topic(self):
"""Verify exception should occur is producer tries to send message to non exist... | stack_v2_sparse_classes_36k_train_014591 | 2,132 | no_license | [
{
"docstring": "Verify producer should send message properly.",
"name": "test_send_message",
"signature": "def test_send_message(self)"
},
{
"docstring": "Verify exception should occur is producer tries to send message to non existing topic.",
"name": "test_send_message_to_non_existing_topic... | 3 | stack_v2_sparse_classes_30k_train_013632 | Implement the Python class `TestProducer` described below.
Class description:
This is to Producer.
Method signatures and docstrings:
- def test_send_message(self): Verify producer should send message properly.
- def test_send_message_to_non_existing_topic(self): Verify exception should occur is producer tries to send... | Implement the Python class `TestProducer` described below.
Class description:
This is to Producer.
Method signatures and docstrings:
- def test_send_message(self): Verify producer should send message properly.
- def test_send_message_to_non_existing_topic(self): Verify exception should occur is producer tries to send... | 4f86f5695b853d4a7871e7b90acf36f5bc6dd21f | <|skeleton|>
class TestProducer:
"""This is to Producer."""
def test_send_message(self):
"""Verify producer should send message properly."""
<|body_0|>
def test_send_message_to_non_existing_topic(self):
"""Verify exception should occur is producer tries to send message to non exist... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestProducer:
"""This is to Producer."""
def test_send_message(self):
"""Verify producer should send message properly."""
producer = Producer()
record_metadata = producer.send_message(TOPIC, URL, REGEX, TEST_DATA).get(timeout=5)
assert record_metadata.topic == TOPIC, 'Stat... | the_stack_v2_python_sparse | testcases/test_producer.py | anujkumar21/monitoring | train | 0 |
44d0167e5b9b26927607cf7af40f95f2f0ed7b84 | [
"if host.name:\n osh = ObjectStateHolder(self.CIT)\n osh.setStringAttribute('name', host.name)\n if host.fqdn:\n osh.setStringAttribute('primary_dns_name', host.fqdn)\nelse:\n osh = self.build_complete_host(str(host.ips[0]))\nreturn osh",
"if not (key and key.strip()):\n raise ValueError('Ho... | <|body_start_0|>
if host.name:
osh = ObjectStateHolder(self.CIT)
osh.setStringAttribute('name', host.name)
if host.fqdn:
osh.setStringAttribute('primary_dns_name', host.fqdn)
else:
osh = self.build_complete_host(str(host.ips[0]))
re... | Builder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Builder:
def build_host(self, host):
"""@types: hana_host.Host -> ObjectStateHolder"""
<|body_0|>
def build_complete_host(self, key):
"""Build generic host @types: str -> ObjectSateHolder @raise ValueError: Host key is not specified"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_014592 | 3,773 | no_license | [
{
"docstring": "@types: hana_host.Host -> ObjectStateHolder",
"name": "build_host",
"signature": "def build_host(self, host)"
},
{
"docstring": "Build generic host @types: str -> ObjectSateHolder @raise ValueError: Host key is not specified",
"name": "build_complete_host",
"signature": "... | 2 | null | Implement the Python class `Builder` described below.
Class description:
Implement the Builder class.
Method signatures and docstrings:
- def build_host(self, host): @types: hana_host.Host -> ObjectStateHolder
- def build_complete_host(self, key): Build generic host @types: str -> ObjectSateHolder @raise ValueError: ... | Implement the Python class `Builder` described below.
Class description:
Implement the Builder class.
Method signatures and docstrings:
- def build_host(self, host): @types: hana_host.Host -> ObjectStateHolder
- def build_complete_host(self, key): Build generic host @types: str -> ObjectSateHolder @raise ValueError: ... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class Builder:
def build_host(self, host):
"""@types: hana_host.Host -> ObjectStateHolder"""
<|body_0|>
def build_complete_host(self, key):
"""Build generic host @types: str -> ObjectSateHolder @raise ValueError: Host key is not specified"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Builder:
def build_host(self, host):
"""@types: hana_host.Host -> ObjectStateHolder"""
if host.name:
osh = ObjectStateHolder(self.CIT)
osh.setStringAttribute('name', host.name)
if host.fqdn:
osh.setStringAttribute('primary_dns_name', host.fqd... | the_stack_v2_python_sparse | reference/ucmdb/discovery/hana_host.py | madmonkyang/cda-record | train | 0 | |
647f2382ae58223e1f2beef5ea52b91fe7bc945e | [
"google_mobility_values, google_mobility_days = get_mobility_data(country_iso3, region, BASE_DATETIME, google_mobility_locations)\nmixing = update_mixing_data(mixing, npi_effectiveness_params, google_mobility_values, google_mobility_days, is_periodic_intervention, periodic_int_params, periodic_end_time)\nmixing_loc... | <|body_start_0|>
google_mobility_values, google_mobility_days = get_mobility_data(country_iso3, region, BASE_DATETIME, google_mobility_locations)
mixing = update_mixing_data(mixing, npi_effectiveness_params, google_mobility_values, google_mobility_days, is_periodic_intervention, periodic_int_params, per... | LocationMixingAdjustment | [
"BSD-2-Clause-Views"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocationMixingAdjustment:
def __init__(self, country_iso3: str, region: str, mixing: dict, npi_effectiveness_params: dict, google_mobility_locations: dict, is_periodic_intervention: bool, periodic_int_params: dict, periodic_end_time: float, microdistancing_params: dict):
"""Build the tim... | stack_v2_sparse_classes_36k_train_014593 | 9,413 | permissive | [
{
"docstring": "Build the time variant location adjustment functions",
"name": "__init__",
"signature": "def __init__(self, country_iso3: str, region: str, mixing: dict, npi_effectiveness_params: dict, google_mobility_locations: dict, is_periodic_intervention: bool, periodic_int_params: dict, periodic_e... | 2 | null | Implement the Python class `LocationMixingAdjustment` described below.
Class description:
Implement the LocationMixingAdjustment class.
Method signatures and docstrings:
- def __init__(self, country_iso3: str, region: str, mixing: dict, npi_effectiveness_params: dict, google_mobility_locations: dict, is_periodic_inte... | Implement the Python class `LocationMixingAdjustment` described below.
Class description:
Implement the LocationMixingAdjustment class.
Method signatures and docstrings:
- def __init__(self, country_iso3: str, region: str, mixing: dict, npi_effectiveness_params: dict, google_mobility_locations: dict, is_periodic_inte... | 0cbd006d1f15da414d02eed44e48bb5c06f0802e | <|skeleton|>
class LocationMixingAdjustment:
def __init__(self, country_iso3: str, region: str, mixing: dict, npi_effectiveness_params: dict, google_mobility_locations: dict, is_periodic_intervention: bool, periodic_int_params: dict, periodic_end_time: float, microdistancing_params: dict):
"""Build the tim... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocationMixingAdjustment:
def __init__(self, country_iso3: str, region: str, mixing: dict, npi_effectiveness_params: dict, google_mobility_locations: dict, is_periodic_intervention: bool, periodic_int_params: dict, periodic_end_time: float, microdistancing_params: dict):
"""Build the time variant loca... | the_stack_v2_python_sparse | apps/covid_19/preprocess/mixing_matrix/adjust_location.py | malanchak/AuTuMN | train | 0 | |
e3972c50452dfb4c9cd4e35861947da5f0523fcd | [
"try:\n api_key = APIKey.query.filter(APIKey.id == uuid.UUID(api_key_id)).one()\nexcept NoResultFound:\n raise NotFound(\"API key doesn't exist\")\nif not g.auth_user.has_rights(Capabilities.manage_users) and g.auth_user.id != api_key.user_id:\n raise NotFound(\"API key doesn't exist\")\nreturn APIKeyToken... | <|body_start_0|>
try:
api_key = APIKey.query.filter(APIKey.id == uuid.UUID(api_key_id)).one()
except NoResultFound:
raise NotFound("API key doesn't exist")
if not g.auth_user.has_rights(Capabilities.manage_users) and g.auth_user.id != api_key.user_id:
raise No... | APIKeyResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIKeyResource:
def get(self, api_key_id):
"""--- summary: Get token for API key description: | Returns token for provided API key identifier. Requires `manage_users` capability if current user doesn't own the key. security: - bearerAuth: [] tags: - api_key parameters: - in: path name: a... | stack_v2_sparse_classes_36k_train_014594 | 4,871 | no_license | [
{
"docstring": "--- summary: Get token for API key description: | Returns token for provided API key identifier. Requires `manage_users` capability if current user doesn't own the key. security: - bearerAuth: [] tags: - api_key parameters: - in: path name: api_key_id schema: type: string description: API key id... | 2 | null | Implement the Python class `APIKeyResource` described below.
Class description:
Implement the APIKeyResource class.
Method signatures and docstrings:
- def get(self, api_key_id): --- summary: Get token for API key description: | Returns token for provided API key identifier. Requires `manage_users` capability if curr... | Implement the Python class `APIKeyResource` described below.
Class description:
Implement the APIKeyResource class.
Method signatures and docstrings:
- def get(self, api_key_id): --- summary: Get token for API key description: | Returns token for provided API key identifier. Requires `manage_users` capability if curr... | f18f56789d2b7db8fdb7e172113a9918b4b72658 | <|skeleton|>
class APIKeyResource:
def get(self, api_key_id):
"""--- summary: Get token for API key description: | Returns token for provided API key identifier. Requires `manage_users` capability if current user doesn't own the key. security: - bearerAuth: [] tags: - api_key parameters: - in: path name: a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class APIKeyResource:
def get(self, api_key_id):
"""--- summary: Get token for API key description: | Returns token for provided API key identifier. Requires `manage_users` capability if current user doesn't own the key. security: - bearerAuth: [] tags: - api_key parameters: - in: path name: api_key_id sche... | the_stack_v2_python_sparse | resources/api_key.py | dskwhitehat/malwarecage | train | 0 | |
019dc7c2b6cec28132611a2138cf657bb3c27ca1 | [
"tf.config.run_functions_eagerly(False)\nname = f'DynaPPO_Agent_{num_experiment_rounds}_{num_model_rounds}'\nif model is None:\n model = DynaPPOEnsemble(len(starting_sequence), alphabet)\n model.train(s_utils.generate_random_sequences(len(starting_sequence), 10, alphabet), [0] * 10)\nsuper().__init__(model, n... | <|body_start_0|>
tf.config.run_functions_eagerly(False)
name = f'DynaPPO_Agent_{num_experiment_rounds}_{num_model_rounds}'
if model is None:
model = DynaPPOEnsemble(len(starting_sequence), alphabet)
model.train(s_utils.generate_random_sequences(len(starting_sequence), 10,... | Explorer which implements DynaPPO. This RL-based sequence design algorithm works as follows: for r in rounds: train_policy(experimental_data_rewards[r]) for m in model_based_rounds: train_policy(model_fitness_rewards[m]) An episode for the agent begins with an empty sequence, and at each timestep, one new residue is ge... | DynaPPO | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynaPPO:
"""Explorer which implements DynaPPO. This RL-based sequence design algorithm works as follows: for r in rounds: train_policy(experimental_data_rewards[r]) for m in model_based_rounds: train_policy(model_fitness_rewards[m]) An episode for the agent begins with an empty sequence, and at e... | stack_v2_sparse_classes_36k_train_014595 | 19,790 | permissive | [
{
"docstring": "Args: num_experiment_rounds: Number of experiment-based rounds to run. This is by default set to 10, the same number of sequence proposal of rounds run. num_model_rounds: Number of model-based rounds to run. env_batch_size: Number of epsisodes to batch together and run in parallel.",
"name":... | 3 | stack_v2_sparse_classes_30k_train_006695 | Implement the Python class `DynaPPO` described below.
Class description:
Explorer which implements DynaPPO. This RL-based sequence design algorithm works as follows: for r in rounds: train_policy(experimental_data_rewards[r]) for m in model_based_rounds: train_policy(model_fitness_rewards[m]) An episode for the agent ... | Implement the Python class `DynaPPO` described below.
Class description:
Explorer which implements DynaPPO. This RL-based sequence design algorithm works as follows: for r in rounds: train_policy(experimental_data_rewards[r]) for m in model_based_rounds: train_policy(model_fitness_rewards[m]) An episode for the agent ... | 744e792456d93e8c48fc58220689c0b4cff6ded9 | <|skeleton|>
class DynaPPO:
"""Explorer which implements DynaPPO. This RL-based sequence design algorithm works as follows: for r in rounds: train_policy(experimental_data_rewards[r]) for m in model_based_rounds: train_policy(model_fitness_rewards[m]) An episode for the agent begins with an empty sequence, and at e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DynaPPO:
"""Explorer which implements DynaPPO. This RL-based sequence design algorithm works as follows: for r in rounds: train_policy(experimental_data_rewards[r]) for m in model_based_rounds: train_policy(model_fitness_rewards[m]) An episode for the agent begins with an empty sequence, and at each timestep,... | the_stack_v2_python_sparse | flexs/baselines/explorers/dyna_ppo.py | jonshao/FLEXS | train | 0 |
1fa03615b2b8c9dcb28be94d0f19c1ced3634251 | [
"try:\n response = installers.ComponentInstaller.MakeRequest(url, command_path)\n if not response:\n return None\n code = response.getcode()\n if code and code != 200:\n return None\n text = response.read()\n return cls(text)\nexcept Exception:\n log.debug('Failed to download [{ur... | <|body_start_0|>
try:
response = installers.ComponentInstaller.MakeRequest(url, command_path)
if not response:
return None
code = response.getcode()
if code and code != 200:
return None
text = response.read()
... | Represents a parsed RELEASE_NOTES file. The file should have the general structure of: # Google Cloud SDK - Release Notes Copyright 2014-2015 Google Inc. All rights reserved. ## 0.9.78 (2015/09/16) * Note * Note 2 ## 0.9.77 (2015/09/09) * Note 3 | ReleaseNotes | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReleaseNotes:
"""Represents a parsed RELEASE_NOTES file. The file should have the general structure of: # Google Cloud SDK - Release Notes Copyright 2014-2015 Google Inc. All rights reserved. ## 0.9.78 (2015/09/16) * Note * Note 2 ## 0.9.77 (2015/09/09) * Note 3"""
def FromURL(cls, url, comm... | stack_v2_sparse_classes_36k_train_014596 | 7,636 | permissive | [
{
"docstring": "Parses release notes from the given URL. Any error in downloading or parsing release notes is logged and swallowed and None is returned. Args: url: str, The URL to download and parse. command_path: str, The command that is calling this for instrumenting the user agent for the download. Returns: ... | 5 | stack_v2_sparse_classes_30k_train_020189 | Implement the Python class `ReleaseNotes` described below.
Class description:
Represents a parsed RELEASE_NOTES file. The file should have the general structure of: # Google Cloud SDK - Release Notes Copyright 2014-2015 Google Inc. All rights reserved. ## 0.9.78 (2015/09/16) * Note * Note 2 ## 0.9.77 (2015/09/09) * No... | Implement the Python class `ReleaseNotes` described below.
Class description:
Represents a parsed RELEASE_NOTES file. The file should have the general structure of: # Google Cloud SDK - Release Notes Copyright 2014-2015 Google Inc. All rights reserved. ## 0.9.78 (2015/09/16) * Note * Note 2 ## 0.9.77 (2015/09/09) * No... | c98b58aeb0994e011df960163541e9379ae7ea06 | <|skeleton|>
class ReleaseNotes:
"""Represents a parsed RELEASE_NOTES file. The file should have the general structure of: # Google Cloud SDK - Release Notes Copyright 2014-2015 Google Inc. All rights reserved. ## 0.9.78 (2015/09/16) * Note * Note 2 ## 0.9.77 (2015/09/09) * Note 3"""
def FromURL(cls, url, comm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReleaseNotes:
"""Represents a parsed RELEASE_NOTES file. The file should have the general structure of: # Google Cloud SDK - Release Notes Copyright 2014-2015 Google Inc. All rights reserved. ## 0.9.78 (2015/09/16) * Note * Note 2 ## 0.9.77 (2015/09/09) * Note 3"""
def FromURL(cls, url, command_path=None... | the_stack_v2_python_sparse | google-cloud-sdk/.install/.backup/lib/googlecloudsdk/core/updater/release_notes.py | KaranToor/MA450 | train | 1 |
6d02a4f74e409d9bc94b26f07bd76be3fd4ded51 | [
"self._dependency_fetcher = ChromeDependencyFetcher(get_repository)\nself._get_repository = get_repository\nself._top_n_frames = top_n_frames\nself._top_n_suspects = top_n_suspects\nself._model = UnnormalizedLogLinearModel(meta_feature, meta_weight)",
"suspects = self.GenerateSuspects(report)\nif not suspects:\n ... | <|body_start_0|>
self._dependency_fetcher = ChromeDependencyFetcher(get_repository)
self._get_repository = get_repository
self._top_n_frames = top_n_frames
self._top_n_suspects = top_n_suspects
self._model = UnnormalizedLogLinearModel(meta_feature, meta_weight)
<|end_body_0|>
<|... | A ``LogLinearModel``-based implementation of CL classification. | ChangelistClassifier | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangelistClassifier:
"""A ``LogLinearModel``-based implementation of CL classification."""
def __init__(self, get_repository, meta_feature, meta_weight, top_n_frames=7, top_n_suspects=3):
"""Args: get_repository (callable): a function from DEP urls to ``Repository`` objects, so we c... | stack_v2_sparse_classes_36k_train_014597 | 6,856 | permissive | [
{
"docstring": "Args: get_repository (callable): a function from DEP urls to ``Repository`` objects, so we can get changelogs and blame for each dep. Notably, to keep the code here generic, we make no assumptions about which subclass of ``Repository`` this function returns. Thus, it is up to the caller to decid... | 5 | stack_v2_sparse_classes_30k_train_005158 | Implement the Python class `ChangelistClassifier` described below.
Class description:
A ``LogLinearModel``-based implementation of CL classification.
Method signatures and docstrings:
- def __init__(self, get_repository, meta_feature, meta_weight, top_n_frames=7, top_n_suspects=3): Args: get_repository (callable): a ... | Implement the Python class `ChangelistClassifier` described below.
Class description:
A ``LogLinearModel``-based implementation of CL classification.
Method signatures and docstrings:
- def __init__(self, get_repository, meta_feature, meta_weight, top_n_frames=7, top_n_suspects=3): Args: get_repository (callable): a ... | 09064105713603f7bf75c772e8354800a1bfa256 | <|skeleton|>
class ChangelistClassifier:
"""A ``LogLinearModel``-based implementation of CL classification."""
def __init__(self, get_repository, meta_feature, meta_weight, top_n_frames=7, top_n_suspects=3):
"""Args: get_repository (callable): a function from DEP urls to ``Repository`` objects, so we c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChangelistClassifier:
"""A ``LogLinearModel``-based implementation of CL classification."""
def __init__(self, get_repository, meta_feature, meta_weight, top_n_frames=7, top_n_suspects=3):
"""Args: get_repository (callable): a function from DEP urls to ``Repository`` objects, so we can get change... | the_stack_v2_python_sparse | appengine/predator/analysis/changelist_classifier.py | mcgreevy/chromium-infra | train | 1 |
f79b421ab3d7a0f11a2568cf3083ba245e3fb9b8 | [
"required_fields = ['name', 'template_id']\nrequest_content, msg = utils.validate_request(schema=SCHEMA.copy(), request=request, required_fields=required_fields)\nif request_content is None:\n return failed(status=1000001, msg=msg)\nvalidate_result, vm_config = utils.validate_vm_config(vm_config=request_content)... | <|body_start_0|>
required_fields = ['name', 'template_id']
request_content, msg = utils.validate_request(schema=SCHEMA.copy(), request=request, required_fields=required_fields)
if request_content is None:
return failed(status=1000001, msg=msg)
validate_result, vm_config = uti... | VmManagerListView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VmManagerListView:
def post(request):
"""create vm with template :param : :return: :rtype:"""
<|body_0|>
def get(self, request):
"""get vm list :param : :return: :rtype:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
required_fields = ['name', 'tem... | stack_v2_sparse_classes_36k_train_014598 | 7,466 | permissive | [
{
"docstring": "create vm with template :param : :return: :rtype:",
"name": "post",
"signature": "def post(request)"
},
{
"docstring": "get vm list :param : :return: :rtype:",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000337 | Implement the Python class `VmManagerListView` described below.
Class description:
Implement the VmManagerListView class.
Method signatures and docstrings:
- def post(request): create vm with template :param : :return: :rtype:
- def get(self, request): get vm list :param : :return: :rtype: | Implement the Python class `VmManagerListView` described below.
Class description:
Implement the VmManagerListView class.
Method signatures and docstrings:
- def post(request): create vm with template :param : :return: :rtype:
- def get(self, request): get vm list :param : :return: :rtype:
<|skeleton|>
class VmManag... | c2af7033a0f097c6f6d7cb3adff66d560d5ef031 | <|skeleton|>
class VmManagerListView:
def post(request):
"""create vm with template :param : :return: :rtype:"""
<|body_0|>
def get(self, request):
"""get vm list :param : :return: :rtype:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VmManagerListView:
def post(request):
"""create vm with template :param : :return: :rtype:"""
required_fields = ['name', 'template_id']
request_content, msg = utils.validate_request(schema=SCHEMA.copy(), request=request, required_fields=required_fields)
if request_content is No... | the_stack_v2_python_sparse | closestack/views/vm_manager.py | pyajs/closestack | train | 6 | |
a8971edc065073fa3dfe1361917e87f8f4dd2e8a | [
"if not root:\n return None\nstack = []\nstring = str(root.val)\nstack.append([root])\nwhile stack:\n current = stack.pop()\n nodes = []\n for node in current:\n if node.left:\n nodes.append(node.left)\n string += ',' + str(node.left.val)\n else:\n string +... | <|body_start_0|>
if not root:
return None
stack = []
string = str(root.val)
stack.append([root])
while stack:
current = stack.pop()
nodes = []
for node in current:
if node.left:
nodes.append(node.... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_014599 | 2,183 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_002265 | 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:... | eb95152a8e57594883f64ad2df4a27baad312090 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return None
stack = []
string = str(root.val)
stack.append([root])
while stack:
current = stack.pop()
nod... | the_stack_v2_python_sparse | 449. Serialize and Deserialize BST.py | cittie/Leetcode---Python | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.