blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
37912e49bc5ea01c4408f2b7bb1e2f2dcad4a4ad | [
"url = BASE_URL + '/users/recovery'\npayload = {'tokentoto': 'thisismynicetoken', 'passwordword': 'nottoday'}\noutput = requests.post(url, json=payload)\nexpected_output = '531'\nerror_status = output.json()['error']['status']\nassert error_status == expected_output",
"url = BASE_URL + '/users/recovery'\npayload ... | <|body_start_0|>
url = BASE_URL + '/users/recovery'
payload = {'tokentoto': 'thisismynicetoken', 'passwordword': 'nottoday'}
output = requests.post(url, json=payload)
expected_output = '531'
error_status = output.json()['error']['status']
assert error_status == expected_o... | TestRecoverPassword | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRecoverPassword:
def test_post_parameter_wrong(self):
"""This test will fail to recover the password because the parameters are wrong"""
<|body_0|>
def test_post_wrong_token(self):
"""This test will fail to recover the password because the token is wrong"""
... | stack_v2_sparse_classes_75kplus_train_006400 | 1,086 | permissive | [
{
"docstring": "This test will fail to recover the password because the parameters are wrong",
"name": "test_post_parameter_wrong",
"signature": "def test_post_parameter_wrong(self)"
},
{
"docstring": "This test will fail to recover the password because the token is wrong",
"name": "test_pos... | 2 | null | Implement the Python class `TestRecoverPassword` described below.
Class description:
Implement the TestRecoverPassword class.
Method signatures and docstrings:
- def test_post_parameter_wrong(self): This test will fail to recover the password because the parameters are wrong
- def test_post_wrong_token(self): This te... | Implement the Python class `TestRecoverPassword` described below.
Class description:
Implement the TestRecoverPassword class.
Method signatures and docstrings:
- def test_post_parameter_wrong(self): This test will fail to recover the password because the parameters are wrong
- def test_post_wrong_token(self): This te... | ba1e287dbc63e34bf9feb80b65b02c1db93ce91c | <|skeleton|>
class TestRecoverPassword:
def test_post_parameter_wrong(self):
"""This test will fail to recover the password because the parameters are wrong"""
<|body_0|>
def test_post_wrong_token(self):
"""This test will fail to recover the password because the token is wrong"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestRecoverPassword:
def test_post_parameter_wrong(self):
"""This test will fail to recover the password because the parameters are wrong"""
url = BASE_URL + '/users/recovery'
payload = {'tokentoto': 'thisismynicetoken', 'passwordword': 'nottoday'}
output = requests.post(url, j... | the_stack_v2_python_sparse | pytest_suit/routes/user/test_recoverPassword.py | HotMaps/Hotmaps-toolbox-service | train | 4 | |
1a0d5ac5132ae7c124adbbf66cfc17bf497c73d8 | [
"cmd = 'fleetrun dist_fleet_tree_node.py'\npro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nout, err = pro.communicate()\npro.wait()\npro.returncode == 0",
"cmd = 'fleetrun dist_fleet_grahp_engine.py'\npro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=s... | <|body_start_0|>
cmd = 'fleetrun dist_fleet_tree_node.py'
pro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = pro.communicate()
pro.wait()
pro.returncode == 0
<|end_body_0|>
<|body_start_1|>
cmd = 'fleetrun dist_fleet_grahp_... | test all comm api | TestTreeNodeAndGrahpEngineApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTreeNodeAndGrahpEngineApi:
"""test all comm api"""
def test_tree_node(self):
"""test_tree_node"""
<|body_0|>
def test_graph_engine(self):
"""test_tree_node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cmd = 'fleetrun dist_fleet_tree_node.... | stack_v2_sparse_classes_75kplus_train_006401 | 762 | no_license | [
{
"docstring": "test_tree_node",
"name": "test_tree_node",
"signature": "def test_tree_node(self)"
},
{
"docstring": "test_tree_node",
"name": "test_graph_engine",
"signature": "def test_graph_engine(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049678 | Implement the Python class `TestTreeNodeAndGrahpEngineApi` described below.
Class description:
test all comm api
Method signatures and docstrings:
- def test_tree_node(self): test_tree_node
- def test_graph_engine(self): test_tree_node | Implement the Python class `TestTreeNodeAndGrahpEngineApi` described below.
Class description:
test all comm api
Method signatures and docstrings:
- def test_tree_node(self): test_tree_node
- def test_graph_engine(self): test_tree_node
<|skeleton|>
class TestTreeNodeAndGrahpEngineApi:
"""test all comm api"""
... | e3562ab40b574f06bba68df6895a055fa31a085d | <|skeleton|>
class TestTreeNodeAndGrahpEngineApi:
"""test all comm api"""
def test_tree_node(self):
"""test_tree_node"""
<|body_0|>
def test_graph_engine(self):
"""test_tree_node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestTreeNodeAndGrahpEngineApi:
"""test all comm api"""
def test_tree_node(self):
"""test_tree_node"""
cmd = 'fleetrun dist_fleet_tree_node.py'
pro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = pro.communicate()
pro.w... | the_stack_v2_python_sparse | dist_cts/dist_fleet_pipeline/test_dist_fleet_tree_node_and_graph_engine.py | gentelyang/scripts | train | 0 |
312c52685fc0f87c4970555425c8988ee971ecfe | [
"super().__init__()\nself.common = nn.Linear(in_features=input_dim, out_features=hidden_dim, bias=False)\nself.left = nn.Linear(in_features=hidden_dim, out_features=1, bias=True)\nself.right = nn.Linear(in_features=hidden_dim, out_features=1, bias=True)\nself.act_func = act_func\nself.wu2019_init = wu2019_init",
... | <|body_start_0|>
super().__init__()
self.common = nn.Linear(in_features=input_dim, out_features=hidden_dim, bias=False)
self.left = nn.Linear(in_features=hidden_dim, out_features=1, bias=True)
self.right = nn.Linear(in_features=hidden_dim, out_features=1, bias=True)
self.act_func... | Dense dual attention layer. .. seealso :: * Paper: https://www.ijcai.org/Proceedings/2019/0733.pdf, eq. (3) and (4) + Code: https://github.com/StephanieWyt/RDGCN/blob/adb2ec056fd4d3df92983583c1e2d3b18cf76d53/include/Model.py#L117-L132 | DenseAttentionLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DenseAttentionLayer:
"""Dense dual attention layer. .. seealso :: * Paper: https://www.ijcai.org/Proceedings/2019/0733.pdf, eq. (3) and (4) + Code: https://github.com/StephanieWyt/RDGCN/blob/adb2ec056fd4d3df92983583c1e2d3b18cf76d53/include/Model.py#L117-L132"""
def __init__(self, input_dim: ... | stack_v2_sparse_classes_75kplus_train_006402 | 18,027 | permissive | [
{
"docstring": "Initialize the module. :param input_dim: >0 The input dimension. :param hidden_dim: >0 The output dimension. :param act_func: The activation function.",
"name": "__init__",
"signature": "def __init__(self, input_dim: int, hidden_dim: int, act_func: nn.Module, wu2019_init: bool=False)"
... | 3 | null | Implement the Python class `DenseAttentionLayer` described below.
Class description:
Dense dual attention layer. .. seealso :: * Paper: https://www.ijcai.org/Proceedings/2019/0733.pdf, eq. (3) and (4) + Code: https://github.com/StephanieWyt/RDGCN/blob/adb2ec056fd4d3df92983583c1e2d3b18cf76d53/include/Model.py#L117-L132... | Implement the Python class `DenseAttentionLayer` described below.
Class description:
Dense dual attention layer. .. seealso :: * Paper: https://www.ijcai.org/Proceedings/2019/0733.pdf, eq. (3) and (4) + Code: https://github.com/StephanieWyt/RDGCN/blob/adb2ec056fd4d3df92983583c1e2d3b18cf76d53/include/Model.py#L117-L132... | 18e92331ab096c2436e26845586cbbe00fdc5052 | <|skeleton|>
class DenseAttentionLayer:
"""Dense dual attention layer. .. seealso :: * Paper: https://www.ijcai.org/Proceedings/2019/0733.pdf, eq. (3) and (4) + Code: https://github.com/StephanieWyt/RDGCN/blob/adb2ec056fd4d3df92983583c1e2d3b18cf76d53/include/Model.py#L117-L132"""
def __init__(self, input_dim: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DenseAttentionLayer:
"""Dense dual attention layer. .. seealso :: * Paper: https://www.ijcai.org/Proceedings/2019/0733.pdf, eq. (3) and (4) + Code: https://github.com/StephanieWyt/RDGCN/blob/adb2ec056fd4d3df92983583c1e2d3b18cf76d53/include/Model.py#L117-L132"""
def __init__(self, input_dim: int, hidden_d... | the_stack_v2_python_sparse | src/kgm/models/matching/rdgcn.py | mberr/ea-sota-comparison | train | 14 |
80d70c23a734e3b7868b64efd2f61538612f7ca1 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ConnectedOrganization()",
"from .connected_organization_state import ConnectedOrganizationState\nfrom .directory_object import DirectoryObject\nfrom .entity import Entity\nfrom .identity_source import IdentitySource\nfrom .connected_or... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ConnectedOrganization()
<|end_body_0|>
<|body_start_1|>
from .connected_organization_state import ConnectedOrganizationState
from .directory_object import DirectoryObject
from .e... | ConnectedOrganization | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectedOrganization:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConnectedOrganization:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | stack_v2_sparse_classes_75kplus_train_006403 | 5,257 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ConnectedOrganization",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | null | Implement the Python class `ConnectedOrganization` described below.
Class description:
Implement the ConnectedOrganization class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConnectedOrganization: Creates a new instance of the appropriate class base... | Implement the Python class `ConnectedOrganization` described below.
Class description:
Implement the ConnectedOrganization class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConnectedOrganization: Creates a new instance of the appropriate class base... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ConnectedOrganization:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConnectedOrganization:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConnectedOrganization:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConnectedOrganization:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | the_stack_v2_python_sparse | msgraph/generated/models/connected_organization.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
1d1632a377ab824b567e386158282e5c401e95ae | [
"re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])\nresult = re\nAssertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])",
"re = MonthTicketBill(userLogin).openMonthTicketBill(send_data['c... | <|body_start_0|>
re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])
result = re
Assertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])
<|end_body_0|>
<|body_start_1|>
... | VIP车无在场宽出 | TestNoPresenceVipWideOutProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNoPresenceVipWideOutProcess:
"""VIP车无在场宽出"""
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
<|body_0|>
def test_openMonthTicketBill(self, userLogin, send_data, expect):
"""用自定义月票类型开通月票"""
<|body_1|>
def test... | stack_v2_sparse_classes_75kplus_train_006404 | 2,390 | no_license | [
{
"docstring": "创建自定义月票类型",
"name": "test_createMonthTicketConfig",
"signature": "def test_createMonthTicketConfig(self, userLogin, send_data, expect)"
},
{
"docstring": "用自定义月票类型开通月票",
"name": "test_openMonthTicketBill",
"signature": "def test_openMonthTicketBill(self, userLogin, send_d... | 4 | stack_v2_sparse_classes_30k_train_015348 | Implement the Python class `TestNoPresenceVipWideOutProcess` described below.
Class description:
VIP车无在场宽出
Method signatures and docstrings:
- def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型
- def test_openMonthTicketBill(self, userLogin, send_data, expect): 用自定义月票类型开通月票
- def test_moc... | Implement the Python class `TestNoPresenceVipWideOutProcess` described below.
Class description:
VIP车无在场宽出
Method signatures and docstrings:
- def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型
- def test_openMonthTicketBill(self, userLogin, send_data, expect): 用自定义月票类型开通月票
- def test_moc... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestNoPresenceVipWideOutProcess:
"""VIP车无在场宽出"""
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
<|body_0|>
def test_openMonthTicketBill(self, userLogin, send_data, expect):
"""用自定义月票类型开通月票"""
<|body_1|>
def test... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestNoPresenceVipWideOutProcess:
"""VIP车无在场宽出"""
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo... | the_stack_v2_python_sparse | test_suite/parkingManage/monthTicket/test_noPresenceVipWideOutProcess.py | oyebino/pomp_api | train | 1 |
318a685996e4a58cca1608159a2299c75c8dca77 | [
"book = BookInfo.objects.latest('id')\nserializer = self.get_serializer(book)\nreturn Response(serializer.data)",
"book = self.get_object()\nbread = request.data.get('bread')\nbook.bread = bread\nbook.save()\nserializer = self.get_serializer(book)\nreturn Response(serializer.data)"
] | <|body_start_0|>
book = BookInfo.objects.latest('id')
serializer = self.get_serializer(book)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
book = self.get_object()
bread = request.data.get('bread')
book.bread = bread
book.save()
seriali... | 视图集 | BookInfoViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookInfoViewSet:
"""视图集"""
def latest(self, request):
"""获取最新发布的图书信息"""
<|body_0|>
def read(self, request, pk):
"""修改指定图书的阅读量(只修改阅读量)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
book = BookInfo.objects.latest('id')
serializer = self.... | stack_v2_sparse_classes_75kplus_train_006405 | 2,085 | no_license | [
{
"docstring": "获取最新发布的图书信息",
"name": "latest",
"signature": "def latest(self, request)"
},
{
"docstring": "修改指定图书的阅读量(只修改阅读量)",
"name": "read",
"signature": "def read(self, request, pk)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042394 | Implement the Python class `BookInfoViewSet` described below.
Class description:
视图集
Method signatures and docstrings:
- def latest(self, request): 获取最新发布的图书信息
- def read(self, request, pk): 修改指定图书的阅读量(只修改阅读量) | Implement the Python class `BookInfoViewSet` described below.
Class description:
视图集
Method signatures and docstrings:
- def latest(self, request): 获取最新发布的图书信息
- def read(self, request, pk): 修改指定图书的阅读量(只修改阅读量)
<|skeleton|>
class BookInfoViewSet:
"""视图集"""
def latest(self, request):
"""获取最新发布的图书信息"""... | f8ec0bec399253e481e16443ba9a3e45e61486f4 | <|skeleton|>
class BookInfoViewSet:
"""视图集"""
def latest(self, request):
"""获取最新发布的图书信息"""
<|body_0|>
def read(self, request, pk):
"""修改指定图书的阅读量(只修改阅读量)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BookInfoViewSet:
"""视图集"""
def latest(self, request):
"""获取最新发布的图书信息"""
book = BookInfo.objects.latest('id')
serializer = self.get_serializer(book)
return Response(serializer.data)
def read(self, request, pk):
"""修改指定图书的阅读量(只修改阅读量)"""
book = self.get_o... | the_stack_v2_python_sparse | drf_demo/booktest/views-12-在视图集中添加额外action处理函数.py | cz495969281/2019_- | train | 0 |
f5db68abd6750d1e54d880c9e6213cd066d1e701 | [
"if proxy:\n PROXY_IP = proxy['IP']\n PROXY_USER = proxy['USER']\n PROXY_PASSWORD = proxy['PASSWORD']\n PROXY_PORT = proxy['PORT']\n proxy_url = 'http://' + PROXY_USER + ':' + PROXY_PASSWORD + '@' + PROXY_IP + ':' + PROXY_PORT\n proxy_support = urllib2.ProxyHandler({'http': proxy_url})\n opener... | <|body_start_0|>
if proxy:
PROXY_IP = proxy['IP']
PROXY_USER = proxy['USER']
PROXY_PASSWORD = proxy['PASSWORD']
PROXY_PORT = proxy['PORT']
proxy_url = 'http://' + PROXY_USER + ':' + PROXY_PASSWORD + '@' + PROXY_IP + ':' + PROXY_PORT
proxy_s... | Comment. | DesktopWallpaper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DesktopWallpaper:
"""Comment."""
def __init__(self, proxy=None):
"""Comment"""
<|body_0|>
def readnatgeo(self):
"""Comment"""
<|body_1|>
def lookforwallpaper(self, content):
"""Comment"""
<|body_2|>
def downloadjpg(self, wallpape... | stack_v2_sparse_classes_75kplus_train_006406 | 2,117 | no_license | [
{
"docstring": "Comment",
"name": "__init__",
"signature": "def __init__(self, proxy=None)"
},
{
"docstring": "Comment",
"name": "readnatgeo",
"signature": "def readnatgeo(self)"
},
{
"docstring": "Comment",
"name": "lookforwallpaper",
"signature": "def lookforwallpaper(s... | 4 | stack_v2_sparse_classes_30k_train_017715 | Implement the Python class `DesktopWallpaper` described below.
Class description:
Comment.
Method signatures and docstrings:
- def __init__(self, proxy=None): Comment
- def readnatgeo(self): Comment
- def lookforwallpaper(self, content): Comment
- def downloadjpg(self, wallpaper): Comment | Implement the Python class `DesktopWallpaper` described below.
Class description:
Comment.
Method signatures and docstrings:
- def __init__(self, proxy=None): Comment
- def readnatgeo(self): Comment
- def lookforwallpaper(self, content): Comment
- def downloadjpg(self, wallpaper): Comment
<|skeleton|>
class DesktopW... | 5fa3a818c3d41bd9c3eb25122e1d376c8910269c | <|skeleton|>
class DesktopWallpaper:
"""Comment."""
def __init__(self, proxy=None):
"""Comment"""
<|body_0|>
def readnatgeo(self):
"""Comment"""
<|body_1|>
def lookforwallpaper(self, content):
"""Comment"""
<|body_2|>
def downloadjpg(self, wallpape... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DesktopWallpaper:
"""Comment."""
def __init__(self, proxy=None):
"""Comment"""
if proxy:
PROXY_IP = proxy['IP']
PROXY_USER = proxy['USER']
PROXY_PASSWORD = proxy['PASSWORD']
PROXY_PORT = proxy['PORT']
proxy_url = 'http://' + PROX... | the_stack_v2_python_sparse | ExtractFeatures/Data/kracekumar/getpicture.py | vivekaxl/LexisNexis | train | 9 |
d48ef221e051f16678b1c833f3bc31589a08420d | [
"super().__init__(None, mode, SYSTEM_REGISTER_PANEL_SIZE, client)\nself.mode = mode\nself.username_static = wx.StaticText(self.pnl, label=USERNAME_STATIC)\nself.password_static = wx.StaticText(self.pnl, label=PASSWORD_STATIC)\nself.user_txt = wx.TextCtrl(self.pnl)\nself.password_txt = wx.TextCtrl(self.pnl)\nself.bt... | <|body_start_0|>
super().__init__(None, mode, SYSTEM_REGISTER_PANEL_SIZE, client)
self.mode = mode
self.username_static = wx.StaticText(self.pnl, label=USERNAME_STATIC)
self.password_static = wx.StaticText(self.pnl, label=PASSWORD_STATIC)
self.user_txt = wx.TextCtrl(self.pnl)
... | enter username & password - connect to server | SystemRegisterGUI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemRegisterGUI:
"""enter username & password - connect to server"""
def __init__(self, mode, client):
""":param mode: LOG IN \\ SIGN UP"""
<|body_0|>
def on_submit(self, e):
""":return: checks the log in \\ sign up method"""
<|body_1|>
def positio... | stack_v2_sparse_classes_75kplus_train_006407 | 3,217 | no_license | [
{
"docstring": ":param mode: LOG IN \\\\ SIGN UP",
"name": "__init__",
"signature": "def __init__(self, mode, client)"
},
{
"docstring": ":return: checks the log in \\\\ sign up method",
"name": "on_submit",
"signature": "def on_submit(self, e)"
},
{
"docstring": ":return: puts t... | 3 | stack_v2_sparse_classes_30k_train_027667 | Implement the Python class `SystemRegisterGUI` described below.
Class description:
enter username & password - connect to server
Method signatures and docstrings:
- def __init__(self, mode, client): :param mode: LOG IN \\ SIGN UP
- def on_submit(self, e): :return: checks the log in \\ sign up method
- def positions(s... | Implement the Python class `SystemRegisterGUI` described below.
Class description:
enter username & password - connect to server
Method signatures and docstrings:
- def __init__(self, mode, client): :param mode: LOG IN \\ SIGN UP
- def on_submit(self, e): :return: checks the log in \\ sign up method
- def positions(s... | b8e9ae3300a7fd79d72109bb3d7db5020fca55d8 | <|skeleton|>
class SystemRegisterGUI:
"""enter username & password - connect to server"""
def __init__(self, mode, client):
""":param mode: LOG IN \\ SIGN UP"""
<|body_0|>
def on_submit(self, e):
""":return: checks the log in \\ sign up method"""
<|body_1|>
def positio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SystemRegisterGUI:
"""enter username & password - connect to server"""
def __init__(self, mode, client):
""":param mode: LOG IN \\ SIGN UP"""
super().__init__(None, mode, SYSTEM_REGISTER_PANEL_SIZE, client)
self.mode = mode
self.username_static = wx.StaticText(self.pnl, la... | the_stack_v2_python_sparse | Classes/SystemRegisterGUI.py | tomerbar2903/CloudProject | train | 0 |
e8c33b338d28408766bf49f47f6ccf72f4acebf5 | [
"cache_key = str(calendar_year)\nif cache_key not in UtilityFactorMethods._cache:\n start_years = np.atleast_1d(UtilityFactorMethods._data['start_year'])\n if len(start_years[start_years <= calendar_year]) > 0:\n calendar_year = max(start_years[start_years <= calendar_year])\n method = UtilityFa... | <|body_start_0|>
cache_key = str(calendar_year)
if cache_key not in UtilityFactorMethods._cache:
start_years = np.atleast_1d(UtilityFactorMethods._data['start_year'])
if len(start_years[start_years <= calendar_year]) > 0:
calendar_year = max(start_years[start_year... | **Loads and provides access to upstream calculation methods by start year.** | UtilityFactorMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilityFactorMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def calc_city_utility_factor(calendar_year, miles):
"""Calculate "city" PHEV fleet utility factor Args: calendar_year (int): the calendar year to get the function for miles: dista... | stack_v2_sparse_classes_75kplus_train_006408 | 11,165 | no_license | [
{
"docstring": "Calculate \"city\" PHEV fleet utility factor Args: calendar_year (int): the calendar year to get the function for miles: distance travelled in charge-depleting driving, scalar or pandas Series Returns: A callable python function used to calculate upstream cert emissions for the given calendar ye... | 3 | stack_v2_sparse_classes_30k_train_000635 | Implement the Python class `UtilityFactorMethods` described below.
Class description:
**Loads and provides access to upstream calculation methods by start year.**
Method signatures and docstrings:
- def calc_city_utility_factor(calendar_year, miles): Calculate "city" PHEV fleet utility factor Args: calendar_year (int... | Implement the Python class `UtilityFactorMethods` described below.
Class description:
**Loads and provides access to upstream calculation methods by start year.**
Method signatures and docstrings:
- def calc_city_utility_factor(calendar_year, miles): Calculate "city" PHEV fleet utility factor Args: calendar_year (int... | afe912c57383b9de90ef30820f7977c3367a30c4 | <|skeleton|>
class UtilityFactorMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def calc_city_utility_factor(calendar_year, miles):
"""Calculate "city" PHEV fleet utility factor Args: calendar_year (int): the calendar year to get the function for miles: dista... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UtilityFactorMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def calc_city_utility_factor(calendar_year, miles):
"""Calculate "city" PHEV fleet utility factor Args: calendar_year (int): the calendar year to get the function for miles: distance travelled... | the_stack_v2_python_sparse | omega_model/policy/utility_factors.py | USEPA/EPA_OMEGA_Model | train | 17 |
d498ab7a37752b28ea9bd872fb2cfe01d17f5e48 | [
"self.count = A[::2]\nself.value = A[1::2]\nself.prefix_sum = self.count[:]\nself.used = 0\nfor i in range(1, len(self.count)):\n self.prefix_sum[i] += self.prefix_sum[i - 1]",
"self.used += n\nindex = bisect.bisect_left(self.prefix_sum, self.used)\nif index == len(self.value):\n return -1\nelse:\n retur... | <|body_start_0|>
self.count = A[::2]
self.value = A[1::2]
self.prefix_sum = self.count[:]
self.used = 0
for i in range(1, len(self.count)):
self.prefix_sum[i] += self.prefix_sum[i - 1]
<|end_body_0|>
<|body_start_1|>
self.used += n
index = bisect.bise... | RLEIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.count = A[::2]
self.value = A[1::2]
self.prefix_sum = self.co... | stack_v2_sparse_classes_75kplus_train_006409 | 626 | no_license | [
{
"docstring": ":type A: List[int]",
"name": "__init__",
"signature": "def __init__(self, A)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "next",
"signature": "def next(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014735 | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int
<|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: Lis... | 238995bd23c8a6c40c6035890e94baa2473d4bbc | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
self.count = A[::2]
self.value = A[1::2]
self.prefix_sum = self.count[:]
self.used = 0
for i in range(1, len(self.count)):
self.prefix_sum[i] += self.prefix_sum[i - 1]
def next(self, n... | the_stack_v2_python_sparse | problems/N900_RLE_Iterator.py | wan-catherine/Leetcode | train | 5 | |
b6880a38e4b3c47987ace83bf5be200767f17ec0 | [
"self.name = name\nself.type = self.RSC_TYPE_MAP.get(type, None)\nif not self.type:\n raise HOTError('Unknown resource type: ' + type)\nself.prop = prop or {}\nself.metadata = metadata\nself.depends_on = depends_on",
"rsc = OrderedDict()\nrsc[self.TYPE] = self.type\nif self.prop:\n rsc[self.PROPERTIES] = se... | <|body_start_0|>
self.name = name
self.type = self.RSC_TYPE_MAP.get(type, None)
if not self.type:
raise HOTError('Unknown resource type: ' + type)
self.prop = prop or {}
self.metadata = metadata
self.depends_on = depends_on
<|end_body_0|>
<|body_start_1|>
... | HOT Resource Attr | Resource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resource:
"""HOT Resource Attr"""
def __init__(self, name, type=None, prop=None, metadata=None, depends_on=None):
"""Init a HOT resource"""
<|body_0|>
def get_output_dict(self):
"""Output a resource as a nested dict"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_006410 | 6,215 | no_license | [
{
"docstring": "Init a HOT resource",
"name": "__init__",
"signature": "def __init__(self, name, type=None, prop=None, metadata=None, depends_on=None)"
},
{
"docstring": "Output a resource as a nested dict",
"name": "get_output_dict",
"signature": "def get_output_dict(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044362 | Implement the Python class `Resource` described below.
Class description:
HOT Resource Attr
Method signatures and docstrings:
- def __init__(self, name, type=None, prop=None, metadata=None, depends_on=None): Init a HOT resource
- def get_output_dict(self): Output a resource as a nested dict | Implement the Python class `Resource` described below.
Class description:
HOT Resource Attr
Method signatures and docstrings:
- def __init__(self, name, type=None, prop=None, metadata=None, depends_on=None): Init a HOT resource
- def get_output_dict(self): Output a resource as a nested dict
<|skeleton|>
class Resour... | 103d9ffb67e98c6e912a5861b73ad0f06d9df80c | <|skeleton|>
class Resource:
"""HOT Resource Attr"""
def __init__(self, name, type=None, prop=None, metadata=None, depends_on=None):
"""Init a HOT resource"""
<|body_0|>
def get_output_dict(self):
"""Output a resource as a nested dict"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Resource:
"""HOT Resource Attr"""
def __init__(self, name, type=None, prop=None, metadata=None, depends_on=None):
"""Init a HOT resource"""
self.name = name
self.type = self.RSC_TYPE_MAP.get(type, None)
if not self.type:
raise HOTError('Unknown resource type: '... | the_stack_v2_python_sparse | sfc-ostack/sfcostack/hot.py | stevelorenz/sfc-ostack | train | 4 |
ee6cf268644065e2e2e4a39c410bdb0ea77118c3 | [
"while True:\n num = (rand7() - 1) * 7 + rand7()\n if num <= 40:\n return num % 10 + 1",
"while True:\n num = (rand7() - 1) * 7 + rand7()\n if num <= 40:\n return num % 10 + 1\n rand9 = num - 40\n num = (rand9 - 1) * 7 + rand7()\n if num <= 60:\n return num % 10 + 1\n ... | <|body_start_0|>
while True:
num = (rand7() - 1) * 7 + rand7()
if num <= 40:
return num % 10 + 1
<|end_body_0|>
<|body_start_1|>
while True:
num = (rand7() - 1) * 7 + rand7()
if num <= 40:
return num % 10 + 1
ra... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rand10(self):
"""拒绝采样"""
<|body_0|>
def rand10_new(self):
"""拒绝采样-减少舍弃数字"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while True:
num = (rand7() - 1) * 7 + rand7()
if num <= 40:
return num % 1... | stack_v2_sparse_classes_75kplus_train_006411 | 1,066 | no_license | [
{
"docstring": "拒绝采样",
"name": "rand10",
"signature": "def rand10(self)"
},
{
"docstring": "拒绝采样-减少舍弃数字",
"name": "rand10_new",
"signature": "def rand10_new(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001099 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rand10(self): 拒绝采样
- def rand10_new(self): 拒绝采样-减少舍弃数字 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rand10(self): 拒绝采样
- def rand10_new(self): 拒绝采样-减少舍弃数字
<|skeleton|>
class Solution:
def rand10(self):
"""拒绝采样"""
<|body_0|>
def rand10_new(self):
... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def rand10(self):
"""拒绝采样"""
<|body_0|>
def rand10_new(self):
"""拒绝采样-减少舍弃数字"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rand10(self):
"""拒绝采样"""
while True:
num = (rand7() - 1) * 7 + rand7()
if num <= 40:
return num % 10 + 1
def rand10_new(self):
"""拒绝采样-减少舍弃数字"""
while True:
num = (rand7() - 1) * 7 + rand7()
if n... | the_stack_v2_python_sparse | 470.用 Rand7() 实现 Rand10()/solution.py | QtTao/daily_leetcode | train | 0 | |
607d49fc73a008c369c525d83266c83445500262 | [
"if not root:\n return None\ntmp = root.left\nroot.left = self.mirrorTree(root.right)\nroot.right = self.mirrorTree(tmp)\nreturn root",
"if not root:\n return\nstack = [root]\nwhile stack:\n node = stack.pop()\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(n... | <|body_start_0|>
if not root:
return None
tmp = root.left
root.left = self.mirrorTree(root.right)
root.right = self.mirrorTree(tmp)
return root
<|end_body_0|>
<|body_start_1|>
if not root:
return
stack = [root]
while stack:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mirrorTree(self, root):
"""递归法构建镜像二叉树 时间复杂度 O(N)O(N) : 其中 NN 为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N)O(N) 时间。 空间复杂度 O(N)O(N) : 最差情况下(当二叉树退化为链表),递归时系统需使用 O(N)O(N) 大小的栈空间。 :type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def mirrorTree_stack(self, root):
""... | stack_v2_sparse_classes_75kplus_train_006412 | 2,272 | no_license | [
{
"docstring": "递归法构建镜像二叉树 时间复杂度 O(N)O(N) : 其中 NN 为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N)O(N) 时间。 空间复杂度 O(N)O(N) : 最差情况下(当二叉树退化为链表),递归时系统需使用 O(N)O(N) 大小的栈空间。 :type root: TreeNode :rtype: TreeNode",
"name": "mirrorTree",
"signature": "def mirrorTree(self, root)"
},
{
"docstring": "利用栈(或队列)遍历树的所有节点 no... | 2 | stack_v2_sparse_classes_30k_test_001688 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mirrorTree(self, root): 递归法构建镜像二叉树 时间复杂度 O(N)O(N) : 其中 NN 为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N)O(N) 时间。 空间复杂度 O(N)O(N) : 最差情况下(当二叉树退化为链表),递归时系统需使用 O(N)O(N) 大小的栈空间。 :type root: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mirrorTree(self, root): 递归法构建镜像二叉树 时间复杂度 O(N)O(N) : 其中 NN 为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N)O(N) 时间。 空间复杂度 O(N)O(N) : 最差情况下(当二叉树退化为链表),递归时系统需使用 O(N)O(N) 大小的栈空间。 :type root: ... | e12ead66d28175d34b51eac4ccdd6de06eb4d92d | <|skeleton|>
class Solution:
def mirrorTree(self, root):
"""递归法构建镜像二叉树 时间复杂度 O(N)O(N) : 其中 NN 为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N)O(N) 时间。 空间复杂度 O(N)O(N) : 最差情况下(当二叉树退化为链表),递归时系统需使用 O(N)O(N) 大小的栈空间。 :type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def mirrorTree_stack(self, root):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mirrorTree(self, root):
"""递归法构建镜像二叉树 时间复杂度 O(N)O(N) : 其中 NN 为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N)O(N) 时间。 空间复杂度 O(N)O(N) : 最差情况下(当二叉树退化为链表),递归时系统需使用 O(N)O(N) 大小的栈空间。 :type root: TreeNode :rtype: TreeNode"""
if not root:
return None
tmp = root.left
root.... | the_stack_v2_python_sparse | tree_27_mirrorTree.py | zhenglinghan/leetcode_jianzhi_Offer | train | 2 | |
4548ac5a5721649c729eaa891cec27902eea63b1 | [
"self.name = msg.name\nself.gateway_name = msg.gateway_name\nself.uri = msg.platform_info.uri\nself.rapps = [rapp.name for rapp in msg.rapps]\nself.start_rapp = rospy.ServiceProxy('/' + self.gateway_name + '/start_rapp', StartRapp)\nself.stop_rapp = rospy.ServiceProxy('/' + self.gateway_name + '/stop_rapp', StopRap... | <|body_start_0|>
self.name = msg.name
self.gateway_name = msg.gateway_name
self.uri = msg.platform_info.uri
self.rapps = [rapp.name for rapp in msg.rapps]
self.start_rapp = rospy.ServiceProxy('/' + self.gateway_name + '/start_rapp', StartRapp)
self.stop_rapp = rospy.Servi... | Initialises from a conductor message detailing information about a concert client. Once established, this instance can be used as a convenience to start and stop rapps on the concert client. | RappHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RappHandler:
"""Initialises from a conductor message detailing information about a concert client. Once established, this instance can be used as a convenience to start and stop rapps on the concert client."""
def __init__(self, msg):
"""Initialise the class with the relevant data re... | stack_v2_sparse_classes_75kplus_train_006413 | 4,193 | no_license | [
{
"docstring": "Initialise the class with the relevant data required to start and stop rapps on this concert client. :param msg concert_msgs/ConcertClient: detailed information about a concert client.",
"name": "__init__",
"signature": "def __init__(self, msg)"
},
{
"docstring": "Start the rapp ... | 3 | null | Implement the Python class `RappHandler` described below.
Class description:
Initialises from a conductor message detailing information about a concert client. Once established, this instance can be used as a convenience to start and stop rapps on the concert client.
Method signatures and docstrings:
- def __init__(s... | Implement the Python class `RappHandler` described below.
Class description:
Initialises from a conductor message detailing information about a concert client. Once established, this instance can be used as a convenience to start and stop rapps on the concert client.
Method signatures and docstrings:
- def __init__(s... | 3430d344a9acac5cd7a4782d599c6d62a305a92e | <|skeleton|>
class RappHandler:
"""Initialises from a conductor message detailing information about a concert client. Once established, this instance can be used as a convenience to start and stop rapps on the concert client."""
def __init__(self, msg):
"""Initialise the class with the relevant data re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RappHandler:
"""Initialises from a conductor message detailing information about a concert client. Once established, this instance can be used as a convenience to start and stop rapps on the concert client."""
def __init__(self, msg):
"""Initialise the class with the relevant data required to sta... | the_stack_v2_python_sparse | rocon/src/concert_scheduling/concert_resource_pool/src/concert_resource_pool/rapp_handler.py | graziegrazie/my_turtlebot | train | 1 |
3c95a63173cdcad25cb616b414a656198a57caf5 | [
"repositoryAccess = 'command=\"bzr serve --inet --directory={}{{}}\"'.format(self.repository) + ',no-port-forwarding,no-X11-forwarding,no-agent-forwarding {}'\nwith open('authorized_keys', 'w') as authorized:\n for user in self.admin:\n authorized.writelines(self.readKeys(user))\n for user in self.writ... | <|body_start_0|>
repositoryAccess = 'command="bzr serve --inet --directory={}{{}}"'.format(self.repository) + ',no-port-forwarding,no-X11-forwarding,no-agent-forwarding {}'
with open('authorized_keys', 'w') as authorized:
for user in self.admin:
authorized.writelines(self.rea... | Build the {authorized_keys} file that grants write access to the repository | Grant | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grant:
"""Build the {authorized_keys} file that grants write access to the repository"""
def main(self, *args, **kwds):
"""Build the {authorized_keys} file"""
<|body_0|>
def readKeys(self, user):
"""Open all the public key file for the given {user} and return all... | stack_v2_sparse_classes_75kplus_train_006414 | 2,429 | permissive | [
{
"docstring": "Build the {authorized_keys} file",
"name": "main",
"signature": "def main(self, *args, **kwds)"
},
{
"docstring": "Open all the public key file for the given {user} and return all the keys it contains",
"name": "readKeys",
"signature": "def readKeys(self, user)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032554 | Implement the Python class `Grant` described below.
Class description:
Build the {authorized_keys} file that grants write access to the repository
Method signatures and docstrings:
- def main(self, *args, **kwds): Build the {authorized_keys} file
- def readKeys(self, user): Open all the public key file for the given ... | Implement the Python class `Grant` described below.
Class description:
Build the {authorized_keys} file that grants write access to the repository
Method signatures and docstrings:
- def main(self, *args, **kwds): Build the {authorized_keys} file
- def readKeys(self, user): Open all the public key file for the given ... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Grant:
"""Build the {authorized_keys} file that grants write access to the repository"""
def main(self, *args, **kwds):
"""Build the {authorized_keys} file"""
<|body_0|>
def readKeys(self, user):
"""Open all the public key file for the given {user} and return all... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Grant:
"""Build the {authorized_keys} file that grants write access to the repository"""
def main(self, *args, **kwds):
"""Build the {authorized_keys} file"""
repositoryAccess = 'command="bzr serve --inet --directory={}{{}}"'.format(self.repository) + ',no-port-forwarding,no-X11-forwardin... | the_stack_v2_python_sparse | etc/people/grant.py | pyre/pyre | train | 27 |
9ac312c95f0d174ce207494b84abb458fb040e6d | [
"self.value = value\nself.category = category\nself.info = info",
"person = self.info.get('person')\ngender = self.info.get('gender')\nnumber = self.info.get('number')\ntense = self.info.get('tense')\nnext = self.info.get('next')\nif self.category in NOMINAL_CATEGORY_LIST:\n return self.value.term(gender, numb... | <|body_start_0|>
self.value = value
self.category = category
self.info = info
<|end_body_0|>
<|body_start_1|>
person = self.info.get('person')
gender = self.info.get('gender')
number = self.info.get('number')
tense = self.info.get('tense')
next = self.inf... | A word, described as an instance of a lexical category. | Word | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Word:
"""A word, described as an instance of a lexical category."""
def __init__(self, value, category, info):
"""Attributes: - self.value: an instance of a lexical category - self.category: the word's lexical category - self.info: a dict containing info about the word, like number, ... | stack_v2_sparse_classes_75kplus_train_006415 | 1,497 | permissive | [
{
"docstring": "Attributes: - self.value: an instance of a lexical category - self.category: the word's lexical category - self.info: a dict containing info about the word, like number, gender, etc., used to obtain the correct declination/conjugation.",
"name": "__init__",
"signature": "def __init__(sel... | 2 | stack_v2_sparse_classes_30k_train_035396 | Implement the Python class `Word` described below.
Class description:
A word, described as an instance of a lexical category.
Method signatures and docstrings:
- def __init__(self, value, category, info): Attributes: - self.value: an instance of a lexical category - self.category: the word's lexical category - self.i... | Implement the Python class `Word` described below.
Class description:
A word, described as an instance of a lexical category.
Method signatures and docstrings:
- def __init__(self, value, category, info): Attributes: - self.value: an instance of a lexical category - self.category: the word's lexical category - self.i... | 97d48e07cd3c574d92e080fcc81fd0bcad56015f | <|skeleton|>
class Word:
"""A word, described as an instance of a lexical category."""
def __init__(self, value, category, info):
"""Attributes: - self.value: an instance of a lexical category - self.category: the word's lexical category - self.info: a dict containing info about the word, like number, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Word:
"""A word, described as an instance of a lexical category."""
def __init__(self, value, category, info):
"""Attributes: - self.value: an instance of a lexical category - self.category: the word's lexical category - self.info: a dict containing info about the word, like number, gender, etc.,... | the_stack_v2_python_sparse | grammar/word.py | andlima/fraseador | train | 1 |
043396430014557307c48bbe90bd12597d88fc0d | [
"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... | 短信自有签名服务 | MessageUserSignServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageUserSignServiceServicer:
"""短信自有签名服务"""
def qryMessageUserSign(self, request, context):
"""查询短信自有签名"""
<|body_0|>
def qryMsgUserSignList(self, request, context):
"""查询短信签名列表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
context.set_code... | stack_v2_sparse_classes_75kplus_train_006416 | 2,413 | no_license | [
{
"docstring": "查询短信自有签名",
"name": "qryMessageUserSign",
"signature": "def qryMessageUserSign(self, request, context)"
},
{
"docstring": "查询短信签名列表",
"name": "qryMsgUserSignList",
"signature": "def qryMsgUserSignList(self, request, context)"
}
] | 2 | null | Implement the Python class `MessageUserSignServiceServicer` described below.
Class description:
短信自有签名服务
Method signatures and docstrings:
- def qryMessageUserSign(self, request, context): 查询短信自有签名
- def qryMsgUserSignList(self, request, context): 查询短信签名列表 | Implement the Python class `MessageUserSignServiceServicer` described below.
Class description:
短信自有签名服务
Method signatures and docstrings:
- def qryMessageUserSign(self, request, context): 查询短信自有签名
- def qryMsgUserSignList(self, request, context): 查询短信签名列表
<|skeleton|>
class MessageUserSignServiceServicer:
"""短信... | 6c4204579f59dbfaa2659dc76a302d9e286112d5 | <|skeleton|>
class MessageUserSignServiceServicer:
"""短信自有签名服务"""
def qryMessageUserSign(self, request, context):
"""查询短信自有签名"""
<|body_0|>
def qryMsgUserSignList(self, request, context):
"""查询短信签名列表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MessageUserSignServiceServicer:
"""短信自有签名服务"""
def qryMessageUserSign(self, request, context):
"""查询短信自有签名"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def qryMsg... | the_stack_v2_python_sparse | test_case/pb2/smschannel/messageusersignservice_pb2_grpc.py | jiaheqi/python-api-test | train | 0 |
7bb72138c6ebe24e8fa0bcb7e4bbcf1c7fca1a4e | [
"awilt = self.env['account.wh.iva.line.tax']\npartner = self.env['res.partner']\nfor rec in self:\n if rec.invoice_id:\n rate = rec.retention_id.type == 'out_invoice' and partner._find_accounting_partner(rec.invoice_id.company_id.partner_id).wh_iva_rate or partner._find_accounting_partner(rec.invoice_id.p... | <|body_start_0|>
awilt = self.env['account.wh.iva.line.tax']
partner = self.env['res.partner']
for rec in self:
if rec.invoice_id:
rate = rec.retention_id.type == 'out_invoice' and partner._find_accounting_partner(rec.invoice_id.company_id.partner_id).wh_iva_rate or p... | AccountWhIvaLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountWhIvaLine:
def load_taxes(self):
"""Clean and load again tax lines of the withholding voucher"""
<|body_0|>
def _amount_all(self):
"""Return amount total each line"""
<|body_1|>
def invoice_id_change(self, invoice_id):
"""Return invoice da... | stack_v2_sparse_classes_75kplus_train_006417 | 40,203 | no_license | [
{
"docstring": "Clean and load again tax lines of the withholding voucher",
"name": "load_taxes",
"signature": "def load_taxes(self)"
},
{
"docstring": "Return amount total each line",
"name": "_amount_all",
"signature": "def _amount_all(self)"
},
{
"docstring": "Return invoice d... | 3 | stack_v2_sparse_classes_30k_train_042905 | Implement the Python class `AccountWhIvaLine` described below.
Class description:
Implement the AccountWhIvaLine class.
Method signatures and docstrings:
- def load_taxes(self): Clean and load again tax lines of the withholding voucher
- def _amount_all(self): Return amount total each line
- def invoice_id_change(sel... | Implement the Python class `AccountWhIvaLine` described below.
Class description:
Implement the AccountWhIvaLine class.
Method signatures and docstrings:
- def load_taxes(self): Clean and load again tax lines of the withholding voucher
- def _amount_all(self): Return amount total each line
- def invoice_id_change(sel... | 718327d01e5b4408add58682c5ad1901fa35b450 | <|skeleton|>
class AccountWhIvaLine:
def load_taxes(self):
"""Clean and load again tax lines of the withholding voucher"""
<|body_0|>
def _amount_all(self):
"""Return amount total each line"""
<|body_1|>
def invoice_id_change(self, invoice_id):
"""Return invoice da... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountWhIvaLine:
def load_taxes(self):
"""Clean and load again tax lines of the withholding voucher"""
awilt = self.env['account.wh.iva.line.tax']
partner = self.env['res.partner']
for rec in self:
if rec.invoice_id:
rate = rec.retention_id.type == ... | the_stack_v2_python_sparse | l10n_ve_withholding_iva/model/wh_iva.py | Vauxoo/odoo-venezuela | train | 15 | |
7d9bf2116c10a31a231cb84a3090654679ba8a43 | [
"res = list(s)\nfor i in range(len(s)):\n if res[i] == ' ':\n res[i] = '%20'\nres = ''.join(res)\nreturn res",
"res = []\nfor c in s:\n if c == ' ':\n res.append('%20')\n else:\n res.append(c)\nreturn ''.join(res)"
] | <|body_start_0|>
res = list(s)
for i in range(len(s)):
if res[i] == ' ':
res[i] = '%20'
res = ''.join(res)
return res
<|end_body_0|>
<|body_start_1|>
res = []
for c in s:
if c == ' ':
res.append('%20')
e... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def replaceSpace(self, s: str) -> str:
"""不是最佳答案 将字符串转换为list,然后对list中各个元素遍历,若为空格,则替换,最后将list进行拼接为字符串"""
<|body_0|>
def replaceSpace(self, s: str) -> str:
"""最佳答案 创建新的列表,遍历字符串中的每个字符,判断是否为空格进行对应的append,最后在join到一起形成字符串"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_006418 | 869 | no_license | [
{
"docstring": "不是最佳答案 将字符串转换为list,然后对list中各个元素遍历,若为空格,则替换,最后将list进行拼接为字符串",
"name": "replaceSpace",
"signature": "def replaceSpace(self, s: str) -> str"
},
{
"docstring": "最佳答案 创建新的列表,遍历字符串中的每个字符,判断是否为空格进行对应的append,最后在join到一起形成字符串",
"name": "replaceSpace",
"signature": "def replaceSpace... | 2 | stack_v2_sparse_classes_30k_train_001316 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def replaceSpace(self, s: str) -> str: 不是最佳答案 将字符串转换为list,然后对list中各个元素遍历,若为空格,则替换,最后将list进行拼接为字符串
- def replaceSpace(self, s: str) -> str: 最佳答案 创建新的列表,遍历字符串中的每个字符,判断是否为空格进行对应的app... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def replaceSpace(self, s: str) -> str: 不是最佳答案 将字符串转换为list,然后对list中各个元素遍历,若为空格,则替换,最后将list进行拼接为字符串
- def replaceSpace(self, s: str) -> str: 最佳答案 创建新的列表,遍历字符串中的每个字符,判断是否为空格进行对应的app... | 0ec1a89e5b1e3d32af4da9693e9e5c36d4cd42eb | <|skeleton|>
class Solution:
def replaceSpace(self, s: str) -> str:
"""不是最佳答案 将字符串转换为list,然后对list中各个元素遍历,若为空格,则替换,最后将list进行拼接为字符串"""
<|body_0|>
def replaceSpace(self, s: str) -> str:
"""最佳答案 创建新的列表,遍历字符串中的每个字符,判断是否为空格进行对应的append,最后在join到一起形成字符串"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def replaceSpace(self, s: str) -> str:
"""不是最佳答案 将字符串转换为list,然后对list中各个元素遍历,若为空格,则替换,最后将list进行拼接为字符串"""
res = list(s)
for i in range(len(s)):
if res[i] == ' ':
res[i] = '%20'
res = ''.join(res)
return res
def replaceSpace(self,... | the_stack_v2_python_sparse | 5.py | zhiweiguo/my_leetcode | train | 1 | |
eb696b4468898438ec693db64d73d95a3383ce75 | [
"current_ts = self.loadts.strftime('%Y-%m-%d %H:%M:%S')\nload_metadata = {'topic_name': self.topic, 'database_name': self.database, 'table_name': self.table, 'load_start_time': current_ts, 'load_end_time': current_ts}\nself.metadata_mgr.insert(load_metadata, 'load')\nself.metadata_mgr.close()\nlogger.info('Finished... | <|body_start_0|>
current_ts = self.loadts.strftime('%Y-%m-%d %H:%M:%S')
load_metadata = {'topic_name': self.topic, 'database_name': self.database, 'table_name': self.table, 'load_start_time': current_ts, 'load_end_time': current_ts}
self.metadata_mgr.insert(load_metadata, 'load')
self.me... | Handler for setup actions | SetupHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetupHandler:
"""Handler for setup actions"""
def setup_metadata(self):
"""Generates and inserts setup phase metadata into FlowView SQL database HDFS and Hive last directory both default set as None :param None: :return: None"""
<|body_0|>
def set_up_hdfs_ts_table(self):... | stack_v2_sparse_classes_75kplus_train_006419 | 3,704 | no_license | [
{
"docstring": "Generates and inserts setup phase metadata into FlowView SQL database HDFS and Hive last directory both default set as None :param None: :return: None",
"name": "setup_metadata",
"signature": "def setup_metadata(self)"
},
{
"docstring": "Sets up Hive table schema for loading mess... | 4 | stack_v2_sparse_classes_30k_train_051907 | Implement the Python class `SetupHandler` described below.
Class description:
Handler for setup actions
Method signatures and docstrings:
- def setup_metadata(self): Generates and inserts setup phase metadata into FlowView SQL database HDFS and Hive last directory both default set as None :param None: :return: None
-... | Implement the Python class `SetupHandler` described below.
Class description:
Handler for setup actions
Method signatures and docstrings:
- def setup_metadata(self): Generates and inserts setup phase metadata into FlowView SQL database HDFS and Hive last directory both default set as None :param None: :return: None
-... | ec029bc1e567775e26ecd333b96ba00c25169b1b | <|skeleton|>
class SetupHandler:
"""Handler for setup actions"""
def setup_metadata(self):
"""Generates and inserts setup phase metadata into FlowView SQL database HDFS and Hive last directory both default set as None :param None: :return: None"""
<|body_0|>
def set_up_hdfs_ts_table(self):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SetupHandler:
"""Handler for setup actions"""
def setup_metadata(self):
"""Generates and inserts setup phase metadata into FlowView SQL database HDFS and Hive last directory both default set as None :param None: :return: None"""
current_ts = self.loadts.strftime('%Y-%m-%d %H:%M:%S')
... | the_stack_v2_python_sparse | flowview/setup_handler.py | XiaoyangQian/FlowView | train | 2 |
1f4d47c84e44ae70d4a2cb87a6e3db858d545bc6 | [
"super(RMinimumSeeker, self).__init__()\nself._callback = callback\nself._accuracy = accuracy",
"start_value = self._callback(start)\nend_value = self._callback(end)\nmiddle_value = self._callback(middle)\nreturn middle_value < start_value and middle_value < end_value",
"start = -2\nend = -1\nprint()\nfor i in ... | <|body_start_0|>
super(RMinimumSeeker, self).__init__()
self._callback = callback
self._accuracy = accuracy
<|end_body_0|>
<|body_start_1|>
start_value = self._callback(start)
end_value = self._callback(end)
middle_value = self._callback(middle)
return middle_val... | Класс, реализующий функции для поиска минимума на отрезке, и поиска отрезка, содержащего минимум функции. | RMinimumSeeker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RMinimumSeeker:
"""Класс, реализующий функции для поиска минимума на отрезке, и поиска отрезка, содержащего минимум функции."""
def __init__(self, callback, accuracy=0.01):
"""Конструктор класса, входными аргументами которого являются функция и точность, с которой вычисляется минимум... | stack_v2_sparse_classes_75kplus_train_006420 | 5,946 | no_license | [
{
"docstring": "Конструктор класса, входными аргументами которого являются функция и точность, с которой вычисляется минимум. Значение точности по умолчанию 0.01",
"name": "__init__",
"signature": "def __init__(self, callback, accuracy=0.01)"
},
{
"docstring": "Вспомогательный метод, определяюща... | 5 | stack_v2_sparse_classes_30k_train_025024 | Implement the Python class `RMinimumSeeker` described below.
Class description:
Класс, реализующий функции для поиска минимума на отрезке, и поиска отрезка, содержащего минимум функции.
Method signatures and docstrings:
- def __init__(self, callback, accuracy=0.01): Конструктор класса, входными аргументами которого я... | Implement the Python class `RMinimumSeeker` described below.
Class description:
Класс, реализующий функции для поиска минимума на отрезке, и поиска отрезка, содержащего минимум функции.
Method signatures and docstrings:
- def __init__(self, callback, accuracy=0.01): Конструктор класса, входными аргументами которого я... | 8c05e15417e99d7236744fe9f960f4d6b09e4e31 | <|skeleton|>
class RMinimumSeeker:
"""Класс, реализующий функции для поиска минимума на отрезке, и поиска отрезка, содержащего минимум функции."""
def __init__(self, callback, accuracy=0.01):
"""Конструктор класса, входными аргументами которого являются функция и точность, с которой вычисляется минимум... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RMinimumSeeker:
"""Класс, реализующий функции для поиска минимума на отрезке, и поиска отрезка, содержащего минимум функции."""
def __init__(self, callback, accuracy=0.01):
"""Конструктор класса, входными аргументами которого являются функция и точность, с которой вычисляется минимум. Значение то... | the_stack_v2_python_sparse | educational/optimization-methods/one-dimentional-optimization/lab1.py | montreal91/workshop | train | 3 |
1a44da99eea577d6c07ebf90345b870c73d1c9d4 | [
"self.f = f\nself.gp = GP(X_init, Y_init, l, sigma_f)\nmin, max = bounds\nX_s = np.linspace(min, max, ac_samples)\nself.X_s = np.sort(X_s).reshape(-1, 1)\nself.xsi = xsi\nself.minimize = minimize",
"mu, sigma = self.gp.predict(self.X_s)\nif self.minimize is True:\n optimize = np.amin(self.gp.Y)\n imp = opti... | <|body_start_0|>
self.f = f
self.gp = GP(X_init, Y_init, l, sigma_f)
min, max = bounds
X_s = np.linspace(min, max, ac_samples)
self.X_s = np.sort(X_s).reshape(-1, 1)
self.xsi = xsi
self.minimize = minimize
<|end_body_0|>
<|body_start_1|>
mu, sigma = self.... | Bayes Optimization using Gaussian Process | BayesianOptimization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianOptimization:
"""Bayes Optimization using Gaussian Process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""* f is the black-box function to be optimized * X_init is a numpy.ndarray of shape (t, 1) representing the inpu... | stack_v2_sparse_classes_75kplus_train_006421 | 4,371 | no_license | [
{
"docstring": "* f is the black-box function to be optimized * X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function * Y_init is a numpy.ndarray of shape (t, 1) representing the outputs of the black-box function for each input in X_init - t is the number ... | 3 | stack_v2_sparse_classes_30k_train_006119 | Implement the Python class `BayesianOptimization` described below.
Class description:
Bayes Optimization using Gaussian Process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): * f is the black-box function to be optimized * X_init... | Implement the Python class `BayesianOptimization` described below.
Class description:
Bayes Optimization using Gaussian Process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): * f is the black-box function to be optimized * X_init... | 5aff923277cfe9f2b5324a773e4e5c3cac810a0c | <|skeleton|>
class BayesianOptimization:
"""Bayes Optimization using Gaussian Process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""* f is the black-box function to be optimized * X_init is a numpy.ndarray of shape (t, 1) representing the inpu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BayesianOptimization:
"""Bayes Optimization using Gaussian Process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""* f is the black-box function to be optimized * X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sa... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/4-bayes_opt.py | cmmolanos1/holbertonschool-machine_learning | train | 1 |
f45439be1eb9a030ef6790a49840485b15078c72 | [
"with open(filename, 'r') as file:\n num_nodes = None\n graph = {}\n for line in file:\n if num_nodes is None:\n num_nodes = int(line)\n graph = {id_: node_cls(id_) for id_ in range(1, num_nodes + 1)}\n else:\n m, n, dist = line.split(' ')\n m = int... | <|body_start_0|>
with open(filename, 'r') as file:
num_nodes = None
graph = {}
for line in file:
if num_nodes is None:
num_nodes = int(line)
graph = {id_: node_cls(id_) for id_ in range(1, num_nodes + 1)}
... | IOManager handles converting between dictionaries of GraphNode objects and .ecegraph files. | IOManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOManager:
"""IOManager handles converting between dictionaries of GraphNode objects and .ecegraph files."""
def import_graph(cls, filename, node_cls=GraphNode):
"""Returns a dictionary of GraphNode objects. Parameters: filename: Name of .ecegraph file to import (ie. map.ecegraph) Re... | stack_v2_sparse_classes_75kplus_train_006422 | 2,331 | no_license | [
{
"docstring": "Returns a dictionary of GraphNode objects. Parameters: filename: Name of .ecegraph file to import (ie. map.ecegraph) Returns: Dictionary where keys are ids and values are GraphNode objects. Example: graph = IOManager.import_graph('g.ecegraph')",
"name": "import_graph",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_val_000196 | Implement the Python class `IOManager` described below.
Class description:
IOManager handles converting between dictionaries of GraphNode objects and .ecegraph files.
Method signatures and docstrings:
- def import_graph(cls, filename, node_cls=GraphNode): Returns a dictionary of GraphNode objects. Parameters: filenam... | Implement the Python class `IOManager` described below.
Class description:
IOManager handles converting between dictionaries of GraphNode objects and .ecegraph files.
Method signatures and docstrings:
- def import_graph(cls, filename, node_cls=GraphNode): Returns a dictionary of GraphNode objects. Parameters: filenam... | faf065e0aae8e242d05f6940ba98be102f6ff6e5 | <|skeleton|>
class IOManager:
"""IOManager handles converting between dictionaries of GraphNode objects and .ecegraph files."""
def import_graph(cls, filename, node_cls=GraphNode):
"""Returns a dictionary of GraphNode objects. Parameters: filename: Name of .ecegraph file to import (ie. map.ecegraph) Re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IOManager:
"""IOManager handles converting between dictionaries of GraphNode objects and .ecegraph files."""
def import_graph(cls, filename, node_cls=GraphNode):
"""Returns a dictionary of GraphNode objects. Parameters: filename: Name of .ecegraph file to import (ie. map.ecegraph) Returns: Dictio... | the_stack_v2_python_sparse | graph/iomanager.py | andrew-zhou/ece457a | train | 0 |
be3423e4ca0687cc80d7361aceacf7a78295ddbc | [
"self.is_constant = is_constant\nself.pvname = pvname\nself.server = server",
"if not self.is_constant and op.value() is not None:\n pv.post(op.value())\n self.server.update_pv(pvname=self.pvname, value=op.value())\nop.done()"
] | <|body_start_0|>
self.is_constant = is_constant
self.pvname = pvname
self.server = server
<|end_body_0|>
<|body_start_1|>
if not self.is_constant and op.value() is not None:
pv.post(op.value())
self.server.update_pv(pvname=self.pvname, value=op.value())
o... | Handler object that defines the callbacks to execute on put operations to input process variables. | PVAccessInputHandler | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PVAccessInputHandler:
"""Handler object that defines the callbacks to execute on put operations to input process variables."""
def __init__(self, pvname: str, is_constant: bool, server: PVAServer):
"""Initialize the handler with prefix and image pv attributes Args: pvname (str): The ... | stack_v2_sparse_classes_75kplus_train_006423 | 11,196 | permissive | [
{
"docstring": "Initialize the handler with prefix and image pv attributes Args: pvname (str): The PV being handled server (PVAServer): Reference to the server holding this PV",
"name": "__init__",
"signature": "def __init__(self, pvname: str, is_constant: bool, server: PVAServer)"
},
{
"docstri... | 2 | stack_v2_sparse_classes_30k_test_001400 | Implement the Python class `PVAccessInputHandler` described below.
Class description:
Handler object that defines the callbacks to execute on put operations to input process variables.
Method signatures and docstrings:
- def __init__(self, pvname: str, is_constant: bool, server: PVAServer): Initialize the handler wit... | Implement the Python class `PVAccessInputHandler` described below.
Class description:
Handler object that defines the callbacks to execute on put operations to input process variables.
Method signatures and docstrings:
- def __init__(self, pvname: str, is_constant: bool, server: PVAServer): Initialize the handler wit... | 9f64fef12127c348e630ebcee2a0caa2c67970a5 | <|skeleton|>
class PVAccessInputHandler:
"""Handler object that defines the callbacks to execute on put operations to input process variables."""
def __init__(self, pvname: str, is_constant: bool, server: PVAServer):
"""Initialize the handler with prefix and image pv attributes Args: pvname (str): The ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PVAccessInputHandler:
"""Handler object that defines the callbacks to execute on put operations to input process variables."""
def __init__(self, pvname: str, is_constant: bool, server: PVAServer):
"""Initialize the handler with prefix and image pv attributes Args: pvname (str): The PV being hand... | the_stack_v2_python_sparse | lume_epics/epics_pva_server.py | lee-edelen/lume-epics | train | 0 |
bea655b1a9dc4075e504d6de139d02d093366659 | [
"LOG.debug('Initializing a polling monitor...')\nsuper(PollingMonitor, self).__init__(monitor_plugins)\nself.polling_timers = []",
"LOG.debug('Starting a polling monitor...')\ntry:\n for plugin in self.monitor_plugins:\n self.polling_timers.append(self.tg.add_timer(plugin.get_polling_interval(), self.ca... | <|body_start_0|>
LOG.debug('Initializing a polling monitor...')
super(PollingMonitor, self).__init__(monitor_plugins)
self.polling_timers = []
<|end_body_0|>
<|body_start_1|>
LOG.debug('Starting a polling monitor...')
try:
for plugin in self.monitor_plugins:
... | A polling based monitor. | PollingMonitor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PollingMonitor:
"""A polling based monitor."""
def __init__(self, monitor_plugins):
"""Initialize a polling monitor."""
<|body_0|>
def start_monitoring(self):
"""Start polling."""
<|body_1|>
def stop_monitoring(self):
"""Stop polling."""
... | stack_v2_sparse_classes_75kplus_train_006424 | 2,095 | permissive | [
{
"docstring": "Initialize a polling monitor.",
"name": "__init__",
"signature": "def __init__(self, monitor_plugins)"
},
{
"docstring": "Start polling.",
"name": "start_monitoring",
"signature": "def start_monitoring(self)"
},
{
"docstring": "Stop polling.",
"name": "stop_mo... | 3 | stack_v2_sparse_classes_30k_train_034731 | Implement the Python class `PollingMonitor` described below.
Class description:
A polling based monitor.
Method signatures and docstrings:
- def __init__(self, monitor_plugins): Initialize a polling monitor.
- def start_monitoring(self): Start polling.
- def stop_monitoring(self): Stop polling. | Implement the Python class `PollingMonitor` described below.
Class description:
A polling based monitor.
Method signatures and docstrings:
- def __init__(self, monitor_plugins): Initialize a polling monitor.
- def start_monitoring(self): Start polling.
- def stop_monitoring(self): Stop polling.
<|skeleton|>
class Po... | 5ecdc85538f8172eb63b13441dc08b166851befe | <|skeleton|>
class PollingMonitor:
"""A polling based monitor."""
def __init__(self, monitor_plugins):
"""Initialize a polling monitor."""
<|body_0|>
def start_monitoring(self):
"""Start polling."""
<|body_1|>
def stop_monitoring(self):
"""Stop polling."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PollingMonitor:
"""A polling based monitor."""
def __init__(self, monitor_plugins):
"""Initialize a polling monitor."""
LOG.debug('Initializing a polling monitor...')
super(PollingMonitor, self).__init__(monitor_plugins)
self.polling_timers = []
def start_monitoring(s... | the_stack_v2_python_sparse | blazar/monitor/polling_monitor.py | ChameleonCloud/blazar | train | 1 |
24b1311596112a082624596d5ec6f9a3c5f8a5e0 | [
"super().__init__()\nself.mode = mode\nself.ndims = settings.get_ndims()",
"mode = mode if mode else self.mode\ncoordinates = coordinates.clone()\nsize = values.shape[2:]\nfor i in range(len(size)):\n coordinates[:, i, ...] = 2 * (coordinates[:, i, ...] / (size[i] - 1) - 0.5)\ncoordinates = coordinates.permute... | <|body_start_0|>
super().__init__()
self.mode = mode
self.ndims = settings.get_ndims()
<|end_body_0|>
<|body_start_1|>
mode = mode if mode else self.mode
coordinates = coordinates.clone()
size = values.shape[2:]
for i in range(len(size)):
coordinates[... | A simple Grid sample operation | GridSampler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GridSampler:
"""A simple Grid sample operation"""
def __init__(self, mode='bilinear'):
"""Instantiates the grid sampler. The grid sampler samples a grid of values at coordinates. Parameters: mode: interpolation mode"""
<|body_0|>
def forward(self, values, coordinates, mo... | stack_v2_sparse_classes_75kplus_train_006425 | 8,565 | no_license | [
{
"docstring": "Instantiates the grid sampler. The grid sampler samples a grid of values at coordinates. Parameters: mode: interpolation mode",
"name": "__init__",
"signature": "def __init__(self, mode='bilinear')"
},
{
"docstring": "Transforms the src with the flow Parameters: src: Tensor (B x ... | 2 | stack_v2_sparse_classes_30k_train_026984 | Implement the Python class `GridSampler` described below.
Class description:
A simple Grid sample operation
Method signatures and docstrings:
- def __init__(self, mode='bilinear'): Instantiates the grid sampler. The grid sampler samples a grid of values at coordinates. Parameters: mode: interpolation mode
- def forwa... | Implement the Python class `GridSampler` described below.
Class description:
A simple Grid sample operation
Method signatures and docstrings:
- def __init__(self, mode='bilinear'): Instantiates the grid sampler. The grid sampler samples a grid of values at coordinates. Parameters: mode: interpolation mode
- def forwa... | c295ab990c8394a4da8fedee01d1e5a3f63d8f04 | <|skeleton|>
class GridSampler:
"""A simple Grid sample operation"""
def __init__(self, mode='bilinear'):
"""Instantiates the grid sampler. The grid sampler samples a grid of values at coordinates. Parameters: mode: interpolation mode"""
<|body_0|>
def forward(self, values, coordinates, mo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GridSampler:
"""A simple Grid sample operation"""
def __init__(self, mode='bilinear'):
"""Instantiates the grid sampler. The grid sampler samples a grid of values at coordinates. Parameters: mode: interpolation mode"""
super().__init__()
self.mode = mode
self.ndims = setti... | the_stack_v2_python_sparse | torchreg/nn/layers.py | SteffenCzolbe/TopologicalChangeDetection | train | 3 |
5ec7fd068f91d7b5dedadbd05abe6421a3970787 | [
"def to_date(s):\n return datetime.strptime(s, '%Y-%m-%d')\nvalidator = Validator({'birthdate': {'required': True, 'type': 'date', 'coerce': to_date}, 'document': {'required': True, 'type': 'string'}, 'name': {'required': True, 'type': 'string'}, 'email': {'required': True, 'type': 'string'}, 'password': {'requi... | <|body_start_0|>
def to_date(s):
return datetime.strptime(s, '%Y-%m-%d')
validator = Validator({'birthdate': {'required': True, 'type': 'date', 'coerce': to_date}, 'document': {'required': True, 'type': 'string'}, 'name': {'required': True, 'type': 'string'}, 'email': {'required': True, 'typ... | Defines the HTTP verbs to user model management. | UserApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserApi:
"""Defines the HTTP verbs to user model management."""
def post(self, request):
"""Create an user. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code."""
<|body_0|>
def g... | stack_v2_sparse_classes_75kplus_train_006426 | 9,574 | permissive | [
{
"docstring": "Create an user. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code.",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Retrieve user list. Parameters ---------- re... | 2 | stack_v2_sparse_classes_30k_train_022351 | Implement the Python class `UserApi` described below.
Class description:
Defines the HTTP verbs to user model management.
Method signatures and docstrings:
- def post(self, request): Create an user. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body r... | Implement the Python class `UserApi` described below.
Class description:
Defines the HTTP verbs to user model management.
Method signatures and docstrings:
- def post(self, request): Create an user. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body r... | d56d365dd840ecd272ce933c26f2d408e01c44c7 | <|skeleton|>
class UserApi:
"""Defines the HTTP verbs to user model management."""
def post(self, request):
"""Create an user. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code."""
<|body_0|>
def g... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserApi:
"""Defines the HTTP verbs to user model management."""
def post(self, request):
"""Create an user. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code."""
def to_date(s):
return... | the_stack_v2_python_sparse | api/views/user/general.py | santiagoSSAA/ParkingLot_Back | train | 0 |
19eba7f6d685ad9ced4caed6f71b2d671bfccada | [
"response = self.client.get(reverse('accounts:login'))\nself.assertEqual(response.status_code, 200)\nself.assertContains(response, 'Sign up')\nself.assertContains(response, 'Log in')\nself.assertNotContains(response, 'Import Music')\nself.assertNotContains(response, 'Insights')\nself.assertNotContains(response, 'Mu... | <|body_start_0|>
response = self.client.get(reverse('accounts:login'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'Sign up')
self.assertContains(response, 'Log in')
self.assertNotContains(response, 'Import Music')
self.assertNotContains(resp... | Test views behaviour related to authentication | TestAuthViewsBehaviour | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAuthViewsBehaviour:
"""Test views behaviour related to authentication"""
def test_navbar(self):
"""Verify that the navbar does not display login based view to an anonymous user."""
<|body_0|>
def test_profile(self):
"""Make sure that the profile page is login... | stack_v2_sparse_classes_75kplus_train_006427 | 3,810 | no_license | [
{
"docstring": "Verify that the navbar does not display login based view to an anonymous user.",
"name": "test_navbar",
"signature": "def test_navbar(self)"
},
{
"docstring": "Make sure that the profile page is login-only and display the required buttons.",
"name": "test_profile",
"signa... | 2 | stack_v2_sparse_classes_30k_train_019375 | Implement the Python class `TestAuthViewsBehaviour` described below.
Class description:
Test views behaviour related to authentication
Method signatures and docstrings:
- def test_navbar(self): Verify that the navbar does not display login based view to an anonymous user.
- def test_profile(self): Make sure that the ... | Implement the Python class `TestAuthViewsBehaviour` described below.
Class description:
Test views behaviour related to authentication
Method signatures and docstrings:
- def test_navbar(self): Verify that the navbar does not display login based view to an anonymous user.
- def test_profile(self): Make sure that the ... | e2d6a0336c7934cae71f833cb34a1f5f21db2d02 | <|skeleton|>
class TestAuthViewsBehaviour:
"""Test views behaviour related to authentication"""
def test_navbar(self):
"""Verify that the navbar does not display login based view to an anonymous user."""
<|body_0|>
def test_profile(self):
"""Make sure that the profile page is login... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAuthViewsBehaviour:
"""Test views behaviour related to authentication"""
def test_navbar(self):
"""Verify that the navbar does not display login based view to an anonymous user."""
response = self.client.get(reverse('accounts:login'))
self.assertEqual(response.status_code, 200... | the_stack_v2_python_sparse | accounts/tests_views.py | gbip/djRDO | train | 3 |
620f5e81278d1a970f3223841d65b4ca6efb003e | [
"_generic_fasta_file.__init__(self, path_file)\nself.read_fasta_file()\nself.identification_key = identification_key",
"list_id = []\nfor key, value in self.dict_fasta_data.items():\n dict_elements = self.split_header_by_square_brackets(value.description)\n list_id.append(dict_elements['protein_id'])\nretur... | <|body_start_0|>
_generic_fasta_file.__init__(self, path_file)
self.read_fasta_file()
self.identification_key = identification_key
<|end_body_0|>
<|body_start_1|>
list_id = []
for key, value in self.dict_fasta_data.items():
dict_elements = self.split_header_by_square... | Class specified in the treatment of the fasta protein nucleotids sequence NCBI format file of fasta. Remember that its a heritage of the class generic_fasta_file that its used to read the data from a file | Fasta_protein_NCBI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fasta_protein_NCBI:
"""Class specified in the treatment of the fasta protein nucleotids sequence NCBI format file of fasta. Remember that its a heritage of the class generic_fasta_file that its used to read the data from a file"""
def __init__(self, path_file, identification_key='protein_id'... | stack_v2_sparse_classes_75kplus_train_006428 | 3,861 | permissive | [
{
"docstring": "Constructor of the class fasta protein class, this one contain all methods for the treatment of fasta protein - proteic sequence of NCBI platform. After the parameters initialisation, the datails loaded :param path_file: Complete path with file name :param identification_key: Key used to obtain ... | 5 | null | Implement the Python class `Fasta_protein_NCBI` described below.
Class description:
Class specified in the treatment of the fasta protein nucleotids sequence NCBI format file of fasta. Remember that its a heritage of the class generic_fasta_file that its used to read the data from a file
Method signatures and docstri... | Implement the Python class `Fasta_protein_NCBI` described below.
Class description:
Class specified in the treatment of the fasta protein nucleotids sequence NCBI format file of fasta. Remember that its a heritage of the class generic_fasta_file that its used to read the data from a file
Method signatures and docstri... | 862eb85746e8a3a9bbc0d6aef9abbd5eebe9765f | <|skeleton|>
class Fasta_protein_NCBI:
"""Class specified in the treatment of the fasta protein nucleotids sequence NCBI format file of fasta. Remember that its a heritage of the class generic_fasta_file that its used to read the data from a file"""
def __init__(self, path_file, identification_key='protein_id'... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fasta_protein_NCBI:
"""Class specified in the treatment of the fasta protein nucleotids sequence NCBI format file of fasta. Remember that its a heritage of the class generic_fasta_file that its used to read the data from a file"""
def __init__(self, path_file, identification_key='protein_id'):
""... | the_stack_v2_python_sparse | files_treatment_new/fasta_protein_NCBI.py | diogo1790/inphinity | train | 1 |
d6874915ef5df99170c06bbd62376d1db425b1aa | [
"self.logger = logger\nself.cfg = cfg\nself.influxdb_client = influxdb_client\nself.root_path = root_path\nself.env_type = env_type\nself.email_notification = email_notification\ntry:\n self.connection = pyodbc.connect('TRUSTED_CONNECTION=Yes' + ';DRIVER={' + self.cfg['mssql']['driver'] + '};SERVER=' + self.cfg[... | <|body_start_0|>
self.logger = logger
self.cfg = cfg
self.influxdb_client = influxdb_client
self.root_path = root_path
self.env_type = env_type
self.email_notification = email_notification
try:
self.connection = pyodbc.connect('TRUSTED_CONNECTION=Yes' ... | MSSQLProducer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MSSQLProducer:
def __init__(self, env_type, logger, cfg, influxdb_client, root_path, email_notification):
"""Конструктор класса Args: env_type (str): тип среды запуска программы logger (TimedRotatingLogger): логер cfg (dict): словарь параметров influxdb_client (InfluxBDProducer): объект ... | stack_v2_sparse_classes_75kplus_train_006429 | 6,535 | no_license | [
{
"docstring": "Конструктор класса Args: env_type (str): тип среды запуска программы logger (TimedRotatingLogger): логер cfg (dict): словарь параметров influxdb_client (InfluxBDProducer): объект для логирования в базу InfluxDB root_path (str): полный корневой путь к программе email_notification (EmailNotificati... | 3 | stack_v2_sparse_classes_30k_train_026344 | Implement the Python class `MSSQLProducer` described below.
Class description:
Implement the MSSQLProducer class.
Method signatures and docstrings:
- def __init__(self, env_type, logger, cfg, influxdb_client, root_path, email_notification): Конструктор класса Args: env_type (str): тип среды запуска программы logger (... | Implement the Python class `MSSQLProducer` described below.
Class description:
Implement the MSSQLProducer class.
Method signatures and docstrings:
- def __init__(self, env_type, logger, cfg, influxdb_client, root_path, email_notification): Конструктор класса Args: env_type (str): тип среды запуска программы logger (... | cf8be435cba3d3a6fc33655cdddefc1c002b6e32 | <|skeleton|>
class MSSQLProducer:
def __init__(self, env_type, logger, cfg, influxdb_client, root_path, email_notification):
"""Конструктор класса Args: env_type (str): тип среды запуска программы logger (TimedRotatingLogger): логер cfg (dict): словарь параметров influxdb_client (InfluxBDProducer): объект ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MSSQLProducer:
def __init__(self, env_type, logger, cfg, influxdb_client, root_path, email_notification):
"""Конструктор класса Args: env_type (str): тип среды запуска программы logger (TimedRotatingLogger): логер cfg (dict): словарь параметров influxdb_client (InfluxBDProducer): объект для логировани... | the_stack_v2_python_sparse | project/parser_efx_kafka/parser_efx_kafka/mssql_producer.py | Vladimir-951/vladimir_repo | train | 0 | |
5baca1b90949d6c801bc2f4f0797a423af2180c5 | [
"self.screen = game.screen\nself.settings = game.settings\nself.ship = game.ship\nself.aliens = pg.sprite.Group()",
"alien = Alien(self)\nalien_width, _ = alien.rect.size\nalien.x = alien_width + 3 / 2 * alien_width * alien_number\nalien.rect.x = alien.x\nalien.rect.y = alien.rect.height + 5 / 2 * alien.rect.heig... | <|body_start_0|>
self.screen = game.screen
self.settings = game.settings
self.ship = game.ship
self.aliens = pg.sprite.Group()
<|end_body_0|>
<|body_start_1|>
alien = Alien(self)
alien_width, _ = alien.rect.size
alien.x = alien_width + 3 / 2 * alien_width * alien... | A class to create a sprite group to store aliens in the alien fleet. | Fleet | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fleet:
"""A class to create a sprite group to store aliens in the alien fleet."""
def __init__(self, game):
"""Initialize the game resources required for this class."""
<|body_0|>
def _create_alien(self, alien_number: int, row_number: int):
"""Create an alien and... | stack_v2_sparse_classes_75kplus_train_006430 | 2,473 | permissive | [
{
"docstring": "Initialize the game resources required for this class.",
"name": "__init__",
"signature": "def __init__(self, game)"
},
{
"docstring": "Create an alien and place it in the row.",
"name": "_create_alien",
"signature": "def _create_alien(self, alien_number: int, row_number:... | 5 | stack_v2_sparse_classes_30k_train_048947 | Implement the Python class `Fleet` described below.
Class description:
A class to create a sprite group to store aliens in the alien fleet.
Method signatures and docstrings:
- def __init__(self, game): Initialize the game resources required for this class.
- def _create_alien(self, alien_number: int, row_number: int)... | Implement the Python class `Fleet` described below.
Class description:
A class to create a sprite group to store aliens in the alien fleet.
Method signatures and docstrings:
- def __init__(self, game): Initialize the game resources required for this class.
- def _create_alien(self, alien_number: int, row_number: int)... | 152fbe43256a80905881055490167d6fe1e3e996 | <|skeleton|>
class Fleet:
"""A class to create a sprite group to store aliens in the alien fleet."""
def __init__(self, game):
"""Initialize the game resources required for this class."""
<|body_0|>
def _create_alien(self, alien_number: int, row_number: int):
"""Create an alien and... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fleet:
"""A class to create a sprite group to store aliens in the alien fleet."""
def __init__(self, game):
"""Initialize the game resources required for this class."""
self.screen = game.screen
self.settings = game.settings
self.ship = game.ship
self.aliens = pg.s... | the_stack_v2_python_sparse | alieninvaders/alien_fleet.py | yatesmac/Alien-Invaders | train | 0 |
f0bbd71133ec267960e996e646cc721fcf07b703 | [
"def dfs(root, s):\n if L <= root.val <= R:\n s += root.val\n if root.left:\n s = dfs(root.left, s)\n if root.right:\n s = dfs(root.right, s)\n return s\nreturn dfs(root, 0)",
"if not root:\n return 0\nif root.val >= L and root.val <= R:\n return root.val + self.rangeSumBST(... | <|body_start_0|>
def dfs(root, s):
if L <= root.val <= R:
s += root.val
if root.left:
s = dfs(root.left, s)
if root.right:
s = dfs(root.right, s)
return s
return dfs(root, 0)
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rangeSumBST(self, root, L, R):
""":type root: TreeNode :type L: int :type R: int :rtype: int 312 ms"""
<|body_0|>
def rangeSumBST_1(self, root, L, R):
""":type root: TreeNode :type L: int :type R: int :rtype: int 308ms"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_006431 | 1,800 | no_license | [
{
"docstring": ":type root: TreeNode :type L: int :type R: int :rtype: int 312 ms",
"name": "rangeSumBST",
"signature": "def rangeSumBST(self, root, L, R)"
},
{
"docstring": ":type root: TreeNode :type L: int :type R: int :rtype: int 308ms",
"name": "rangeSumBST_1",
"signature": "def ran... | 2 | stack_v2_sparse_classes_30k_train_051689 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rangeSumBST(self, root, L, R): :type root: TreeNode :type L: int :type R: int :rtype: int 312 ms
- def rangeSumBST_1(self, root, L, R): :type root: TreeNode :type L: int :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rangeSumBST(self, root, L, R): :type root: TreeNode :type L: int :type R: int :rtype: int 312 ms
- def rangeSumBST_1(self, root, L, R): :type root: TreeNode :type L: int :typ... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def rangeSumBST(self, root, L, R):
""":type root: TreeNode :type L: int :type R: int :rtype: int 312 ms"""
<|body_0|>
def rangeSumBST_1(self, root, L, R):
""":type root: TreeNode :type L: int :type R: int :rtype: int 308ms"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rangeSumBST(self, root, L, R):
""":type root: TreeNode :type L: int :type R: int :rtype: int 312 ms"""
def dfs(root, s):
if L <= root.val <= R:
s += root.val
if root.left:
s = dfs(root.left, s)
if root.right:
... | the_stack_v2_python_sparse | RangeSumOfBST_MID_938.py | 953250587/leetcode-python | train | 2 | |
f906a812493d23234d910156ed46c265a6f39f2c | [
"super().__init__(num_qubits)\nself.gate_depth = gate_depth\nself.params = product_ansatz_parameters(self.num_qubits, self.gate_depth, 0.0)\nself.params.declare_memory_references(self.circuit)\nself._write_circuit()",
"for q in range(self.num_qubits):\n for g in range(self.gate_depth):\n self.circuit.in... | <|body_start_0|>
super().__init__(num_qubits)
self.gate_depth = gate_depth
self.params = product_ansatz_parameters(self.num_qubits, self.gate_depth, 0.0)
self.params.declare_memory_references(self.circuit)
self._write_circuit()
<|end_body_0|>
<|body_start_1|>
for q in ra... | Class for working with product ansatze. | ProductAnsatz | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductAnsatz:
"""Class for working with product ansatze."""
def __init__(self, num_qubits, gate_depth=3):
"""Initializes a ProductAnsatz. Args: num_qubits : int Number of qubits in the ansatz. gate_depth : int Number of hardware gates in the pattern ----[Rx(pi / 2)]----[Rz(parameter... | stack_v2_sparse_classes_75kplus_train_006432 | 2,290 | permissive | [
{
"docstring": "Initializes a ProductAnsatz. Args: num_qubits : int Number of qubits in the ansatz. gate_depth : int Number of hardware gates in the pattern ----[Rx(pi / 2)]----[Rz(parameter)]---- This pattern is a gate_depth of one.",
"name": "__init__",
"signature": "def __init__(self, num_qubits, gat... | 2 | null | Implement the Python class `ProductAnsatz` described below.
Class description:
Class for working with product ansatze.
Method signatures and docstrings:
- def __init__(self, num_qubits, gate_depth=3): Initializes a ProductAnsatz. Args: num_qubits : int Number of qubits in the ansatz. gate_depth : int Number of hardwa... | Implement the Python class `ProductAnsatz` described below.
Class description:
Class for working with product ansatze.
Method signatures and docstrings:
- def __init__(self, num_qubits, gate_depth=3): Initializes a ProductAnsatz. Args: num_qubits : int Number of qubits in the ansatz. gate_depth : int Number of hardwa... | 5fe919f100f54310a9300b32a838f965f834bbdf | <|skeleton|>
class ProductAnsatz:
"""Class for working with product ansatze."""
def __init__(self, num_qubits, gate_depth=3):
"""Initializes a ProductAnsatz. Args: num_qubits : int Number of qubits in the ansatz. gate_depth : int Number of hardware gates in the pattern ----[Rx(pi / 2)]----[Rz(parameter... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductAnsatz:
"""Class for working with product ansatze."""
def __init__(self, num_qubits, gate_depth=3):
"""Initializes a ProductAnsatz. Args: num_qubits : int Number of qubits in the ansatz. gate_depth : int Number of hardware gates in the pattern ----[Rx(pi / 2)]----[Rz(parameter)]---- This p... | the_stack_v2_python_sparse | src/nisqai/layer/_product_ansatz.py | rmlarose/nisqai-dev | train | 15 |
22fa8c173d91211b1bb7c376805f07d8a15b7c10 | [
"ret = 0\n\ndef minmax(node: TreeNode) -> Tuple:\n nonlocal ret\n vals = []\n if node.left:\n vals.extend(minmax(node.left))\n if node.right:\n vals.extend(minmax(node.right))\n if vals:\n ret = max(ret, abs(node.val - min(vals)), abs(node.val - max(vals)))\n vals.append(node.... | <|body_start_0|>
ret = 0
def minmax(node: TreeNode) -> Tuple:
nonlocal ret
vals = []
if node.left:
vals.extend(minmax(node.left))
if node.right:
vals.extend(minmax(node.right))
if vals:
ret = max... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
"""Jan 08, 2022 21:38"""
<|body_0|>
def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
"""Jan 08, 2022 21:38"""
<|body_1|>
def maxAncestorDiff(self, root: Optional[TreeNode]) ... | stack_v2_sparse_classes_75kplus_train_006433 | 3,056 | no_license | [
{
"docstring": "Jan 08, 2022 21:38",
"name": "maxAncestorDiff",
"signature": "def maxAncestorDiff(self, root: Optional[TreeNode]) -> int"
},
{
"docstring": "Jan 08, 2022 21:38",
"name": "maxAncestorDiff",
"signature": "def maxAncestorDiff(self, root: Optional[TreeNode]) -> int"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: Jan 08, 2022 21:38
- def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: Jan 08, 2022 21:38
- def maxAncestorD... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: Jan 08, 2022 21:38
- def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: Jan 08, 2022 21:38
- def maxAncestorD... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
"""Jan 08, 2022 21:38"""
<|body_0|>
def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
"""Jan 08, 2022 21:38"""
<|body_1|>
def maxAncestorDiff(self, root: Optional[TreeNode]) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
"""Jan 08, 2022 21:38"""
ret = 0
def minmax(node: TreeNode) -> Tuple:
nonlocal ret
vals = []
if node.left:
vals.extend(minmax(node.left))
if node.right... | the_stack_v2_python_sparse | leetcode/solved/1092_Maximum_Difference_Between_Node_and_Ancestor/solution.py | sungminoh/algorithms | train | 0 | |
1323917bc89f552c5935d845b1ebb59bb441728a | [
"if not type(lst) is list:\n raise TypeError(f\"Parameter 'lst' is of type {type(lst)}. This parameter must be an instance of list.\")\nlist_of_str = all((isinstance(e, str) for e in lst))\nlist_of_dicts = all((isinstance(e, dict) for e in lst))\nif not list_of_dicts and (not list_of_str):\n raise TypeError(f... | <|body_start_0|>
if not type(lst) is list:
raise TypeError(f"Parameter 'lst' is of type {type(lst)}. This parameter must be an instance of list.")
list_of_str = all((isinstance(e, str) for e in lst))
list_of_dicts = all((isinstance(e, dict) for e in lst))
if not list_of_dicts... | A plugin to extract emojis from text. | EmojiFilterPlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmojiFilterPlugin:
"""A plugin to extract emojis from text."""
def filter(self, lst, target_key=None):
"""Filters emojis from data and return the result in a dictionary with key called 'emojis'. Suports emojis with different skin colors tones, flags and ZWJ sequences of emojis. :para... | stack_v2_sparse_classes_75kplus_train_006434 | 3,643 | no_license | [
{
"docstring": "Filters emojis from data and return the result in a dictionary with key called 'emojis'. Suports emojis with different skin colors tones, flags and ZWJ sequences of emojis. :param lst: texts for emoji extraction :type lst: list of strings or list of dictionaries :param target_key: a valid key th... | 2 | stack_v2_sparse_classes_30k_train_039801 | Implement the Python class `EmojiFilterPlugin` described below.
Class description:
A plugin to extract emojis from text.
Method signatures and docstrings:
- def filter(self, lst, target_key=None): Filters emojis from data and return the result in a dictionary with key called 'emojis'. Suports emojis with different sk... | Implement the Python class `EmojiFilterPlugin` described below.
Class description:
A plugin to extract emojis from text.
Method signatures and docstrings:
- def filter(self, lst, target_key=None): Filters emojis from data and return the result in a dictionary with key called 'emojis'. Suports emojis with different sk... | 09186dc7edb3cd39d54969c33ddde6dd14c32ee6 | <|skeleton|>
class EmojiFilterPlugin:
"""A plugin to extract emojis from text."""
def filter(self, lst, target_key=None):
"""Filters emojis from data and return the result in a dictionary with key called 'emojis'. Suports emojis with different skin colors tones, flags and ZWJ sequences of emojis. :para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmojiFilterPlugin:
"""A plugin to extract emojis from text."""
def filter(self, lst, target_key=None):
"""Filters emojis from data and return the result in a dictionary with key called 'emojis'. Suports emojis with different skin colors tones, flags and ZWJ sequences of emojis. :param lst: texts ... | the_stack_v2_python_sparse | plugins/emoji_filter_plugin.py | willsimoes/projeto-final | train | 0 |
966fa0628c2c25ad169d05c02191e8cd27334b15 | [
"files = os.listdir('kaggledatasets/' + username + '/')\npaths = [os.path.join('kaggledatasets/' + username + '/', basename) for basename in files]\nlatest_file = max(paths, key=os.path.getctime)\nprint(latest_file)\ntreeinfo = {}\nwith open(latest_file) as json_file:\n data = json.load(json_file)\n exp = lis... | <|body_start_0|>
files = os.listdir('kaggledatasets/' + username + '/')
paths = [os.path.join('kaggledatasets/' + username + '/', basename) for basename in files]
latest_file = max(paths, key=os.path.getctime)
print(latest_file)
treeinfo = {}
with open(latest_file) as jso... | DataProcessor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataProcessor:
def getsets(self, username):
"""gets datasets from Kaggle :type username: string :param username: the Kaggle username of the active user"""
<|body_0|>
def uploadrawdata(self, username):
"""uploads current dataset to Kaggle :type username: string :param... | stack_v2_sparse_classes_75kplus_train_006435 | 6,862 | permissive | [
{
"docstring": "gets datasets from Kaggle :type username: string :param username: the Kaggle username of the active user",
"name": "getsets",
"signature": "def getsets(self, username)"
},
{
"docstring": "uploads current dataset to Kaggle :type username: string :param username: the Kaggle usernam... | 2 | stack_v2_sparse_classes_30k_val_001021 | Implement the Python class `DataProcessor` described below.
Class description:
Implement the DataProcessor class.
Method signatures and docstrings:
- def getsets(self, username): gets datasets from Kaggle :type username: string :param username: the Kaggle username of the active user
- def uploadrawdata(self, username... | Implement the Python class `DataProcessor` described below.
Class description:
Implement the DataProcessor class.
Method signatures and docstrings:
- def getsets(self, username): gets datasets from Kaggle :type username: string :param username: the Kaggle username of the active user
- def uploadrawdata(self, username... | 02822901edda2d3e27e9d79052437c8a6fddc249 | <|skeleton|>
class DataProcessor:
def getsets(self, username):
"""gets datasets from Kaggle :type username: string :param username: the Kaggle username of the active user"""
<|body_0|>
def uploadrawdata(self, username):
"""uploads current dataset to Kaggle :type username: string :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataProcessor:
def getsets(self, username):
"""gets datasets from Kaggle :type username: string :param username: the Kaggle username of the active user"""
files = os.listdir('kaggledatasets/' + username + '/')
paths = [os.path.join('kaggledatasets/' + username + '/', basename) for base... | the_stack_v2_python_sparse | apps/kaggle2.py | Andrew-Ritchie/Web-Based-Dashboard-for-Nanoindentation-Experiments | train | 1 | |
cfd94754e7e855a1624dbdc67904e8225aa86dc0 | [
"self.filepath = '{}{}.json'.format(self.config_path, filename)\nself.pretty = pretty\nif not exists(self.config_path):\n mkdir(self.config_path)\nloaded_data = self.load() if load else None\nif data is not None and (not loaded_data):\n self.data = data\nelif loaded_data:\n updated = False\n if type(loa... | <|body_start_0|>
self.filepath = '{}{}.json'.format(self.config_path, filename)
self.pretty = pretty
if not exists(self.config_path):
mkdir(self.config_path)
loaded_data = self.load() if load else None
if data is not None and (not loaded_data):
self.data =... | Config | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
def __init__(self, filename: str, data=None, load: bool=True, pretty=False):
"""Setup the config file if it does not exist. :param filename: usually a string representing the module name. :param data: default data setup, usually an empty/defaulted dictionary or list. :param load:... | stack_v2_sparse_classes_75kplus_train_006436 | 3,640 | permissive | [
{
"docstring": "Setup the config file if it does not exist. :param filename: usually a string representing the module name. :param data: default data setup, usually an empty/defaulted dictionary or list. :param load: should the config file load when initialized? Only loads when a config already exists.",
"n... | 3 | null | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self, filename: str, data=None, load: bool=True, pretty=False): Setup the config file if it does not exist. :param filename: usually a string representing the module nam... | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self, filename: str, data=None, load: bool=True, pretty=False): Setup the config file if it does not exist. :param filename: usually a string representing the module nam... | b2f31c1512e47e108d762c9fc22597d057d95e50 | <|skeleton|>
class Config:
def __init__(self, filename: str, data=None, load: bool=True, pretty=False):
"""Setup the config file if it does not exist. :param filename: usually a string representing the module name. :param data: default data setup, usually an empty/defaulted dictionary or list. :param load:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Config:
def __init__(self, filename: str, data=None, load: bool=True, pretty=False):
"""Setup the config file if it does not exist. :param filename: usually a string representing the module name. :param data: default data setup, usually an empty/defaulted dictionary or list. :param load: should the co... | the_stack_v2_python_sparse | pcbot/config.py | pckv/pcbot | train | 5 | |
36d005638c04e322a358545e4258028c2e388bcc | [
"errors = []\nif not HAS_TEXTFSM:\n errors.append(missing_required_lib('textfsm'))\nreturn {'errors': errors}",
"cli_output = self._task_args.get('text')\nres = self._check_reqs()\nif res.get('errors'):\n return {'errors': res.get('errors')}\ntry:\n template = open(self._task_args.get('parser').get('temp... | <|body_start_0|>
errors = []
if not HAS_TEXTFSM:
errors.append(missing_required_lib('textfsm'))
return {'errors': errors}
<|end_body_0|>
<|body_start_1|>
cli_output = self._task_args.get('text')
res = self._check_reqs()
if res.get('errors'):
retur... | The textfsm parser class Convert raw text to structured data using textfsm | CliParser | [
"GPL-3.0-or-later",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CliParser:
"""The textfsm parser class Convert raw text to structured data using textfsm"""
def _check_reqs():
"""Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path"""
<|body_0|>
def parse(self, *_args, **_kwargs):
... | stack_v2_sparse_classes_75kplus_train_006437 | 2,009 | permissive | [
{
"docstring": "Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path",
"name": "_check_reqs",
"signature": "def _check_reqs()"
},
{
"docstring": "Std entry point for a cli_parse parse execution :return: Errors or parsed text as structured data :rtype... | 2 | stack_v2_sparse_classes_30k_train_043950 | Implement the Python class `CliParser` described below.
Class description:
The textfsm parser class Convert raw text to structured data using textfsm
Method signatures and docstrings:
- def _check_reqs(): Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path
- def parse(se... | Implement the Python class `CliParser` described below.
Class description:
The textfsm parser class Convert raw text to structured data using textfsm
Method signatures and docstrings:
- def _check_reqs(): Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path
- def parse(se... | 2ea7d4f00212f502bc684ac257371ada73da1ca9 | <|skeleton|>
class CliParser:
"""The textfsm parser class Convert raw text to structured data using textfsm"""
def _check_reqs():
"""Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path"""
<|body_0|>
def parse(self, *_args, **_kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CliParser:
"""The textfsm parser class Convert raw text to structured data using textfsm"""
def _check_reqs():
"""Check the prerequisites for the textfsm parser :return dict: A dict with errors or a template_path"""
errors = []
if not HAS_TEXTFSM:
errors.append(missing... | the_stack_v2_python_sparse | intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/ansible/netcommon/plugins/cli_parsers/textfsm_parser.py | SimonFangCisco/dne-dna-code | train | 0 |
cc860b29375d98cbbad73336b6919396ffa08e9c | [
"if not check_exist(file):\n assert False, 'Cannot find the KPOINTS file. Check the path: ' + file\nelse:\n self.kpoints = open(file, 'r').readlines()",
"plane = self.kpoints[0].split()[-5]\nkrange = np.float64(self.kpoints[0].split()[-4:-2])\nnpoint = np.int64(self.kpoints[0].split()[-2:])\nreturn (plane, ... | <|body_start_0|>
if not check_exist(file):
assert False, 'Cannot find the KPOINTS file. Check the path: ' + file
else:
self.kpoints = open(file, 'r').readlines()
<|end_body_0|>
<|body_start_1|>
plane = self.kpoints[0].split()[-5]
krange = np.float64(self.kpoints[... | KPOINTS | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KPOINTS:
def __init__(self, file='KPOINTS'):
"""Read KPOINTS TODO: extend it to Selective dynamics"""
<|body_0|>
def get_spin_kmesh(self):
"""Read the kmesh header"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not check_exist(file):
... | stack_v2_sparse_classes_75kplus_train_006438 | 31,019 | permissive | [
{
"docstring": "Read KPOINTS TODO: extend it to Selective dynamics",
"name": "__init__",
"signature": "def __init__(self, file='KPOINTS')"
},
{
"docstring": "Read the kmesh header",
"name": "get_spin_kmesh",
"signature": "def get_spin_kmesh(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036151 | Implement the Python class `KPOINTS` described below.
Class description:
Implement the KPOINTS class.
Method signatures and docstrings:
- def __init__(self, file='KPOINTS'): Read KPOINTS TODO: extend it to Selective dynamics
- def get_spin_kmesh(self): Read the kmesh header | Implement the Python class `KPOINTS` described below.
Class description:
Implement the KPOINTS class.
Method signatures and docstrings:
- def __init__(self, file='KPOINTS'): Read KPOINTS TODO: extend it to Selective dynamics
- def get_spin_kmesh(self): Read the kmesh header
<|skeleton|>
class KPOINTS:
def __ini... | 42945ee15465caa6fad1983597e23beac78b774d | <|skeleton|>
class KPOINTS:
def __init__(self, file='KPOINTS'):
"""Read KPOINTS TODO: extend it to Selective dynamics"""
<|body_0|>
def get_spin_kmesh(self):
"""Read the kmesh header"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KPOINTS:
def __init__(self, file='KPOINTS'):
"""Read KPOINTS TODO: extend it to Selective dynamics"""
if not check_exist(file):
assert False, 'Cannot find the KPOINTS file. Check the path: ' + file
else:
self.kpoints = open(file, 'r').readlines()
def get_sp... | the_stack_v2_python_sparse | mcu/vasp/vasp_io.py | hungpham2017/mcu | train | 44 | |
b7cd4560515c40c2d3afe70e1a64fc617e99658c | [
"self.port = port\nself.folder = folder\nself.mappings = ['.'] if mappings is None else mappings\nself.lab = lab",
"helpMessage = HELP_TEMPLATE.format(port=self.port, folder=self.folder)\nsubparsers.add_parser('jupyter', help=helpMessage)\nreturn subparsers",
"docker.build(config, host=host, verbose=args.verbos... | <|body_start_0|>
self.port = port
self.folder = folder
self.mappings = ['.'] if mappings is None else mappings
self.lab = lab
<|end_body_0|>
<|body_start_1|>
helpMessage = HELP_TEMPLATE.format(port=self.port, folder=self.folder)
subparsers.add_parser('jupyter', help=help... | Jupyter Class Provides the ability to spin up Jupyter notebooks inside a Docker container with the exact configuration as the rest of the project and it's jobs | Jupyter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Jupyter:
"""Jupyter Class Provides the ability to spin up Jupyter notebooks inside a Docker container with the exact configuration as the rest of the project and it's jobs"""
def __init__(self, port=8888, folder='.', mappings=None, lab=False):
"""Initialize the class with simple defa... | stack_v2_sparse_classes_75kplus_train_006439 | 2,824 | permissive | [
{
"docstring": "Initialize the class with simple default values for port and folder",
"name": "__init__",
"signature": "def __init__(self, port=8888, folder='.', mappings=None, lab=False)"
},
{
"docstring": "SkeleParser Hook Adds a parser for the jupter command the starts up the notebooks in Doc... | 3 | stack_v2_sparse_classes_30k_train_032241 | Implement the Python class `Jupyter` described below.
Class description:
Jupyter Class Provides the ability to spin up Jupyter notebooks inside a Docker container with the exact configuration as the rest of the project and it's jobs
Method signatures and docstrings:
- def __init__(self, port=8888, folder='.', mapping... | Implement the Python class `Jupyter` described below.
Class description:
Jupyter Class Provides the ability to spin up Jupyter notebooks inside a Docker container with the exact configuration as the rest of the project and it's jobs
Method signatures and docstrings:
- def __init__(self, port=8888, folder='.', mapping... | c4299702994cdd55738de4591e85f4dc2a424d19 | <|skeleton|>
class Jupyter:
"""Jupyter Class Provides the ability to spin up Jupyter notebooks inside a Docker container with the exact configuration as the rest of the project and it's jobs"""
def __init__(self, port=8888, folder='.', mappings=None, lab=False):
"""Initialize the class with simple defa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Jupyter:
"""Jupyter Class Provides the ability to spin up Jupyter notebooks inside a Docker container with the exact configuration as the rest of the project and it's jobs"""
def __init__(self, port=8888, folder='.', mappings=None, lab=False):
"""Initialize the class with simple default values fo... | the_stack_v2_python_sparse | skelebot/components/jupyter.py | carsdotcom/skelebot | train | 37 |
2e34bb6ca90e92b267ad0946f69640262d974f71 | [
"super().__init__(*args, **kwargs)\nif ext_args == {}:\n self._freq = 1\nelse:\n self._freq = ext_args.freq",
"if engine.last_iter.val % self._freq == 0:\n engine.lr_scheduler.step()\nengine.log_buffer['cur_lr'] = engine.lr_scheduler.get_lr()[0]"
] | <|body_start_0|>
super().__init__(*args, **kwargs)
if ext_args == {}:
self._freq = 1
else:
self._freq = ext_args.freq
<|end_body_0|>
<|body_start_1|>
if engine.last_iter.val % self._freq == 0:
engine.lr_scheduler.step()
engine.log_buffer['cur_... | Overview: Hook used to set LrScheduler in learner Interfaces: __init__, __call__ Property: name, priority, position | LrSchedulerHook | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LrSchedulerHook:
"""Overview: Hook used to set LrScheduler in learner Interfaces: __init__, __call__ Property: name, priority, position"""
def __init__(self, *args, ext_args: EasyDict=EasyDict(), **kwargs) -> None:
"""Overview: init LrSchedulerHook Arguments: - ext_args (:obj:`EasyDi... | stack_v2_sparse_classes_75kplus_train_006440 | 13,409 | permissive | [
{
"docstring": "Overview: init LrSchedulerHook Arguments: - ext_args (:obj:`EasyDict`): extended_args, use ext_args.freq to set lr_freq",
"name": "__init__",
"signature": "def __init__(self, *args, ext_args: EasyDict=EasyDict(), **kwargs) -> None"
},
{
"docstring": "Overview: step the lr_schedul... | 2 | null | Implement the Python class `LrSchedulerHook` described below.
Class description:
Overview: Hook used to set LrScheduler in learner Interfaces: __init__, __call__ Property: name, priority, position
Method signatures and docstrings:
- def __init__(self, *args, ext_args: EasyDict=EasyDict(), **kwargs) -> None: Overview:... | Implement the Python class `LrSchedulerHook` described below.
Class description:
Overview: Hook used to set LrScheduler in learner Interfaces: __init__, __call__ Property: name, priority, position
Method signatures and docstrings:
- def __init__(self, *args, ext_args: EasyDict=EasyDict(), **kwargs) -> None: Overview:... | 09d507c412235a2f0cf9c0b3485ec9ed15fb6421 | <|skeleton|>
class LrSchedulerHook:
"""Overview: Hook used to set LrScheduler in learner Interfaces: __init__, __call__ Property: name, priority, position"""
def __init__(self, *args, ext_args: EasyDict=EasyDict(), **kwargs) -> None:
"""Overview: init LrSchedulerHook Arguments: - ext_args (:obj:`EasyDi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LrSchedulerHook:
"""Overview: Hook used to set LrScheduler in learner Interfaces: __init__, __call__ Property: name, priority, position"""
def __init__(self, *args, ext_args: EasyDict=EasyDict(), **kwargs) -> None:
"""Overview: init LrSchedulerHook Arguments: - ext_args (:obj:`EasyDict`): extende... | the_stack_v2_python_sparse | ctools/worker/learner/learner_hook.py | LFhase/DI-star | train | 1 |
076d1b8ec7f07af7351596ea7a9d26ea26313b1d | [
"super().__init__(hass, _LOGGER, name=f'octoprint-{config_entry.entry_id}', update_interval=timedelta(seconds=interval))\nself.config_entry = config_entry\nself._octoprint = octoprint\nself._printer_offline = False\nself.data = {'printer': None, 'job': None, 'last_read_time': None}",
"printer = None\ntry:\n jo... | <|body_start_0|>
super().__init__(hass, _LOGGER, name=f'octoprint-{config_entry.entry_id}', update_interval=timedelta(seconds=interval))
self.config_entry = config_entry
self._octoprint = octoprint
self._printer_offline = False
self.data = {'printer': None, 'job': None, 'last_rea... | Class to manage fetching Octoprint data. | OctoprintDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OctoprintDataUpdateCoordinator:
"""Class to manage fetching Octoprint data."""
def __init__(self, hass: HomeAssistant, octoprint: OctoprintClient, config_entry: ConfigEntry, interval: int) -> None:
"""Initialize."""
<|body_0|>
async def _async_update_data(self):
... | stack_v2_sparse_classes_75kplus_train_006441 | 3,236 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, octoprint: OctoprintClient, config_entry: ConfigEntry, interval: int) -> None"
},
{
"docstring": "Update data via API.",
"name": "_async_update_data",
"signature": "async def _async_up... | 3 | stack_v2_sparse_classes_30k_test_000647 | Implement the Python class `OctoprintDataUpdateCoordinator` described below.
Class description:
Class to manage fetching Octoprint data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, octoprint: OctoprintClient, config_entry: ConfigEntry, interval: int) -> None: Initialize.
- async def _a... | Implement the Python class `OctoprintDataUpdateCoordinator` described below.
Class description:
Class to manage fetching Octoprint data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, octoprint: OctoprintClient, config_entry: ConfigEntry, interval: int) -> None: Initialize.
- async def _a... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OctoprintDataUpdateCoordinator:
"""Class to manage fetching Octoprint data."""
def __init__(self, hass: HomeAssistant, octoprint: OctoprintClient, config_entry: ConfigEntry, interval: int) -> None:
"""Initialize."""
<|body_0|>
async def _async_update_data(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OctoprintDataUpdateCoordinator:
"""Class to manage fetching Octoprint data."""
def __init__(self, hass: HomeAssistant, octoprint: OctoprintClient, config_entry: ConfigEntry, interval: int) -> None:
"""Initialize."""
super().__init__(hass, _LOGGER, name=f'octoprint-{config_entry.entry_id}'... | the_stack_v2_python_sparse | homeassistant/components/octoprint/coordinator.py | home-assistant/core | train | 35,501 |
197fe39d4c39cbd0fe79fd7199c7b1f4fa2a98ec | [
"gr.sync_block.__init__(self, name='bayes_decision', in_sig=[np.dtype((np.float32, 1024)), np.dtype((_type, 1024))], out_sig=None)\nself._algorithm = algorithm\nself._count = 0\nself._iteraction = 0\nself._time = 0\nLogger.register('bayes_decision', ['hypothesis', 'activation', 'count', 'time'])\nLogger.register('f... | <|body_start_0|>
gr.sync_block.__init__(self, name='bayes_decision', in_sig=[np.dtype((np.float32, 1024)), np.dtype((_type, 1024))], out_sig=None)
self._algorithm = algorithm
self._count = 0
self._iteraction = 0
self._time = 0
Logger.register('bayes_decision', ['hypothesi... | HierarchicalFeedbackAlgorithm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HierarchicalFeedbackAlgorithm:
def __init__(self, algorithm, _type=np.float32):
"""CTOR @param algorithm @param _type @param learner Algorithm that will be adjusted. ??????????? @param a_feedback_strategy FeedbackTimeStrategy object. ????????????"""
<|body_0|>
def work(self,... | stack_v2_sparse_classes_75kplus_train_006442 | 9,018 | permissive | [
{
"docstring": "CTOR @param algorithm @param _type @param learner Algorithm that will be adjusted. ??????????? @param a_feedback_strategy FeedbackTimeStrategy object. ????????????",
"name": "__init__",
"signature": "def __init__(self, algorithm, _type=np.float32)"
},
{
"docstring": "@param input... | 2 | stack_v2_sparse_classes_30k_train_003702 | Implement the Python class `HierarchicalFeedbackAlgorithm` described below.
Class description:
Implement the HierarchicalFeedbackAlgorithm class.
Method signatures and docstrings:
- def __init__(self, algorithm, _type=np.float32): CTOR @param algorithm @param _type @param learner Algorithm that will be adjusted. ????... | Implement the Python class `HierarchicalFeedbackAlgorithm` described below.
Class description:
Implement the HierarchicalFeedbackAlgorithm class.
Method signatures and docstrings:
- def __init__(self, algorithm, _type=np.float32): CTOR @param algorithm @param _type @param learner Algorithm that will be adjusted. ????... | aafc0e93a81da86f414743b6b19ff4739045763a | <|skeleton|>
class HierarchicalFeedbackAlgorithm:
def __init__(self, algorithm, _type=np.float32):
"""CTOR @param algorithm @param _type @param learner Algorithm that will be adjusted. ??????????? @param a_feedback_strategy FeedbackTimeStrategy object. ????????????"""
<|body_0|>
def work(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HierarchicalFeedbackAlgorithm:
def __init__(self, algorithm, _type=np.float32):
"""CTOR @param algorithm @param _type @param learner Algorithm that will be adjusted. ??????????? @param a_feedback_strategy FeedbackTimeStrategy object. ????????????"""
gr.sync_block.__init__(self, name='bayes_dec... | the_stack_v2_python_sparse | python/algorithm/feedbackAlgorithm.py | ComputerNetworks-UFRGS/OpERA | train | 3 | |
2d171e5bee3beef595cc69bcb5e34165cfd1c058 | [
"self.screen = screen\nself.ai_settigns = ai_settings\nself.stats = stats\nself.screen_rect = screen.get_rect()\nself.text_color = (30, 30, 30)\nself.font = pygame.font.SysFont(None, 48)\nself.prep_score()\nself.prep_highest_score()\nself.prep_level()\nself.prep_ships()",
"rounded_score = int(round(self.stats.sco... | <|body_start_0|>
self.screen = screen
self.ai_settigns = ai_settings
self.stats = stats
self.screen_rect = screen.get_rect()
self.text_color = (30, 30, 30)
self.font = pygame.font.SysFont(None, 48)
self.prep_score()
self.prep_highest_score()
self.p... | Scoreboad | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scoreboad:
def __init__(self, ai_settings, screen, stats):
"""初始化得分涉及的属性"""
<|body_0|>
def prep_score(self):
"""将得分转化为渲染的图像"""
<|body_1|>
def prep_highest_score(self):
"""将最高分转化为渲染的图像"""
<|body_2|>
def prep_level(self):
"""将等... | stack_v2_sparse_classes_75kplus_train_006443 | 2,910 | no_license | [
{
"docstring": "初始化得分涉及的属性",
"name": "__init__",
"signature": "def __init__(self, ai_settings, screen, stats)"
},
{
"docstring": "将得分转化为渲染的图像",
"name": "prep_score",
"signature": "def prep_score(self)"
},
{
"docstring": "将最高分转化为渲染的图像",
"name": "prep_highest_score",
"signa... | 6 | stack_v2_sparse_classes_30k_train_046905 | Implement the Python class `Scoreboad` described below.
Class description:
Implement the Scoreboad class.
Method signatures and docstrings:
- def __init__(self, ai_settings, screen, stats): 初始化得分涉及的属性
- def prep_score(self): 将得分转化为渲染的图像
- def prep_highest_score(self): 将最高分转化为渲染的图像
- def prep_level(self): 将等级转化为渲染的图像
... | Implement the Python class `Scoreboad` described below.
Class description:
Implement the Scoreboad class.
Method signatures and docstrings:
- def __init__(self, ai_settings, screen, stats): 初始化得分涉及的属性
- def prep_score(self): 将得分转化为渲染的图像
- def prep_highest_score(self): 将最高分转化为渲染的图像
- def prep_level(self): 将等级转化为渲染的图像
... | 763493f0f73f4d6633c1fb9fc6a58d6144718db4 | <|skeleton|>
class Scoreboad:
def __init__(self, ai_settings, screen, stats):
"""初始化得分涉及的属性"""
<|body_0|>
def prep_score(self):
"""将得分转化为渲染的图像"""
<|body_1|>
def prep_highest_score(self):
"""将最高分转化为渲染的图像"""
<|body_2|>
def prep_level(self):
"""将等... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Scoreboad:
def __init__(self, ai_settings, screen, stats):
"""初始化得分涉及的属性"""
self.screen = screen
self.ai_settigns = ai_settings
self.stats = stats
self.screen_rect = screen.get_rect()
self.text_color = (30, 30, 30)
self.font = pygame.font.SysFont(None, 4... | the_stack_v2_python_sparse | alien_invasion/Scoreboard.py | Dgama/Eric-Matthes-Python-Programming | train | 0 | |
8ff439ea58283a670d4946e8c36332923a914901 | [
"self.mockInit = MagicMock()\nexpected = {'product_code': '23', 'description': 'toaster', 'market_price': 49.99, 'rental_price': 37.95}\n_ = self.mockInit(*expected.values())\nself.mockInit.assert_called_with(*expected.values())\nself.mockInit.assert_called_with('23', 'toaster', 49.99, 37.95)",
"expected = {'prod... | <|body_start_0|>
self.mockInit = MagicMock()
expected = {'product_code': '23', 'description': 'toaster', 'market_price': 49.99, 'rental_price': 37.95}
_ = self.mockInit(*expected.values())
self.mockInit.assert_called_with(*expected.values())
self.mockInit.assert_called_with('23',... | TestInventoryClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestInventoryClass:
def test_inventory_init(self):
"""Mock test that a inventory.__init__ is called with the correct parameters"""
<|body_0|>
def test_inventory_return(self):
"""Test that a inventory object is created"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_006444 | 8,711 | no_license | [
{
"docstring": "Mock test that a inventory.__init__ is called with the correct parameters",
"name": "test_inventory_init",
"signature": "def test_inventory_init(self)"
},
{
"docstring": "Test that a inventory object is created",
"name": "test_inventory_return",
"signature": "def test_inv... | 2 | stack_v2_sparse_classes_30k_train_006278 | Implement the Python class `TestInventoryClass` described below.
Class description:
Implement the TestInventoryClass class.
Method signatures and docstrings:
- def test_inventory_init(self): Mock test that a inventory.__init__ is called with the correct parameters
- def test_inventory_return(self): Test that a invent... | Implement the Python class `TestInventoryClass` described below.
Class description:
Implement the TestInventoryClass class.
Method signatures and docstrings:
- def test_inventory_init(self): Mock test that a inventory.__init__ is called with the correct parameters
- def test_inventory_return(self): Test that a invent... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestInventoryClass:
def test_inventory_init(self):
"""Mock test that a inventory.__init__ is called with the correct parameters"""
<|body_0|>
def test_inventory_return(self):
"""Test that a inventory object is created"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestInventoryClass:
def test_inventory_init(self):
"""Mock test that a inventory.__init__ is called with the correct parameters"""
self.mockInit = MagicMock()
expected = {'product_code': '23', 'description': 'toaster', 'market_price': 49.99, 'rental_price': 37.95}
_ = self.mock... | the_stack_v2_python_sparse | students/erica_edwards/lesson01/assignment/test_unit.py | JavaRod/SP_Python220B_2019 | train | 1 | |
42d13a36626ddd8c17a3c3a60834e4e4587d6b59 | [
"Parametre.__init__(self, 'contrôle', 'control')\nself.tronquer = True\nself.schema = '(<texte_libre>)'\nself.aide_courte = 'consulte ou modifie les contrôles'\nself.aide_longue = \"Les contrôles sont des formes d'ordres prolongés. Ils nécessitent généralement la présence d'un commandant (un capitaine ou un second)... | <|body_start_0|>
Parametre.__init__(self, 'contrôle', 'control')
self.tronquer = True
self.schema = '(<texte_libre>)'
self.aide_courte = 'consulte ou modifie les contrôles'
self.aide_longue = "Les contrôles sont des formes d'ordres prolongés. Ils nécessitent généralement la prése... | Commande 'équipage contrôle'. | PrmControle | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmControle:
"""Commande 'équipage contrôle'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parame... | stack_v2_sparse_classes_75kplus_train_006445 | 4,660 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007911 | Implement the Python class `PrmControle` described below.
Class description:
Commande 'équipage contrôle'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmControle` described below.
Class description:
Commande 'équipage contrôle'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmControle:
"""Commande 'é... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmControle:
"""Commande 'équipage contrôle'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrmControle:
"""Commande 'équipage contrôle'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'contrôle', 'control')
self.tronquer = True
self.schema = '(<texte_libre>)'
self.aide_courte = 'consulte ou modifie les contrôles'
... | the_stack_v2_python_sparse | src/secondaires/navigation/commandes/equipage/controle.py | vincent-lg/tsunami | train | 5 |
4dc63b922656a2fb05122b7c64420738e435b6ee | [
"if not matrix:\n return\nm, n = (len(matrix), len(matrix[0]))\ndp = [[0 for _ in xrange(n)] for _ in xrange(m)]\nfor i in xrange(m):\n for j in xrange(n):\n dp[i][j] = matrix[i][j]\n if i > 0:\n dp[i][j] += dp[i - 1][j]\n if j > 0:\n dp[i][j] += dp[i][j - 1]\n ... | <|body_start_0|>
if not matrix:
return
m, n = (len(matrix), len(matrix[0]))
dp = [[0 for _ in xrange(n)] for _ in xrange(m)]
for i in xrange(m):
for j in xrange(n):
dp[i][j] = matrix[i][j]
if i > 0:
dp[i][j] += d... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_75kplus_train_006446 | 1,325 | no_license | [
{
"docstring": "initialize your data structure here. :type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtyp... | 2 | stack_v2_sparse_classes_30k_train_026123 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | 0f45a05d258d7dced844c657da2362d87bee15a8 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
if not matrix:
return
m, n = (len(matrix), len(matrix[0]))
dp = [[0 for _ in xrange(n)] for _ in xrange(m)]
for i in xrange(m):
for j ... | the_stack_v2_python_sparse | 304-Range-Sum-Query-2D---Immutable/solution.py | zmxrice/leetcodetraining | train | 0 | |
16c12f01934348029b38ebb6f13fefb456af781c | [
"self.mdp = mdp\nself.sampleReward = sampleReward\nself.eventID = -1\nself.events = np.empty(0)\nself.sFlowURL = 'http://localhost:8008'\nself.floodLightURL = 'http://localhost:8080'",
"reward = self.sampleReward(self.mdp.R[action, state])\nwhile len(self.events) == 0:\n r = requests.get(self.sFlowURL + '/even... | <|body_start_0|>
self.mdp = mdp
self.sampleReward = sampleReward
self.eventID = -1
self.events = np.empty(0)
self.sFlowURL = 'http://localhost:8008'
self.floodLightURL = 'http://localhost:8080'
<|end_body_0|>
<|body_start_1|>
reward = self.sampleReward(self.mdp.R... | RL | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RL:
def __init__(self, mdp, sampleReward):
"""Constructor for the RL class Inputs: mdp -- Markov decision process (T, R, discount) sampleReward -- Function to sample rewards (e.g., bernoulli, Gaussian). This function takes one argument: the mean of the distributon and returns a sample fr... | stack_v2_sparse_classes_75kplus_train_006447 | 6,454 | permissive | [
{
"docstring": "Constructor for the RL class Inputs: mdp -- Markov decision process (T, R, discount) sampleReward -- Function to sample rewards (e.g., bernoulli, Gaussian). This function takes one argument: the mean of the distributon and returns a sample from the distribution.",
"name": "__init__",
"si... | 4 | stack_v2_sparse_classes_30k_train_027782 | Implement the Python class `RL` described below.
Class description:
Implement the RL class.
Method signatures and docstrings:
- def __init__(self, mdp, sampleReward): Constructor for the RL class Inputs: mdp -- Markov decision process (T, R, discount) sampleReward -- Function to sample rewards (e.g., bernoulli, Gauss... | Implement the Python class `RL` described below.
Class description:
Implement the RL class.
Method signatures and docstrings:
- def __init__(self, mdp, sampleReward): Constructor for the RL class Inputs: mdp -- Markov decision process (T, R, discount) sampleReward -- Function to sample rewards (e.g., bernoulli, Gauss... | 66da8398bb590bceecd7c7d51fa969d41a9a2619 | <|skeleton|>
class RL:
def __init__(self, mdp, sampleReward):
"""Constructor for the RL class Inputs: mdp -- Markov decision process (T, R, discount) sampleReward -- Function to sample rewards (e.g., bernoulli, Gaussian). This function takes one argument: the mean of the distributon and returns a sample fr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RL:
def __init__(self, mdp, sampleReward):
"""Constructor for the RL class Inputs: mdp -- Markov decision process (T, R, discount) sampleReward -- Function to sample rewards (e.g., bernoulli, Gaussian). This function takes one argument: the mean of the distributon and returns a sample from the distrib... | the_stack_v2_python_sparse | scripts/RLnetwork.py | li-ch/mind | train | 0 | |
bb486832bd19166be0735fed34e46da3db61ff77 | [
"super(FourierDQNNetwork, self).__init__(name=name)\nself.num_actions = num_actions\nself.fourier_basis_order = fourier_basis_order\nself.min_vals = min_vals\nself.max_vals = max_vals\nself.flatten = tf.keras.layers.Flatten()\nself.last_layer = tf.keras.layers.Dense(num_actions, use_bias=False, name='fully_connecte... | <|body_start_0|>
super(FourierDQNNetwork, self).__init__(name=name)
self.num_actions = num_actions
self.fourier_basis_order = fourier_basis_order
self.min_vals = min_vals
self.max_vals = max_vals
self.flatten = tf.keras.layers.Flatten()
self.last_layer = tf.keras.... | Keras model for DQN. | FourierDQNNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FourierDQNNetwork:
"""Keras model for DQN."""
def __init__(self, min_vals, max_vals, num_actions, fourier_basis_order=3, name=None):
"""Builds the function approximator used to compute the agent's Q-values. It uses the features of the FourierBasis class and a linear layer without bia... | stack_v2_sparse_classes_75kplus_train_006448 | 15,474 | permissive | [
{
"docstring": "Builds the function approximator used to compute the agent's Q-values. It uses the features of the FourierBasis class and a linear layer without bias. Value Function Approximation in Reinforcement Learning using the Fourier Basis\", Konidaris, Osentoski and Thomas (2011). Args: min_vals: float, ... | 2 | stack_v2_sparse_classes_30k_train_042053 | Implement the Python class `FourierDQNNetwork` described below.
Class description:
Keras model for DQN.
Method signatures and docstrings:
- def __init__(self, min_vals, max_vals, num_actions, fourier_basis_order=3, name=None): Builds the function approximator used to compute the agent's Q-values. It uses the features... | Implement the Python class `FourierDQNNetwork` described below.
Class description:
Keras model for DQN.
Method signatures and docstrings:
- def __init__(self, min_vals, max_vals, num_actions, fourier_basis_order=3, name=None): Builds the function approximator used to compute the agent's Q-values. It uses the features... | 44a51d0b2d484670637bf67f80be7f1ec31d8992 | <|skeleton|>
class FourierDQNNetwork:
"""Keras model for DQN."""
def __init__(self, min_vals, max_vals, num_actions, fourier_basis_order=3, name=None):
"""Builds the function approximator used to compute the agent's Q-values. It uses the features of the FourierBasis class and a linear layer without bia... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FourierDQNNetwork:
"""Keras model for DQN."""
def __init__(self, min_vals, max_vals, num_actions, fourier_basis_order=3, name=None):
"""Builds the function approximator used to compute the agent's Q-values. It uses the features of the FourierBasis class and a linear layer without bias. Value Func... | the_stack_v2_python_sparse | dopamine/discrete_domains/gym_lib.py | fmxFranky/dopamine | train | 2 |
ceba7e10142bebc83c30d9dadf34b4945360476e | [
"Axis.__init__(self, min=min, max=max, start=start, end=end, majorticks=majorticks, minorticks=minorticks, majorlength=majorlength, minorlength=minorlength, labelformat=labelformat, id=id, classes=classes, baseid=baseid, baseclasses=baseclasses, labelidprefix=labelidprefix, labelclasses=labelclasses, majoridprefix=... | <|body_start_0|>
Axis.__init__(self, min=min, max=max, start=start, end=end, majorticks=majorticks, minorticks=minorticks, majorlength=majorlength, minorlength=minorlength, labelformat=labelformat, id=id, classes=classes, baseid=baseid, baseclasses=baseclasses, labelidprefix=labelidprefix, labelclasses=labelcla... | An X Axis element. | XAxis | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XAxis:
"""An X Axis element."""
def __init__(self, min=0.0, max=1.0, start=0.0, end=1.0, majorticks=5, minorticks=20, majorlength=10, minorlength=5, y=0.0, labelformat='%d', id=u'', classes=(), baseid=u'', baseclasses=(), labelidprefix=u'', labelclasses=(), majoridprefix=u'', majorclasses=()... | stack_v2_sparse_classes_75kplus_train_006449 | 4,059 | permissive | [
{
"docstring": "@param min: The minimum value of the axis @param max: The maximum value of the axis @param start: The starting coordinate of the axis @param end: The ending coordinate of the axis @param majorticks: The number of major tick marks @type majorticks: integer @param minorticks: The number of minor t... | 2 | stack_v2_sparse_classes_30k_train_053132 | Implement the Python class `XAxis` described below.
Class description:
An X Axis element.
Method signatures and docstrings:
- def __init__(self, min=0.0, max=1.0, start=0.0, end=1.0, majorticks=5, minorticks=20, majorlength=10, minorlength=5, y=0.0, labelformat='%d', id=u'', classes=(), baseid=u'', baseclasses=(), la... | Implement the Python class `XAxis` described below.
Class description:
An X Axis element.
Method signatures and docstrings:
- def __init__(self, min=0.0, max=1.0, start=0.0, end=1.0, majorticks=5, minorticks=20, majorlength=10, minorlength=5, y=0.0, labelformat='%d', id=u'', classes=(), baseid=u'', baseclasses=(), la... | ff440f55f38d64658fcad3c60ded5236b1c0a401 | <|skeleton|>
class XAxis:
"""An X Axis element."""
def __init__(self, min=0.0, max=1.0, start=0.0, end=1.0, majorticks=5, minorticks=20, majorlength=10, minorlength=5, y=0.0, labelformat='%d', id=u'', classes=(), baseid=u'', baseclasses=(), labelidprefix=u'', labelclasses=(), majoridprefix=u'', majorclasses=()... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XAxis:
"""An X Axis element."""
def __init__(self, min=0.0, max=1.0, start=0.0, end=1.0, majorticks=5, minorticks=20, majorlength=10, minorlength=5, y=0.0, labelformat='%d', id=u'', classes=(), baseid=u'', baseclasses=(), labelidprefix=u'', labelclasses=(), majoridprefix=u'', majorclasses=(), minoridpref... | the_stack_v2_python_sparse | lib/elements/XAxis.py | agold/svgchart | train | 1 |
2b25e47f29bf8b885c0f9f607f263a959cb36501 | [
"matrix = [list(map(int, list(x))) for x in matrix]\nres = 0\nfor i in range(len(matrix)):\n vector = [0] * len(matrix[0])\n for j in range(len(matrix[i])):\n t = i\n while t < len(matrix) and matrix[t][j] == 1:\n vector[j] += 1\n t += 1\n res = max(self.largestRectangle... | <|body_start_0|>
matrix = [list(map(int, list(x))) for x in matrix]
res = 0
for i in range(len(matrix)):
vector = [0] * len(matrix[0])
for j in range(len(matrix[i])):
t = i
while t < len(matrix) and matrix[t][j] == 1:
ve... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
matrix = [list(... | stack_v2_sparse_classes_75kplus_train_006450 | 1,729 | no_license | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalRectangle",
"signature": "def maximalRectangle(self, matrix)"
},
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights)"
}
] | 2 | stack_v2_sparse_classes_30k_train_029048 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
<|skeleton|>
class ... | d1d49a34b3c2a1ba5c6962923fc74be9a1eff668 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
matrix = [list(map(int, list(x))) for x in matrix]
res = 0
for i in range(len(matrix)):
vector = [0] * len(matrix[0])
for j in range(len(matrix[i])):
... | the_stack_v2_python_sparse | 85.Maximal_Rectangle.py | daquexian/leetcode | train | 0 | |
ca716f1deb6911b79e00e20169db93a476e9411a | [
"def tree_to_list(root):\n from collections import deque\n if root == None:\n return []\n ans = []\n q = deque([root])\n while len(q) != 0:\n node = q.popleft()\n ans.append(node.val if node else None)\n if node:\n q.append(node.left)\n q.append(node.... | <|body_start_0|>
def tree_to_list(root):
from collections import deque
if root == None:
return []
ans = []
q = deque([root])
while len(q) != 0:
node = q.popleft()
ans.append(node.val if node else None)
... | 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: stra :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_006451 | 1,924 | 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: stra :rtype: TreeNode",
"name": "deserialize",
"signature": "def deseriali... | 2 | stack_v2_sparse_classes_30k_train_021494 | 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: stra :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: stra :rtype... | 48ba21799f63225c104f649c3871444a29ab978a | <|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: stra :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def tree_to_list(root):
from collections import deque
if root == None:
return []
ans = []
q = deque([root])
wh... | the_stack_v2_python_sparse | archive/449SerializeandDeserializeBST.py | doraemon1293/Leetcode | train | 0 | |
30ff358cdba387a38bcc36d0415dcff5005f6ec9 | [
"self.set_author('MPA')\nself.set_name('SinWaves')\nself.add_stream('1hz', unit='unit')\nself.add_stream('2hz', unit='unit')\nself.set_version(12)",
"last_end_date = self.unpersist('end_timestamp', None)\ntarget_end_date = self.date('2014-09-18T00:30:00')\nif last_end_date is None:\n last_end_date = self.date(... | <|body_start_0|>
self.set_author('MPA')
self.set_name('SinWaves')
self.add_stream('1hz', unit='unit')
self.add_stream('2hz', unit='unit')
self.set_version(12)
<|end_body_0|>
<|body_start_1|>
last_end_date = self.unpersist('end_timestamp', None)
target_end_date = ... | Example1HZ | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Example1HZ:
def setup(self, opts):
"""This constructs your distillate algorithm"""
<|body_0|>
def compute(self):
"""This is called to compute your algorithm. This example generates some sin waves at different frequencies. It also ensures that this sin wave extends fr... | stack_v2_sparse_classes_75kplus_train_006452 | 3,194 | no_license | [
{
"docstring": "This constructs your distillate algorithm",
"name": "setup",
"signature": "def setup(self, opts)"
},
{
"docstring": "This is called to compute your algorithm. This example generates some sin waves at different frequencies. It also ensures that this sin wave extends from Sep 17th ... | 2 | stack_v2_sparse_classes_30k_train_007562 | Implement the Python class `Example1HZ` described below.
Class description:
Implement the Example1HZ class.
Method signatures and docstrings:
- def setup(self, opts): This constructs your distillate algorithm
- def compute(self): This is called to compute your algorithm. This example generates some sin waves at diffe... | Implement the Python class `Example1HZ` described below.
Class description:
Implement the Example1HZ class.
Method signatures and docstrings:
- def setup(self, opts): This constructs your distillate algorithm
- def compute(self): This is called to compute your algorithm. This example generates some sin waves at diffe... | 9db4446f29c86776ecc24e07ee4024466fdf7c77 | <|skeleton|>
class Example1HZ:
def setup(self, opts):
"""This constructs your distillate algorithm"""
<|body_0|>
def compute(self):
"""This is called to compute your algorithm. This example generates some sin waves at different frequencies. It also ensures that this sin wave extends fr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Example1HZ:
def setup(self, opts):
"""This constructs your distillate algorithm"""
self.set_author('MPA')
self.set_name('SinWaves')
self.add_stream('1hz', unit='unit')
self.add_stream('2hz', unit='unit')
self.set_version(12)
def compute(self):
"""Th... | the_stack_v2_python_sparse | legacy/MPA/example_sin.py | mindis/upmu_algorithms | train | 0 | |
e434fe0be53f62eab4e41078d149a9fdc04845d2 | [
"longest = ''\nfor i in range(len(s)):\n center = self._expand(i, i, s)\n mirror = self._expand(i, i + 1, s)\n longest = max(center, mirror, longest, key=len)\nreturn longest",
"while left > -1 and right < len(s) and (s[left] == s[right]):\n left -= 1\n right += 1\nreturn s[left + 1:right]"
] | <|body_start_0|>
longest = ''
for i in range(len(s)):
center = self._expand(i, i, s)
mirror = self._expand(i, i + 1, s)
longest = max(center, mirror, longest, key=len)
return longest
<|end_body_0|>
<|body_start_1|>
while left > -1 and right < len(s) a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""Returns the longest palindrome within a given string. If there exist two or more palindromes of the same length, whichever comes first aphabetically will be returned. Example: longestPalindrome('babad') -> 'aba' longestPalindrome('... | stack_v2_sparse_classes_75kplus_train_006453 | 941 | no_license | [
{
"docstring": "Returns the longest palindrome within a given string. If there exist two or more palindromes of the same length, whichever comes first aphabetically will be returned. Example: longestPalindrome('babad') -> 'aba' longestPalindrome('cddb') -> 'bb'",
"name": "longestPalindrome",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_051929 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: Returns the longest palindrome within a given string. If there exist two or more palindromes of the same length, whichever comes first... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: Returns the longest palindrome within a given string. If there exist two or more palindromes of the same length, whichever comes first... | c6d600bc74afd14e00d4f0ffed40696192b229c3 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""Returns the longest palindrome within a given string. If there exist two or more palindromes of the same length, whichever comes first aphabetically will be returned. Example: longestPalindrome('babad') -> 'aba' longestPalindrome('... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestPalindrome(self, s: str) -> str:
"""Returns the longest palindrome within a given string. If there exist two or more palindromes of the same length, whichever comes first aphabetically will be returned. Example: longestPalindrome('babad') -> 'aba' longestPalindrome('cddb') -> 'bb'... | the_stack_v2_python_sparse | python/Top Interview Questions - Medium/Array and Strings/longestpalindromesubstring.py | Hilldrupca/LeetCode | train | 0 | |
fb7f952c7f01b52a0cb0b2f3f0e5893d08421183 | [
"try:\n registry = oai_registry_api.get_by_id(registry_id)\n serializer = serializers.RegistrySerializer(registry, context={'request': request})\n return Response(serializer.data, status=status.HTTP_200_OK)\nexcept exceptions.DoesNotExist:\n content = OaiPmhMessage.get_message_labelled('No registry foun... | <|body_start_0|>
try:
registry = oai_registry_api.get_by_id(registry_id)
serializer = serializers.RegistrySerializer(registry, context={'request': request})
return Response(serializer.data, status=status.HTTP_200_OK)
except exceptions.DoesNotExist:
content... | Registry Detail | RegistryDetail | [
"NIST-Software",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistryDetail:
"""Registry Detail"""
def get(self, request, registry_id):
"""Retrieve a Registry (Data provider) Args: request: HTTP request registry_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 content: Internal server er... | stack_v2_sparse_classes_75kplus_train_006454 | 17,640 | permissive | [
{
"docstring": "Retrieve a Registry (Data provider) Args: request: HTTP request registry_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 content: Internal server error",
"name": "get",
"signature": "def get(self, request, registry_id)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_000886 | Implement the Python class `RegistryDetail` described below.
Class description:
Registry Detail
Method signatures and docstrings:
- def get(self, request, registry_id): Retrieve a Registry (Data provider) Args: request: HTTP request registry_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Obj... | Implement the Python class `RegistryDetail` described below.
Class description:
Registry Detail
Method signatures and docstrings:
- def get(self, request, registry_id): Retrieve a Registry (Data provider) Args: request: HTTP request registry_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Obj... | bc5e31a9d7e5f66e34340230ae17a3cc2d08e7e7 | <|skeleton|>
class RegistryDetail:
"""Registry Detail"""
def get(self, request, registry_id):
"""Retrieve a Registry (Data provider) Args: request: HTTP request registry_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 content: Internal server er... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegistryDetail:
"""Registry Detail"""
def get(self, request, registry_id):
"""Retrieve a Registry (Data provider) Args: request: HTTP request registry_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 content: Internal server error"""
... | the_stack_v2_python_sparse | core_oaipmh_harvester_app/rest/oai_registry/views.py | usnistgov/core_oaipmh_harvester_app | train | 1 |
2ea8e6159d37a2d2a12d34435833a8fc22149001 | [
"self.head = head\nself.curr = head\nself.curr2 = head\nself.ct = 1\nnode = head\nwhile node.next:\n self.ct += 1\n node = node.next\nfor i in range(random.randint(0, self.ct - 1)):\n self.curr2 = self.curr2.next\nnode.next = head",
"if random.randint(0, 1) == 0:\n self.curr = self.curr.next\n self... | <|body_start_0|>
self.head = head
self.curr = head
self.curr2 = head
self.ct = 1
node = head
while node.next:
self.ct += 1
node = node.next
for i in range(random.randint(0, self.ct - 1)):
self.curr2 = self.curr2.next
nod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_006455 | 1,220 | no_license | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.",
"name": "__init__",
"signature": "def __init__(self, head: ListNode)"
},
{
"docstring": "Returns a random node's value.",
"name": "getRandom",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_017953 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRandom(self) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRandom(self) -... | 1b1fd6d9b7cf0c8c5362bc5fc4d7864e3367bd2f | <|skeleton|>
class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
self.head = head
self.curr = head
self.curr2 = head
self.ct = 1
node = head
while n... | the_stack_v2_python_sparse | 202106/20210630-382-linked-list-random-node.py | wenchonglai/leetcode-practice | train | 0 | |
7ffdb873a62b93ce11e5b610f9e09ce292ea6c97 | [
"self.times_wrong = int(self.request.POST.get('times_wrong'))\nresponse = super().post(request=self.request)\nreturn response",
"context = super().get_context_data()\ncontext['times_wrong'] = self.times_wrong\nreturn context",
"kwargs = super(BaseFormView, self).get_form_kwargs()\ntry:\n person_record = Adul... | <|body_start_0|>
self.times_wrong = int(self.request.POST.get('times_wrong'))
response = super().post(request=self.request)
return response
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data()
context['times_wrong'] = self.times_wrong
return context
<|end... | View to validate the entered date of birth against the stored value for the current adult in home | DobAuthView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DobAuthView:
"""View to validate the entered date of birth against the stored value for the current adult in home"""
def post(self, request=None):
"""extension of the inbuilt post method to add the times wrong value from the post request to the object :param request: :return:"""
... | stack_v2_sparse_classes_75kplus_train_006456 | 2,127 | no_license | [
{
"docstring": "extension of the inbuilt post method to add the times wrong value from the post request to the object :param request: :return:",
"name": "post",
"signature": "def post(self, request=None)"
},
{
"docstring": "Adds the times_wrong variable to the context, having been defined in the... | 4 | null | Implement the Python class `DobAuthView` described below.
Class description:
View to validate the entered date of birth against the stored value for the current adult in home
Method signatures and docstrings:
- def post(self, request=None): extension of the inbuilt post method to add the times wrong value from the po... | Implement the Python class `DobAuthView` described below.
Class description:
View to validate the entered date of birth against the stored value for the current adult in home
Method signatures and docstrings:
- def post(self, request=None): extension of the inbuilt post method to add the times wrong value from the po... | fa6ca6a8164763e1dfe1581702ca5d36e44859de | <|skeleton|>
class DobAuthView:
"""View to validate the entered date of birth against the stored value for the current adult in home"""
def post(self, request=None):
"""extension of the inbuilt post method to add the times wrong value from the post request to the object :param request: :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DobAuthView:
"""View to validate the entered date of birth against the stored value for the current adult in home"""
def post(self, request=None):
"""extension of the inbuilt post method to add the times wrong value from the post request to the object :param request: :return:"""
self.time... | the_stack_v2_python_sparse | application/views/other_people_health_check/dob_auth.py | IS-JAQU-CAZ/OFS-MORE-Childminder-Website | train | 0 |
8b6f68877cc8ea312f3b73537d8b62a24c12554c | [
"req = query_production.parse_args(strict=True)\ncondition = []\nif req.get('merchant_code'):\n condition.append(TbMerchant.code == req['merchant_code'])\nmerchants = TbMerchant.query.filter(*condition).paginate(page=req['page'], per_page=req['page_size'])\nreturn ({'results': [{'merchant_name': i.name, 'merchan... | <|body_start_0|>
req = query_production.parse_args(strict=True)
condition = []
if req.get('merchant_code'):
condition.append(TbMerchant.code == req['merchant_code'])
merchants = TbMerchant.query.filter(*condition).paginate(page=req['page'], per_page=req['page_size'])
... | Production | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Production:
def get(self):
"""获取产品列表"""
<|body_0|>
def put(self):
"""更新产品信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
req = query_production.parse_args(strict=True)
condition = []
if req.get('merchant_code'):
condit... | stack_v2_sparse_classes_75kplus_train_006457 | 9,260 | no_license | [
{
"docstring": "获取产品列表",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "更新产品信息",
"name": "put",
"signature": "def put(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051348 | Implement the Python class `Production` described below.
Class description:
Implement the Production class.
Method signatures and docstrings:
- def get(self): 获取产品列表
- def put(self): 更新产品信息 | Implement the Python class `Production` described below.
Class description:
Implement the Production class.
Method signatures and docstrings:
- def get(self): 获取产品列表
- def put(self): 更新产品信息
<|skeleton|>
class Production:
def get(self):
"""获取产品列表"""
<|body_0|>
def put(self):
"""更新产品信... | 9f4553a6ea6d703f0ff3e330b090ee10e2b9a12a | <|skeleton|>
class Production:
def get(self):
"""获取产品列表"""
<|body_0|>
def put(self):
"""更新产品信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Production:
def get(self):
"""获取产品列表"""
req = query_production.parse_args(strict=True)
condition = []
if req.get('merchant_code'):
condition.append(TbMerchant.code == req['merchant_code'])
merchants = TbMerchant.query.filter(*condition).paginate(page=req['pa... | the_stack_v2_python_sparse | xxw/support/src/modules/business_user/public.py | GSIL-Monitor/xxw | train | 0 | |
b2a54b0c910ee800d826c76902a1e05816a5ead7 | [
"freq = {}\nresult = []\nfor num in nums:\n if num not in freq:\n freq[num] = 0\n freq[num] += 1\nfor key in freq:\n if freq[key] > 1:\n result.append(key)\nreturn result",
"result = []\nfor i in range(len(nums)):\n index = abs(nums[i]) - 1\n if nums[index] < 1:\n result.append... | <|body_start_0|>
freq = {}
result = []
for num in nums:
if num not in freq:
freq[num] = 0
freq[num] += 1
for key in freq:
if freq[key] > 1:
result.append(key)
return result
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicates(self, nums):
"""HIGH LEVEL: This is what I can come up with right off the bat. * Have a hashmap that stores the values and their corresponding frequencies. * traverse through the list, and if the key has a frequency count > 1 * add that key to the result list... | stack_v2_sparse_classes_75kplus_train_006458 | 1,581 | no_license | [
{
"docstring": "HIGH LEVEL: This is what I can come up with right off the bat. * Have a hashmap that stores the values and their corresponding frequencies. * traverse through the list, and if the key has a frequency count > 1 * add that key to the result list. * return the list. Complexities: Time: O(n), n = le... | 2 | stack_v2_sparse_classes_30k_val_002035 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicates(self, nums): HIGH LEVEL: This is what I can come up with right off the bat. * Have a hashmap that stores the values and their corresponding frequencies. * trav... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicates(self, nums): HIGH LEVEL: This is what I can come up with right off the bat. * Have a hashmap that stores the values and their corresponding frequencies. * trav... | d7fd565163535873b1799016614753059be7b6a9 | <|skeleton|>
class Solution:
def findDuplicates(self, nums):
"""HIGH LEVEL: This is what I can come up with right off the bat. * Have a hashmap that stores the values and their corresponding frequencies. * traverse through the list, and if the key has a frequency count > 1 * add that key to the result list... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findDuplicates(self, nums):
"""HIGH LEVEL: This is what I can come up with right off the bat. * Have a hashmap that stores the values and their corresponding frequencies. * traverse through the list, and if the key has a frequency count > 1 * add that key to the result list. * return the... | the_stack_v2_python_sparse | Arrays/442_findDupsArray.py | kevinmolina-io/leetcode | train | 0 | |
7e02965940320e29f8daaa24cbf45901c9cda60a | [
"user_uuid = get_jwt_identity()\ntry:\n page = int(request.args.get('page'))\nexcept (ValueError, TypeError):\n page = 1\nreturn GameService.get_popular_games(page, user_uuid)",
"user_uuid = get_jwt_identity()\ndata = request.get_json()\nreturn GameService.add_additional_game(user_uuid, data)"
] | <|body_start_0|>
user_uuid = get_jwt_identity()
try:
page = int(request.args.get('page'))
except (ValueError, TypeError):
page = 1
return GameService.get_popular_games(page, user_uuid)
<|end_body_0|>
<|body_start_1|>
user_uuid = get_jwt_identity()
... | GameResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameResource:
def get(self):
"""Get list of the most popular Games"""
<|body_0|>
def post(self):
"""Add additional Game for validation"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user_uuid = get_jwt_identity()
try:
page = int... | stack_v2_sparse_classes_75kplus_train_006459 | 8,073 | no_license | [
{
"docstring": "Get list of the most popular Games",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Add additional Game for validation",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004174 | Implement the Python class `GameResource` described below.
Class description:
Implement the GameResource class.
Method signatures and docstrings:
- def get(self): Get list of the most popular Games
- def post(self): Add additional Game for validation | Implement the Python class `GameResource` described below.
Class description:
Implement the GameResource class.
Method signatures and docstrings:
- def get(self): Get list of the most popular Games
- def post(self): Add additional Game for validation
<|skeleton|>
class GameResource:
def get(self):
"""Ge... | 2e7b4e07f149ede884cfe37130d9842ff9bb7be2 | <|skeleton|>
class GameResource:
def get(self):
"""Get list of the most popular Games"""
<|body_0|>
def post(self):
"""Add additional Game for validation"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GameResource:
def get(self):
"""Get list of the most popular Games"""
user_uuid = get_jwt_identity()
try:
page = int(request.args.get('page'))
except (ValueError, TypeError):
page = 1
return GameService.get_popular_games(page, user_uuid)
def... | the_stack_v2_python_sparse | src/resources/game_resource.py | RomainCtl/RecoFinement-api | train | 0 | |
8906fd160df9f500953a687991e6a58d9537e4ac | [
"assert isinstance(withAttributes, bool), 'Invalid with attributes flag %s' % withAttributes\nassert isinstance(sepMain, str), 'Invalid separator main %s' % sepMain\nassert isinstance(sepAttr, str), 'Invalid separator attributes %s' % sepAttr\nassert isinstance(sepValue, str), 'Invalid separator values %s' % sepVal... | <|body_start_0|>
assert isinstance(withAttributes, bool), 'Invalid with attributes flag %s' % withAttributes
assert isinstance(sepMain, str), 'Invalid separator main %s' % sepMain
assert isinstance(sepAttr, str), 'Invalid separator attributes %s' % sepAttr
assert isinstance(sepValue, str... | Multiple values header complex operator. | HeaderCmx | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeaderCmx:
"""Multiple values header complex operator."""
def __init__(self, name, withAttributes, sepMain=SEPARATOR_MAIN, sepAttr=SEPARATOR_ATTR, sepValue=SEPARATOR_VALUE):
"""Construct a multiple values complex header. @see: Header.__init__ @param withAttributes: boolean Flag indic... | stack_v2_sparse_classes_75kplus_train_006460 | 16,831 | no_license | [
{
"docstring": "Construct a multiple values complex header. @see: Header.__init__ @param withAttributes: boolean Flag indicating that also the attributes should be fetched. @param sepMain: string The separator used in splitting value and attributes from each other. @param sepAttr: string The separator used betw... | 5 | null | Implement the Python class `HeaderCmx` described below.
Class description:
Multiple values header complex operator.
Method signatures and docstrings:
- def __init__(self, name, withAttributes, sepMain=SEPARATOR_MAIN, sepAttr=SEPARATOR_ATTR, sepValue=SEPARATOR_VALUE): Construct a multiple values complex header. @see: ... | Implement the Python class `HeaderCmx` described below.
Class description:
Multiple values header complex operator.
Method signatures and docstrings:
- def __init__(self, name, withAttributes, sepMain=SEPARATOR_MAIN, sepAttr=SEPARATOR_ATTR, sepValue=SEPARATOR_VALUE): Construct a multiple values complex header. @see: ... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class HeaderCmx:
"""Multiple values header complex operator."""
def __init__(self, name, withAttributes, sepMain=SEPARATOR_MAIN, sepAttr=SEPARATOR_ATTR, sepValue=SEPARATOR_VALUE):
"""Construct a multiple values complex header. @see: Header.__init__ @param withAttributes: boolean Flag indic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HeaderCmx:
"""Multiple values header complex operator."""
def __init__(self, name, withAttributes, sepMain=SEPARATOR_MAIN, sepAttr=SEPARATOR_ATTR, sepValue=SEPARATOR_VALUE):
"""Construct a multiple values complex header. @see: Header.__init__ @param withAttributes: boolean Flag indicating that al... | the_stack_v2_python_sparse | components/ally-http/ally/http/spec/headers.py | cristidomsa/Ally-Py | train | 0 |
8d3a9fb76eb1f0773d367d53c9226fbd0faefec2 | [
"pairing_list = {}\nfor pairing in PairedNabaztags.objects.all().filter(nabaztag=self.id):\n pairing_list.update({pairing.paired_nabaztag.id: pairing.paired_nabaztag.name})\nreturn pairing_list",
"connection = RedisPublisher(facility=self.id, broadcast=True)\nmessage = {'ear': ear, 'pos': position}\nconnection... | <|body_start_0|>
pairing_list = {}
for pairing in PairedNabaztags.objects.all().filter(nabaztag=self.id):
pairing_list.update({pairing.paired_nabaztag.id: pairing.paired_nabaztag.name})
return pairing_list
<|end_body_0|>
<|body_start_1|>
connection = RedisPublisher(facility=... | Instances of this class represent a Nabaztag device. | Nabaztag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nabaztag:
"""Instances of this class represent a Nabaztag device."""
def get_pairings(self):
"""Returns a Dict of all Nabaztags which this Nabaztag is paired to."""
<|body_0|>
def move_ear(self, ear, position):
"""Places an ear message in the redis pub-sub messag... | stack_v2_sparse_classes_75kplus_train_006461 | 3,683 | no_license | [
{
"docstring": "Returns a Dict of all Nabaztags which this Nabaztag is paired to.",
"name": "get_pairings",
"signature": "def get_pairings(self)"
},
{
"docstring": "Places an ear message in the redis pub-sub message queue identified by this Nabaztag's identifier. :param ear: The ear to move. :pa... | 4 | stack_v2_sparse_classes_30k_test_002159 | Implement the Python class `Nabaztag` described below.
Class description:
Instances of this class represent a Nabaztag device.
Method signatures and docstrings:
- def get_pairings(self): Returns a Dict of all Nabaztags which this Nabaztag is paired to.
- def move_ear(self, ear, position): Places an ear message in the... | Implement the Python class `Nabaztag` described below.
Class description:
Instances of this class represent a Nabaztag device.
Method signatures and docstrings:
- def get_pairings(self): Returns a Dict of all Nabaztags which this Nabaztag is paired to.
- def move_ear(self, ear, position): Places an ear message in the... | 90243309d07190e03c563dc3980b75e275197525 | <|skeleton|>
class Nabaztag:
"""Instances of this class represent a Nabaztag device."""
def get_pairings(self):
"""Returns a Dict of all Nabaztags which this Nabaztag is paired to."""
<|body_0|>
def move_ear(self, ear, position):
"""Places an ear message in the redis pub-sub messag... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Nabaztag:
"""Instances of this class represent a Nabaztag device."""
def get_pairings(self):
"""Returns a Dict of all Nabaztags which this Nabaztag is paired to."""
pairing_list = {}
for pairing in PairedNabaztags.objects.all().filter(nabaztag=self.id):
pairing_list.up... | the_stack_v2_python_sparse | nabaztag_code/nabaztagserver/nabaztag/models.py | milesarmstrong/resurrecting-the-rabbit | train | 1 |
be61de41076fae63ad04c0beee3b101c50e2ae5e | [
"def dfs(node):\n if node is None:\n return\n l = node.left\n r = node.right\n while l:\n l.next = r\n l = l.right\n r = r.left\n if node.left:\n dfs(node.left)\n dfs(node.right)\ndfs(root)\nreturn root",
"from collections import deque\nif root is None:\n ... | <|body_start_0|>
def dfs(node):
if node is None:
return
l = node.left
r = node.right
while l:
l.next = r
l = l.right
r = r.left
if node.left:
dfs(node.left)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def connect(self, root: 'Node') -> 'Node':
"""Recursive1, Time: O(n), Space: O(logn) for recursive stack"""
<|body_0|>
def connect(self, root: 'Node') -> 'Node':
"""BFS, Time: O(n), Space: O(logn)"""
<|body_1|>
def connect(self, root: 'Node') -... | stack_v2_sparse_classes_75kplus_train_006462 | 2,251 | no_license | [
{
"docstring": "Recursive1, Time: O(n), Space: O(logn) for recursive stack",
"name": "connect",
"signature": "def connect(self, root: 'Node') -> 'Node'"
},
{
"docstring": "BFS, Time: O(n), Space: O(logn)",
"name": "connect",
"signature": "def connect(self, root: 'Node') -> 'Node'"
},
... | 4 | stack_v2_sparse_classes_30k_train_030747 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root: 'Node') -> 'Node': Recursive1, Time: O(n), Space: O(logn) for recursive stack
- def connect(self, root: 'Node') -> 'Node': BFS, Time: O(n), Space: O(logn)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root: 'Node') -> 'Node': Recursive1, Time: O(n), Space: O(logn) for recursive stack
- def connect(self, root: 'Node') -> 'Node': BFS, Time: O(n), Space: O(logn)... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def connect(self, root: 'Node') -> 'Node':
"""Recursive1, Time: O(n), Space: O(logn) for recursive stack"""
<|body_0|>
def connect(self, root: 'Node') -> 'Node':
"""BFS, Time: O(n), Space: O(logn)"""
<|body_1|>
def connect(self, root: 'Node') -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def connect(self, root: 'Node') -> 'Node':
"""Recursive1, Time: O(n), Space: O(logn) for recursive stack"""
def dfs(node):
if node is None:
return
l = node.left
r = node.right
while l:
l.next = r
... | the_stack_v2_python_sparse | python/116-Populating Next Right Pointers in Each Node.py | cwza/leetcode | train | 0 | |
bcded976eed321ea693eb4817c9aee6473cf5afc | [
"formfield = super(TweetableAdminMixin, self).formfield_for_dbfield(db_field, request, **kwargs)\nif Api and db_field.name == 'status' and get_auth_settings():\n\n def wrapper(render):\n\n def wrapped(*args, **kwargs):\n rendered = render(*args, **kwargs)\n label = _('Send to Twitter... | <|body_start_0|>
formfield = super(TweetableAdminMixin, self).formfield_for_dbfield(db_field, request, **kwargs)
if Api and db_field.name == 'status' and get_auth_settings():
def wrapper(render):
def wrapped(*args, **kwargs):
rendered = render(*args, **k... | Admin mixin that adds a "Send to Twitter" checkbox to the add/change views, which when checked, will send a tweet with the title and link to the object being saved. | TweetableAdminMixin | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TweetableAdminMixin:
"""Admin mixin that adds a "Send to Twitter" checkbox to the add/change views, which when checked, will send a tweet with the title and link to the object being saved."""
def formfield_for_dbfield(self, db_field, request, **kwargs):
"""Adds the "Send to Twitter" ... | stack_v2_sparse_classes_75kplus_train_006463 | 2,268 | permissive | [
{
"docstring": "Adds the \"Send to Twitter\" checkbox after the \"status\" field, provided by any ``Displayable`` models. The approach here is quite a hack, however the sane approach of using a custom form with a boolean field defined, and then adding it to the formsets attribute of the admin class fell apart q... | 2 | stack_v2_sparse_classes_30k_train_030485 | Implement the Python class `TweetableAdminMixin` described below.
Class description:
Admin mixin that adds a "Send to Twitter" checkbox to the add/change views, which when checked, will send a tweet with the title and link to the object being saved.
Method signatures and docstrings:
- def formfield_for_dbfield(self, ... | Implement the Python class `TweetableAdminMixin` described below.
Class description:
Admin mixin that adds a "Send to Twitter" checkbox to the add/change views, which when checked, will send a tweet with the title and link to the object being saved.
Method signatures and docstrings:
- def formfield_for_dbfield(self, ... | 29203de1d111a6d94d576a89430b37edd24cef55 | <|skeleton|>
class TweetableAdminMixin:
"""Admin mixin that adds a "Send to Twitter" checkbox to the add/change views, which when checked, will send a tweet with the title and link to the object being saved."""
def formfield_for_dbfield(self, db_field, request, **kwargs):
"""Adds the "Send to Twitter" ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TweetableAdminMixin:
"""Admin mixin that adds a "Send to Twitter" checkbox to the add/change views, which when checked, will send a tweet with the title and link to the object being saved."""
def formfield_for_dbfield(self, db_field, request, **kwargs):
"""Adds the "Send to Twitter" checkbox afte... | the_stack_v2_python_sparse | mezzanine/twitter/admin.py | fermorltd/mezzanine | train | 6 |
ec06aacb55ae8a6fb88b3528b33fffcc2bdfc405 | [
"queue = [root]\nret = []\nwhile queue:\n node = queue[0]\n queue = queue[1:]\n if not node:\n ret.append('null')\n continue\n ret.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\nreturn ','.join(ret)",
"if not data or data == 'null':\n return None\nno... | <|body_start_0|>
queue = [root]
ret = []
while queue:
node = queue[0]
queue = queue[1:]
if not node:
ret.append('null')
continue
ret.append(str(node.val))
queue.append(node.left)
queue.append(... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_006464 | 1,649 | 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_037361 | 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:... | 9687f8e743a8b6396fff192f22b5256d1025f86b | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
queue = [root]
ret = []
while queue:
node = queue[0]
queue = queue[1:]
if not node:
ret.append('null')
... | the_stack_v2_python_sparse | 2022/practice/tree/xu-lie-hua-er-cha-shu-lcof.py | buhuipao/LeetCode | train | 5 | |
0021363b807ab0c3627294a1b7e7c535db413e3c | [
"self.MODULE = MODULE\nself.ScenePackager = ScenePackager(self.MODULE)\nself.waitWindow = qt.QMessageBox(1, 'Uploading', 'Please wait while file uploads...')",
"if self.MODULE.View.sessionManager.sessionArgs:\n self.MODULE.View.setEnabled(False)\n fileSaveDialog = XnatFileSaveDialog(self.MODULE, self)\n ... | <|body_start_0|>
self.MODULE = MODULE
self.ScenePackager = ScenePackager(self.MODULE)
self.waitWindow = qt.QMessageBox(1, 'Uploading', 'Please wait while file uploads...')
<|end_body_0|>
<|body_start_1|>
if self.MODULE.View.sessionManager.sessionArgs:
self.MODULE.View.setEna... | Workflow_Save manages all of the processes needed to upload a file to an XNAT. Packaging scenes are conducted here. | Workflow_Save | [
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Workflow_Save:
"""Workflow_Save manages all of the processes needed to upload a file to an XNAT. Packaging scenes are conducted here."""
def __init__(self, MODULE):
"""Init function."""
<|body_0|>
def beginWorkflow(self):
"""Conducts some prelimiary steps (i.e. o... | stack_v2_sparse_classes_75kplus_train_006465 | 6,288 | permissive | [
{
"docstring": "Init function.",
"name": "__init__",
"signature": "def __init__(self, MODULE)"
},
{
"docstring": "Conducts some prelimiary steps (i.e. origin identification) before uploading the scene to the XNAT host.",
"name": "beginWorkflow",
"signature": "def beginWorkflow(self)"
}... | 3 | stack_v2_sparse_classes_30k_train_037111 | Implement the Python class `Workflow_Save` described below.
Class description:
Workflow_Save manages all of the processes needed to upload a file to an XNAT. Packaging scenes are conducted here.
Method signatures and docstrings:
- def __init__(self, MODULE): Init function.
- def beginWorkflow(self): Conducts some pre... | Implement the Python class `Workflow_Save` described below.
Class description:
Workflow_Save manages all of the processes needed to upload a file to an XNAT. Packaging scenes are conducted here.
Method signatures and docstrings:
- def __init__(self, MODULE): Init function.
- def beginWorkflow(self): Conducts some pre... | 06867037842e2a074ae5ed3b0bdf4bf016a231a5 | <|skeleton|>
class Workflow_Save:
"""Workflow_Save manages all of the processes needed to upload a file to an XNAT. Packaging scenes are conducted here."""
def __init__(self, MODULE):
"""Init function."""
<|body_0|>
def beginWorkflow(self):
"""Conducts some prelimiary steps (i.e. o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Workflow_Save:
"""Workflow_Save manages all of the processes needed to upload a file to an XNAT. Packaging scenes are conducted here."""
def __init__(self, MODULE):
"""Init function."""
self.MODULE = MODULE
self.ScenePackager = ScenePackager(self.MODULE)
self.waitWindow = ... | the_stack_v2_python_sparse | XNATSlicer/XnatSlicerLib/io/Workflow_Save.py | NrgXnat/XNATSlicer | train | 4 |
25dc2cb652a4f700d5d48982006f2b2025892991 | [
"self.min = np.array([0.0, 0.0])\nself.value = 0.0\nself.domain = np.array([[-10.0, 10.0], [-10.0, 10.0]])\nself.n = 2\nself.smooth = True\nself.info = [True, True, True]\nself.latex_name = 'Matyas Function'\nself.latex_type = 'Plate-Shaped'\nself.latex_cost = '\\\\[ f(\\\\mathbf{x}) = 0.26(x_0^2 + x_1^2) - 0.48 x_... | <|body_start_0|>
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domain = np.array([[-10.0, 10.0], [-10.0, 10.0]])
self.n = 2
self.smooth = True
self.info = [True, True, True]
self.latex_name = 'Matyas Function'
self.latex_type = 'Plate-Shaped'
... | Matyas Function. | Matyas | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Matyas:
"""Matyas Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
def grad(self, x):
"""Grad function."""
<|body_2|>
def hess(self, x):
"""Hess function.""... | stack_v2_sparse_classes_75kplus_train_006466 | 1,412 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Cost function.",
"name": "cost",
"signature": "def cost(self, x)"
},
{
"docstring": "Grad function.",
"name": "grad",
"signature": "def grad(self, x)"
},
{
"doc... | 4 | null | Implement the Python class `Matyas` described below.
Class description:
Matyas Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
- def grad(self, x): Grad function.
- def hess(self, x): Hess function. | Implement the Python class `Matyas` described below.
Class description:
Matyas Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
- def grad(self, x): Grad function.
- def hess(self, x): Hess function.
<|skeleton|>
class Matyas:
"""Matyas Function."... | f2a74df3ab01ac35ea8d80569da909ffa1e86af3 | <|skeleton|>
class Matyas:
"""Matyas Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
def grad(self, x):
"""Grad function."""
<|body_2|>
def hess(self, x):
"""Hess function.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Matyas:
"""Matyas Function."""
def __init__(self):
"""Constructor."""
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domain = np.array([[-10.0, 10.0], [-10.0, 10.0]])
self.n = 2
self.smooth = True
self.info = [True, True, True]
self.l... | the_stack_v2_python_sparse | ctf/functions2d/matyas.py | cntaylor/ctf | train | 1 |
def5449a62b3078fff8934896ff9cc0e00b9b081 | [
"self.pos = pos[:]\nself.size = size[:]\nself.active = 0\nself.onClick = None\nself.onMottion = None\nself.onUnder = None",
"mx, my = pygame.mouse.get_pos()\nif self.IsUnder((mx, my)) == True:\n if self.onUnder != None:\n self.onUnder(self)\n if self.onClick != None and event.type == pygame.MOUSEBUTT... | <|body_start_0|>
self.pos = pos[:]
self.size = size[:]
self.active = 0
self.onClick = None
self.onMottion = None
self.onUnder = None
<|end_body_0|>
<|body_start_1|>
mx, my = pygame.mouse.get_pos()
if self.IsUnder((mx, my)) == True:
if self.onU... | base class for all widgets | Widget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Widget:
"""base class for all widgets"""
def __init__(self, parent, pos=[0, 0], size=[10, 10]):
"""init widget"""
<|body_0|>
def Update(self, event):
"""update widget (send events)"""
<|body_1|>
def IsUnder(self, point):
"""check is point is ... | stack_v2_sparse_classes_75kplus_train_006467 | 1,376 | no_license | [
{
"docstring": "init widget",
"name": "__init__",
"signature": "def __init__(self, parent, pos=[0, 0], size=[10, 10])"
},
{
"docstring": "update widget (send events)",
"name": "Update",
"signature": "def Update(self, event)"
},
{
"docstring": "check is point is under widget retur... | 4 | stack_v2_sparse_classes_30k_train_016861 | Implement the Python class `Widget` described below.
Class description:
base class for all widgets
Method signatures and docstrings:
- def __init__(self, parent, pos=[0, 0], size=[10, 10]): init widget
- def Update(self, event): update widget (send events)
- def IsUnder(self, point): check is point is under widget re... | Implement the Python class `Widget` described below.
Class description:
base class for all widgets
Method signatures and docstrings:
- def __init__(self, parent, pos=[0, 0], size=[10, 10]): init widget
- def Update(self, event): update widget (send events)
- def IsUnder(self, point): check is point is under widget re... | 6fce940a4ca3ad51aa62aa48067d41d39c5a75a2 | <|skeleton|>
class Widget:
"""base class for all widgets"""
def __init__(self, parent, pos=[0, 0], size=[10, 10]):
"""init widget"""
<|body_0|>
def Update(self, event):
"""update widget (send events)"""
<|body_1|>
def IsUnder(self, point):
"""check is point is ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Widget:
"""base class for all widgets"""
def __init__(self, parent, pos=[0, 0], size=[10, 10]):
"""init widget"""
self.pos = pos[:]
self.size = size[:]
self.active = 0
self.onClick = None
self.onMottion = None
self.onUnder = None
def Update(sel... | the_stack_v2_python_sparse | src/widget.py | sugar-activities/4721-activity | train | 0 |
52a5d62fcccf5911e5875785fa2a864d72050c5b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ProcessEvidence()",
"from .alert_evidence import AlertEvidence\nfrom .detection_status import DetectionStatus\nfrom .file_details import FileDetails\nfrom .user_account import UserAccount\nfrom .alert_evidence import AlertEvidence\nfro... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ProcessEvidence()
<|end_body_0|>
<|body_start_1|>
from .alert_evidence import AlertEvidence
from .detection_status import DetectionStatus
from .file_details import FileDetails
... | ProcessEvidence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProcessEvidence:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_75kplus_train_006468 | 5,608 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ProcessEvidence",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | stack_v2_sparse_classes_30k_train_000789 | Implement the Python class `ProcessEvidence` described below.
Class description:
Implement the ProcessEvidence class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProcessEvidence: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `ProcessEvidence` described below.
Class description:
Implement the ProcessEvidence class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProcessEvidence: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ProcessEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProcessEvidence:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProcessEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProcessEvidence:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ProcessE... | the_stack_v2_python_sparse | msgraph/generated/models/security/process_evidence.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
e6a5ea90b73b0a6f07fbca580f8ccbc70854e13a | [
"tf.random.set_seed(seed)\nnp.random.seed(seed)\nself.train_X = train_X\nself.train_y = train_y\nself.validation_X = validation_X\nself.validation_y = validation_y\nself.seed = seed\nself.class_weight = class_weight\nself.output_activation = output_activation\nself.classes = classes\nself.metric = metric\nself.metr... | <|body_start_0|>
tf.random.set_seed(seed)
np.random.seed(seed)
self.train_X = train_X
self.train_y = train_y
self.validation_X = validation_X
self.validation_y = validation_y
self.seed = seed
self.class_weight = class_weight
self.output_activation ... | Keras MLP objective to optimize for Optuna study. | KerasMLPObjective | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KerasMLPObjective:
"""Keras MLP objective to optimize for Optuna study."""
def __init__(self, train_X: Union[pd.DataFrame, np.array], train_y: Union[pd.Series, pd.DataFrame, np.array], validation_X: Union[pd.DataFrame, np.array], validation_y: Union[pd.Series, np.array], classes: int, metric... | stack_v2_sparse_classes_75kplus_train_006469 | 8,830 | permissive | [
{
"docstring": "Initializes the objective train_X - training set features train_y - training set targets validation_X - validation set features validation_y - validation set targets classes - count of classes metric - metric to use seed - random seed to use class_weight - class weight passed to Keras fit output... | 4 | null | Implement the Python class `KerasMLPObjective` described below.
Class description:
Keras MLP objective to optimize for Optuna study.
Method signatures and docstrings:
- def __init__(self, train_X: Union[pd.DataFrame, np.array], train_y: Union[pd.Series, pd.DataFrame, np.array], validation_X: Union[pd.DataFrame, np.ar... | Implement the Python class `KerasMLPObjective` described below.
Class description:
Keras MLP objective to optimize for Optuna study.
Method signatures and docstrings:
- def __init__(self, train_X: Union[pd.DataFrame, np.array], train_y: Union[pd.Series, pd.DataFrame, np.array], validation_X: Union[pd.DataFrame, np.ar... | f0d89a157a34d788d6849b9d4aea8464a1de6d14 | <|skeleton|>
class KerasMLPObjective:
"""Keras MLP objective to optimize for Optuna study."""
def __init__(self, train_X: Union[pd.DataFrame, np.array], train_y: Union[pd.Series, pd.DataFrame, np.array], validation_X: Union[pd.DataFrame, np.array], validation_y: Union[pd.Series, np.array], classes: int, metric... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KerasMLPObjective:
"""Keras MLP objective to optimize for Optuna study."""
def __init__(self, train_X: Union[pd.DataFrame, np.array], train_y: Union[pd.Series, pd.DataFrame, np.array], validation_X: Union[pd.DataFrame, np.array], validation_y: Union[pd.Series, np.array], classes: int, metric, seed: int=4... | the_stack_v2_python_sparse | android_malware_labeling/training/mlp.py | dmacko232/AndroidMalwareLabeling | train | 0 |
dc5ede1c14d55a3946c904f5acf7db914fc1e712 | [
"if not head or not head.next or (not head.next.next):\n return\nhead2 = self.findMid(head)\nhead2 = self.reverseList(head2)\nself.zigZagMerge(head, head2)",
"slow, fast = (head, head.next)\nwhile fast:\n slow = slow.next\n fast = fast.next.next if fast.next else None\nhead2, slow.next = (slow.next, None... | <|body_start_0|>
if not head or not head.next or (not head.next.next):
return
head2 = self.findMid(head)
head2 = self.reverseList(head2)
self.zigZagMerge(head, head2)
<|end_body_0|>
<|body_start_1|>
slow, fast = (head, head.next)
while fast:
slow ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reorderList(self, head):
""":type head: ListNode :rtype: None Do not return anything, modify head in-place instead."""
<|body_0|>
def findMid(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
def reverseList(self, head):
... | stack_v2_sparse_classes_75kplus_train_006470 | 2,938 | no_license | [
{
"docstring": ":type head: ListNode :rtype: None Do not return anything, modify head in-place instead.",
"name": "reorderList",
"signature": "def reorderList(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "findMid",
"signature": "def findMid(self, head)"... | 4 | stack_v2_sparse_classes_30k_train_010973 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reorderList(self, head): :type head: ListNode :rtype: None Do not return anything, modify head in-place instead.
- def findMid(self, head): :type head: ListNode :rtype: ListN... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reorderList(self, head): :type head: ListNode :rtype: None Do not return anything, modify head in-place instead.
- def findMid(self, head): :type head: ListNode :rtype: ListN... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class Solution:
def reorderList(self, head):
""":type head: ListNode :rtype: None Do not return anything, modify head in-place instead."""
<|body_0|>
def findMid(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
def reverseList(self, head):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reorderList(self, head):
""":type head: ListNode :rtype: None Do not return anything, modify head in-place instead."""
if not head or not head.next or (not head.next.next):
return
head2 = self.findMid(head)
head2 = self.reverseList(head2)
self.... | the_stack_v2_python_sparse | Solutions/0143_reorderList.py | YoupengLi/leetcode-sorting | train | 3 | |
2056a904b6abb09fab0199dd06001d5b73294760 | [
"role_account = [u'业务运营', u'角色管理', u'角色账户', u'展开']\nself.user_login(user_name, password)\nsleep(2)\nself.click_more_button_for_one(role_account)\nsleep(3)",
"self.channel_code = self.get_table_cell_text(1, 2)\nself.account_code = self.get_table_cell_text(1, 3)\nself.account_name = self.get_table_cell_text(1, 5)\n... | <|body_start_0|>
role_account = [u'业务运营', u'角色管理', u'角色账户', u'展开']
self.user_login(user_name, password)
sleep(2)
self.click_more_button_for_one(role_account)
sleep(3)
<|end_body_0|>
<|body_start_1|>
self.channel_code = self.get_table_cell_text(1, 2)
self.account_... | 角色管理-角色账户测试 | RoleAccountTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleAccountTest:
"""角色管理-角色账户测试"""
def open_role_account(self, user_name='zxl_test', password='123456'):
"""打开角色管理-角色账户界面"""
<|body_0|>
def get_and_input_search_info(self):
"""获取并输入查询信息"""
<|body_1|>
def test_role_account_search(self):
"""角色账... | stack_v2_sparse_classes_75kplus_train_006471 | 8,001 | no_license | [
{
"docstring": "打开角色管理-角色账户界面",
"name": "open_role_account",
"signature": "def open_role_account(self, user_name='zxl_test', password='123456')"
},
{
"docstring": "获取并输入查询信息",
"name": "get_and_input_search_info",
"signature": "def get_and_input_search_info(self)"
},
{
"docstring"... | 5 | stack_v2_sparse_classes_30k_train_045459 | Implement the Python class `RoleAccountTest` described below.
Class description:
角色管理-角色账户测试
Method signatures and docstrings:
- def open_role_account(self, user_name='zxl_test', password='123456'): 打开角色管理-角色账户界面
- def get_and_input_search_info(self): 获取并输入查询信息
- def test_role_account_search(self): 角色账户查询
- def test_... | Implement the Python class `RoleAccountTest` described below.
Class description:
角色管理-角色账户测试
Method signatures and docstrings:
- def open_role_account(self, user_name='zxl_test', password='123456'): 打开角色管理-角色账户界面
- def get_and_input_search_info(self): 获取并输入查询信息
- def test_role_account_search(self): 角色账户查询
- def test_... | dcae68955b2857bbfe411145432865c57561c9ef | <|skeleton|>
class RoleAccountTest:
"""角色管理-角色账户测试"""
def open_role_account(self, user_name='zxl_test', password='123456'):
"""打开角色管理-角色账户界面"""
<|body_0|>
def get_and_input_search_info(self):
"""获取并输入查询信息"""
<|body_1|>
def test_role_account_search(self):
"""角色账... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RoleAccountTest:
"""角色管理-角色账户测试"""
def open_role_account(self, user_name='zxl_test', password='123456'):
"""打开角色管理-角色账户界面"""
role_account = [u'业务运营', u'角色管理', u'角色账户', u'展开']
self.user_login(user_name, password)
sleep(2)
self.click_more_button_for_one(role_account)... | the_stack_v2_python_sparse | genlot_vlt2/cases/BusinessOperation/permission_maintain/role_manage_test.py | bbwdi/auto | train | 1 |
d10cab625a76da941cf8cda0e1fb65505639e4b4 | [
"nvars = 2\nif u0 is None:\n u0 = [2.0, 0.0]\nsuper().__init__((nvars, None, np.dtype('float64')))\nself._makeAttributeAndRegister('nvars', 'u0', localVars=locals(), readOnly=True)\nself._makeAttributeAndRegister('mu', 'newton_maxiter', 'newton_tol', 'stop_at_nan', 'crash_at_maxiter', localVars=locals())\nself.w... | <|body_start_0|>
nvars = 2
if u0 is None:
u0 = [2.0, 0.0]
super().__init__((nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister('nvars', 'u0', localVars=locals(), readOnly=True)
self._makeAttributeAndRegister('mu', 'newton_maxiter', 'newton_tol', 'stop_a... | This class implements the stiff Van der Pol oscillator given by the equation .. math:: \\frac{d^2 u(t)}{d t^2} - \\mu (1 - u(t)^2) \\frac{d u(t)}{dt} + u(t) = 0. Parameters ---------- u0 : sequence of array_like, optional Initial condition. mu : float, optional Stiff parameter :math:`\\mu`. newton_maxiter : int, option... | vanderpol | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class vanderpol:
"""This class implements the stiff Van der Pol oscillator given by the equation .. math:: \\frac{d^2 u(t)}{d t^2} - \\mu (1 - u(t)^2) \\frac{d u(t)}{dt} + u(t) = 0. Parameters ---------- u0 : sequence of array_like, optional Initial condition. mu : float, optional Stiff parameter :math... | stack_v2_sparse_classes_75kplus_train_006472 | 5,657 | permissive | [
{
"docstring": "Initialization routine",
"name": "__init__",
"signature": "def __init__(self, u0=None, mu=5.0, newton_maxiter=100, newton_tol=1e-09, stop_at_nan=True, crash_at_maxiter=True)"
},
{
"docstring": "Routine to approximate the exact solution at time t by scipy or give initial condition... | 4 | stack_v2_sparse_classes_30k_train_026209 | Implement the Python class `vanderpol` described below.
Class description:
This class implements the stiff Van der Pol oscillator given by the equation .. math:: \\frac{d^2 u(t)}{d t^2} - \\mu (1 - u(t)^2) \\frac{d u(t)}{dt} + u(t) = 0. Parameters ---------- u0 : sequence of array_like, optional Initial condition. mu ... | Implement the Python class `vanderpol` described below.
Class description:
This class implements the stiff Van der Pol oscillator given by the equation .. math:: \\frac{d^2 u(t)}{d t^2} - \\mu (1 - u(t)^2) \\frac{d u(t)}{dt} + u(t) = 0. Parameters ---------- u0 : sequence of array_like, optional Initial condition. mu ... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class vanderpol:
"""This class implements the stiff Van der Pol oscillator given by the equation .. math:: \\frac{d^2 u(t)}{d t^2} - \\mu (1 - u(t)^2) \\frac{d u(t)}{dt} + u(t) = 0. Parameters ---------- u0 : sequence of array_like, optional Initial condition. mu : float, optional Stiff parameter :math... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class vanderpol:
"""This class implements the stiff Van der Pol oscillator given by the equation .. math:: \\frac{d^2 u(t)}{d t^2} - \\mu (1 - u(t)^2) \\frac{d u(t)}{dt} + u(t) = 0. Parameters ---------- u0 : sequence of array_like, optional Initial condition. mu : float, optional Stiff parameter :math:`\\mu`. newt... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/Van_der_Pol_implicit.py | Parallel-in-Time/pySDC | train | 30 |
6e96da9e36f016657f88f96d935bf2dae303519d | [
"p = toint(params.get('p', '1'))\nps = toint(params.get('ps', '10'))\nttype = toint(params.get('ttype', '0'))\ntid = toint(params.get('tid', '0'))\nrating = toint(params.get('rating', '0'))\nis_img = toint(params.get('is_img', '0'))\nq = db.session.query(Comment.comment_id, Comment.uid, Comment.nickname, Comment.av... | <|body_start_0|>
p = toint(params.get('p', '1'))
ps = toint(params.get('ps', '10'))
ttype = toint(params.get('ttype', '0'))
tid = toint(params.get('tid', '0'))
rating = toint(params.get('rating', '0'))
is_img = toint(params.get('is_img', '0'))
q = db.session.query... | 评论静态方法Service | CommentStaticMethodsService | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentStaticMethodsService:
"""评论静态方法Service"""
def comments(params, is_pagination=False):
"""获取评论列表"""
<|body_0|>
def index_page(args):
"""评论首页"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
p = toint(params.get('p', '1'))
ps = toint(... | stack_v2_sparse_classes_75kplus_train_006473 | 4,721 | permissive | [
{
"docstring": "获取评论列表",
"name": "comments",
"signature": "def comments(params, is_pagination=False)"
},
{
"docstring": "评论首页",
"name": "index_page",
"signature": "def index_page(args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044075 | Implement the Python class `CommentStaticMethodsService` described below.
Class description:
评论静态方法Service
Method signatures and docstrings:
- def comments(params, is_pagination=False): 获取评论列表
- def index_page(args): 评论首页 | Implement the Python class `CommentStaticMethodsService` described below.
Class description:
评论静态方法Service
Method signatures and docstrings:
- def comments(params, is_pagination=False): 获取评论列表
- def index_page(args): 评论首页
<|skeleton|>
class CommentStaticMethodsService:
"""评论静态方法Service"""
def comments(param... | 469444e33ef8a57d024e02c76040b1a7a6df983d | <|skeleton|>
class CommentStaticMethodsService:
"""评论静态方法Service"""
def comments(params, is_pagination=False):
"""获取评论列表"""
<|body_0|>
def index_page(args):
"""评论首页"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentStaticMethodsService:
"""评论静态方法Service"""
def comments(params, is_pagination=False):
"""获取评论列表"""
p = toint(params.get('p', '1'))
ps = toint(params.get('ps', '10'))
ttype = toint(params.get('ttype', '0'))
tid = toint(params.get('tid', '0'))
rating = ... | the_stack_v2_python_sparse | app/services/api/comment.py | lanshizhen/theonestore | train | 0 |
d22a79da3d83615a71b8655311577274abb8584e | [
"from networkx import has_path\nfrom goldstone.core.models import Region\nchildren = [self._tree(x) for x in resource.instances.graph.successors(node) if any((y[TYPE] == TOPOLOGICALLY_OWNS for y in resource.instances.graph.get_edge_data(node, x).values()))]\nif not children:\n children = None\nregionnodes = reso... | <|body_start_0|>
from networkx import has_path
from goldstone.core.models import Region
children = [self._tree(x) for x in resource.instances.graph.successors(node) if any((y[TYPE] == TOPOLOGICALLY_OWNS for y in resource.instances.graph.get_edge_data(node, x).values()))]
if not children:... | Return the cloud's topology. In the present codebase, there is only one OpenStack cloud. | TopologyView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopologyView:
"""Return the cloud's topology. In the present codebase, there is only one OpenStack cloud."""
def _tree(self, node):
"""Return the topology of the cloud starting at a node. :param node: A resource graph node :type node: GraphNode :return: The topology of this down "dow... | stack_v2_sparse_classes_75kplus_train_006474 | 30,838 | permissive | [
{
"docstring": "Return the topology of the cloud starting at a node. :param node: A resource graph node :type node: GraphNode :return: The topology of this down \"downward,\" including all of its children :rtype: dict",
"name": "_tree",
"signature": "def _tree(self, node)"
},
{
"docstring": "Ret... | 2 | stack_v2_sparse_classes_30k_train_000311 | Implement the Python class `TopologyView` described below.
Class description:
Return the cloud's topology. In the present codebase, there is only one OpenStack cloud.
Method signatures and docstrings:
- def _tree(self, node): Return the topology of the cloud starting at a node. :param node: A resource graph node :typ... | Implement the Python class `TopologyView` described below.
Class description:
Return the cloud's topology. In the present codebase, there is only one OpenStack cloud.
Method signatures and docstrings:
- def _tree(self, node): Return the topology of the cloud starting at a node. :param node: A resource graph node :typ... | d7f1f1f1ff926148d2aa541d0bd4758173aa76d5 | <|skeleton|>
class TopologyView:
"""Return the cloud's topology. In the present codebase, there is only one OpenStack cloud."""
def _tree(self, node):
"""Return the topology of the cloud starting at a node. :param node: A resource graph node :type node: GraphNode :return: The topology of this down "dow... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopologyView:
"""Return the cloud's topology. In the present codebase, there is only one OpenStack cloud."""
def _tree(self, node):
"""Return the topology of the cloud starting at a node. :param node: A resource graph node :type node: GraphNode :return: The topology of this down "downward," inclu... | the_stack_v2_python_sparse | goldstone/core/views.py | leftees/goldstone-server | train | 0 |
00ee51e86a4465ac85776798e6e4c9e3f7a81f26 | [
"if not nums:\n return\nRED, WHITE, BLUE = (0, 1, 2)\nleft, mid, right = (0, 0, len(nums) - 1)\nwhile mid <= right:\n if nums[mid] == RED:\n nums[left], nums[mid] = (nums[mid], nums[left])\n left += 1\n mid += 1\n elif nums[mid] == WHITE:\n mid += 1\n else:\n nums[mid]... | <|body_start_0|>
if not nums:
return
RED, WHITE, BLUE = (0, 1, 2)
left, mid, right = (0, 0, len(nums) - 1)
while mid <= right:
if nums[mid] == RED:
nums[left], nums[mid] = (nums[mid], nums[left])
left += 1
mid += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors_twopass(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place inst... | stack_v2_sparse_classes_75kplus_train_006475 | 2,295 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "so... | 2 | stack_v2_sparse_classes_30k_train_046246 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def sortColors_twopass(self, nums): :type nums: List[int] :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def sortColors_twopass(self, nums): :type nums: List[int] :... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors_twopass(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place inst... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
if not nums:
return
RED, WHITE, BLUE = (0, 1, 2)
left, mid, right = (0, 0, len(nums) - 1)
while mid <= right:
if ... | the_stack_v2_python_sparse | src/lt_75.py | oxhead/CodingYourWay | train | 0 | |
bd47cb4327463b386e295fd066f2d1930aeb14fe | [
"super(ATOCCommunicationNet, self).__init__()\nassert thought_size % 2 == 0\nself._thought_size = thought_size\nself._comm_hidden_size = thought_size // 2\nself._bi_lstm = nn.LSTM(self._thought_size, self._comm_hidden_size, bidirectional=True)",
"self._bi_lstm.flatten_parameters()\nx = data\nif isinstance(data, D... | <|body_start_0|>
super(ATOCCommunicationNet, self).__init__()
assert thought_size % 2 == 0
self._thought_size = thought_size
self._comm_hidden_size = thought_size // 2
self._bi_lstm = nn.LSTM(self._thought_size, self._comm_hidden_size, bidirectional=True)
<|end_body_0|>
<|body_s... | Overview: atoc commnication net is a bi-direction LSTM, so it can integrate all the thoughts in the group Interface: __init__, forward | ATOCCommunicationNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ATOCCommunicationNet:
"""Overview: atoc commnication net is a bi-direction LSTM, so it can integrate all the thoughts in the group Interface: __init__, forward"""
def __init__(self, thought_size: int) -> None:
"""Overview: init method of the communication network Arguments: - thought... | stack_v2_sparse_classes_75kplus_train_006476 | 18,821 | permissive | [
{
"docstring": "Overview: init method of the communication network Arguments: - thought_size (:obj:`int`): the size of input thought .. note:: communication hidden size should be half of the actor_hidden_size because of the bi-direction lstm",
"name": "__init__",
"signature": "def __init__(self, thought... | 2 | stack_v2_sparse_classes_30k_train_039196 | Implement the Python class `ATOCCommunicationNet` described below.
Class description:
Overview: atoc commnication net is a bi-direction LSTM, so it can integrate all the thoughts in the group Interface: __init__, forward
Method signatures and docstrings:
- def __init__(self, thought_size: int) -> None: Overview: init... | Implement the Python class `ATOCCommunicationNet` described below.
Class description:
Overview: atoc commnication net is a bi-direction LSTM, so it can integrate all the thoughts in the group Interface: __init__, forward
Method signatures and docstrings:
- def __init__(self, thought_size: int) -> None: Overview: init... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class ATOCCommunicationNet:
"""Overview: atoc commnication net is a bi-direction LSTM, so it can integrate all the thoughts in the group Interface: __init__, forward"""
def __init__(self, thought_size: int) -> None:
"""Overview: init method of the communication network Arguments: - thought... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ATOCCommunicationNet:
"""Overview: atoc commnication net is a bi-direction LSTM, so it can integrate all the thoughts in the group Interface: __init__, forward"""
def __init__(self, thought_size: int) -> None:
"""Overview: init method of the communication network Arguments: - thought_size (:obj:`... | the_stack_v2_python_sparse | ding/model/template/atoc.py | shengxuesun/DI-engine | train | 1 |
cb2b664c116dfc5e316c2f16f775db73d4680e6e | [
"if not tf.io.gfile.exists(default_hparams_file):\n raise ValueError('Expected a valid path to a YAML file, which represents the default hyperparameters file. {}'.format(default_hparams_file))\nself._params = {}\nself._params_source = {}\nself._default_hparams_file = default_hparams_file\nself._specific_hparams_... | <|body_start_0|>
if not tf.io.gfile.exists(default_hparams_file):
raise ValueError('Expected a valid path to a YAML file, which represents the default hyperparameters file. {}'.format(default_hparams_file))
self._params = {}
self._params_source = {}
self._default_hparams_file... | _Hyperparameters class to generate final hparams from various inputs. | _Hyperparameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Hyperparameters:
"""_Hyperparameters class to generate final hparams from various inputs."""
def __init__(self, default_hparams_file, specific_hparams_file, input_flags, hparams_overrides):
"""Initialze and load parameter dictionary with different input sources. Args: default_hparam... | stack_v2_sparse_classes_75kplus_train_006477 | 8,591 | permissive | [
{
"docstring": "Initialze and load parameter dictionary with different input sources. Args: default_hparams_file: YAML storing default values of all hyperparameters. specific_hparams_file: YAML file storing accelerator specific values of hyperparameters to override the default values. input_flags: Command line ... | 3 | null | Implement the Python class `_Hyperparameters` described below.
Class description:
_Hyperparameters class to generate final hparams from various inputs.
Method signatures and docstrings:
- def __init__(self, default_hparams_file, specific_hparams_file, input_flags, hparams_overrides): Initialze and load parameter dict... | Implement the Python class `_Hyperparameters` described below.
Class description:
_Hyperparameters class to generate final hparams from various inputs.
Method signatures and docstrings:
- def __init__(self, default_hparams_file, specific_hparams_file, input_flags, hparams_overrides): Initialze and load parameter dict... | 3ca77c4a5fb62c60372e8a2839b1fccc3c4e4212 | <|skeleton|>
class _Hyperparameters:
"""_Hyperparameters class to generate final hparams from various inputs."""
def __init__(self, default_hparams_file, specific_hparams_file, input_flags, hparams_overrides):
"""Initialze and load parameter dictionary with different input sources. Args: default_hparam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Hyperparameters:
"""_Hyperparameters class to generate final hparams from various inputs."""
def __init__(self, default_hparams_file, specific_hparams_file, input_flags, hparams_overrides):
"""Initialze and load parameter dictionary with different input sources. Args: default_hparams_file: YAML ... | the_stack_v2_python_sparse | TensorFlow/computer_vision/maskrcnn/mask_rcnn/hyperparameters/hyperparameters.py | HabanaAI/Model-References | train | 108 |
bed1b73cf10394348ac87c1d86dd406b9b7a6a2c | [
"if probability_fn is None:\n probability_fn = nn_ops.softmax\nif dtype is None:\n dtype = dtypes.float32\nwrapped_probability_fn = lambda score, _: probability_fn(score)\nself._num_units = num_units\nself._normalize = normalize\nself._name_or_scope = name_or_scope\nwith variable_scope.variable_scope(name_or_... | <|body_start_0|>
if probability_fn is None:
probability_fn = nn_ops.softmax
if dtype is None:
dtype = dtypes.float32
wrapped_probability_fn = lambda score, _: probability_fn(score)
self._num_units = num_units
self._normalize = normalize
self._name_... | Implements Bahdanau-style (additive) attention. This attention has two forms. The first is Bahdanau attention, as described in: Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio. "Neural Machine Translation by Jointly Learning to Align and Translate." ICLR 2015. https://arxiv.org/abs/1409.0473 The second is the normalized... | BahdanauAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BahdanauAttention:
"""Implements Bahdanau-style (additive) attention. This attention has two forms. The first is Bahdanau attention, as described in: Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio. "Neural Machine Translation by Jointly Learning to Align and Translate." ICLR 2015. https://arxiv.o... | stack_v2_sparse_classes_75kplus_train_006478 | 49,693 | permissive | [
{
"docstring": "Construct the Attention mechanism. :param num_units: The depth of the query mechanism. :param memory: The memory to query; usually the output of an RNN encoder. This tensor should be shaped `[batch_size, max_time, ...]`. :param memory_sequence_length: (optional): Sequence lengths for the batch e... | 2 | null | Implement the Python class `BahdanauAttention` described below.
Class description:
Implements Bahdanau-style (additive) attention. This attention has two forms. The first is Bahdanau attention, as described in: Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio. "Neural Machine Translation by Jointly Learning to Align and... | Implement the Python class `BahdanauAttention` described below.
Class description:
Implements Bahdanau-style (additive) attention. This attention has two forms. The first is Bahdanau attention, as described in: Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio. "Neural Machine Translation by Jointly Learning to Align and... | e752f02f34936bbae904815708904cabda554b57 | <|skeleton|>
class BahdanauAttention:
"""Implements Bahdanau-style (additive) attention. This attention has two forms. The first is Bahdanau attention, as described in: Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio. "Neural Machine Translation by Jointly Learning to Align and Translate." ICLR 2015. https://arxiv.o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BahdanauAttention:
"""Implements Bahdanau-style (additive) attention. This attention has two forms. The first is Bahdanau attention, as described in: Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio. "Neural Machine Translation by Jointly Learning to Align and Translate." ICLR 2015. https://arxiv.org/abs/1409.0... | the_stack_v2_python_sparse | diplomacy_research/models/layers/attention.py | JACKHAHA363/research | train | 0 |
ea40a36f44e1bd812588da6ce9c432fd239fdd92 | [
"assert user_id\nuser = (yield UserService.get_user_detail(user_id=user_id))\nresult_string = UserMapper.to_record(user)\nself.set_status(httplib.OK)\nself.write(result_string)",
"assert user_id\nuser = (yield UserService.get_user_detail(user_id=user_id))\nrequest_body = json.loads(self.request.body)\nactivated_v... | <|body_start_0|>
assert user_id
user = (yield UserService.get_user_detail(user_id=user_id))
result_string = UserMapper.to_record(user)
self.set_status(httplib.OK)
self.write(result_string)
<|end_body_0|>
<|body_start_1|>
assert user_id
user = (yield UserService.g... | UserInformationHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserInformationHandler:
def get(self, user_id):
"""handle the get request from /user/{user_id}?access_token={access_token} and write it back with proper fetched user information :param String user_id: :return:"""
<|body_0|>
def post(self, user_id):
"""handle the post... | stack_v2_sparse_classes_75kplus_train_006479 | 3,088 | no_license | [
{
"docstring": "handle the get request from /user/{user_id}?access_token={access_token} and write it back with proper fetched user information :param String user_id: :return:",
"name": "get",
"signature": "def get(self, user_id)"
},
{
"docstring": "handle the post request from /user/{user_id}?ac... | 2 | stack_v2_sparse_classes_30k_train_000754 | Implement the Python class `UserInformationHandler` described below.
Class description:
Implement the UserInformationHandler class.
Method signatures and docstrings:
- def get(self, user_id): handle the get request from /user/{user_id}?access_token={access_token} and write it back with proper fetched user information... | Implement the Python class `UserInformationHandler` described below.
Class description:
Implement the UserInformationHandler class.
Method signatures and docstrings:
- def get(self, user_id): handle the get request from /user/{user_id}?access_token={access_token} and write it back with proper fetched user information... | fd759c16b9864f6b1b47b1ba3f1af77f8d08af20 | <|skeleton|>
class UserInformationHandler:
def get(self, user_id):
"""handle the get request from /user/{user_id}?access_token={access_token} and write it back with proper fetched user information :param String user_id: :return:"""
<|body_0|>
def post(self, user_id):
"""handle the post... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserInformationHandler:
def get(self, user_id):
"""handle the get request from /user/{user_id}?access_token={access_token} and write it back with proper fetched user information :param String user_id: :return:"""
assert user_id
user = (yield UserService.get_user_detail(user_id=user_id)... | the_stack_v2_python_sparse | ParkingFinder/handlers/user_information.py | Big-Lemon/ParkingFinder | train | 2 | |
b4754f2145aac4e720beebc0be5a5b35cbb76467 | [
"super().__init__(base_url='https://panacea.threatgrid.com/api/v3/feeds/', verify=verify)\nself.first_fetch = first_fetch\nself.feed_name = feed_name\nself.feed_tags = feed_tags\nself.tlp_color = tlp_color\nself.create_relationships = create_relationships\nself._api_key = api_key\nself._proxies = handle_proxy()",
... | <|body_start_0|>
super().__init__(base_url='https://panacea.threatgrid.com/api/v3/feeds/', verify=verify)
self.first_fetch = first_fetch
self.feed_name = feed_name
self.feed_tags = feed_tags
self.tlp_color = tlp_color
self.create_relationships = create_relationships
... | Client | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Client:
def __init__(self, api_key, verify, first_fetch, feed_name, feed_tags, tlp_color, create_relationships):
"""Implements class for the feed. Args: api_key: API Key. verify: boolean, if *false* feed HTTPS server certificate is verified. Default: *false* first_fetch: The date from wh... | stack_v2_sparse_classes_75kplus_train_006480 | 12,402 | permissive | [
{
"docstring": "Implements class for the feed. Args: api_key: API Key. verify: boolean, if *false* feed HTTPS server certificate is verified. Default: *false* first_fetch: The date from which to start fetching feeds feed_name: The feed names to fetch feed_tags: feed tags. tlp_color: Traffic Light Protocol color... | 2 | stack_v2_sparse_classes_30k_val_002850 | Implement the Python class `Client` described below.
Class description:
Implement the Client class.
Method signatures and docstrings:
- def __init__(self, api_key, verify, first_fetch, feed_name, feed_tags, tlp_color, create_relationships): Implements class for the feed. Args: api_key: API Key. verify: boolean, if *f... | Implement the Python class `Client` described below.
Class description:
Implement the Client class.
Method signatures and docstrings:
- def __init__(self, api_key, verify, first_fetch, feed_name, feed_tags, tlp_color, create_relationships): Implements class for the feed. Args: api_key: API Key. verify: boolean, if *f... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class Client:
def __init__(self, api_key, verify, first_fetch, feed_name, feed_tags, tlp_color, create_relationships):
"""Implements class for the feed. Args: api_key: API Key. verify: boolean, if *false* feed HTTPS server certificate is verified. Default: *false* first_fetch: The date from wh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Client:
def __init__(self, api_key, verify, first_fetch, feed_name, feed_tags, tlp_color, create_relationships):
"""Implements class for the feed. Args: api_key: API Key. verify: boolean, if *false* feed HTTPS server certificate is verified. Default: *false* first_fetch: The date from which to start f... | the_stack_v2_python_sparse | Packs/ThreatGrid/Integrations/FeedCiscoSecureMalwareAnalytics/FeedCiscoSecureMalwareAnalytics.py | demisto/content | train | 1,023 | |
88d7b11954e80f375f72b31493d387380432b295 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MalwareStateForWindowsDevice()",
"from .entity import Entity\nfrom .windows_malware_execution_state import WindowsMalwareExecutionState\nfrom .windows_malware_threat_state import WindowsMalwareThreatState\nfrom .entity import Entity\nf... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return MalwareStateForWindowsDevice()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .windows_malware_execution_state import WindowsMalwareExecutionState
from .windows_... | Malware state for a windows device | MalwareStateForWindowsDevice | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MalwareStateForWindowsDevice:
"""Malware state for a windows device"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MalwareStateForWindowsDevice:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The pars... | stack_v2_sparse_classes_75kplus_train_006481 | 4,702 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: MalwareStateForWindowsDevice",
"name": "create_from_discriminator_value",
"signature": "def create_from_disc... | 3 | stack_v2_sparse_classes_30k_val_002001 | Implement the Python class `MalwareStateForWindowsDevice` described below.
Class description:
Malware state for a windows device
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MalwareStateForWindowsDevice: Creates a new instance of the appropriate clas... | Implement the Python class `MalwareStateForWindowsDevice` described below.
Class description:
Malware state for a windows device
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MalwareStateForWindowsDevice: Creates a new instance of the appropriate clas... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class MalwareStateForWindowsDevice:
"""Malware state for a windows device"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MalwareStateForWindowsDevice:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The pars... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MalwareStateForWindowsDevice:
"""Malware state for a windows device"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MalwareStateForWindowsDevice:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use... | the_stack_v2_python_sparse | msgraph/generated/models/malware_state_for_windows_device.py | microsoftgraph/msgraph-sdk-python | train | 135 |
1d3b8925bc64906de86eb2b5e25d1f8cc54e9267 | [
"logger.info('Delete directory in workdir.', wdir_uuid=wdir_uuid, basename=basename, path=os.path.join(path, basename))\nurl = urljoin(self.URL_BASE, 'workdirs/{}/changes'.format(wdir_uuid))\npayload = {'action': 'delete', 'filemode': 40000, 'basename': path, 'basename': basename}\nresponse = self.request(url, 'GET... | <|body_start_0|>
logger.info('Delete directory in workdir.', wdir_uuid=wdir_uuid, basename=basename, path=os.path.join(path, basename))
url = urljoin(self.URL_BASE, 'workdirs/{}/changes'.format(wdir_uuid))
payload = {'action': 'delete', 'filemode': 40000, 'basename': path, 'basename': basename}
... | Datary RemoveOperation module class | DataryRemoveOperation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataryRemoveOperation:
"""Datary RemoveOperation module class"""
def delete_dir(self, wdir_uuid, path, basename):
"""Delete directory. -- NOT IN USE -- ================ ============= ==================================== Parameter Type Description ================ ============= ======... | stack_v2_sparse_classes_75kplus_train_006482 | 5,600 | permissive | [
{
"docstring": "Delete directory. -- NOT IN USE -- ================ ============= ==================================== Parameter Type Description ================ ============= ==================================== wdir_uuid str working directory uuid path str path to directory basename str directory name ======... | 4 | stack_v2_sparse_classes_30k_train_013658 | Implement the Python class `DataryRemoveOperation` described below.
Class description:
Datary RemoveOperation module class
Method signatures and docstrings:
- def delete_dir(self, wdir_uuid, path, basename): Delete directory. -- NOT IN USE -- ================ ============= ==================================== Paramet... | Implement the Python class `DataryRemoveOperation` described below.
Class description:
Datary RemoveOperation module class
Method signatures and docstrings:
- def delete_dir(self, wdir_uuid, path, basename): Delete directory. -- NOT IN USE -- ================ ============= ==================================== Paramet... | 2790a50e1ad262cbe3210665dc34f497625e923d | <|skeleton|>
class DataryRemoveOperation:
"""Datary RemoveOperation module class"""
def delete_dir(self, wdir_uuid, path, basename):
"""Delete directory. -- NOT IN USE -- ================ ============= ==================================== Parameter Type Description ================ ============= ======... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataryRemoveOperation:
"""Datary RemoveOperation module class"""
def delete_dir(self, wdir_uuid, path, basename):
"""Delete directory. -- NOT IN USE -- ================ ============= ==================================== Parameter Type Description ================ ============= ===================... | the_stack_v2_python_sparse | datary/operations/remove.py | Datary/python-sdk | train | 0 |
4511b9f574582a9614dd738414109b8f0154d6e8 | [
"request = pecan.request\ncontext = request.environ['context']\ntransfer_accepts = self.central_api.get_zone_transfer_accept(context, transfer_accept_id)\nLOG.info('Retrieved %(transfer_accepts)s', {'transfer_accepts': transfer_accepts})\nreturn DesignateAdapter.render('API_v2', transfer_accepts, request=request)",... | <|body_start_0|>
request = pecan.request
context = request.environ['context']
transfer_accepts = self.central_api.get_zone_transfer_accept(context, transfer_accept_id)
LOG.info('Retrieved %(transfer_accepts)s', {'transfer_accepts': transfer_accepts})
return DesignateAdapter.rende... | TransferAcceptsController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransferAcceptsController:
def get_one(self, transfer_accept_id):
"""Get transfer_accepts"""
<|body_0|>
def get_all(self, **params):
"""List ZoneTransferAccepts"""
<|body_1|>
def post_all(self):
"""Create ZoneTransferAccept"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_006483 | 3,661 | permissive | [
{
"docstring": "Get transfer_accepts",
"name": "get_one",
"signature": "def get_one(self, transfer_accept_id)"
},
{
"docstring": "List ZoneTransferAccepts",
"name": "get_all",
"signature": "def get_all(self, **params)"
},
{
"docstring": "Create ZoneTransferAccept",
"name": "p... | 3 | stack_v2_sparse_classes_30k_train_047589 | Implement the Python class `TransferAcceptsController` described below.
Class description:
Implement the TransferAcceptsController class.
Method signatures and docstrings:
- def get_one(self, transfer_accept_id): Get transfer_accepts
- def get_all(self, **params): List ZoneTransferAccepts
- def post_all(self): Create... | Implement the Python class `TransferAcceptsController` described below.
Class description:
Implement the TransferAcceptsController class.
Method signatures and docstrings:
- def get_one(self, transfer_accept_id): Get transfer_accepts
- def get_all(self, **params): List ZoneTransferAccepts
- def post_all(self): Create... | 360433b38b449d1c53ab1357fdb0c4608c09efa5 | <|skeleton|>
class TransferAcceptsController:
def get_one(self, transfer_accept_id):
"""Get transfer_accepts"""
<|body_0|>
def get_all(self, **params):
"""List ZoneTransferAccepts"""
<|body_1|>
def post_all(self):
"""Create ZoneTransferAccept"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransferAcceptsController:
def get_one(self, transfer_accept_id):
"""Get transfer_accepts"""
request = pecan.request
context = request.environ['context']
transfer_accepts = self.central_api.get_zone_transfer_accept(context, transfer_accept_id)
LOG.info('Retrieved %(tran... | the_stack_v2_python_sparse | designate/api/v2/controllers/zones/tasks/transfer_accepts.py | openstack/designate | train | 156 | |
0e4784a39b2cd309cfb61b668a4581d49371fd1f | [
"from nestedworld_api.db import Plant as DbPlant\nPlants = DbPlant.query.all()\nreturn Plants",
"from nestedworld_api.db import db\nfrom nestedworld_api.db import Plant as DbPlant\nPlant = DbPlant.query.filter(DbPlant.name == data['name']).first()\nif Plant is not None:\n plant.abort(409, message='Plant alread... | <|body_start_0|>
from nestedworld_api.db import Plant as DbPlant
Plants = DbPlant.query.all()
return Plants
<|end_body_0|>
<|body_start_1|>
from nestedworld_api.db import db
from nestedworld_api.db import Plant as DbPlant
Plant = DbPlant.query.filter(DbPlant.name == data... | Plant | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plant:
def get(self):
"""Retrieve all plants This request is used for retrieve the list of all the existing plants."""
<|body_0|>
def post(self, data):
"""Create a new plant This request is used for create a new plant (Only used by the admin through the admin interfa... | stack_v2_sparse_classes_75kplus_train_006484 | 1,628 | no_license | [
{
"docstring": "Retrieve all plants This request is used for retrieve the list of all the existing plants.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a new plant This request is used for create a new plant (Only used by the admin through the admin interface).",
"... | 2 | stack_v2_sparse_classes_30k_train_013319 | Implement the Python class `Plant` described below.
Class description:
Implement the Plant class.
Method signatures and docstrings:
- def get(self): Retrieve all plants This request is used for retrieve the list of all the existing plants.
- def post(self, data): Create a new plant This request is used for create a n... | Implement the Python class `Plant` described below.
Class description:
Implement the Plant class.
Method signatures and docstrings:
- def get(self): Retrieve all plants This request is used for retrieve the list of all the existing plants.
- def post(self, data): Create a new plant This request is used for create a n... | af2262742b04c823d2cf6e0fa40fa0fc6456671e | <|skeleton|>
class Plant:
def get(self):
"""Retrieve all plants This request is used for retrieve the list of all the existing plants."""
<|body_0|>
def post(self, data):
"""Create a new plant This request is used for create a new plant (Only used by the admin through the admin interfa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Plant:
def get(self):
"""Retrieve all plants This request is used for retrieve the list of all the existing plants."""
from nestedworld_api.db import Plant as DbPlant
Plants = DbPlant.query.all()
return Plants
def post(self, data):
"""Create a new plant This reques... | the_stack_v2_python_sparse | nestedworld_api/views/api/v1/object/plant.py | NestedWorld/NestedWorld-Server-API | train | 1 | |
e78c4a8e6da07336a96067045a35270eef83cfc4 | [
"super(SurfaceClassifier, self).__init__()\nself.filters = []\nself.num_views = num_views\nself.no_residual = no_residual\nfilter_channels = filter_channels\nself.last_op = last_op\nself.opt = opt\nif self.no_residual:\n for l in range(0, len(filter_channels) - 1):\n self.filters.append(nn.Conv1d(filter_c... | <|body_start_0|>
super(SurfaceClassifier, self).__init__()
self.filters = []
self.num_views = num_views
self.no_residual = no_residual
filter_channels = filter_channels
self.last_op = last_op
self.opt = opt
if self.no_residual:
for l in range(0... | SurfaceClassifier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SurfaceClassifier:
def __init__(self, filter_channels, num_views=1, no_residual=True, last_op=None, opt=None):
"""input filter_channels: default is [257, 1024, 512, 256, 128, 1] no_residual : default is False"""
<|body_0|>
def forward(self, feature):
"""Input feature... | stack_v2_sparse_classes_75kplus_train_006485 | 8,364 | no_license | [
{
"docstring": "input filter_channels: default is [257, 1024, 512, 256, 128, 1] no_residual : default is False",
"name": "__init__",
"signature": "def __init__(self, filter_channels, num_views=1, no_residual=True, last_op=None, opt=None)"
},
{
"docstring": "Input feature: (B * num_views, opt.hou... | 2 | stack_v2_sparse_classes_30k_test_002799 | Implement the Python class `SurfaceClassifier` described below.
Class description:
Implement the SurfaceClassifier class.
Method signatures and docstrings:
- def __init__(self, filter_channels, num_views=1, no_residual=True, last_op=None, opt=None): input filter_channels: default is [257, 1024, 512, 256, 128, 1] no_r... | Implement the Python class `SurfaceClassifier` described below.
Class description:
Implement the SurfaceClassifier class.
Method signatures and docstrings:
- def __init__(self, filter_channels, num_views=1, no_residual=True, last_op=None, opt=None): input filter_channels: default is [257, 1024, 512, 256, 128, 1] no_r... | 0b570802d6c46d7230bb505e2a8c3d5a1cf7086a | <|skeleton|>
class SurfaceClassifier:
def __init__(self, filter_channels, num_views=1, no_residual=True, last_op=None, opt=None):
"""input filter_channels: default is [257, 1024, 512, 256, 128, 1] no_residual : default is False"""
<|body_0|>
def forward(self, feature):
"""Input feature... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SurfaceClassifier:
def __init__(self, filter_channels, num_views=1, no_residual=True, last_op=None, opt=None):
"""input filter_channels: default is [257, 1024, 512, 256, 128, 1] no_residual : default is False"""
super(SurfaceClassifier, self).__init__()
self.filters = []
self.n... | the_stack_v2_python_sparse | geopifu/lib/model/SurfaceClassifier.py | alicedingyueming/Geo-PIFu | train | 0 | |
0bbdaad3ff08e9ef65e16d6852f0e091cd5cd10e | [
"parser.add_argument('--device', '-d', help='Device to record video from', type=types.connected_android_device, default=defaults.connected_android_device()).completer = completion.android_devices\nparser.add_argument('--bitrate', '-b', help='Video bit rate, by default 8000000 (6Mbps)', type=int, default=8000000)\np... | <|body_start_0|>
parser.add_argument('--device', '-d', help='Device to record video from', type=types.connected_android_device, default=defaults.connected_android_device()).completer = completion.android_devices
parser.add_argument('--bitrate', '-b', help='Video bit rate, by default 8000000 (6Mbps)', ty... | Action for recording video. | RecordVideoAction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecordVideoAction:
"""Action for recording video."""
def init_parser(parser):
"""Initializes argument parser with own arguments. :param parser: argparse.ArgumentParser, parser instance to initialize it with custom arguments."""
<|body_0|>
def __call__(self, device, timeo... | stack_v2_sparse_classes_75kplus_train_006486 | 3,003 | permissive | [
{
"docstring": "Initializes argument parser with own arguments. :param parser: argparse.ArgumentParser, parser instance to initialize it with custom arguments.",
"name": "init_parser",
"signature": "def init_parser(parser)"
},
{
"docstring": "Takes one or more screenshots from specified device. ... | 2 | stack_v2_sparse_classes_30k_train_034412 | Implement the Python class `RecordVideoAction` described below.
Class description:
Action for recording video.
Method signatures and docstrings:
- def init_parser(parser): Initializes argument parser with own arguments. :param parser: argparse.ArgumentParser, parser instance to initialize it with custom arguments.
- ... | Implement the Python class `RecordVideoAction` described below.
Class description:
Action for recording video.
Method signatures and docstrings:
- def init_parser(parser): Initializes argument parser with own arguments. :param parser: argparse.ArgumentParser, parser instance to initialize it with custom arguments.
- ... | 46dcb27b0ee25153b697d19c17801cee35e136ce | <|skeleton|>
class RecordVideoAction:
"""Action for recording video."""
def init_parser(parser):
"""Initializes argument parser with own arguments. :param parser: argparse.ArgumentParser, parser instance to initialize it with custom arguments."""
<|body_0|>
def __call__(self, device, timeo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecordVideoAction:
"""Action for recording video."""
def init_parser(parser):
"""Initializes argument parser with own arguments. :param parser: argparse.ArgumentParser, parser instance to initialize it with custom arguments."""
parser.add_argument('--device', '-d', help='Device to record ... | the_stack_v2_python_sparse | action/RecordVideoAction.py | maxim-filkov/mobile-test-helper | train | 1 |
068bdb5741c4267c63f443eb1e7eeb3dcd573bf8 | [
"if not os.path.exists(download_instance.target_directory):\n if download_instance.createdir:\n print(f'\\nCreating directory {download_instance.target_directory} \\n')\n os.makedirs(download_instance.target_directory)",
"sublist = list()\nif limits is not None:\n start, end = limits\nelse:\n ... | <|body_start_0|>
if not os.path.exists(download_instance.target_directory):
if download_instance.createdir:
print(f'\nCreating directory {download_instance.target_directory} \n')
os.makedirs(download_instance.target_directory)
<|end_body_0|>
<|body_start_1|>
... | Class of Utililities containing static methods | UtilsDl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilsDl:
"""Class of Utililities containing static methods"""
def create_dir(download_instance):
"""Create a directory on localhost :param download_instance: instance of calling class"""
<|body_0|>
def get_sublist(download_instance, limits):
"""Methods to return ... | stack_v2_sparse_classes_75kplus_train_006487 | 3,311 | no_license | [
{
"docstring": "Create a directory on localhost :param download_instance: instance of calling class",
"name": "create_dir",
"signature": "def create_dir(download_instance)"
},
{
"docstring": "Methods to return a sublist of element to download :param download_instance: instance of calling class :... | 4 | null | Implement the Python class `UtilsDl` described below.
Class description:
Class of Utililities containing static methods
Method signatures and docstrings:
- def create_dir(download_instance): Create a directory on localhost :param download_instance: instance of calling class
- def get_sublist(download_instance, limits... | Implement the Python class `UtilsDl` described below.
Class description:
Class of Utililities containing static methods
Method signatures and docstrings:
- def create_dir(download_instance): Create a directory on localhost :param download_instance: instance of calling class
- def get_sublist(download_instance, limits... | fe98b8b1f40829ea369ee5feb5f674a14e283e03 | <|skeleton|>
class UtilsDl:
"""Class of Utililities containing static methods"""
def create_dir(download_instance):
"""Create a directory on localhost :param download_instance: instance of calling class"""
<|body_0|>
def get_sublist(download_instance, limits):
"""Methods to return ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UtilsDl:
"""Class of Utililities containing static methods"""
def create_dir(download_instance):
"""Create a directory on localhost :param download_instance: instance of calling class"""
if not os.path.exists(download_instance.target_directory):
if download_instance.createdir:... | the_stack_v2_python_sparse | Downloader_Ytube/UtilsDl.py | StephaneDci/python_code | train | 1 |
4695784a3f157e9a6d3e17212f1f079d42b282fc | [
"assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nBOARDS = ['Shore Fishing Missed NESA']\nURLS = ['https://www.nesa.co.uk/forums/shore-fishing/']\nLAST_SCRAPED = 501\nPAGES = [994 - LAST_SCRAPED]\nassert len(BOARDS) == len(URLS) == len(PAGES), 'Setup list lengths DO NOT match'\nfor i, root_url i... | <|body_start_0|>
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
BOARDS = ['Shore Fishing Missed NESA']
URLS = ['https://www.nesa.co.uk/forums/shore-fishing/']
LAST_SCRAPED = 501
PAGES = [994 - LAST_SCRAPED]
assert len(BOARDS) == len(URLS) == len(PAGES... | scrape reports from angling addicts forum | NESASpiderShoreMissed | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NESASpiderShoreMissed:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board"""
<|body_0|>
def crawl_board_threads(self, response):
"""crawl"""
<|body_1|>
def parse_thread(self, response):
... | stack_v2_sparse_classes_75kplus_train_006488 | 13,051 | no_license | [
{
"docstring": "generate links to pages in a board",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "crawl",
"name": "crawl_board_threads",
"signature": "def crawl_board_threads(self, response)"
},
{
"docstring": "open a report thread and parse first ... | 3 | stack_v2_sparse_classes_30k_train_003756 | Implement the Python class `NESASpiderShoreMissed` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board
- def crawl_board_threads(self, response): crawl
- def parse_thread(self, response): open a... | Implement the Python class `NESASpiderShoreMissed` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board
- def crawl_board_threads(self, response): crawl
- def parse_thread(self, response): open a... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class NESASpiderShoreMissed:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board"""
<|body_0|>
def crawl_board_threads(self, response):
"""crawl"""
<|body_1|>
def parse_thread(self, response):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NESASpiderShoreMissed:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board"""
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
BOARDS = ['Shore Fishing Missed NESA']
URLS = ['https://www.nesa.c... | the_stack_v2_python_sparse | imgscrape/spiders/nesa.py | gmonkman/python | train | 0 |
29344c8d49a2e83dd2b3cddd1c951817faf74026 | [
"self.hass = hass\nself.last_approved_entities: dict[str, tuple[State, Any]] = {}\nself.extra_significant_check = extra_significant_check",
"old_data: tuple[State, Any] | None = self.last_approved_entities.get(new_state.entity_id)\nif old_data is None:\n self.last_approved_entities[new_state.entity_id] = (new_... | <|body_start_0|>
self.hass = hass
self.last_approved_entities: dict[str, tuple[State, Any]] = {}
self.extra_significant_check = extra_significant_check
<|end_body_0|>
<|body_start_1|>
old_data: tuple[State, Any] | None = self.last_approved_entities.get(new_state.entity_id)
if ol... | Class to keep track of entities to see if they have significantly changed. Will always compare the entity to the last entity that was considered significant. | SignificantlyChangedChecker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignificantlyChangedChecker:
"""Class to keep track of entities to see if they have significantly changed. Will always compare the entity to the last entity that was considered significant."""
def __init__(self, hass: HomeAssistant, extra_significant_check: ExtraCheckTypeFunc | None=None) ->... | stack_v2_sparse_classes_75kplus_train_006489 | 7,052 | permissive | [
{
"docstring": "Test if an entity has significantly changed.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, extra_significant_check: ExtraCheckTypeFunc | None=None) -> None"
},
{
"docstring": "Return if this was a significant change. Extra kwargs are passed to the ex... | 2 | stack_v2_sparse_classes_30k_train_008365 | Implement the Python class `SignificantlyChangedChecker` described below.
Class description:
Class to keep track of entities to see if they have significantly changed. Will always compare the entity to the last entity that was considered significant.
Method signatures and docstrings:
- def __init__(self, hass: HomeAs... | Implement the Python class `SignificantlyChangedChecker` described below.
Class description:
Class to keep track of entities to see if they have significantly changed. Will always compare the entity to the last entity that was considered significant.
Method signatures and docstrings:
- def __init__(self, hass: HomeAs... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SignificantlyChangedChecker:
"""Class to keep track of entities to see if they have significantly changed. Will always compare the entity to the last entity that was considered significant."""
def __init__(self, hass: HomeAssistant, extra_significant_check: ExtraCheckTypeFunc | None=None) ->... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SignificantlyChangedChecker:
"""Class to keep track of entities to see if they have significantly changed. Will always compare the entity to the last entity that was considered significant."""
def __init__(self, hass: HomeAssistant, extra_significant_check: ExtraCheckTypeFunc | None=None) -> None:
... | the_stack_v2_python_sparse | homeassistant/helpers/significant_change.py | home-assistant/core | train | 35,501 |
9f1987d9000f7eb623a7292dda6b0ed32b6b32a4 | [
"bank, _ = UserBank.objects.get_or_create(user=request.user)\nprofile = UserProfile.objects.get(user=request.user)\ntry:\n if not bank.stripe_customer_id:\n customer = stripe.Customer.create(source=request.POST.get('id'), email=request.user.email, description=profile.membership)\n bank.stripe_custo... | <|body_start_0|>
bank, _ = UserBank.objects.get_or_create(user=request.user)
profile = UserProfile.objects.get(user=request.user)
try:
if not bank.stripe_customer_id:
customer = stripe.Customer.create(source=request.POST.get('id'), email=request.user.email, descriptio... | API endpoint for handling payments managements. | PaymentsViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaymentsViewSet:
"""API endpoint for handling payments managements."""
def create(self, request):
"""Create a user account at Stripe with payment info."""
<|body_0|>
def list(self, request):
"""List all payments associatd to a user."""
<|body_1|>
def... | stack_v2_sparse_classes_75kplus_train_006490 | 8,004 | no_license | [
{
"docstring": "Create a user account at Stripe with payment info.",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "List all payments associatd to a user.",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Destroy associatd ... | 3 | stack_v2_sparse_classes_30k_train_027878 | Implement the Python class `PaymentsViewSet` described below.
Class description:
API endpoint for handling payments managements.
Method signatures and docstrings:
- def create(self, request): Create a user account at Stripe with payment info.
- def list(self, request): List all payments associatd to a user.
- def des... | Implement the Python class `PaymentsViewSet` described below.
Class description:
API endpoint for handling payments managements.
Method signatures and docstrings:
- def create(self, request): Create a user account at Stripe with payment info.
- def list(self, request): List all payments associatd to a user.
- def des... | 4c6afe763353ba38951cad61832ebe3f932971de | <|skeleton|>
class PaymentsViewSet:
"""API endpoint for handling payments managements."""
def create(self, request):
"""Create a user account at Stripe with payment info."""
<|body_0|>
def list(self, request):
"""List all payments associatd to a user."""
<|body_1|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PaymentsViewSet:
"""API endpoint for handling payments managements."""
def create(self, request):
"""Create a user account at Stripe with payment info."""
bank, _ = UserBank.objects.get_or_create(user=request.user)
profile = UserProfile.objects.get(user=request.user)
try:
... | the_stack_v2_python_sparse | fremancer_invoices/views.py | nvutri/fremancer-django | train | 0 |
3c69d82bf70110373a00967ffdbbbe65837f441f | [
"serializer = serializers_anio.CreateSingleCursoSerializer(data=request.data)\ndata = {}\nif serializer.is_valid(raise_exception=True):\n get_object_or_404(Anio.objects.filter(carrera__institucion_id=request.user.institucion.id), pk=serializer.validated_data['anio'].pk)\n try:\n instance = serializer.c... | <|body_start_0|>
serializer = serializers_anio.CreateSingleCursoSerializer(data=request.data)
data = {}
if serializer.is_valid(raise_exception=True):
get_object_or_404(Anio.objects.filter(carrera__institucion_id=request.user.institucion.id), pk=serializer.validated_data['anio'].pk)
... | CursoViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CursoViewSet:
def create(self, request):
"""Crear un curso"""
<|body_0|>
def destroy(self, request, pk=None):
"""Elimina un Curso"""
<|body_1|>
def update(self, request, pk=None):
"""Edita un curso"""
<|body_2|>
def get(self, request... | stack_v2_sparse_classes_75kplus_train_006491 | 9,416 | no_license | [
{
"docstring": "Crear un curso",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Elimina un Curso",
"name": "destroy",
"signature": "def destroy(self, request, pk=None)"
},
{
"docstring": "Edita un curso",
"name": "update",
"signature": "def ... | 5 | stack_v2_sparse_classes_30k_train_043699 | Implement the Python class `CursoViewSet` described below.
Class description:
Implement the CursoViewSet class.
Method signatures and docstrings:
- def create(self, request): Crear un curso
- def destroy(self, request, pk=None): Elimina un Curso
- def update(self, request, pk=None): Edita un curso
- def get(self, req... | Implement the Python class `CursoViewSet` described below.
Class description:
Implement the CursoViewSet class.
Method signatures and docstrings:
- def create(self, request): Crear un curso
- def destroy(self, request, pk=None): Elimina un Curso
- def update(self, request, pk=None): Edita un curso
- def get(self, req... | be80b2d15f84a8eeba898e753efee348de6ce998 | <|skeleton|>
class CursoViewSet:
def create(self, request):
"""Crear un curso"""
<|body_0|>
def destroy(self, request, pk=None):
"""Elimina un Curso"""
<|body_1|>
def update(self, request, pk=None):
"""Edita un curso"""
<|body_2|>
def get(self, request... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CursoViewSet:
def create(self, request):
"""Crear un curso"""
serializer = serializers_anio.CreateSingleCursoSerializer(data=request.data)
data = {}
if serializer.is_valid(raise_exception=True):
get_object_or_404(Anio.objects.filter(carrera__institucion_id=request.u... | the_stack_v2_python_sparse | curricula/api/views/anio.py | Clear-Education/ontrack_backend | train | 1 | |
794f9d7b3649d82a90420d646c16563bddc0c8ec | [
"def dfs(nums, i, k, value, res):\n if i >= len(nums) or value * nums[i] >= k:\n reslist.append(res)\n res = []\n return\n else:\n res.append(nums[i])\n dfs(nums, i + 1, k, value * nums[i], res)\nreslist = []\nfor i in range(len(nums)):\n if nums[i] < k:\n reslist.... | <|body_start_0|>
def dfs(nums, i, k, value, res):
if i >= len(nums) or value * nums[i] >= k:
reslist.append(res)
res = []
return
else:
res.append(nums[i])
dfs(nums, i + 1, k, value * nums[i], res)
res... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubarrayProductLessThanK(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def numSubarrayProductLessThanKSol(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_006492 | 1,774 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "numSubarrayProductLessThanK",
"signature": "def numSubarrayProductLessThanK(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "numSubarrayProductLessThanKSol",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_026753 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayProductLessThanK(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def numSubarrayProductLessThanKSol(self, nums, k): :type nums: List[int] :type k:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayProductLessThanK(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def numSubarrayProductLessThanKSol(self, nums, k): :type nums: List[int] :type k:... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class Solution:
def numSubarrayProductLessThanK(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def numSubarrayProductLessThanKSol(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numSubarrayProductLessThanK(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
def dfs(nums, i, k, value, res):
if i >= len(nums) or value * nums[i] >= k:
reslist.append(res)
res = []
return
... | the_stack_v2_python_sparse | medium/subarray_product_less_than_k.py | gerrycfchang/leetcode-python | train | 2 | |
6abbd9fd476791cd4854bb44874f1dca88ce1430 | [
"super(DuplicateFilter, self).__init__(order)\nself.info = 'Filters search results and removes ones already stored by the application using this filter (link field used for this check).'\nself.existingResults = existingResults",
"for result in results:\n found = False\n for url in self.existingResults:\n ... | <|body_start_0|>
super(DuplicateFilter, self).__init__(order)
self.info = 'Filters search results and removes ones already stored by the application using this filter (link field used for this check).'
self.existingResults = existingResults
<|end_body_0|>
<|body_start_1|>
for result in ... | Filters search results and rejects ones already stored by an application. This is done by default by checking the link field of new results against a list of ones currently stored by the application. If found, they are rejected. Options: * order (int): defines when, in the pipeline, this filter will be executed * exist... | DuplicateFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DuplicateFilter:
"""Filters search results and rejects ones already stored by an application. This is done by default by checking the link field of new results against a list of ones currently stored by the application. If found, they are rejected. Options: * order (int): defines when, in the pip... | stack_v2_sparse_classes_75kplus_train_006493 | 1,643 | permissive | [
{
"docstring": "Constructor for DuplicateFilter.",
"name": "__init__",
"signature": "def __init__(self, order=0, existingResults=[])"
},
{
"docstring": "Filters search results and rejects ones already stored by the application using this filter (link field used for this check). Parameters: * res... | 2 | stack_v2_sparse_classes_30k_train_010520 | Implement the Python class `DuplicateFilter` described below.
Class description:
Filters search results and rejects ones already stored by an application. This is done by default by checking the link field of new results against a list of ones currently stored by the application. If found, they are rejected. Options: ... | Implement the Python class `DuplicateFilter` described below.
Class description:
Filters search results and rejects ones already stored by an application. This is done by default by checking the link field of new results against a list of ones currently stored by the application. If found, they are rejected. Options: ... | ed72aee466649bd834d5b4459eb6e0173df6e2ec | <|skeleton|>
class DuplicateFilter:
"""Filters search results and rejects ones already stored by an application. This is done by default by checking the link field of new results against a list of ones currently stored by the application. If found, they are rejected. Options: * order (int): defines when, in the pip... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DuplicateFilter:
"""Filters search results and rejects ones already stored by an application. This is done by default by checking the link field of new results against a list of ones currently stored by the application. If found, they are rejected. Options: * order (int): defines when, in the pipeline, this f... | the_stack_v2_python_sparse | reference-code/puppy/result/filter/duplicatefilter.py | Granvanoeli/ifind | train | 0 |
bf2cb6ce763e0e859c5699c57c1a5b7a28b81ecb | [
"model_params = {'architecture': 'ResNet101', 'pooling': 'gem', 'whitening': False, 'pretrained': True}\nmodel = global_model.GlobalFeatureNet(**model_params)\nexpected_meta = {'architecture': 'ResNet101', 'pooling': 'gem', 'whitening': False, 'outputdim': 2048}\nself.assertEqual(expected_meta, model.meta)",
"mod... | <|body_start_0|>
model_params = {'architecture': 'ResNet101', 'pooling': 'gem', 'whitening': False, 'pretrained': True}
model = global_model.GlobalFeatureNet(**model_params)
expected_meta = {'architecture': 'ResNet101', 'pooling': 'gem', 'whitening': False, 'outputdim': 2048}
self.assert... | Tests for the GlobalFeatureNet backbone. | GlobalFeatureNetTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlobalFeatureNetTest:
"""Tests for the GlobalFeatureNet backbone."""
def testInitModel(self):
"""Testing GlobalFeatureNet initialization."""
<|body_0|>
def testExtractVectors(self):
"""Tests extraction of global descriptors from list."""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus_train_006494 | 3,230 | permissive | [
{
"docstring": "Testing GlobalFeatureNet initialization.",
"name": "testInitModel",
"signature": "def testInitModel(self)"
},
{
"docstring": "Tests extraction of global descriptors from list.",
"name": "testExtractVectors",
"signature": "def testExtractVectors(self)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_002294 | Implement the Python class `GlobalFeatureNetTest` described below.
Class description:
Tests for the GlobalFeatureNet backbone.
Method signatures and docstrings:
- def testInitModel(self): Testing GlobalFeatureNet initialization.
- def testExtractVectors(self): Tests extraction of global descriptors from list.
- def t... | Implement the Python class `GlobalFeatureNetTest` described below.
Class description:
Tests for the GlobalFeatureNet backbone.
Method signatures and docstrings:
- def testInitModel(self): Testing GlobalFeatureNet initialization.
- def testExtractVectors(self): Tests extraction of global descriptors from list.
- def t... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class GlobalFeatureNetTest:
"""Tests for the GlobalFeatureNet backbone."""
def testInitModel(self):
"""Testing GlobalFeatureNet initialization."""
<|body_0|>
def testExtractVectors(self):
"""Tests extraction of global descriptors from list."""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GlobalFeatureNetTest:
"""Tests for the GlobalFeatureNet backbone."""
def testInitModel(self):
"""Testing GlobalFeatureNet initialization."""
model_params = {'architecture': 'ResNet101', 'pooling': 'gem', 'whitening': False, 'pretrained': True}
model = global_model.GlobalFeatureNet... | the_stack_v2_python_sparse | research/delf/delf/python/training/model/global_model_test.py | jianzhnie/models | train | 2 |
ebbc86b01ff06fed0be9bc8a6a1ce4f34dc3947c | [
"super(SRTMLoader, self).__init__(filename)\nself.logger.info('Loading: {} Latitude span: {}, Longitude span: {}, Resolution: {} ArcSec/point.'.format(filename, span_latitude, span_longitude, arcsec_resolution))\nself.span_latitude = span_latitude\nself.span_longitude = span_longitude\nself.arcsec_resolution = arcs... | <|body_start_0|>
super(SRTMLoader, self).__init__(filename)
self.logger.info('Loading: {} Latitude span: {}, Longitude span: {}, Resolution: {} ArcSec/point.'.format(filename, span_latitude, span_longitude, arcsec_resolution))
self.span_latitude = span_latitude
self.span_longitude = span... | SRTMLoader | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SRTMLoader:
def __init__(self, filename, arcsec_resolution=1, span_latitude=3601, span_longitude=3601):
""":param filename: File name, for instance ~/N44W072.hgt :param arcsec_resolution: how many arcseconds per measurement unit. :param span_latitude: source datamap point span along lati... | stack_v2_sparse_classes_75kplus_train_006495 | 4,240 | permissive | [
{
"docstring": ":param filename: File name, for instance ~/N44W072.hgt :param arcsec_resolution: how many arcseconds per measurement unit. :param span_latitude: source datamap point span along latitude :param span_longitude: source datamap point span along longitude",
"name": "__init__",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_016537 | Implement the Python class `SRTMLoader` described below.
Class description:
Implement the SRTMLoader class.
Method signatures and docstrings:
- def __init__(self, filename, arcsec_resolution=1, span_latitude=3601, span_longitude=3601): :param filename: File name, for instance ~/N44W072.hgt :param arcsec_resolution: h... | Implement the Python class `SRTMLoader` described below.
Class description:
Implement the SRTMLoader class.
Method signatures and docstrings:
- def __init__(self, filename, arcsec_resolution=1, span_latitude=3601, span_longitude=3601): :param filename: File name, for instance ~/N44W072.hgt :param arcsec_resolution: h... | df378834dbb0302bf3e0cc5364b3fa682f4c91bf | <|skeleton|>
class SRTMLoader:
def __init__(self, filename, arcsec_resolution=1, span_latitude=3601, span_longitude=3601):
""":param filename: File name, for instance ~/N44W072.hgt :param arcsec_resolution: how many arcseconds per measurement unit. :param span_latitude: source datamap point span along lati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SRTMLoader:
def __init__(self, filename, arcsec_resolution=1, span_latitude=3601, span_longitude=3601):
""":param filename: File name, for instance ~/N44W072.hgt :param arcsec_resolution: how many arcseconds per measurement unit. :param span_latitude: source datamap point span along latitude :param sp... | the_stack_v2_python_sparse | pyprom/dataload.py | lowellmower/pyProm | train | 0 | |
c0198bd760324f7637a1012c4d35c3abdb8b40a5 | [
"if old in old2new:\n return old2new[old]\nnew = UndirectedGraphNode(old.label)\nnew.neighbors = [None] * len(old.neighbors)\nold2new[old] = new\nfor i, old_neighbor in enumerate(old.neighbors):\n new_neighbor = self._clone(old_neighbor, old2new)\n new.neighbors[i] = new_neighbor\nreturn new",
"if not no... | <|body_start_0|>
if old in old2new:
return old2new[old]
new = UndirectedGraphNode(old.label)
new.neighbors = [None] * len(old.neighbors)
old2new[old] = new
for i, old_neighbor in enumerate(old.neighbors):
new_neighbor = self._clone(old_neighbor, old2new)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _clone(self, old, old2new):
"""d maps old node to new neighbors"""
<|body_0|>
def cloneGraph(self, node):
""":type node: UndirectedGraphNode :rtype: UndirectedGraphNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if old in old2new:... | stack_v2_sparse_classes_75kplus_train_006496 | 938 | no_license | [
{
"docstring": "d maps old node to new neighbors",
"name": "_clone",
"signature": "def _clone(self, old, old2new)"
},
{
"docstring": ":type node: UndirectedGraphNode :rtype: UndirectedGraphNode",
"name": "cloneGraph",
"signature": "def cloneGraph(self, node)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004341 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _clone(self, old, old2new): d maps old node to new neighbors
- def cloneGraph(self, node): :type node: UndirectedGraphNode :rtype: UndirectedGraphNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _clone(self, old, old2new): d maps old node to new neighbors
- def cloneGraph(self, node): :type node: UndirectedGraphNode :rtype: UndirectedGraphNode
<|skeleton|>
class Sol... | 20580185c6f72f3c09a725168af48893156161f5 | <|skeleton|>
class Solution:
def _clone(self, old, old2new):
"""d maps old node to new neighbors"""
<|body_0|>
def cloneGraph(self, node):
""":type node: UndirectedGraphNode :rtype: UndirectedGraphNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _clone(self, old, old2new):
"""d maps old node to new neighbors"""
if old in old2new:
return old2new[old]
new = UndirectedGraphNode(old.label)
new.neighbors = [None] * len(old.neighbors)
old2new[old] = new
for i, old_neighbor in enumera... | the_stack_v2_python_sparse | coding/00133-clone-graph/solution.py | misaka-10032/leetcode | train | 3 | |
79dc669b800405f49eac753ec6022d673168ebc8 | [
"super(ComputeAnomalySubtask, self).__init__(config=parentTask.config, taskName=parentTask.taskName, componentName='ocean', tags=parentTask.tags, subtaskName=subtaskName)\nself.mpasTimeSeriesTask = mpasTimeSeriesTask\nself.run_after(mpasTimeSeriesTask)\nself.outFileName = outFileName\nself.variableList = variableLi... | <|body_start_0|>
super(ComputeAnomalySubtask, self).__init__(config=parentTask.config, taskName=parentTask.taskName, componentName='ocean', tags=parentTask.tags, subtaskName=subtaskName)
self.mpasTimeSeriesTask = mpasTimeSeriesTask
self.run_after(mpasTimeSeriesTask)
self.outFileName = ou... | A subtask for computing anomalies of moving averages and writing them out. Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file name (usually without full path) where the resulting data set should be written variable... | ComputeAnomalySubtask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComputeAnomalySubtask:
"""A subtask for computing anomalies of moving averages and writing them out. Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file name (usually without full path) where ... | stack_v2_sparse_classes_75kplus_train_006497 | 5,592 | no_license | [
{
"docstring": "Construct the analysis task. Parameters ---------- parentTask : ``AnalysisTask`` The parent task of which this is a subtask mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file name (usually without full path) wher... | 3 | stack_v2_sparse_classes_30k_train_015025 | Implement the Python class `ComputeAnomalySubtask` described below.
Class description:
A subtask for computing anomalies of moving averages and writing them out. Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file ... | Implement the Python class `ComputeAnomalySubtask` described below.
Class description:
A subtask for computing anomalies of moving averages and writing them out. Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file ... | e56da52b9885a79c051e2f0f7c2619e14caf8a21 | <|skeleton|>
class ComputeAnomalySubtask:
"""A subtask for computing anomalies of moving averages and writing them out. Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file name (usually without full path) where ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComputeAnomalySubtask:
"""A subtask for computing anomalies of moving averages and writing them out. Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file name (usually without full path) where the resulting... | the_stack_v2_python_sparse | mpas_analysis/ocean/compute_anomaly_subtask.py | zengxiaoqing/MPAS-Analysis | train | 0 |
f1c9c63a6772bda35746e2885fdfc74470b03d63 | [
"for k, v in kwargs.items():\n if not hasattr(self, k):\n warnings.warn('\\nWarning: opt has not attribut %s' % k)\n setattr(self, k, v)\nif self.print_config == True:\n print('user config:')\n for k, v in self.__class__.__dict__.items():\n if not k.startswith('__'):\n print(k, ... | <|body_start_0|>
for k, v in kwargs.items():
if not hasattr(self, k):
warnings.warn('\nWarning: opt has not attribut %s' % k)
setattr(self, k, v)
if self.print_config == True:
print('user config:')
for k, v in self.__class__.__dict__.items(... | TODO 舍弃此类直接传args 使用范例: import models from config import Configuration config = Configuration() lr = config.lr model = getattr(models, config.arch) dataset = DogCat_dataset(config.train_data_root) | Configuration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configuration:
"""TODO 舍弃此类直接传args 使用范例: import models from config import Configuration config = Configuration() lr = config.lr model = getattr(models, config.arch) dataset = DogCat_dataset(config.train_data_root)"""
def update_config(self, kwargs):
"""根据字典kwargs 更新 config 参数 config ... | stack_v2_sparse_classes_75kplus_train_006498 | 5,691 | no_license | [
{
"docstring": "根据字典kwargs 更新 config 参数 config = Configuration() new_config = {'lr':0.1,'use_gpu':False} config.update_config(new_config) config.lr == 0.1",
"name": "update_config",
"signature": "def update_config(self, kwargs)"
},
{
"docstring": "自动检测config配置是否合理",
"name": "check_config",
... | 2 | stack_v2_sparse_classes_30k_train_001165 | Implement the Python class `Configuration` described below.
Class description:
TODO 舍弃此类直接传args 使用范例: import models from config import Configuration config = Configuration() lr = config.lr model = getattr(models, config.arch) dataset = DogCat_dataset(config.train_data_root)
Method signatures and docstrings:
- def upd... | Implement the Python class `Configuration` described below.
Class description:
TODO 舍弃此类直接传args 使用范例: import models from config import Configuration config = Configuration() lr = config.lr model = getattr(models, config.arch) dataset = DogCat_dataset(config.train_data_root)
Method signatures and docstrings:
- def upd... | 2d34ec72c2358a5bf4dd0b2855a7900fbb8feae7 | <|skeleton|>
class Configuration:
"""TODO 舍弃此类直接传args 使用范例: import models from config import Configuration config = Configuration() lr = config.lr model = getattr(models, config.arch) dataset = DogCat_dataset(config.train_data_root)"""
def update_config(self, kwargs):
"""根据字典kwargs 更新 config 参数 config ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Configuration:
"""TODO 舍弃此类直接传args 使用范例: import models from config import Configuration config = Configuration() lr = config.lr model = getattr(models, config.arch) dataset = DogCat_dataset(config.train_data_root)"""
def update_config(self, kwargs):
"""根据字典kwargs 更新 config 参数 config = Configurati... | the_stack_v2_python_sparse | utils/config.py | meetsiyuan/MCTS | train | 0 |
3f1ed110fd2690216ccc93944995037fa7c4e902 | [
"for idx, c in enumerate(s):\n if c not in s[idx + 1:] and c not in s[:idx]:\n return idx\nreturn -1",
"m = {}\nfor c in s:\n m[c] = m.get(c, 0) + 1\nfor c in s:\n if m[c] == 1:\n return s.index(c)\nreturn -1",
"a = [0] * 26\nfor c in s:\n a[ord(c) - ord('a')] += 1\nfor c in s:\n if... | <|body_start_0|>
for idx, c in enumerate(s):
if c not in s[idx + 1:] and c not in s[:idx]:
return idx
return -1
<|end_body_0|>
<|body_start_1|>
m = {}
for c in s:
m[c] = m.get(c, 0) + 1
for c in s:
if m[c] == 1:
... | 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。"""
def firstUniqChar(self, s: str) -> i... | stack_v2_sparse_classes_75kplus_train_006499 | 2,094 | permissive | [
{
"docstring": "遍历字符串中的字符,如果满足以下两个条件,则返回idx 1. 该字符不存在于 s[:idx] 2. 该字符不存在于 s[idx + 1:] :param s: :return:",
"name": "firstUniqChar",
"signature": "def firstUniqChar(self, s: str) -> int"
},
{
"docstring": "1. 将所有字符存入dict,value表示出现的次数 2. 从头遍历一次字符串,第一次出现 value = 1 的字符就是要找字符 :param s: :return:",
... | 3 | stack_v2_sparse_classes_30k_train_038390 | Implement the Python class `Solution` described below.
Class description:
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Meth... | Implement the Python class `Solution` described below.
Class description:
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Meth... | d599e223bed1b957a1283face7606cb651b28ec4 | <|skeleton|>
class Solution:
"""给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。"""
def firstUniqChar(self, s: str) -> i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。"""
def firstUniqChar(self, s: str) -> int:
"... | the_stack_v2_python_sparse | problems/0387-first-unique-character-in-a-string.py | tzxyz/leetcode | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.