blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d0c34a3185e2333a46fa0f7369266aa4e10b1685 | [
"resblk_cls = ConditionalResidualBlock\nnorm_layer = lambda num_features: ConditionalBatchNorm2d(num_features, num_classes)\nsuper(ConditionalGenerator, self).__init__(conv_channels, conv_upsample, resblk_cls=resblk_cls, norm_layer=norm_layer, dim_z=dim_z, im_channels=im_channels)",
"c = c.view(-1)\nx = self.line... | <|body_start_0|>
resblk_cls = ConditionalResidualBlock
norm_layer = lambda num_features: ConditionalBatchNorm2d(num_features, num_classes)
super(ConditionalGenerator, self).__init__(conv_channels, conv_upsample, resblk_cls=resblk_cls, norm_layer=norm_layer, dim_z=dim_z, im_channels=im_channels)
... | ConditionalGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionalGenerator:
def __init__(self, conv_channels, conv_upsample, num_classes, dim_z=128, im_channels=3):
"""norm_layer = lambda num_features: ConditionalBatchNorm2d(num_features, num_classes)"""
<|body_0|>
def forward(self, x, c):
"""x batch_size x im_channels ... | stack_v2_sparse_classes_36k_train_026500 | 18,748 | no_license | [
{
"docstring": "norm_layer = lambda num_features: ConditionalBatchNorm2d(num_features, num_classes)",
"name": "__init__",
"signature": "def __init__(self, conv_channels, conv_upsample, num_classes, dim_z=128, im_channels=3)"
},
{
"docstring": "x batch_size x im_channels x h x w c batch_size",
... | 2 | stack_v2_sparse_classes_30k_train_015033 | Implement the Python class `ConditionalGenerator` described below.
Class description:
Implement the ConditionalGenerator class.
Method signatures and docstrings:
- def __init__(self, conv_channels, conv_upsample, num_classes, dim_z=128, im_channels=3): norm_layer = lambda num_features: ConditionalBatchNorm2d(num_feat... | Implement the Python class `ConditionalGenerator` described below.
Class description:
Implement the ConditionalGenerator class.
Method signatures and docstrings:
- def __init__(self, conv_channels, conv_upsample, num_classes, dim_z=128, im_channels=3): norm_layer = lambda num_features: ConditionalBatchNorm2d(num_feat... | 0a6653a66f1fb2590df9d6697e4cd69d32a2baaa | <|skeleton|>
class ConditionalGenerator:
def __init__(self, conv_channels, conv_upsample, num_classes, dim_z=128, im_channels=3):
"""norm_layer = lambda num_features: ConditionalBatchNorm2d(num_features, num_classes)"""
<|body_0|>
def forward(self, x, c):
"""x batch_size x im_channels ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionalGenerator:
def __init__(self, conv_channels, conv_upsample, num_classes, dim_z=128, im_channels=3):
"""norm_layer = lambda num_features: ConditionalBatchNorm2d(num_features, num_classes)"""
resblk_cls = ConditionalResidualBlock
norm_layer = lambda num_features: ConditionalBa... | the_stack_v2_python_sparse | pe/models_cgan.py | tt6746690/misc_impl | train | 0 | |
94467135918c3509198c45f17fd23ee74b5699be | [
"self.host = host\nself.port = port\nself.roles = roles",
"if dictionary is None:\n return None\nhost = dictionary.get('host')\nport = dictionary.get('port')\nroles = dictionary.get('roles')\nreturn cls(host, port, roles)"
] | <|body_start_0|>
self.host = host
self.port = port
self.roles = roles
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
host = dictionary.get('host')
port = dictionary.get('port')
roles = dictionary.get('roles')
return cls(hos... | Implementation of the 'Server' model. TODO: type model description here. Attributes: host (string): The IP address of the syslog server port (int): The port of the syslog server roles (list of string): A list of roles for the syslog server. Options (case-insensitive): 'Wireless event log', 'Appliance event log', 'Switc... | ServerModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerModel:
"""Implementation of the 'Server' model. TODO: type model description here. Attributes: host (string): The IP address of the syslog server port (int): The port of the syslog server roles (list of string): A list of roles for the syslog server. Options (case-insensitive): 'Wireless ev... | stack_v2_sparse_classes_36k_train_026501 | 1,998 | permissive | [
{
"docstring": "Constructor for the ServerModel class",
"name": "__init__",
"signature": "def __init__(self, host=None, port=None, roles=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtai... | 2 | null | Implement the Python class `ServerModel` described below.
Class description:
Implementation of the 'Server' model. TODO: type model description here. Attributes: host (string): The IP address of the syslog server port (int): The port of the syslog server roles (list of string): A list of roles for the syslog server. O... | Implement the Python class `ServerModel` described below.
Class description:
Implementation of the 'Server' model. TODO: type model description here. Attributes: host (string): The IP address of the syslog server port (int): The port of the syslog server roles (list of string): A list of roles for the syslog server. O... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class ServerModel:
"""Implementation of the 'Server' model. TODO: type model description here. Attributes: host (string): The IP address of the syslog server port (int): The port of the syslog server roles (list of string): A list of roles for the syslog server. Options (case-insensitive): 'Wireless ev... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServerModel:
"""Implementation of the 'Server' model. TODO: type model description here. Attributes: host (string): The IP address of the syslog server port (int): The port of the syslog server roles (list of string): A list of roles for the syslog server. Options (case-insensitive): 'Wireless event log', 'Ap... | the_stack_v2_python_sparse | meraki_sdk/models/server_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
579a0b07dad117162c119cc43c9ae6f84a3085f4 | [
"mock_settings.ENABLE_NOTIFICATIONS = True\n\n@do_maybe_notification\ndef create_split():\n Splits = namedtuple('Splits', 'data')\n return Splits([{'id': 1}, {'id': 2}])\ncreate_split()\nmock_queue.add.assert_has_calls([mock.call(params={'split': 1}, url='/notifications/notify/'), mock.call(params={'split': 2... | <|body_start_0|>
mock_settings.ENABLE_NOTIFICATIONS = True
@do_maybe_notification
def create_split():
Splits = namedtuple('Splits', 'data')
return Splits([{'id': 1}, {'id': 2}])
create_split()
mock_queue.add.assert_has_calls([mock.call(params={'split': 1}... | NotifyTestCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotifyTestCase:
def test_task_queue_decorator(self, mock_queue, mock_settings):
"""Test the decorator that puts message tasks in the queue."""
<|body_0|>
def test_notify_endpoint(self, mock_send):
"""Test sending an update message from a post to /notify."""
<... | stack_v2_sparse_classes_36k_train_026502 | 2,183 | permissive | [
{
"docstring": "Test the decorator that puts message tasks in the queue.",
"name": "test_task_queue_decorator",
"signature": "def test_task_queue_decorator(self, mock_queue, mock_settings)"
},
{
"docstring": "Test sending an update message from a post to /notify.",
"name": "test_notify_endpo... | 2 | stack_v2_sparse_classes_30k_train_012752 | Implement the Python class `NotifyTestCase` described below.
Class description:
Implement the NotifyTestCase class.
Method signatures and docstrings:
- def test_task_queue_decorator(self, mock_queue, mock_settings): Test the decorator that puts message tasks in the queue.
- def test_notify_endpoint(self, mock_send): ... | Implement the Python class `NotifyTestCase` described below.
Class description:
Implement the NotifyTestCase class.
Method signatures and docstrings:
- def test_task_queue_decorator(self, mock_queue, mock_settings): Test the decorator that puts message tasks in the queue.
- def test_notify_endpoint(self, mock_send): ... | 46c4a1fe409a45e8595210a5cf242425d40d4b41 | <|skeleton|>
class NotifyTestCase:
def test_task_queue_decorator(self, mock_queue, mock_settings):
"""Test the decorator that puts message tasks in the queue."""
<|body_0|>
def test_notify_endpoint(self, mock_send):
"""Test sending an update message from a post to /notify."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotifyTestCase:
def test_task_queue_decorator(self, mock_queue, mock_settings):
"""Test the decorator that puts message tasks in the queue."""
mock_settings.ENABLE_NOTIFICATIONS = True
@do_maybe_notification
def create_split():
Splits = namedtuple('Splits', 'data')... | the_stack_v2_python_sparse | apps/notifications/tests.py | tractiming/trac-gae | train | 5 | |
502966ef4ae859f32787aeeee635bc0a68408f83 | [
"if isinstance(obj, dict):\n copy = {}\n for key, val in list(obj.items()):\n if isinstance(val, dict):\n val = json.loads(json.dumps(val, cls=JSON))\n else:\n val = JsonEncoder._encode(val)\n if type(key) == str and key[0] == '!':\n pass\n else:\n ... | <|body_start_0|>
if isinstance(obj, dict):
copy = {}
for key, val in list(obj.items()):
if isinstance(val, dict):
val = json.loads(json.dumps(val, cls=JSON))
else:
val = JsonEncoder._encode(val)
if ty... | JsonEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonEncoder:
def _encode(obj: Any) -> Any:
"""This JSON encoder function will try it's best to convert any archinstall data structures, instances or variables into something that's understandable by the json.parse()/json.loads() lib. _encode() will skip any dictionary key starting with a... | stack_v2_sparse_classes_36k_train_026503 | 18,654 | no_license | [
{
"docstring": "This JSON encoder function will try it's best to convert any archinstall data structures, instances or variables into something that's understandable by the json.parse()/json.loads() lib. _encode() will skip any dictionary key starting with an exclamation mark (!)",
"name": "_encode",
"s... | 2 | stack_v2_sparse_classes_30k_train_000392 | Implement the Python class `JsonEncoder` described below.
Class description:
Implement the JsonEncoder class.
Method signatures and docstrings:
- def _encode(obj: Any) -> Any: This JSON encoder function will try it's best to convert any archinstall data structures, instances or variables into something that's underst... | Implement the Python class `JsonEncoder` described below.
Class description:
Implement the JsonEncoder class.
Method signatures and docstrings:
- def _encode(obj: Any) -> Any: This JSON encoder function will try it's best to convert any archinstall data structures, instances or variables into something that's underst... | 37d9babb5c5e5e048c4a1b4f211a72c7985f12e7 | <|skeleton|>
class JsonEncoder:
def _encode(obj: Any) -> Any:
"""This JSON encoder function will try it's best to convert any archinstall data structures, instances or variables into something that's understandable by the json.parse()/json.loads() lib. _encode() will skip any dictionary key starting with a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JsonEncoder:
def _encode(obj: Any) -> Any:
"""This JSON encoder function will try it's best to convert any archinstall data structures, instances or variables into something that's understandable by the json.parse()/json.loads() lib. _encode() will skip any dictionary key starting with an exclamation ... | the_stack_v2_python_sparse | installer/archinstall/lib/general.py | mrkatebzadeh/Siarch | train | 2 | |
28fb6769a60fccf9be3a25729e94f5053b33ff50 | [
"with open(file, 'r', encoding='utf-8') as f:\n line = f.readline()\n while line:\n cls.__create_lrc(line)\n line = f.readline()\n cls.__all_lrcs.sort(reverse=True)",
"lrcs = line.split(']')\nlrc = lrcs[-1]\nfor index in range(0, len(lrcs) - 1):\n time = lrcs[index]\n lrc_obj = Lyrics... | <|body_start_0|>
with open(file, 'r', encoding='utf-8') as f:
line = f.readline()
while line:
cls.__create_lrc(line)
line = f.readline()
cls.__all_lrcs.sort(reverse=True)
<|end_body_0|>
<|body_start_1|>
lrcs = line.split(']')
l... | 歌词解析类 | LrcAnalyze | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LrcAnalyze:
"""歌词解析类"""
def __analyze(cls, file):
"""读取歌词内容"""
<|body_0|>
def __create_lrc(cls, line):
"""创建歌词对象"""
<|body_1|>
def get_lrc(cls, time, file):
"""根据时间获取歌词"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
with op... | stack_v2_sparse_classes_36k_train_026504 | 4,828 | no_license | [
{
"docstring": "读取歌词内容",
"name": "__analyze",
"signature": "def __analyze(cls, file)"
},
{
"docstring": "创建歌词对象",
"name": "__create_lrc",
"signature": "def __create_lrc(cls, line)"
},
{
"docstring": "根据时间获取歌词",
"name": "get_lrc",
"signature": "def get_lrc(cls, time, file)... | 3 | null | Implement the Python class `LrcAnalyze` described below.
Class description:
歌词解析类
Method signatures and docstrings:
- def __analyze(cls, file): 读取歌词内容
- def __create_lrc(cls, line): 创建歌词对象
- def get_lrc(cls, time, file): 根据时间获取歌词 | Implement the Python class `LrcAnalyze` described below.
Class description:
歌词解析类
Method signatures and docstrings:
- def __analyze(cls, file): 读取歌词内容
- def __create_lrc(cls, line): 创建歌词对象
- def get_lrc(cls, time, file): 根据时间获取歌词
<|skeleton|>
class LrcAnalyze:
"""歌词解析类"""
def __analyze(cls, file):
"... | 59bd17bbb7d3bb2fdd0fc811390bee126161050c | <|skeleton|>
class LrcAnalyze:
"""歌词解析类"""
def __analyze(cls, file):
"""读取歌词内容"""
<|body_0|>
def __create_lrc(cls, line):
"""创建歌词对象"""
<|body_1|>
def get_lrc(cls, time, file):
"""根据时间获取歌词"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LrcAnalyze:
"""歌词解析类"""
def __analyze(cls, file):
"""读取歌词内容"""
with open(file, 'r', encoding='utf-8') as f:
line = f.readline()
while line:
cls.__create_lrc(line)
line = f.readline()
cls.__all_lrcs.sort(reverse=True)
... | the_stack_v2_python_sparse | day15-类和对象/zuoye.py | M0use7/python | train | 0 |
dc7edeb3d911e5d8e85d52b8b40dd2e9f67f71aa | [
"super(UpsampleChecker, self).__init__()\nself.upsample = nn.Upsample(scale_factor=scale_factor, mode=mode)\nself.reflection_pad = reflection_padding\nself.conv = nn.Conv3d(channels, channels // ch_mult, kernel_size=kernel_size, stride=stride, padding=conv_padding, bias=deconv_bias)",
"print('upsample')\nprint('o... | <|body_start_0|>
super(UpsampleChecker, self).__init__()
self.upsample = nn.Upsample(scale_factor=scale_factor, mode=mode)
self.reflection_pad = reflection_padding
self.conv = nn.Conv3d(channels, channels // ch_mult, kernel_size=kernel_size, stride=stride, padding=conv_padding, bias=deco... | UpsampleChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpsampleChecker:
def __init__(self, scale_factor, mode, reflection_padding, channels, ch_mult, kernel_size, conv_padding, stride, deconv_bias):
"""https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/190 nn.Upsample(scale_factor = 2, mode='bilinear'), nn.ReflectionPad2d(1), nn.... | stack_v2_sparse_classes_36k_train_026505 | 12,177 | no_license | [
{
"docstring": "https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/190 nn.Upsample(scale_factor = 2, mode='bilinear'), nn.ReflectionPad2d(1), nn.Conv2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=1, padding=0) nn.Upsample mode (string, optional) – the upsampling algorithm: one of nearest,... | 2 | stack_v2_sparse_classes_30k_train_021430 | Implement the Python class `UpsampleChecker` described below.
Class description:
Implement the UpsampleChecker class.
Method signatures and docstrings:
- def __init__(self, scale_factor, mode, reflection_padding, channels, ch_mult, kernel_size, conv_padding, stride, deconv_bias): https://github.com/junyanz/pytorch-Cy... | Implement the Python class `UpsampleChecker` described below.
Class description:
Implement the UpsampleChecker class.
Method signatures and docstrings:
- def __init__(self, scale_factor, mode, reflection_padding, channels, ch_mult, kernel_size, conv_padding, stride, deconv_bias): https://github.com/junyanz/pytorch-Cy... | 67f7126cf2f4e5c09e52efd3553754e463e90a0e | <|skeleton|>
class UpsampleChecker:
def __init__(self, scale_factor, mode, reflection_padding, channels, ch_mult, kernel_size, conv_padding, stride, deconv_bias):
"""https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/190 nn.Upsample(scale_factor = 2, mode='bilinear'), nn.ReflectionPad2d(1), nn.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpsampleChecker:
def __init__(self, scale_factor, mode, reflection_padding, channels, ch_mult, kernel_size, conv_padding, stride, deconv_bias):
"""https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/190 nn.Upsample(scale_factor = 2, mode='bilinear'), nn.ReflectionPad2d(1), nn.Conv2d(ngf * m... | the_stack_v2_python_sparse | mmd_gan/models/decoder_v04_UpsampleConv.py | NYU-CDS-Capstone-Project/HydroGAN | train | 1 | |
ff9ddca5f5fcae922243d5a07ca737197b28eb38 | [
"self.fontFamily = fontFamily\nself.glyphDictionary = {}\nself.glyphXMLElementDictionary = {}\nself.missingGlyph = None\nfileName = os.path.join(getFontsDirectoryPath(), fontFamily + '.svg')\nself.xmlParser = XMLSimpleReader(fileName, None, archive.getFileText(fileName))\nself.fontXMLElement = self.xmlParser.getRoo... | <|body_start_0|>
self.fontFamily = fontFamily
self.glyphDictionary = {}
self.glyphXMLElementDictionary = {}
self.missingGlyph = None
fileName = os.path.join(getFontsDirectoryPath(), fontFamily + '.svg')
self.xmlParser = XMLSimpleReader(fileName, None, archive.getFileText(... | Class to read a font in the fonts folder. | FontReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FontReader:
"""Class to read a font in the fonts folder."""
def __init__(self, fontFamily):
"""Initialize."""
<|body_0|>
def getGlyph(self, character, yAxisPointingUpward):
"""Get the glyph for the character."""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_026506 | 39,231 | no_license | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, fontFamily)"
},
{
"docstring": "Get the glyph for the character.",
"name": "getGlyph",
"signature": "def getGlyph(self, character, yAxisPointingUpward)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013177 | Implement the Python class `FontReader` described below.
Class description:
Class to read a font in the fonts folder.
Method signatures and docstrings:
- def __init__(self, fontFamily): Initialize.
- def getGlyph(self, character, yAxisPointingUpward): Get the glyph for the character. | Implement the Python class `FontReader` described below.
Class description:
Class to read a font in the fonts folder.
Method signatures and docstrings:
- def __init__(self, fontFamily): Initialize.
- def getGlyph(self, character, yAxisPointingUpward): Get the glyph for the character.
<|skeleton|>
class FontReader:
... | c1b00a76f1550df2cbb457248205159e51fd4308 | <|skeleton|>
class FontReader:
"""Class to read a font in the fonts folder."""
def __init__(self, fontFamily):
"""Initialize."""
<|body_0|>
def getGlyph(self, character, yAxisPointingUpward):
"""Get the glyph for the character."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FontReader:
"""Class to read a font in the fonts folder."""
def __init__(self, fontFamily):
"""Initialize."""
self.fontFamily = fontFamily
self.glyphDictionary = {}
self.glyphXMLElementDictionary = {}
self.missingGlyph = None
fileName = os.path.join(getFont... | the_stack_v2_python_sparse | fabmetheus_utilities/svg_reader.py | amsler/skeinforge | train | 10 |
c8009485b360571ec704e38e2dedea7ba1e74faf | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | MatchServiceV1Servicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchServiceV1Servicer:
"""Missing associated documentation comment in .proto file."""
def GetAccountMatchSetting(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def UpdateAccountMatchSetting(self, request, context):
... | stack_v2_sparse_classes_36k_train_026507 | 17,987 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetAccountMatchSetting",
"signature": "def GetAccountMatchSetting(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "UpdateAccountMatchSetting",
... | 5 | null | Implement the Python class `MatchServiceV1Servicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetAccountMatchSetting(self, request, context): Missing associated documentation comment in .proto file.
- def UpdateAccountMatchSett... | Implement the Python class `MatchServiceV1Servicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetAccountMatchSetting(self, request, context): Missing associated documentation comment in .proto file.
- def UpdateAccountMatchSett... | 8111787d1d20eb87733ae360d8baa745a65e2743 | <|skeleton|>
class MatchServiceV1Servicer:
"""Missing associated documentation comment in .proto file."""
def GetAccountMatchSetting(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def UpdateAccountMatchSetting(self, request, context):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MatchServiceV1Servicer:
"""Missing associated documentation comment in .proto file."""
def GetAccountMatchSetting(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not... | the_stack_v2_python_sparse | CmsAdmin/codegen_protos/interactive_main_service_pb2_grpc.py | Final-Game/social_network_backend | train | 0 |
6e57c67fd6bf71d91188e06f3c8b27ec3efc6122 | [
"num_removed = 0\nfor name, field in form.fields.items():\n if not name.startswith('del_attachment_') or not field:\n continue\n sodar_uuid = name[len('del_attachment_'):]\n try:\n form.instance.get_attachment_files().get(sodar_uuid=sodar_uuid).delete()\n num_removed += 1\n except F... | <|body_start_0|>
num_removed = 0
for name, field in form.fields.items():
if not name.startswith('del_attachment_') or not field:
continue
sodar_uuid = name[len('del_attachment_'):]
try:
form.instance.get_attachment_files().get(sodar_uui... | Mixin with helper functions for message attachments. | MessageAttachmentHelpersMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageAttachmentHelpersMixin:
"""Mixin with helper functions for message attachments."""
def _handle_attachment_removal(self, form):
"""Handle the removal of files."""
<|body_0|>
def _handle_file_uploads(self, message):
"""Handle file uploads, if any. Ensures to... | stack_v2_sparse_classes_36k_train_026508 | 31,734 | permissive | [
{
"docstring": "Handle the removal of files.",
"name": "_handle_attachment_removal",
"signature": "def _handle_attachment_removal(self, form)"
},
{
"docstring": "Handle file uploads, if any. Ensures to remove the file upload folder for this message.",
"name": "_handle_file_uploads",
"sig... | 4 | stack_v2_sparse_classes_30k_train_005689 | Implement the Python class `MessageAttachmentHelpersMixin` described below.
Class description:
Mixin with helper functions for message attachments.
Method signatures and docstrings:
- def _handle_attachment_removal(self, form): Handle the removal of files.
- def _handle_file_uploads(self, message): Handle file upload... | Implement the Python class `MessageAttachmentHelpersMixin` described below.
Class description:
Mixin with helper functions for message attachments.
Method signatures and docstrings:
- def _handle_attachment_removal(self, form): Handle the removal of files.
- def _handle_file_uploads(self, message): Handle file upload... | 83f94d068d8592d83254a0b4271be9523334339d | <|skeleton|>
class MessageAttachmentHelpersMixin:
"""Mixin with helper functions for message attachments."""
def _handle_attachment_removal(self, form):
"""Handle the removal of files."""
<|body_0|>
def _handle_file_uploads(self, message):
"""Handle file uploads, if any. Ensures to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MessageAttachmentHelpersMixin:
"""Mixin with helper functions for message attachments."""
def _handle_attachment_removal(self, form):
"""Handle the removal of files."""
num_removed = 0
for name, field in form.fields.items():
if not name.startswith('del_attachment_') or... | the_stack_v2_python_sparse | flowcells/views.py | bihealth/digestiflow-server | train | 16 |
1c09e2ced8ed33aaf69f92e353bcdee1631818af | [
"self.pack_id = pack_id\nself._last_rn_file_path = rn_file_path\nself._update_type = update_type\nself._update_rn_obj = UpdateRN(pack_path=f'{PACKS_DIR}/{pack_id}', update_type=update_type.value, modified_files_in_pack=set(), added_files=set(), pack=pack_id, is_force=True)\nself._bc_file = self._last_rn_file_path.w... | <|body_start_0|>
self.pack_id = pack_id
self._last_rn_file_path = rn_file_path
self._update_type = update_type
self._update_rn_obj = UpdateRN(pack_path=f'{PACKS_DIR}/{pack_id}', update_type=update_type.value, modified_files_in_pack=set(), added_files=set(), pack=pack_id, is_force=True)
... | PackAutoBumper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackAutoBumper:
def __init__(self, pack_id: str, rn_file_path: Path, update_type: UpdateType):
"""Autobump pack version. Args: pack_id: Pack id to its release notes. rn_file_path: last release notes path. update_type: the update type that was in the pr."""
<|body_0|>
def set... | stack_v2_sparse_classes_36k_train_026509 | 11,815 | permissive | [
{
"docstring": "Autobump pack version. Args: pack_id: Pack id to its release notes. rn_file_path: last release notes path. update_type: the update type that was in the pr.",
"name": "__init__",
"signature": "def __init__(self, pack_id: str, rn_file_path: Path, update_type: UpdateType)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_train_010596 | Implement the Python class `PackAutoBumper` described below.
Class description:
Implement the PackAutoBumper class.
Method signatures and docstrings:
- def __init__(self, pack_id: str, rn_file_path: Path, update_type: UpdateType): Autobump pack version. Args: pack_id: Pack id to its release notes. rn_file_path: last ... | Implement the Python class `PackAutoBumper` described below.
Class description:
Implement the PackAutoBumper class.
Method signatures and docstrings:
- def __init__(self, pack_id: str, rn_file_path: Path, update_type: UpdateType): Autobump pack version. Args: pack_id: Pack id to its release notes. rn_file_path: last ... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class PackAutoBumper:
def __init__(self, pack_id: str, rn_file_path: Path, update_type: UpdateType):
"""Autobump pack version. Args: pack_id: Pack id to its release notes. rn_file_path: last release notes path. update_type: the update type that was in the pr."""
<|body_0|>
def set... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PackAutoBumper:
def __init__(self, pack_id: str, rn_file_path: Path, update_type: UpdateType):
"""Autobump pack version. Args: pack_id: Pack id to its release notes. rn_file_path: last release notes path. update_type: the update type that was in the pr."""
self.pack_id = pack_id
self._... | the_stack_v2_python_sparse | Utils/github_workflow_scripts/autobump_release_notes/autobump_rn.py | demisto/content | train | 1,023 | |
b81782b5bc2d6622f7e3c74f9237a47911480627 | [
"super(RatRelease6, self).__init__(name, system, root_dep, 'geant4.10.0.p02', 'scons-2.3.4', tar_name)\nself._curl_dep = 'curl-7.26.0'\nself._bzip_dep = 'bzip2-1.0.6'\nself._gsl_dep = 'gsl-1.16'\nself._postgres_dep = 'postgresql-9.5.2'\nself._require_postgres = postgres",
"if self._require_postgres is True:\n ... | <|body_start_0|>
super(RatRelease6, self).__init__(name, system, root_dep, 'geant4.10.0.p02', 'scons-2.3.4', tar_name)
self._curl_dep = 'curl-7.26.0'
self._bzip_dep = 'bzip2-1.0.6'
self._gsl_dep = 'gsl-1.16'
self._postgres_dep = 'postgresql-9.5.2'
self._require_postgres =... | Base installer for rat relase 6.0.0 onwards. | RatRelease6 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RatRelease6:
"""Base installer for rat relase 6.0.0 onwards."""
def __init__(self, name, system, root_dep, tar_name, postgres=False):
"""Initlaise, take extra dependencies."""
<|body_0|>
def _get_dependencies(self):
"""Return the extra dependencies."""
<|... | stack_v2_sparse_classes_36k_train_026510 | 21,151 | permissive | [
{
"docstring": "Initlaise, take extra dependencies.",
"name": "__init__",
"signature": "def __init__(self, name, system, root_dep, tar_name, postgres=False)"
},
{
"docstring": "Return the extra dependencies.",
"name": "_get_dependencies",
"signature": "def _get_dependencies(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_011684 | Implement the Python class `RatRelease6` described below.
Class description:
Base installer for rat relase 6.0.0 onwards.
Method signatures and docstrings:
- def __init__(self, name, system, root_dep, tar_name, postgres=False): Initlaise, take extra dependencies.
- def _get_dependencies(self): Return the extra depend... | Implement the Python class `RatRelease6` described below.
Class description:
Base installer for rat relase 6.0.0 onwards.
Method signatures and docstrings:
- def __init__(self, name, system, root_dep, tar_name, postgres=False): Initlaise, take extra dependencies.
- def _get_dependencies(self): Return the extra depend... | 2881a32467ad198c7081da0ceb57d5835657f229 | <|skeleton|>
class RatRelease6:
"""Base installer for rat relase 6.0.0 onwards."""
def __init__(self, name, system, root_dep, tar_name, postgres=False):
"""Initlaise, take extra dependencies."""
<|body_0|>
def _get_dependencies(self):
"""Return the extra dependencies."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RatRelease6:
"""Base installer for rat relase 6.0.0 onwards."""
def __init__(self, name, system, root_dep, tar_name, postgres=False):
"""Initlaise, take extra dependencies."""
super(RatRelease6, self).__init__(name, system, root_dep, 'geant4.10.0.p02', 'scons-2.3.4', tar_name)
sel... | the_stack_v2_python_sparse | packages/ratreleases.py | snoplus/snoing | train | 6 |
f7c47753b2cea6523eebb5fe23b1ac6dab84ff01 | [
"super(ResNet, self).__init__()\nself.output_channel_block = [int(output_channel / 4), int(output_channel / 2), output_channel, output_channel]\nself.inplanes = int(output_channel / 8)\nself.conv0_1 = nn.Conv2d(input_channel, int(output_channel / 16), kernel_size=3, stride=1, padding=1, bias=False)\nself.bn0_1 = nn... | <|body_start_0|>
super(ResNet, self).__init__()
self.output_channel_block = [int(output_channel / 4), int(output_channel / 2), output_channel, output_channel]
self.inplanes = int(output_channel / 8)
self.conv0_1 = nn.Conv2d(input_channel, int(output_channel / 16), kernel_size=3, stride=1... | Res-Net network structure | ResNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNet:
"""Res-Net network structure"""
def __init__(self, input_channel, output_channel, block, layers):
"""Args: input_channel (int): input channel output_channel (int): output channel block (BasicBlock): convolution block layers (list): layers of the block"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_026511 | 9,680 | permissive | [
{
"docstring": "Args: input_channel (int): input channel output_channel (int): output channel block (BasicBlock): convolution block layers (list): layers of the block",
"name": "__init__",
"signature": "def __init__(self, input_channel, output_channel, block, layers)"
},
{
"docstring": "Args: bl... | 3 | null | Implement the Python class `ResNet` described below.
Class description:
Res-Net network structure
Method signatures and docstrings:
- def __init__(self, input_channel, output_channel, block, layers): Args: input_channel (int): input channel output_channel (int): output channel block (BasicBlock): convolution block la... | Implement the Python class `ResNet` described below.
Class description:
Res-Net network structure
Method signatures and docstrings:
- def __init__(self, input_channel, output_channel, block, layers): Args: input_channel (int): input channel output_channel (int): output channel block (BasicBlock): convolution block la... | fb47a96d1a38f5ce634c6f12d710ed5300cc89fc | <|skeleton|>
class ResNet:
"""Res-Net network structure"""
def __init__(self, input_channel, output_channel, block, layers):
"""Args: input_channel (int): input channel output_channel (int): output channel block (BasicBlock): convolution block layers (list): layers of the block"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResNet:
"""Res-Net network structure"""
def __init__(self, input_channel, output_channel, block, layers):
"""Args: input_channel (int): input channel output_channel (int): output channel block (BasicBlock): convolution block layers (list): layers of the block"""
super(ResNet, self).__init... | the_stack_v2_python_sparse | davarocr/davarocr/davar_rcg/models/backbones/ResNet32.py | OCRWorld/DAVAR-Lab-OCR | train | 0 |
e88574b2c9476b472d6703c85c1dd4bd3baf53f6 | [
"super(ComputeOutputDataList, self).__init__()\nself.version = __RCSID__\nself.listoutput = []",
"if 'listoutput' in self.step_commons:\n self.listoutput = self.step_commons['listoutput']\nif 'outputList' in self.workflow_commons:\n self.workflow_commons['outputList'] = self.workflow_commons['outputList'] +... | <|body_start_0|>
super(ComputeOutputDataList, self).__init__()
self.version = __RCSID__
self.listoutput = []
<|end_body_0|>
<|body_start_1|>
if 'listoutput' in self.step_commons:
self.listoutput = self.step_commons['listoutput']
if 'outputList' in self.workflow_commo... | In case the previous module executed properly, add the output to the listoutput. This is used in the prduction context to ensure only the files coming from successful applications are added to the output list. Otherwise, there is a risk to register corrupted files. | ComputeOutputDataList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComputeOutputDataList:
"""In case the previous module executed properly, add the output to the listoutput. This is used in the prduction context to ensure only the files coming from successful applications are added to the output list. Otherwise, there is a risk to register corrupted files."""
... | stack_v2_sparse_classes_36k_train_026512 | 1,437 | no_license | [
{
"docstring": "Module initialization.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Update the workflow_commons dictionary with the current step's output",
"name": "applicationSpecificInputs",
"signature": "def applicationSpecificInputs(self)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_007005 | Implement the Python class `ComputeOutputDataList` described below.
Class description:
In case the previous module executed properly, add the output to the listoutput. This is used in the prduction context to ensure only the files coming from successful applications are added to the output list. Otherwise, there is a ... | Implement the Python class `ComputeOutputDataList` described below.
Class description:
In case the previous module executed properly, add the output to the listoutput. This is used in the prduction context to ensure only the files coming from successful applications are added to the output list. Otherwise, there is a ... | 9c366957fdd680a284df675c318989cb88e5959c | <|skeleton|>
class ComputeOutputDataList:
"""In case the previous module executed properly, add the output to the listoutput. This is used in the prduction context to ensure only the files coming from successful applications are added to the output list. Otherwise, there is a risk to register corrupted files."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComputeOutputDataList:
"""In case the previous module executed properly, add the output to the listoutput. This is used in the prduction context to ensure only the files coming from successful applications are added to the output list. Otherwise, there is a risk to register corrupted files."""
def __init... | the_stack_v2_python_sparse | Workflow/Modules/ComputeOutputDataList.py | LCDsoft/ILCDIRAC | train | 1 |
b3a6eac109954d03992f938dc52c1c7431ba60a8 | [
"ret_head = head.next if head and head.next else head\npp_head = None\nwhile head:\n if not head.next:\n break\n pre_head = head\n cur_head = head.next\n next_head = cur_head.next\n cur_head.next = pre_head\n pre_head.next = next_head\n if pp_head:\n pp_head.next = cur_head\n p... | <|body_start_0|>
ret_head = head.next if head and head.next else head
pp_head = None
while head:
if not head.next:
break
pre_head = head
cur_head = head.next
next_head = cur_head.next
cur_head.next = pre_head
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def rewrite(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret_head = head.next if head and head.next ... | stack_v2_sparse_classes_36k_train_026513 | 2,173 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs",
"signature": "def swapPairs(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "rewrite",
"signature": "def rewrite(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007615 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def rewrite(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def rewrite(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def swapPairs... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def rewrite(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
ret_head = head.next if head and head.next else head
pp_head = None
while head:
if not head.next:
break
pre_head = head
cur_head = head.next
... | the_stack_v2_python_sparse | co_ms/24_Swap_Nodes_in_Pairs.py | vsdrun/lc_public | train | 6 | |
74c6d4e319c3e7b37600a75b220f46486ca427a4 | [
"root = Newick.Clade()\nroot.name = 'root'\nbuildTree(3, 2, root, 'root')\ntarget_name = 'root.1.2.1'\ntarget = phyloutil.findNodeByName(target_name, root)\nself.assertTrue(target.name == target_name)",
"root = Newick.Clade()\nroot.name = 'cellular organisms'\ninf = open('./test-phyloutil/test1/Pseudozyma-antarct... | <|body_start_0|>
root = Newick.Clade()
root.name = 'root'
buildTree(3, 2, root, 'root')
target_name = 'root.1.2.1'
target = phyloutil.findNodeByName(target_name, root)
self.assertTrue(target.name == target_name)
<|end_body_0|>
<|body_start_1|>
root = Newick.Clade... | test001 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test001:
def test_search(self):
"""Find by name"""
<|body_0|>
def test_reading_from_class_table(self):
"""Read table"""
<|body_1|>
def test_reading_from_guide_table(self):
"""Read table"""
<|body_2|>
def test_simple_manual_tree(self)... | stack_v2_sparse_classes_36k_train_026514 | 2,303 | no_license | [
{
"docstring": "Find by name",
"name": "test_search",
"signature": "def test_search(self)"
},
{
"docstring": "Read table",
"name": "test_reading_from_class_table",
"signature": "def test_reading_from_class_table(self)"
},
{
"docstring": "Read table",
"name": "test_reading_fro... | 5 | null | Implement the Python class `test001` described below.
Class description:
Implement the test001 class.
Method signatures and docstrings:
- def test_search(self): Find by name
- def test_reading_from_class_table(self): Read table
- def test_reading_from_guide_table(self): Read table
- def test_simple_manual_tree(self):... | Implement the Python class `test001` described below.
Class description:
Implement the test001 class.
Method signatures and docstrings:
- def test_search(self): Find by name
- def test_reading_from_class_table(self): Read table
- def test_reading_from_guide_table(self): Read table
- def test_simple_manual_tree(self):... | d7ddd2b585a841c6d986974a24a53e4d1abe71ba | <|skeleton|>
class test001:
def test_search(self):
"""Find by name"""
<|body_0|>
def test_reading_from_class_table(self):
"""Read table"""
<|body_1|>
def test_reading_from_guide_table(self):
"""Read table"""
<|body_2|>
def test_simple_manual_tree(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test001:
def test_search(self):
"""Find by name"""
root = Newick.Clade()
root.name = 'root'
buildTree(3, 2, root, 'root')
target_name = 'root.1.2.1'
target = phyloutil.findNodeByName(target_name, root)
self.assertTrue(target.name == target_name)
def... | the_stack_v2_python_sparse | src/phyloutil_test.py | dad/base | train | 0 | |
2b895cf4392273b689ddafc6f26c5ab11f737a5a | [
"super(CustomCrossEntropyLoss, self).__init__()\nself.use_sigmoid = use_sigmoid\nself.use_mask = use_mask\nself.reduction = reduction\nself.loss_weight = loss_weight\nif self.use_sigmoid:\n self.loss_function = binary_cross_entropy\nelif self.use_mask:\n self.loss_function = mask_cross_entropy\nelse:\n sel... | <|body_start_0|>
super(CustomCrossEntropyLoss, self).__init__()
self.use_sigmoid = use_sigmoid
self.use_mask = use_mask
self.reduction = reduction
self.loss_weight = loss_weight
if self.use_sigmoid:
self.loss_function = binary_cross_entropy
elif self.u... | Cross Entropy Loss. | CustomCrossEntropyLoss | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomCrossEntropyLoss:
"""Cross Entropy Loss."""
def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0):
"""Init Cross Entropy loss. :param desc: config dict"""
<|body_0|>
def forward(self, cls_score, label, weight, avg_factor, reductio... | stack_v2_sparse_classes_36k_train_026515 | 13,829 | permissive | [
{
"docstring": "Init Cross Entropy loss. :param desc: config dict",
"name": "__init__",
"signature": "def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0)"
},
{
"docstring": "Forward compute.",
"name": "forward",
"signature": "def forward(self, cls_sco... | 2 | stack_v2_sparse_classes_30k_train_014020 | Implement the Python class `CustomCrossEntropyLoss` described below.
Class description:
Cross Entropy Loss.
Method signatures and docstrings:
- def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0): Init Cross Entropy loss. :param desc: config dict
- def forward(self, cls_score, lab... | Implement the Python class `CustomCrossEntropyLoss` described below.
Class description:
Cross Entropy Loss.
Method signatures and docstrings:
- def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0): Init Cross Entropy loss. :param desc: config dict
- def forward(self, cls_score, lab... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class CustomCrossEntropyLoss:
"""Cross Entropy Loss."""
def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0):
"""Init Cross Entropy loss. :param desc: config dict"""
<|body_0|>
def forward(self, cls_score, label, weight, avg_factor, reductio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomCrossEntropyLoss:
"""Cross Entropy Loss."""
def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0):
"""Init Cross Entropy loss. :param desc: config dict"""
super(CustomCrossEntropyLoss, self).__init__()
self.use_sigmoid = use_sigmoid
... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/pytorch/operator/rpn.py | Huawei-Ascend/modelzoo | train | 1 |
11da08c546f382f94a9fc3b13cf725630d0111fd | [
"self.selected_features = selected_features\nself.input_data_description = input_data_description\nself.name = 'feature_extract'\nself.new_input_data_description = {}\nself.new_input_data_description.update({'NI': len(self.selected_features)})\nold_input_types = self.input_data_description['input_types']\nnew_input... | <|body_start_0|>
self.selected_features = selected_features
self.input_data_description = input_data_description
self.name = 'feature_extract'
self.new_input_data_description = {}
self.new_input_data_description.update({'NI': len(self.selected_features)})
old_input_types ... | feature_extract_model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class feature_extract_model:
def __init__(self, selected_features, input_data_description):
"""Parameters ---------- selected_features: list of indices Features to be retained input_data_description: dict Description of the input features"""
<|body_0|>
def transform(self, X):
... | stack_v2_sparse_classes_36k_train_026516 | 2,216 | permissive | [
{
"docstring": "Parameters ---------- selected_features: list of indices Features to be retained input_data_description: dict Description of the input features",
"name": "__init__",
"signature": "def __init__(self, selected_features, input_data_description)"
},
{
"docstring": "Transform data by ... | 2 | stack_v2_sparse_classes_30k_train_012945 | Implement the Python class `feature_extract_model` described below.
Class description:
Implement the feature_extract_model class.
Method signatures and docstrings:
- def __init__(self, selected_features, input_data_description): Parameters ---------- selected_features: list of indices Features to be retained input_da... | Implement the Python class `feature_extract_model` described below.
Class description:
Implement the feature_extract_model class.
Method signatures and docstrings:
- def __init__(self, selected_features, input_data_description): Parameters ---------- selected_features: list of indices Features to be retained input_da... | ccc0a7674a04ae0d00bedc38893b33184c5f68c6 | <|skeleton|>
class feature_extract_model:
def __init__(self, selected_features, input_data_description):
"""Parameters ---------- selected_features: list of indices Features to be retained input_data_description: dict Description of the input features"""
<|body_0|>
def transform(self, X):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class feature_extract_model:
def __init__(self, selected_features, input_data_description):
"""Parameters ---------- selected_features: list of indices Features to be retained input_data_description: dict Description of the input features"""
self.selected_features = selected_features
self.in... | the_stack_v2_python_sparse | MMLL/preprocessors/feature_extract.py | Musketeer-H2020/MMLL-Robust | train | 0 | |
22ec3713c3592add9205e4f539a934c6af6f4544 | [
"res, n, M = (0, len(arr), 10 ** 9 + 7)\nst = [-1]\ndp = [0] * (n + 1)\nfor i in range(1, n + 1):\n while st[-1] != -1 and arr[st[-1]] >= arr[i - 1]:\n st.pop()\n dp[i] = (dp[st[-1] + 1] + (i - 1 - st[-1]) * arr[i - 1]) % M\n st.append(i - 1)\n res = (res + dp[i]) % M\nreturn res",
"res = 0\ns ... | <|body_start_0|>
res, n, M = (0, len(arr), 10 ** 9 + 7)
st = [-1]
dp = [0] * (n + 1)
for i in range(1, n + 1):
while st[-1] != -1 and arr[st[-1]] >= arr[i - 1]:
st.pop()
dp[i] = (dp[st[-1] + 1] + (i - 1 - st[-1]) * arr[i - 1]) % M
st.ap... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumSubarrayMins(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def sumSubarrayMins2(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res, n, M = (0, len(arr), 10 ** 9 + 7)
... | stack_v2_sparse_classes_36k_train_026517 | 1,665 | no_license | [
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "sumSubarrayMins",
"signature": "def sumSubarrayMins(self, arr)"
},
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "sumSubarrayMins2",
"signature": "def sumSubarrayMins2(self, arr)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017750 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumSubarrayMins(self, arr): :type arr: List[int] :rtype: int
- def sumSubarrayMins2(self, arr): :type arr: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumSubarrayMins(self, arr): :type arr: List[int] :rtype: int
- def sumSubarrayMins2(self, arr): :type arr: List[int] :rtype: int
<|skeleton|>
class Solution:
def sumSub... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def sumSubarrayMins(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def sumSubarrayMins2(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumSubarrayMins(self, arr):
""":type arr: List[int] :rtype: int"""
res, n, M = (0, len(arr), 10 ** 9 + 7)
st = [-1]
dp = [0] * (n + 1)
for i in range(1, n + 1):
while st[-1] != -1 and arr[st[-1]] >= arr[i - 1]:
st.pop()
... | the_stack_v2_python_sparse | S/SumofSubarrayMinimums.py | bssrdf/pyleet | train | 2 | |
1afbed1de83adfd2a5b4eda4460ba01f1e2b346c | [
"params = ProductsForm(data=request.GET)\nparams.is_valid(raise_exception=True)\ncursor = params.data.get('cursor')\nlimit = params.data.get('limit')\nproducts = ProductBasic(products_service.search_product_list(params), many=True)\nresponse = dict()\nresponse['products'] = products.data\nresponse['total_count'] = ... | <|body_start_0|>
params = ProductsForm(data=request.GET)
params.is_valid(raise_exception=True)
cursor = params.data.get('cursor')
limit = params.data.get('limit')
products = ProductBasic(products_service.search_product_list(params), many=True)
response = dict()
re... | ProductView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductView:
def list(self, request):
"""제품 리스트 (검색)"""
<|body_0|>
def detail(self, request, pk=None):
"""제품 상세 정보"""
<|body_1|>
def pricing(self, request):
"""제품 최저/최고 가격 --- json 형태의 파라미터 <br> data = [{ <br> 'id': Integer, <br> 'cnt': Integer, ... | stack_v2_sparse_classes_36k_train_026518 | 7,107 | no_license | [
{
"docstring": "제품 리스트 (검색)",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "제품 상세 정보",
"name": "detail",
"signature": "def detail(self, request, pk=None)"
},
{
"docstring": "제품 최저/최고 가격 --- json 형태의 파라미터 <br> data = [{ <br> 'id': Integer, <br> 'cnt': I... | 3 | null | Implement the Python class `ProductView` described below.
Class description:
Implement the ProductView class.
Method signatures and docstrings:
- def list(self, request): 제품 리스트 (검색)
- def detail(self, request, pk=None): 제품 상세 정보
- def pricing(self, request): 제품 최저/최고 가격 --- json 형태의 파라미터 <br> data = [{ <br> 'id': In... | Implement the Python class `ProductView` described below.
Class description:
Implement the ProductView class.
Method signatures and docstrings:
- def list(self, request): 제품 리스트 (검색)
- def detail(self, request, pk=None): 제품 상세 정보
- def pricing(self, request): 제품 최저/최고 가격 --- json 형태의 파라미터 <br> data = [{ <br> 'id': In... | 0edc046f57a1c171c10be5dfa4b4e26f440847be | <|skeleton|>
class ProductView:
def list(self, request):
"""제품 리스트 (검색)"""
<|body_0|>
def detail(self, request, pk=None):
"""제품 상세 정보"""
<|body_1|>
def pricing(self, request):
"""제품 최저/최고 가격 --- json 형태의 파라미터 <br> data = [{ <br> 'id': Integer, <br> 'cnt': Integer, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductView:
def list(self, request):
"""제품 리스트 (검색)"""
params = ProductsForm(data=request.GET)
params.is_valid(raise_exception=True)
cursor = params.data.get('cursor')
limit = params.data.get('limit')
products = ProductBasic(products_service.search_product_list... | the_stack_v2_python_sparse | backends/ec/v2/products.py | jmp7786/coins | train | 0 | |
1da618b2c8f35de4d1fcb1c536d7fb5f17b35791 | [
"super(ProjectSubjectDatabase, self).__init__(main_confs, syn)\nif isinstance(project_id, int):\n pass\nelif isinstance(project_id, str):\n try:\n project_id = int(project_id)\n except ValueError:\n if not project_id.startswith('syn'):\n raise ValueError('Invalid `project_id` value... | <|body_start_0|>
super(ProjectSubjectDatabase, self).__init__(main_confs, syn)
if isinstance(project_id, int):
pass
elif isinstance(project_id, str):
try:
project_id = int(project_id)
except ValueError:
if not project_id.startsw... | Manage interactions with Synapse concerning accessing, downloading, and combining subject database files from a single Synapse Project. | ProjectSubjectDatabase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectSubjectDatabase:
"""Manage interactions with Synapse concerning accessing, downloading, and combining subject database files from a single Synapse Project."""
def __init__(self, main_confs, syn, project_id):
"""Initialize and validate basic information. Args: main_confs (dict-... | stack_v2_sparse_classes_36k_train_026519 | 5,910 | permissive | [
{
"docstring": "Initialize and validate basic information. Args: main_confs (dict-like): refernce to main configuration tree. syn (Synapse): an active synapse connection object. project_id (str): Synapse ID for a project.",
"name": "__init__",
"signature": "def __init__(self, main_confs, syn, project_id... | 3 | stack_v2_sparse_classes_30k_train_020469 | Implement the Python class `ProjectSubjectDatabase` described below.
Class description:
Manage interactions with Synapse concerning accessing, downloading, and combining subject database files from a single Synapse Project.
Method signatures and docstrings:
- def __init__(self, main_confs, syn, project_id): Initializ... | Implement the Python class `ProjectSubjectDatabase` described below.
Class description:
Manage interactions with Synapse concerning accessing, downloading, and combining subject database files from a single Synapse Project.
Method signatures and docstrings:
- def __init__(self, main_confs, syn, project_id): Initializ... | cf77b6e916a25aa586a388e489d55a86974eaddc | <|skeleton|>
class ProjectSubjectDatabase:
"""Manage interactions with Synapse concerning accessing, downloading, and combining subject database files from a single Synapse Project."""
def __init__(self, main_confs, syn, project_id):
"""Initialize and validate basic information. Args: main_confs (dict-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectSubjectDatabase:
"""Manage interactions with Synapse concerning accessing, downloading, and combining subject database files from a single Synapse Project."""
def __init__(self, main_confs, syn, project_id):
"""Initialize and validate basic information. Args: main_confs (dict-like): refern... | the_stack_v2_python_sparse | src/veoibd_synapse/cli/syncdb.py | Sage-Bionetworks/veoibd-synapse-data-manager | train | 0 |
d603ab78096a1feef099faa888d181caaa7b1781 | [
"response = self.testapp.get(feconf.LEARN_GALLERY_URL)\nself.assertEqual(response.status_int, 200)\nresponse.mustcontain('Gallery', 'Categories', no=[CAN_EDIT_STR, CAN_CLONE_STR, 'Create New Exploration'])\nself.assertRegexpMatches(response.body, 'class=\"active\">\\\\s+<a href=\"/learn\">Learn')",
"exp_services.... | <|body_start_0|>
response = self.testapp.get(feconf.LEARN_GALLERY_URL)
self.assertEqual(response.status_int, 200)
response.mustcontain('Gallery', 'Categories', no=[CAN_EDIT_STR, CAN_CLONE_STR, 'Create New Exploration'])
self.assertRegexpMatches(response.body, 'class="active">\\s+<a href=... | LearnGalleryTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearnGalleryTest:
def test_learn_gallery_page(self):
"""Test access to the learners' gallery page."""
<|body_0|>
def test_learn_gallery_handler(self):
"""Test access to the learners' gallery data handler."""
<|body_1|>
def test_login_message(self):
... | stack_v2_sparse_classes_36k_train_026520 | 23,453 | permissive | [
{
"docstring": "Test access to the learners' gallery page.",
"name": "test_learn_gallery_page",
"signature": "def test_learn_gallery_page(self)"
},
{
"docstring": "Test access to the learners' gallery data handler.",
"name": "test_learn_gallery_handler",
"signature": "def test_learn_gall... | 4 | stack_v2_sparse_classes_30k_train_006211 | Implement the Python class `LearnGalleryTest` described below.
Class description:
Implement the LearnGalleryTest class.
Method signatures and docstrings:
- def test_learn_gallery_page(self): Test access to the learners' gallery page.
- def test_learn_gallery_handler(self): Test access to the learners' gallery data ha... | Implement the Python class `LearnGalleryTest` described below.
Class description:
Implement the LearnGalleryTest class.
Method signatures and docstrings:
- def test_learn_gallery_page(self): Test access to the learners' gallery page.
- def test_learn_gallery_handler(self): Test access to the learners' gallery data ha... | aead304c95a282c9ca8035bc25c4794864d07578 | <|skeleton|>
class LearnGalleryTest:
def test_learn_gallery_page(self):
"""Test access to the learners' gallery page."""
<|body_0|>
def test_learn_gallery_handler(self):
"""Test access to the learners' gallery data handler."""
<|body_1|>
def test_login_message(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LearnGalleryTest:
def test_learn_gallery_page(self):
"""Test access to the learners' gallery page."""
response = self.testapp.get(feconf.LEARN_GALLERY_URL)
self.assertEqual(response.status_int, 200)
response.mustcontain('Gallery', 'Categories', no=[CAN_EDIT_STR, CAN_CLONE_STR, ... | the_stack_v2_python_sparse | core/controllers/galleries_test.py | aldeka/oppia | train | 3 | |
b6b5cf6bbb49711013c081c2904e7d8b0b3ca705 | [
"id = self.request.get('id', '')\ndivision = self.request.get('division', '')\nage_bracket = self.request.get('age_bracket', '')\ntry:\n enum_division = scores_messages.Division(division)\n enum_age_bracket = scores_messages.AgeBracket(age_bracket)\nexcept TypeError as e:\n logging.error('Could not parse p... | <|body_start_0|>
id = self.request.get('id', '')
division = self.request.get('division', '')
age_bracket = self.request.get('age_bracket', '')
try:
enum_division = scores_messages.Division(division)
enum_age_bracket = scores_messages.AgeBracket(age_bracket)
... | Handler for /tasks/sr/crawl_team. | TeamHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamHandler:
"""Handler for /tasks/sr/crawl_team."""
def get(self):
"""Loads the team page and crawls it."""
<|body_0|>
def _PossiblyAddTeamLookup(self, team_id, tourney_id):
"""Add the mapping between tourney ID and full team ID if needed. Args: team_id: ID for ... | stack_v2_sparse_classes_36k_train_026521 | 15,774 | permissive | [
{
"docstring": "Loads the team page and crawls it.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Add the mapping between tourney ID and full team ID if needed. Args: team_id: ID for team page with all games. tourney_id: ID for tournament-specific team page.",
"name": "_Pos... | 4 | stack_v2_sparse_classes_30k_train_020538 | Implement the Python class `TeamHandler` described below.
Class description:
Handler for /tasks/sr/crawl_team.
Method signatures and docstrings:
- def get(self): Loads the team page and crawls it.
- def _PossiblyAddTeamLookup(self, team_id, tourney_id): Add the mapping between tourney ID and full team ID if needed. A... | Implement the Python class `TeamHandler` described below.
Class description:
Handler for /tasks/sr/crawl_team.
Method signatures and docstrings:
- def get(self): Loads the team page and crawls it.
- def _PossiblyAddTeamLookup(self, team_id, tourney_id): Add the mapping between tourney ID and full team ID if needed. A... | 58197798a0a3a4fbcd54ffa0a2fab2e865985bfd | <|skeleton|>
class TeamHandler:
"""Handler for /tasks/sr/crawl_team."""
def get(self):
"""Loads the team page and crawls it."""
<|body_0|>
def _PossiblyAddTeamLookup(self, team_id, tourney_id):
"""Add the mapping between tourney ID and full team ID if needed. Args: team_id: ID for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamHandler:
"""Handler for /tasks/sr/crawl_team."""
def get(self):
"""Loads the team page and crawls it."""
id = self.request.get('id', '')
division = self.request.get('division', '')
age_bracket = self.request.get('age_bracket', '')
try:
enum_division... | the_stack_v2_python_sparse | score_reporter_handler.py | martincochran/score-minion | train | 0 |
21639194887df2f98431e86357f386c05261a0dc | [
"data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.add_dataStage02PhysiologySimulatedData(data.data)\ndata.clear_data()",
"data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.update_dataStage02PhysiologySimulatedData(data.data)\ndata.clear_data()"
] | <|body_start_0|>
data = base_importData()
data.read_csv(filename)
data.format_data()
self.add_dataStage02PhysiologySimulatedData(data.data)
data.clear_data()
<|end_body_0|>
<|body_start_1|>
data = base_importData()
data.read_csv(filename)
data.format_data... | stage02_physiology_simulatedData_io | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stage02_physiology_simulatedData_io:
def import_dataStage02PhysiologySimulatedData_add(self, filename):
"""table adds"""
<|body_0|>
def import_dataStage02PhysiologySimulatedData_update(self, filename):
"""table adds"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_026522 | 1,037 | permissive | [
{
"docstring": "table adds",
"name": "import_dataStage02PhysiologySimulatedData_add",
"signature": "def import_dataStage02PhysiologySimulatedData_add(self, filename)"
},
{
"docstring": "table adds",
"name": "import_dataStage02PhysiologySimulatedData_update",
"signature": "def import_data... | 2 | stack_v2_sparse_classes_30k_train_018417 | Implement the Python class `stage02_physiology_simulatedData_io` described below.
Class description:
Implement the stage02_physiology_simulatedData_io class.
Method signatures and docstrings:
- def import_dataStage02PhysiologySimulatedData_add(self, filename): table adds
- def import_dataStage02PhysiologySimulatedDat... | Implement the Python class `stage02_physiology_simulatedData_io` described below.
Class description:
Implement the stage02_physiology_simulatedData_io class.
Method signatures and docstrings:
- def import_dataStage02PhysiologySimulatedData_add(self, filename): table adds
- def import_dataStage02PhysiologySimulatedDat... | 65635495c4fb7cc98f5c6629e495850e908ea858 | <|skeleton|>
class stage02_physiology_simulatedData_io:
def import_dataStage02PhysiologySimulatedData_add(self, filename):
"""table adds"""
<|body_0|>
def import_dataStage02PhysiologySimulatedData_update(self, filename):
"""table adds"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stage02_physiology_simulatedData_io:
def import_dataStage02PhysiologySimulatedData_add(self, filename):
"""table adds"""
data = base_importData()
data.read_csv(filename)
data.format_data()
self.add_dataStage02PhysiologySimulatedData(data.data)
data.clear_data()
... | the_stack_v2_python_sparse | SBaaS_COBRA/stage02_physiology_simulatedData_io.py | dmccloskey/SBaaS_COBRA | train | 0 | |
a80d9e4f7269b1a815086a5a70346805f02f1b54 | [
"params = {att: val for att, val in params.items() if att not in ('self', 'args', 'kwargs')}\nfor att, val in params.items():\n setattr(self, att, val)",
"params = {k: v for k, v in self.__dict__.items() if k[0] != '_'}\nparams_path = os.path.join(exp_dir, 'experiment.json')\nos.makedirs(exp_dir, exist_ok=True... | <|body_start_0|>
params = {att: val for att, val in params.items() if att not in ('self', 'args', 'kwargs')}
for att, val in params.items():
setattr(self, att, val)
<|end_body_0|>
<|body_start_1|>
params = {k: v for k, v in self.__dict__.items() if k[0] != '_'}
params_path =... | Base experiment class. | BaseExperiment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseExperiment:
"""Base experiment class."""
def init_params(self, params):
"""Adds params as object attributes."""
<|body_0|>
def save_params(self, exp_dir):
"""Saves params in experiment.json"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
par... | stack_v2_sparse_classes_36k_train_026523 | 723 | no_license | [
{
"docstring": "Adds params as object attributes.",
"name": "init_params",
"signature": "def init_params(self, params)"
},
{
"docstring": "Saves params in experiment.json",
"name": "save_params",
"signature": "def save_params(self, exp_dir)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010573 | Implement the Python class `BaseExperiment` described below.
Class description:
Base experiment class.
Method signatures and docstrings:
- def init_params(self, params): Adds params as object attributes.
- def save_params(self, exp_dir): Saves params in experiment.json | Implement the Python class `BaseExperiment` described below.
Class description:
Base experiment class.
Method signatures and docstrings:
- def init_params(self, params): Adds params as object attributes.
- def save_params(self, exp_dir): Saves params in experiment.json
<|skeleton|>
class BaseExperiment:
"""Base ... | fc5c19e7ad6e2dc8a6d4e48a15a1b31fcb5f4af3 | <|skeleton|>
class BaseExperiment:
"""Base experiment class."""
def init_params(self, params):
"""Adds params as object attributes."""
<|body_0|>
def save_params(self, exp_dir):
"""Saves params in experiment.json"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseExperiment:
"""Base experiment class."""
def init_params(self, params):
"""Adds params as object attributes."""
params = {att: val for att, val in params.items() if att not in ('self', 'args', 'kwargs')}
for att, val in params.items():
setattr(self, att, val)
... | the_stack_v2_python_sparse | common/experiment.py | richardtml/mtar | train | 2 |
868aeb86a4728152bf25df78e61a471f5fc7e9e2 | [
"link = urlresolvers.reverse('api_author_detail', args=[author.pk])\ninfo = {'first_name': author.first_name, 'last_name': author.last_name, 'link': link}\nif full:\n info['bio'] = author.bio\nreturn info",
"try:\n return Author(first_name=force_unicode(d['first_name']), last_name=force_unicode(d['last_name... | <|body_start_0|>
link = urlresolvers.reverse('api_author_detail', args=[author.pk])
info = {'first_name': author.first_name, 'last_name': author.last_name, 'link': link}
if full:
info['bio'] = author.bio
return info
<|end_body_0|>
<|body_start_1|>
try:
re... | Base class for all Author resources providing conversion between Author objects and simple flat dicts. | AuthorResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthorResource:
"""Base class for all Author resources providing conversion between Author objects and simple flat dicts."""
def format(self, author, full=False):
"""Convert from an Author object to a dict."""
<|body_0|>
def parse(self, d):
"""Convert from a dict... | stack_v2_sparse_classes_36k_train_026524 | 3,552 | no_license | [
{
"docstring": "Convert from an Author object to a dict.",
"name": "format",
"signature": "def format(self, author, full=False)"
},
{
"docstring": "Convert from a dict to an Author object.",
"name": "parse",
"signature": "def parse(self, d)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010719 | Implement the Python class `AuthorResource` described below.
Class description:
Base class for all Author resources providing conversion between Author objects and simple flat dicts.
Method signatures and docstrings:
- def format(self, author, full=False): Convert from an Author object to a dict.
- def parse(self, d)... | Implement the Python class `AuthorResource` described below.
Class description:
Base class for all Author resources providing conversion between Author objects and simple flat dicts.
Method signatures and docstrings:
- def format(self, author, full=False): Convert from an Author object to a dict.
- def parse(self, d)... | b522925af03235127b47b150ab264386ff10e2d1 | <|skeleton|>
class AuthorResource:
"""Base class for all Author resources providing conversion between Author objects and simple flat dicts."""
def format(self, author, full=False):
"""Convert from an Author object to a dict."""
<|body_0|>
def parse(self, d):
"""Convert from a dict... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthorResource:
"""Base class for all Author resources providing conversion between Author objects and simple flat dicts."""
def format(self, author, full=False):
"""Convert from an Author object to a dict."""
link = urlresolvers.reverse('api_author_detail', args=[author.pk])
info... | the_stack_v2_python_sparse | snippets/python/1740.py | canicue/TEMPLATE_DOJANGO | train | 0 |
1fb9d33b2b19d3d33c28edd7f09727cf938467c3 | [
"if not head or not head.next:\n return head\nret = head.next\nhead.next = self.swapPairs(head.next.next)\nret.next = head\nreturn ret",
"dummy, dummy.next = (self, head)\nwhile dummy.next and dummy.next.next:\n node1 = dummy.next\n node2 = dummy.next.next\n dummy.next, node1.next, node2.next = (node2... | <|body_start_0|>
if not head or not head.next:
return head
ret = head.next
head.next = self.swapPairs(head.next.next)
ret.next = head
return ret
<|end_body_0|>
<|body_start_1|>
dummy, dummy.next = (self, head)
while dummy.next and dummy.next.next:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""递归实现"""
<|body_0|>
def swapPairs_1(self, head: ListNode) -> ListNode:
"""迭代实现"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or not head.next:
return head
... | stack_v2_sparse_classes_36k_train_026525 | 844 | no_license | [
{
"docstring": "递归实现",
"name": "swapPairs",
"signature": "def swapPairs(self, head: ListNode) -> ListNode"
},
{
"docstring": "迭代实现",
"name": "swapPairs_1",
"signature": "def swapPairs_1(self, head: ListNode) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_003528 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head: ListNode) -> ListNode: 递归实现
- def swapPairs_1(self, head: ListNode) -> ListNode: 迭代实现 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head: ListNode) -> ListNode: 递归实现
- def swapPairs_1(self, head: ListNode) -> ListNode: 迭代实现
<|skeleton|>
class Solution:
def swapPairs(self, head: ListN... | 41d6d4c748a6543d1c4027badb17ffbb64b43f2d | <|skeleton|>
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""递归实现"""
<|body_0|>
def swapPairs_1(self, head: ListNode) -> ListNode:
"""迭代实现"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""递归实现"""
if not head or not head.next:
return head
ret = head.next
head.next = self.swapPairs(head.next.next)
ret.next = head
return ret
def swapPairs_1(self, head: ListNode) -> ListNo... | the_stack_v2_python_sparse | learn/24.py | xiaoqiangjava/python-algorithm | train | 0 | |
d8dcca9d54989dbf7c7e0a29b829a7746134e1fe | [
"threading.Thread.__init__(self, group=group, target=target, name=name, verbose=verbose)\nself.current_forks = []\nself.index = args[0]\nself.set_forks(args[1])\nself.has_eaten = 0",
"logging.debug('Thinking for a few seconds')\ntime.sleep(random.random())\nself.pick_up_forks()",
"if self.index == 0:\n self.... | <|body_start_0|>
threading.Thread.__init__(self, group=group, target=target, name=name, verbose=verbose)
self.current_forks = []
self.index = args[0]
self.set_forks(args[1])
self.has_eaten = 0
<|end_body_0|>
<|body_start_1|>
logging.debug('Thinking for a few seconds')
... | Philosopher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Philosopher:
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None):
"""Setup our philosopher."""
<|body_0|>
def run(self):
"""Main thread process where they are deep in thought."""
<|body_1|>
def set_forks(self, forks... | stack_v2_sparse_classes_36k_train_026526 | 3,062 | no_license | [
{
"docstring": "Setup our philosopher.",
"name": "__init__",
"signature": "def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None)"
},
{
"docstring": "Main thread process where they are deep in thought.",
"name": "run",
"signature": "def run(self)"
},... | 6 | null | Implement the Python class `Philosopher` described below.
Class description:
Implement the Philosopher class.
Method signatures and docstrings:
- def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): Setup our philosopher.
- def run(self): Main thread process where they are deep ... | Implement the Python class `Philosopher` described below.
Class description:
Implement the Philosopher class.
Method signatures and docstrings:
- def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): Setup our philosopher.
- def run(self): Main thread process where they are deep ... | 913964dff3fd2e37e1eab44896f70b5bb5bfffba | <|skeleton|>
class Philosopher:
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None):
"""Setup our philosopher."""
<|body_0|>
def run(self):
"""Main thread process where they are deep in thought."""
<|body_1|>
def set_forks(self, forks... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Philosopher:
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None):
"""Setup our philosopher."""
threading.Thread.__init__(self, group=group, target=target, name=name, verbose=verbose)
self.current_forks = []
self.index = args[0]
sel... | the_stack_v2_python_sparse | python/concurrency/problems/dining_philosophers/threading_solution.py | dansackett/learning-playground | train | 3 | |
683859b8ebbb5d83222e3e406b7333fa266a277e | [
"x = np.array([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], requires_grad=True)\ny = np.array(0.56, requires_grad=True)\n\ndef cost(weights):\n return fn.scatter_element_add(weights[0], [1, 2], weights[1] ** 2)\nres = cost([x, y])\nassert isinstance(res, np.ndarray)\nassert fn.allclose(res, onp.array([[1.0, 1.0, 1.0], [1.... | <|body_start_0|>
x = np.array([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], requires_grad=True)
y = np.array(0.56, requires_grad=True)
def cost(weights):
return fn.scatter_element_add(weights[0], [1, 2], weights[1] ** 2)
res = cost([x, y])
assert isinstance(res, np.ndarray)
... | Tests for the scatter_element_add function | TestScatterElementAdd | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestScatterElementAdd:
"""Tests for the scatter_element_add function"""
def test_array(self):
"""Test that a NumPy array is differentiable when using scatter addition"""
<|body_0|>
def test_tensorflow(self):
"""Test that a TF tensor is differentiable when using s... | stack_v2_sparse_classes_36k_train_026527 | 47,600 | permissive | [
{
"docstring": "Test that a NumPy array is differentiable when using scatter addition",
"name": "test_array",
"signature": "def test_array(self)"
},
{
"docstring": "Test that a TF tensor is differentiable when using scatter addition",
"name": "test_tensorflow",
"signature": "def test_ten... | 4 | null | Implement the Python class `TestScatterElementAdd` described below.
Class description:
Tests for the scatter_element_add function
Method signatures and docstrings:
- def test_array(self): Test that a NumPy array is differentiable when using scatter addition
- def test_tensorflow(self): Test that a TF tensor is differ... | Implement the Python class `TestScatterElementAdd` described below.
Class description:
Tests for the scatter_element_add function
Method signatures and docstrings:
- def test_array(self): Test that a NumPy array is differentiable when using scatter addition
- def test_tensorflow(self): Test that a TF tensor is differ... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class TestScatterElementAdd:
"""Tests for the scatter_element_add function"""
def test_array(self):
"""Test that a NumPy array is differentiable when using scatter addition"""
<|body_0|>
def test_tensorflow(self):
"""Test that a TF tensor is differentiable when using s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestScatterElementAdd:
"""Tests for the scatter_element_add function"""
def test_array(self):
"""Test that a NumPy array is differentiable when using scatter addition"""
x = np.array([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], requires_grad=True)
y = np.array(0.56, requires_grad=True)
... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits_backup/pennylane/pennylane#1081/before/test_functions.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
3f3b7edd48c2133ca8c765295f66b72f84e28500 | [
"formatter = StructFileSupportedFormat.get_format_handler(fmt=file_format)\ntemp_directory = pathlib.Path(tempfile.mkdtemp())\ncls.add_future_clearing_path(path=temp_directory)\nfile_path = temp_directory / f'{key}.{file_format}'\nformatter.write(obj=obj, file_path=str(file_path))\nartifact = Artifact(key=key, src_... | <|body_start_0|>
formatter = StructFileSupportedFormat.get_format_handler(fmt=file_format)
temp_directory = pathlib.Path(tempfile.mkdtemp())
cls.add_future_clearing_path(path=temp_directory)
file_path = temp_directory / f'{key}.{file_format}'
formatter.write(obj=obj, file_path=st... | A base packager for builtin python dictionaries and lists as they share common artifact and file types. | _BuiltinCollectionPackager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _BuiltinCollectionPackager:
"""A base packager for builtin python dictionaries and lists as they share common artifact and file types."""
def pack_file(cls, obj: Union[dict, list], key: str, file_format: str=DEFAULT_STRUCT_FILE_FORMAT) -> Tuple[Artifact, dict]:
"""Pack a builtin coll... | stack_v2_sparse_classes_36k_train_026528 | 22,787 | permissive | [
{
"docstring": "Pack a builtin collection as a file by the given format. :param obj: The builtin collection to pack. :param key: The key to use for the artifact. :param file_format: The file format to save as. Default is json. :return: The packed artifact and instructions.",
"name": "pack_file",
"signat... | 2 | null | Implement the Python class `_BuiltinCollectionPackager` described below.
Class description:
A base packager for builtin python dictionaries and lists as they share common artifact and file types.
Method signatures and docstrings:
- def pack_file(cls, obj: Union[dict, list], key: str, file_format: str=DEFAULT_STRUCT_F... | Implement the Python class `_BuiltinCollectionPackager` described below.
Class description:
A base packager for builtin python dictionaries and lists as they share common artifact and file types.
Method signatures and docstrings:
- def pack_file(cls, obj: Union[dict, list], key: str, file_format: str=DEFAULT_STRUCT_F... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class _BuiltinCollectionPackager:
"""A base packager for builtin python dictionaries and lists as they share common artifact and file types."""
def pack_file(cls, obj: Union[dict, list], key: str, file_format: str=DEFAULT_STRUCT_FILE_FORMAT) -> Tuple[Artifact, dict]:
"""Pack a builtin coll... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _BuiltinCollectionPackager:
"""A base packager for builtin python dictionaries and lists as they share common artifact and file types."""
def pack_file(cls, obj: Union[dict, list], key: str, file_format: str=DEFAULT_STRUCT_FILE_FORMAT) -> Tuple[Artifact, dict]:
"""Pack a builtin collection as a f... | the_stack_v2_python_sparse | mlrun/package/packagers/python_standard_library_packagers.py | mlrun/mlrun | train | 1,093 |
536a28636200fbed323bea3982d11a5905130e77 | [
"if data is None:\n if n <= 0:\n raise ValueError('n must be a positive value')\n if p <= 0 or p >= 1:\n raise ValueError('p must be greater than 0 and less than 1')\n self.n = int(n)\n self.p = float(p)\nelse:\n if type(data) is not list:\n raise TypeError('data must be a list')... | <|body_start_0|>
if data is None:
if n <= 0:
raise ValueError('n must be a positive value')
if p <= 0 or p >= 1:
raise ValueError('p must be greater than 0 and less than 1')
self.n = int(n)
self.p = float(p)
else:
... | Class represents a binomial distribution | Binomial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Binomial:
"""Class represents a binomial distribution"""
def __init__(self, data=None, n=1, p=0.5):
"""Binomial distribution"""
<|body_0|>
def pmf(self, k):
"""Calculates value of PMF for given number k"""
<|body_1|>
def cdf(self, k):
"""Calc... | stack_v2_sparse_classes_36k_train_026529 | 1,713 | no_license | [
{
"docstring": "Binomial distribution",
"name": "__init__",
"signature": "def __init__(self, data=None, n=1, p=0.5)"
},
{
"docstring": "Calculates value of PMF for given number k",
"name": "pmf",
"signature": "def pmf(self, k)"
},
{
"docstring": "Calculates value CDF for given nu... | 3 | null | Implement the Python class `Binomial` described below.
Class description:
Class represents a binomial distribution
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Binomial distribution
- def pmf(self, k): Calculates value of PMF for given number k
- def cdf(self, k): Calculates value CD... | Implement the Python class `Binomial` described below.
Class description:
Class represents a binomial distribution
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Binomial distribution
- def pmf(self, k): Calculates value of PMF for given number k
- def cdf(self, k): Calculates value CD... | 4ac942126918c7acaa9ef88d18efe299b2f726fe | <|skeleton|>
class Binomial:
"""Class represents a binomial distribution"""
def __init__(self, data=None, n=1, p=0.5):
"""Binomial distribution"""
<|body_0|>
def pmf(self, k):
"""Calculates value of PMF for given number k"""
<|body_1|>
def cdf(self, k):
"""Calc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Binomial:
"""Class represents a binomial distribution"""
def __init__(self, data=None, n=1, p=0.5):
"""Binomial distribution"""
if data is None:
if n <= 0:
raise ValueError('n must be a positive value')
if p <= 0 or p >= 1:
raise Val... | the_stack_v2_python_sparse | math/0x03-probability/binomial.py | DracoMindz/holbertonschool-machine_learning | train | 2 |
8b5e8c7b4dd014523e41e88d52899ea7a1e01f59 | [
"from dials.util.options import ArgumentParser\nusage = 'dials.apply_mask models.expt input.mask=pixels.mask'\nself.parser = ArgumentParser(usage=usage, epilog=help_message, phil=phil_scope, read_experiments=True)",
"from dials.util import Sorry\nfrom dials.util.options import flatten_experiments\nparams, options... | <|body_start_0|>
from dials.util.options import ArgumentParser
usage = 'dials.apply_mask models.expt input.mask=pixels.mask'
self.parser = ArgumentParser(usage=usage, epilog=help_message, phil=phil_scope, read_experiments=True)
<|end_body_0|>
<|body_start_1|>
from dials.util import Sorr... | A class to encapsulate the script. | Script | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Script:
"""A class to encapsulate the script."""
def __init__(self):
"""Initialise the script."""
<|body_0|>
def run(self, args=None):
"""Run the script."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from dials.util.options import ArgumentPars... | stack_v2_sparse_classes_36k_train_026530 | 3,228 | permissive | [
{
"docstring": "Initialise the script.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Run the script.",
"name": "run",
"signature": "def run(self, args=None)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000830 | Implement the Python class `Script` described below.
Class description:
A class to encapsulate the script.
Method signatures and docstrings:
- def __init__(self): Initialise the script.
- def run(self, args=None): Run the script. | Implement the Python class `Script` described below.
Class description:
A class to encapsulate the script.
Method signatures and docstrings:
- def __init__(self): Initialise the script.
- def run(self, args=None): Run the script.
<|skeleton|>
class Script:
"""A class to encapsulate the script."""
def __init... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class Script:
"""A class to encapsulate the script."""
def __init__(self):
"""Initialise the script."""
<|body_0|>
def run(self, args=None):
"""Run the script."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Script:
"""A class to encapsulate the script."""
def __init__(self):
"""Initialise the script."""
from dials.util.options import ArgumentParser
usage = 'dials.apply_mask models.expt input.mask=pixels.mask'
self.parser = ArgumentParser(usage=usage, epilog=help_message, phil... | the_stack_v2_python_sparse | src/dials/command_line/apply_mask.py | dials/dials | train | 71 |
1355d8e5fb49031ac6ab52459aaaa445917f45dd | [
"self.medida = Medida.objects.get(nomenclatura='MED-1')\nself.target_url = reverse('medidas:borrar-medida', kwargs={'pk': self.medida.pk})\nsuper().setUp()",
"self.login()\nresponse = self.client.get(self.target_url)\nactual = response.resolver_match.func.__name__\nexpected = MedidaDeleteView.as_view().__name__\n... | <|body_start_0|>
self.medida = Medida.objects.get(nomenclatura='MED-1')
self.target_url = reverse('medidas:borrar-medida', kwargs={'pk': self.medida.pk})
super().setUp()
<|end_body_0|>
<|body_start_1|>
self.login()
response = self.client.get(self.target_url)
actual = res... | Pruebas para la vista de eliminacion de medidas | MedidaDeleteViewTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedidaDeleteViewTestCase:
"""Pruebas para la vista de eliminacion de medidas"""
def setUp(self):
"""Ambiente para el suite de pruebas"""
<|body_0|>
def test_url_view_correspondence(self):
"""Prueba que el url sea manejado por la vista MedidaDeleteView"""
... | stack_v2_sparse_classes_36k_train_026531 | 7,967 | no_license | [
{
"docstring": "Ambiente para el suite de pruebas",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Prueba que el url sea manejado por la vista MedidaDeleteView",
"name": "test_url_view_correspondence",
"signature": "def test_url_view_correspondence(self)"
},
{
... | 6 | null | Implement the Python class `MedidaDeleteViewTestCase` described below.
Class description:
Pruebas para la vista de eliminacion de medidas
Method signatures and docstrings:
- def setUp(self): Ambiente para el suite de pruebas
- def test_url_view_correspondence(self): Prueba que el url sea manejado por la vista MedidaD... | Implement the Python class `MedidaDeleteViewTestCase` described below.
Class description:
Pruebas para la vista de eliminacion de medidas
Method signatures and docstrings:
- def setUp(self): Ambiente para el suite de pruebas
- def test_url_view_correspondence(self): Prueba que el url sea manejado por la vista MedidaD... | 64a8f8350f9092126864f3676f27dc690ed2a5f8 | <|skeleton|>
class MedidaDeleteViewTestCase:
"""Pruebas para la vista de eliminacion de medidas"""
def setUp(self):
"""Ambiente para el suite de pruebas"""
<|body_0|>
def test_url_view_correspondence(self):
"""Prueba que el url sea manejado por la vista MedidaDeleteView"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedidaDeleteViewTestCase:
"""Pruebas para la vista de eliminacion de medidas"""
def setUp(self):
"""Ambiente para el suite de pruebas"""
self.medida = Medida.objects.get(nomenclatura='MED-1')
self.target_url = reverse('medidas:borrar-medida', kwargs={'pk': self.medida.pk})
... | the_stack_v2_python_sparse | medidas/test_views.py | german1608/EIA_CI4712 | train | 1 |
de638576fc05c91d81ca96ecb29b62478482b64c | [
"if logreg_model_file is None:\n logreg_model_file = resource_filename(__name__, 'scoring_models/logistic_regression_all.yml')\nlogreg_model_serialized = read_config_file(logreg_model_file)\nself.classifier, self.feature_names = logreg_classifier_from_dict(logreg_model_serialized)\nself.min_n_eff_over_l = min_n_... | <|body_start_0|>
if logreg_model_file is None:
logreg_model_file = resource_filename(__name__, 'scoring_models/logistic_regression_all.yml')
logreg_model_serialized = read_config_file(logreg_model_file)
self.classifier, self.feature_names = logreg_classifier_from_dict(logreg_model_se... | Rescore ECs based on logistic regression model fitted to large set of runs | LogisticRegressionScorer | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogisticRegressionScorer:
"""Rescore ECs based on logistic regression model fitted to large set of runs"""
def __init__(self, logreg_model_file=None, min_n_eff_over_l=0.375):
"""Create new logistic regression-based EC rescorer Parameters ---------- logreg_model_file : str, optional (... | stack_v2_sparse_classes_36k_train_026532 | 32,808 | permissive | [
{
"docstring": "Create new logistic regression-based EC rescorer Parameters ---------- logreg_model_file : str, optional (default: None) Specify path to yml file with logistic regression model parameters; if None, will use default model included with package (evcouplings/couplings/scoring_models/logistic_regres... | 3 | stack_v2_sparse_classes_30k_val_000072 | Implement the Python class `LogisticRegressionScorer` described below.
Class description:
Rescore ECs based on logistic regression model fitted to large set of runs
Method signatures and docstrings:
- def __init__(self, logreg_model_file=None, min_n_eff_over_l=0.375): Create new logistic regression-based EC rescorer ... | Implement the Python class `LogisticRegressionScorer` described below.
Class description:
Rescore ECs based on logistic regression model fitted to large set of runs
Method signatures and docstrings:
- def __init__(self, logreg_model_file=None, min_n_eff_over_l=0.375): Create new logistic regression-based EC rescorer ... | af27842c5fc72c291831261c9a19849a3e313efd | <|skeleton|>
class LogisticRegressionScorer:
"""Rescore ECs based on logistic regression model fitted to large set of runs"""
def __init__(self, logreg_model_file=None, min_n_eff_over_l=0.375):
"""Create new logistic regression-based EC rescorer Parameters ---------- logreg_model_file : str, optional (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogisticRegressionScorer:
"""Rescore ECs based on logistic regression model fitted to large set of runs"""
def __init__(self, logreg_model_file=None, min_n_eff_over_l=0.375):
"""Create new logistic regression-based EC rescorer Parameters ---------- logreg_model_file : str, optional (default: None... | the_stack_v2_python_sparse | evcouplings/couplings/pairs.py | debbiemarkslab/EVcouplings | train | 184 |
d71d1a3f9133cdbf417c63ac6676c9155b9880d4 | [
"assert lower_mileage_bound < upper_mileage_bound\nself.lower_mileage_bound = lower_mileage_bound\nself.upper_mileage_bound = upper_mileage_bound\nself.level_of_service = level_of_service\nself.base_rate = base_rate\nself.revenue_per_mile = revenue_per_mile",
"if not self.lower_mileage_bound <= miles <= self.uppe... | <|body_start_0|>
assert lower_mileage_bound < upper_mileage_bound
self.lower_mileage_bound = lower_mileage_bound
self.upper_mileage_bound = upper_mileage_bound
self.level_of_service = level_of_service
self.base_rate = base_rate
self.revenue_per_mile = revenue_per_mile
<|e... | This class represents the revenue details associated with a travel distance in miles and the level of service. It stores a lower travel distance bound, upper travel distance bound, a base rate, a rate per mile, and a specific level of service. It extends from the SQLAlchemy Base class as the revenue rates are polled fr... | RevenueRate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RevenueRate:
"""This class represents the revenue details associated with a travel distance in miles and the level of service. It stores a lower travel distance bound, upper travel distance bound, a base rate, a rate per mile, and a specific level of service. It extends from the SQLAlchemy Base c... | stack_v2_sparse_classes_36k_train_026533 | 3,891 | permissive | [
{
"docstring": "Inititalize a RevenueRate object with the neccessary details to compute revenue earned :param lower_mileage_bound: Lower bound (inclusive) for with the rate applies :param upper_mileage_bound: Upper bound (inclusive) for which the rate applies :param level_of_service: The level of service for wh... | 2 | null | Implement the Python class `RevenueRate` described below.
Class description:
This class represents the revenue details associated with a travel distance in miles and the level of service. It stores a lower travel distance bound, upper travel distance bound, a base rate, a rate per mile, and a specific level of service... | Implement the Python class `RevenueRate` described below.
Class description:
This class represents the revenue details associated with a travel distance in miles and the level of service. It stores a lower travel distance bound, upper travel distance bound, a base rate, a rate per mile, and a specific level of service... | e4eaf69d905631034949b18433bc70e4a08f0e58 | <|skeleton|>
class RevenueRate:
"""This class represents the revenue details associated with a travel distance in miles and the level of service. It stores a lower travel distance bound, upper travel distance bound, a base rate, a rate per mile, and a specific level of service. It extends from the SQLAlchemy Base c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RevenueRate:
"""This class represents the revenue details associated with a travel distance in miles and the level of service. It stores a lower travel distance bound, upper travel distance bound, a base rate, a rate per mile, and a specific level of service. It extends from the SQLAlchemy Base class as the r... | the_stack_v2_python_sparse | avicena/models/RevenueRate.py | ribsthakkar/RiderPickup | train | 2 |
748fd9fbff8d2bffaa672eeb189d44c734e754ef | [
"if self.tenancy_id.is_landlord_rent:\n account_jrnl_obj = self.env['account.journal'].search([('type', '=', 'purchase')], limit=1)\n inv_lines_values = {'name': 'Rent Cost for' + self.tenancy_id.name, 'quantity': 1, 'price_unit': self.amount or 0.0, 'account_id': self.tenancy_id.property_id.account_depreciat... | <|body_start_0|>
if self.tenancy_id.is_landlord_rent:
account_jrnl_obj = self.env['account.journal'].search([('type', '=', 'purchase')], limit=1)
inv_lines_values = {'name': 'Rent Cost for' + self.tenancy_id.name, 'quantity': 1, 'price_unit': self.amount or 0.0, 'account_id': self.tenanc... | TenancyRentSchedule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenancyRentSchedule:
def create_landlord_invoice(self):
"""Create invoice for Rent Schedule. ------------------------------------ @param self: The object pointer"""
<|body_0|>
def open_landlord_invoice(self):
"""Description: This method is used to open Invoice which ... | stack_v2_sparse_classes_36k_train_026534 | 18,494 | no_license | [
{
"docstring": "Create invoice for Rent Schedule. ------------------------------------ @param self: The object pointer",
"name": "create_landlord_invoice",
"signature": "def create_landlord_invoice(self)"
},
{
"docstring": "Description: This method is used to open Invoice which is created. Decor... | 2 | stack_v2_sparse_classes_30k_train_003165 | Implement the Python class `TenancyRentSchedule` described below.
Class description:
Implement the TenancyRentSchedule class.
Method signatures and docstrings:
- def create_landlord_invoice(self): Create invoice for Rent Schedule. ------------------------------------ @param self: The object pointer
- def open_landlor... | Implement the Python class `TenancyRentSchedule` described below.
Class description:
Implement the TenancyRentSchedule class.
Method signatures and docstrings:
- def create_landlord_invoice(self): Create invoice for Rent Schedule. ------------------------------------ @param self: The object pointer
- def open_landlor... | 163136f382faa8607db8fb6cda42a5ba07c4076b | <|skeleton|>
class TenancyRentSchedule:
def create_landlord_invoice(self):
"""Create invoice for Rent Schedule. ------------------------------------ @param self: The object pointer"""
<|body_0|>
def open_landlord_invoice(self):
"""Description: This method is used to open Invoice which ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenancyRentSchedule:
def create_landlord_invoice(self):
"""Create invoice for Rent Schedule. ------------------------------------ @param self: The object pointer"""
if self.tenancy_id.is_landlord_rent:
account_jrnl_obj = self.env['account.journal'].search([('type', '=', 'purchase')... | the_stack_v2_python_sparse | property_landlord_management_ee/models/account_analytic.py | maarejsys/Roya | train | 0 | |
4a9cf49521b1d5efb99f675eb5a7431c06f342fc | [
"super().__init__()\nself.dropout = nn.Dropout(p=dropout)\nself.layers = numlayers\nself.dirs = 2 if bidirectional else 1\nself.hsz = hiddensize\nif input_dropout > 0 and unknown_idx is None:\n raise RuntimeError('input_dropout > 0 but unknown_idx not set')\nself.input_dropout = UnknownDropout(unknown_idx, input... | <|body_start_0|>
super().__init__()
self.dropout = nn.Dropout(p=dropout)
self.layers = numlayers
self.dirs = 2 if bidirectional else 1
self.hsz = hiddensize
if input_dropout > 0 and unknown_idx is None:
raise RuntimeError('input_dropout > 0 but unknown_idx not... | RNN Encoder. | RNNEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""RNN Encoder."""
def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unknown_idx=None, sparse=False):
"""Initialize recurrent encode... | stack_v2_sparse_classes_36k_train_026535 | 24,820 | permissive | [
{
"docstring": "Initialize recurrent encoder.",
"name": "__init__",
"signature": "def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unknown_idx=None, sparse=False)"... | 2 | null | Implement the Python class `RNNEncoder` described below.
Class description:
RNN Encoder.
Method signatures and docstrings:
- def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unk... | Implement the Python class `RNNEncoder` described below.
Class description:
RNN Encoder.
Method signatures and docstrings:
- def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unk... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class RNNEncoder:
"""RNN Encoder."""
def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unknown_idx=None, sparse=False):
"""Initialize recurrent encode... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNEncoder:
"""RNN Encoder."""
def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unknown_idx=None, sparse=False):
"""Initialize recurrent encoder."""
... | the_stack_v2_python_sparse | parlai/agents/seq2seq/modules.py | facebookresearch/ParlAI | train | 10,943 |
42cd333e1a576c41e07004f92f345bc1aa7a8fa4 | [
"super(AwsDiskSpec, cls)._ApplyFlags(config_values, flag_values)\nif flag_values['aws_provisioned_iops'].present:\n config_values['iops'] = flag_values.aws_provisioned_iops\nif flag_values['aws_provisioned_throughput'].present:\n config_values['throughput'] = flag_values.aws_provisioned_throughput",
"result... | <|body_start_0|>
super(AwsDiskSpec, cls)._ApplyFlags(config_values, flag_values)
if flag_values['aws_provisioned_iops'].present:
config_values['iops'] = flag_values.aws_provisioned_iops
if flag_values['aws_provisioned_throughput'].present:
config_values['throughput'] = fl... | Object holding the information needed to create an AwsDisk. Attributes: iops: None or int. IOPS for Provisioned IOPS (SSD) volumes in AWS. throughput: None or int. Throughput for (SSD) volumes in AWS. | AwsDiskSpec | [
"Classpath-exception-2.0",
"BSD-3-Clause",
"AGPL-3.0-only",
"MIT",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AwsDiskSpec:
"""Object holding the information needed to create an AwsDisk. Attributes: iops: None or int. IOPS for Provisioned IOPS (SSD) volumes in AWS. throughput: None or int. Throughput for (SSD) volumes in AWS."""
def _ApplyFlags(cls, config_values, flag_values):
"""Modifies co... | stack_v2_sparse_classes_36k_train_026536 | 17,465 | permissive | [
{
"docstring": "Modifies config options based on runtime flag values. Can be overridden by derived classes to add support for specific flags. Args: config_values: dict mapping config option names to provided values. May be modified by this function. flag_values: flags.FlagValues. Runtime flags that may override... | 2 | stack_v2_sparse_classes_30k_train_002070 | Implement the Python class `AwsDiskSpec` described below.
Class description:
Object holding the information needed to create an AwsDisk. Attributes: iops: None or int. IOPS for Provisioned IOPS (SSD) volumes in AWS. throughput: None or int. Throughput for (SSD) volumes in AWS.
Method signatures and docstrings:
- def ... | Implement the Python class `AwsDiskSpec` described below.
Class description:
Object holding the information needed to create an AwsDisk. Attributes: iops: None or int. IOPS for Provisioned IOPS (SSD) volumes in AWS. throughput: None or int. Throughput for (SSD) volumes in AWS.
Method signatures and docstrings:
- def ... | d0699f32998898757b036704fba39e5471641f01 | <|skeleton|>
class AwsDiskSpec:
"""Object holding the information needed to create an AwsDisk. Attributes: iops: None or int. IOPS for Provisioned IOPS (SSD) volumes in AWS. throughput: None or int. Throughput for (SSD) volumes in AWS."""
def _ApplyFlags(cls, config_values, flag_values):
"""Modifies co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AwsDiskSpec:
"""Object holding the information needed to create an AwsDisk. Attributes: iops: None or int. IOPS for Provisioned IOPS (SSD) volumes in AWS. throughput: None or int. Throughput for (SSD) volumes in AWS."""
def _ApplyFlags(cls, config_values, flag_values):
"""Modifies config options ... | the_stack_v2_python_sparse | perfkitbenchmarker/providers/aws/aws_disk.py | GoogleCloudPlatform/PerfKitBenchmarker | train | 1,923 |
a9035bad76c1e9068b587c89e388b6f6cc41c029 | [
"if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.ON]:\n tango.Except.throw_exception(f'Disable() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke Disable command on SdpMasterLeafNode.', 'SdpMasterLeafNode.Disable() ', tango.ErrSeverity.ERR)\nreturn True"... | <|body_start_0|>
if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.ON]:
tango.Except.throw_exception(f'Disable() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke Disable command on SdpMasterLeafNode.', 'SdpMasterLeafNode.Disable() ', tango.Err... | A class for SDP master's Disable() command. Disable command is inherited from BaseCommand. Sets the State to Disable. | Disable | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Disable:
"""A class for SDP master's Disable() command. Disable command is inherited from BaseCommand. Sets the State to Disable."""
def check_allowed(self):
"""Check Whether this command is allowed to be run in current device state. :return: True if this command is allowed to be run... | stack_v2_sparse_classes_36k_train_026537 | 3,959 | permissive | [
{
"docstring": "Check Whether this command is allowed to be run in current device state. :return: True if this command is allowed to be run in current device state. :rtype: boolean :raises: DevFailed if this command is not allowed to be run in current device state.",
"name": "check_allowed",
"signature"... | 3 | stack_v2_sparse_classes_30k_val_000231 | Implement the Python class `Disable` described below.
Class description:
A class for SDP master's Disable() command. Disable command is inherited from BaseCommand. Sets the State to Disable.
Method signatures and docstrings:
- def check_allowed(self): Check Whether this command is allowed to be run in current device ... | Implement the Python class `Disable` described below.
Class description:
A class for SDP master's Disable() command. Disable command is inherited from BaseCommand. Sets the State to Disable.
Method signatures and docstrings:
- def check_allowed(self): Check Whether this command is allowed to be run in current device ... | 7ee65a9c8dada9b28893144b372a398bd0646195 | <|skeleton|>
class Disable:
"""A class for SDP master's Disable() command. Disable command is inherited from BaseCommand. Sets the State to Disable."""
def check_allowed(self):
"""Check Whether this command is allowed to be run in current device state. :return: True if this command is allowed to be run... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Disable:
"""A class for SDP master's Disable() command. Disable command is inherited from BaseCommand. Sets the State to Disable."""
def check_allowed(self):
"""Check Whether this command is allowed to be run in current device state. :return: True if this command is allowed to be run in current d... | the_stack_v2_python_sparse | temp_src/ska_tmc_sdpmasterleafnode_mid/disable_command.py | ska-telescope/tmc-prototype | train | 4 |
43a7c566183b79aec6abb11b1be4e2f052d246d9 | [
"super().make()\nif self.options.make_CL == True:\n self.make_charge_line()",
"name = 'Charge_Line'\np = self.p\ncl_arm = draw.box(0, 0, -p.cl_width, p.cl_length)\ncl_cpw = draw.box(0, 0, -8 * p.cl_width, p.cl_width)\ncl_metal = draw.cascaded_union([cl_arm, cl_cpw])\ncl_etcher = draw.buffer(cl_metal, p.cl_gap)... | <|body_start_0|>
super().make()
if self.options.make_CL == True:
self.make_charge_line()
<|end_body_0|>
<|body_start_1|>
name = 'Charge_Line'
p = self.p
cl_arm = draw.box(0, 0, -p.cl_width, p.cl_length)
cl_cpw = draw.box(0, 0, -8 * p.cl_width, p.cl_width)
... | The base `TransmonPocketCL` class. Inherits `TransmonPocket` class. Create a standard pocket transmon qubit for a ground plane, with two pads connected by a junction (see drawing below). Connector lines can be added using the `connection_pads` dictionary. Each connector line has a name and a list of default properties.... | TransmonPocketCL | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransmonPocketCL:
"""The base `TransmonPocketCL` class. Inherits `TransmonPocket` class. Create a standard pocket transmon qubit for a ground plane, with two pads connected by a junction (see drawing below). Connector lines can be added using the `connection_pads` dictionary. Each connector line ... | stack_v2_sparse_classes_36k_train_026538 | 8,366 | permissive | [
{
"docstring": "Define the way the options are turned into QGeometry.",
"name": "make",
"signature": "def make(self)"
},
{
"docstring": "Creates the charge line if the user has charge line option to TRUE.",
"name": "make_charge_line",
"signature": "def make_charge_line(self)"
}
] | 2 | null | Implement the Python class `TransmonPocketCL` described below.
Class description:
The base `TransmonPocketCL` class. Inherits `TransmonPocket` class. Create a standard pocket transmon qubit for a ground plane, with two pads connected by a junction (see drawing below). Connector lines can be added using the `connection... | Implement the Python class `TransmonPocketCL` described below.
Class description:
The base `TransmonPocketCL` class. Inherits `TransmonPocket` class. Create a standard pocket transmon qubit for a ground plane, with two pads connected by a junction (see drawing below). Connector lines can be added using the `connection... | 24c58d192a576f25acb8d4208a92a317d0ebb2fd | <|skeleton|>
class TransmonPocketCL:
"""The base `TransmonPocketCL` class. Inherits `TransmonPocket` class. Create a standard pocket transmon qubit for a ground plane, with two pads connected by a junction (see drawing below). Connector lines can be added using the `connection_pads` dictionary. Each connector line ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransmonPocketCL:
"""The base `TransmonPocketCL` class. Inherits `TransmonPocket` class. Create a standard pocket transmon qubit for a ground plane, with two pads connected by a junction (see drawing below). Connector lines can be added using the `connection_pads` dictionary. Each connector line has a name an... | the_stack_v2_python_sparse | qiskit_metal/qlibrary/qubits/transmon_pocket_cl.py | jessica-angel7/qiskit-metal | train | 1 |
2cf32106e665979ae9197b2774982e66165629d2 | [
"stack = [-1]\nmax_area = 0\nfor i, curr_height in enumerate(heights):\n if stack[-1] == -1 or curr_height >= heights[stack[-1]]:\n stack.append(i)\n elif curr_height < heights[stack[-1]]:\n while stack[-1] != -1 and heights[stack[-1]] >= curr_height:\n curr_area = (i - stack[-2] - 1)... | <|body_start_0|>
stack = [-1]
max_area = 0
for i, curr_height in enumerate(heights):
if stack[-1] == -1 or curr_height >= heights[stack[-1]]:
stack.append(i)
elif curr_height < heights[stack[-1]]:
while stack[-1] != -1 and heights[stack[-1]... | SolutionStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionStack:
def largest_area(self, heights):
"""Stack based algorithm. Time complexity: O(n). Space complexity: O(n), n is len(heights)."""
<|body_0|>
def largest_area(self, heights):
"""Optimized version of stack based algorithm. Time complexity: O(n). Space comp... | stack_v2_sparse_classes_36k_train_026539 | 8,024 | no_license | [
{
"docstring": "Stack based algorithm. Time complexity: O(n). Space complexity: O(n), n is len(heights).",
"name": "largest_area",
"signature": "def largest_area(self, heights)"
},
{
"docstring": "Optimized version of stack based algorithm. Time complexity: O(n). Space complexity: O(n), n is len... | 2 | stack_v2_sparse_classes_30k_train_006296 | Implement the Python class `SolutionStack` described below.
Class description:
Implement the SolutionStack class.
Method signatures and docstrings:
- def largest_area(self, heights): Stack based algorithm. Time complexity: O(n). Space complexity: O(n), n is len(heights).
- def largest_area(self, heights): Optimized v... | Implement the Python class `SolutionStack` described below.
Class description:
Implement the SolutionStack class.
Method signatures and docstrings:
- def largest_area(self, heights): Stack based algorithm. Time complexity: O(n). Space complexity: O(n), n is len(heights).
- def largest_area(self, heights): Optimized v... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class SolutionStack:
def largest_area(self, heights):
"""Stack based algorithm. Time complexity: O(n). Space complexity: O(n), n is len(heights)."""
<|body_0|>
def largest_area(self, heights):
"""Optimized version of stack based algorithm. Time complexity: O(n). Space comp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolutionStack:
def largest_area(self, heights):
"""Stack based algorithm. Time complexity: O(n). Space complexity: O(n), n is len(heights)."""
stack = [-1]
max_area = 0
for i, curr_height in enumerate(heights):
if stack[-1] == -1 or curr_height >= heights[stack[-1]]... | the_stack_v2_python_sparse | Stack/largest_rectangle_histogram.py | vladn90/Algorithms | train | 0 | |
5cf4d6b1215a27cb9aa981eadf4357749960b2cc | [
"tortoise, hare = (head, head)\nwhile hare and hare.next:\n tortoise = tortoise.next\n hare = hare.next.next\n if tortoise == hare:\n return True\nreturn False",
"tortoise, hare = (head, head)\nwhile True:\n if not hare or not hare.next:\n return None\n tortoise = tortoise.next\n h... | <|body_start_0|>
tortoise, hare = (head, head)
while hare and hare.next:
tortoise = tortoise.next
hare = hare.next.next
if tortoise == hare:
return True
return False
<|end_body_0|>
<|body_start_1|>
tortoise, hare = (head, head)
... | Implementation of Floyd's Tortoise and Hare Algorithm | FloydTortoiseAndHare | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloydTortoiseAndHare:
"""Implementation of Floyd's Tortoise and Hare Algorithm"""
def check_cycle(self, head):
"""Return True if cycle is present else False :param head: :return:"""
<|body_0|>
def cycle_node(self, head):
"""Finding the node where cycle exists :pa... | stack_v2_sparse_classes_36k_train_026540 | 3,925 | permissive | [
{
"docstring": "Return True if cycle is present else False :param head: :return:",
"name": "check_cycle",
"signature": "def check_cycle(self, head)"
},
{
"docstring": "Finding the node where cycle exists :param head: :return:",
"name": "cycle_node",
"signature": "def cycle_node(self, hea... | 2 | stack_v2_sparse_classes_30k_train_011046 | Implement the Python class `FloydTortoiseAndHare` described below.
Class description:
Implementation of Floyd's Tortoise and Hare Algorithm
Method signatures and docstrings:
- def check_cycle(self, head): Return True if cycle is present else False :param head: :return:
- def cycle_node(self, head): Finding the node w... | Implement the Python class `FloydTortoiseAndHare` described below.
Class description:
Implementation of Floyd's Tortoise and Hare Algorithm
Method signatures and docstrings:
- def check_cycle(self, head): Return True if cycle is present else False :param head: :return:
- def cycle_node(self, head): Finding the node w... | d24c4001a797c12347973263a0f4f98939e86900 | <|skeleton|>
class FloydTortoiseAndHare:
"""Implementation of Floyd's Tortoise and Hare Algorithm"""
def check_cycle(self, head):
"""Return True if cycle is present else False :param head: :return:"""
<|body_0|>
def cycle_node(self, head):
"""Finding the node where cycle exists :pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FloydTortoiseAndHare:
"""Implementation of Floyd's Tortoise and Hare Algorithm"""
def check_cycle(self, head):
"""Return True if cycle is present else False :param head: :return:"""
tortoise, hare = (head, head)
while hare and hare.next:
tortoise = tortoise.next
... | the_stack_v2_python_sparse | algorithms/LinkedList/floyds_tortoise_and_hare.py | bellatrixdatacommunity/data-structure-and-algorithms | train | 4 |
a01f40def4606dbbb33e812126fdf5e3713e20a7 | [
"n = len(nums)\ndp = [0] * (n + 2)\nfor i in reversed(range(n)):\n dp[i] = max(nums[i] + dp[i + 2], dp[i + 1])\nreturn dp[0]",
"last, now = (0, 0)\nfor x in nums:\n last, now = (now, max(last + x, now))\nreturn now"
] | <|body_start_0|>
n = len(nums)
dp = [0] * (n + 2)
for i in reversed(range(n)):
dp[i] = max(nums[i] + dp[i + 2], dp[i + 1])
return dp[0]
<|end_body_0|>
<|body_start_1|>
last, now = (0, 0)
for x in nums:
last, now = (now, max(last + x, now))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
dp = [0] * (n + 2)
for i in re... | stack_v2_sparse_classes_36k_train_026541 | 1,446 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob2",
"signature": "def rob2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000477 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
"... | fa6504cb5145d10952f4615478fa745f4b35ba13 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
n = len(nums)
dp = [0] * (n + 2)
for i in reversed(range(n)):
dp[i] = max(nums[i] + dp[i + 2], dp[i + 1])
return dp[0]
def rob2(self, nums):
""":type nums: List[int] :rtype: ... | the_stack_v2_python_sparse | Algorithms/challenges/lc198_house_robber.py | snowdj/cs_course | train | 0 | |
7f72141f2862046e017ff3bffefbcd64b38851e8 | [
"if s == s[::-1]:\n return True\nfor i in range(len(s)):\n temp = s[:i] + s[i + 1:]\n if temp == temp[::-1]:\n return True\nreturn False",
"if s == s[::-1]:\n return True\nle = 0\nri = len(s) - 1\nwhile le < ri:\n if s[le] == s[ri]:\n le += 1\n ri -= 1\n else:\n break... | <|body_start_0|>
if s == s[::-1]:
return True
for i in range(len(s)):
temp = s[:i] + s[i + 1:]
if temp == temp[::-1]:
return True
return False
<|end_body_0|>
<|body_start_1|>
if s == s[::-1]:
return True
le = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def validPalindrome_2(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if s == s[::-1]:
return True
for i in... | stack_v2_sparse_classes_36k_train_026542 | 1,738 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "validPalindrome",
"signature": "def validPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "validPalindrome_2",
"signature": "def validPalindrome_2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000915 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPalindrome(self, s): :type s: str :rtype: bool
- def validPalindrome_2(self, s): :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPalindrome(self, s): :type s: str :rtype: bool
- def validPalindrome_2(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def validPalindrome(self, s... | b925bb22d1daa4a56c5a238a5758a926905559b4 | <|skeleton|>
class Solution:
def validPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def validPalindrome_2(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validPalindrome(self, s):
""":type s: str :rtype: bool"""
if s == s[::-1]:
return True
for i in range(len(s)):
temp = s[:i] + s[i + 1:]
if temp == temp[::-1]:
return True
return False
def validPalindrome_2(s... | the_stack_v2_python_sparse | String/680. Valid Palindrome II.py | beninghton/notGivenUpToG | train | 0 | |
70edcb73239287b25b55f3bf69d90b40addb98ae | [
"self.min = min_num\nself.max = max_num\nself.element_filter = element_filter",
"test_list = []\nif self.min or self.max:\n test_list = filter(self.element_filter, field.data)\nif self.min:\n if self.min > len(test_list):\n raise ValidationError('Minimum %s %s required.' % (self.min, 'entry is' if se... | <|body_start_0|>
self.min = min_num
self.max = max_num
self.element_filter = element_filter
<|end_body_0|>
<|body_start_1|>
test_list = []
if self.min or self.max:
test_list = filter(self.element_filter, field.data)
if self.min:
if self.min > len(... | Require number of elements. :param min_num: Minimum number of elements. :param max_num: Maximum number of elements. :param element_filter: Callable used to filter the list prior to testing the number of elements. Useful to remove empty elements. | ListLength | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListLength:
"""Require number of elements. :param min_num: Minimum number of elements. :param max_num: Maximum number of elements. :param element_filter: Callable used to filter the list prior to testing the number of elements. Useful to remove empty elements."""
def __init__(self, min_num=N... | stack_v2_sparse_classes_36k_train_026543 | 11,750 | no_license | [
{
"docstring": "Initialize the validator.",
"name": "__init__",
"signature": "def __init__(self, min_num=None, max_num=None, element_filter=lambda x: True)"
},
{
"docstring": "Validate.",
"name": "__call__",
"signature": "def __call__(self, form, field)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013817 | Implement the Python class `ListLength` described below.
Class description:
Require number of elements. :param min_num: Minimum number of elements. :param max_num: Maximum number of elements. :param element_filter: Callable used to filter the list prior to testing the number of elements. Useful to remove empty element... | Implement the Python class `ListLength` described below.
Class description:
Require number of elements. :param min_num: Minimum number of elements. :param max_num: Maximum number of elements. :param element_filter: Callable used to filter the list prior to testing the number of elements. Useful to remove empty element... | 4de8910fff569fc9028300c70b63200da521ddb9 | <|skeleton|>
class ListLength:
"""Require number of elements. :param min_num: Minimum number of elements. :param max_num: Maximum number of elements. :param element_filter: Callable used to filter the list prior to testing the number of elements. Useful to remove empty elements."""
def __init__(self, min_num=N... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListLength:
"""Require number of elements. :param min_num: Minimum number of elements. :param max_num: Maximum number of elements. :param element_filter: Callable used to filter the list prior to testing the number of elements. Useful to remove empty elements."""
def __init__(self, min_num=None, max_num=... | the_stack_v2_python_sparse | inspirehep/modules/forms/validation_utils.py | nikpap/inspire-next | train | 1 |
22c00a3ebea5cf1f5d8ae317e0c9a91c359c66bd | [
"self.segments = segments\nself.shade = shade\nself.base = base\nself.pos = pos",
"fill(self.shade)\npushMatrix()\ntranslate(self.pos.x, self.pos.y)\nfor i in range(int(self.segments)):\n diam = map(i, 0, self.segments - 1, self.base, self.base * 0.35)\n translate(0, -diam / 2)\n ellipse(0, 0, diam, diam... | <|body_start_0|>
self.segments = segments
self.shade = shade
self.base = base
self.pos = pos
<|end_body_0|>
<|body_start_1|>
fill(self.shade)
pushMatrix()
translate(self.pos.x, self.pos.y)
for i in range(int(self.segments)):
diam = map(i, 0, s... | Snowman class: draws a snowman | Snowman | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Snowman:
"""Snowman class: draws a snowman"""
def __init__(self, pos, base, segments=3, shade=255):
"""segments: number of body parts (typically 3) shade: fill color of snowman (typically white) base: diameter of the base segment pos: position of the bottom of the snowman"""
... | stack_v2_sparse_classes_36k_train_026544 | 1,595 | no_license | [
{
"docstring": "segments: number of body parts (typically 3) shade: fill color of snowman (typically white) base: diameter of the base segment pos: position of the bottom of the snowman",
"name": "__init__",
"signature": "def __init__(self, pos, base, segments=3, shade=255)"
},
{
"docstring": "d... | 2 | stack_v2_sparse_classes_30k_train_000525 | Implement the Python class `Snowman` described below.
Class description:
Snowman class: draws a snowman
Method signatures and docstrings:
- def __init__(self, pos, base, segments=3, shade=255): segments: number of body parts (typically 3) shade: fill color of snowman (typically white) base: diameter of the base segme... | Implement the Python class `Snowman` described below.
Class description:
Snowman class: draws a snowman
Method signatures and docstrings:
- def __init__(self, pos, base, segments=3, shade=255): segments: number of body parts (typically 3) shade: fill color of snowman (typically white) base: diameter of the base segme... | 8ed5bc37b8f9d766cbfeaadf01959dda8eb6d49d | <|skeleton|>
class Snowman:
"""Snowman class: draws a snowman"""
def __init__(self, pos, base, segments=3, shade=255):
"""segments: number of body parts (typically 3) shade: fill color of snowman (typically white) base: diameter of the base segment pos: position of the bottom of the snowman"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Snowman:
"""Snowman class: draws a snowman"""
def __init__(self, pos, base, segments=3, shade=255):
"""segments: number of body parts (typically 3) shade: fill color of snowman (typically white) base: diameter of the base segment pos: position of the bottom of the snowman"""
self.segments... | the_stack_v2_python_sparse | 08-oop/snowmen.pyde | jeisenma/ProgrammingConcepts | train | 0 |
f2020912a71289a8bd434ec54c6ec29d3f6b9747 | [
"self.lockIO = Lock()\nself.bus = bus\nself.bus.register(self)\nself.data = [0] * (16131 + 1)\nreturn",
"if self.bus.address < 16636 or self.bus.address > 32767:\n return\nif self.bus.mode == MODE.READ:\n self.lockIO.acquire()\n self.bus.data = self.data[self.bus.address - 16636]\n self.lockIO.release... | <|body_start_0|>
self.lockIO = Lock()
self.bus = bus
self.bus.register(self)
self.data = [0] * (16131 + 1)
return
<|end_body_0|>
<|body_start_1|>
if self.bus.address < 16636 or self.bus.address > 32767:
return
if self.bus.mode == MODE.READ:
... | class IO ======================== Cette classe représente les entrées/sorties du micro-ordinateur. À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effectuer une lecture ou écriture en mémoire. :example: >>> test = IO(modBus.Bus()) | IO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IO:
"""class IO ======================== Cette classe représente les entrées/sorties du micro-ordinateur. À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effectuer une lecture ou écriture en mémoire. :example: >>> test = IO(modBus.Bus())"""
def __init__(self, bus):
... | stack_v2_sparse_classes_36k_train_026545 | 4,185 | permissive | [
{
"docstring": "Constructeur de la classe IO. Le constructeur s'occupe d'initialiser la mémoire IO et lie ce composant avec le bus. :example: >>> test = IO(modBus.Bus()) :param bus: Composant Bus du Micro-Ordinateur. :type bus: Bus",
"name": "__init__",
"signature": "def __init__(self, bus)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_002994 | Implement the Python class `IO` described below.
Class description:
class IO ======================== Cette classe représente les entrées/sorties du micro-ordinateur. À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effectuer une lecture ou écriture en mémoire. :example: >>> test = IO(modBus.Bus()... | Implement the Python class `IO` described below.
Class description:
class IO ======================== Cette classe représente les entrées/sorties du micro-ordinateur. À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effectuer une lecture ou écriture en mémoire. :example: >>> test = IO(modBus.Bus()... | 0a3a9b0deffa16e8c851eb53e6aad1a8983936e6 | <|skeleton|>
class IO:
"""class IO ======================== Cette classe représente les entrées/sorties du micro-ordinateur. À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effectuer une lecture ou écriture en mémoire. :example: >>> test = IO(modBus.Bus())"""
def __init__(self, bus):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IO:
"""class IO ======================== Cette classe représente les entrées/sorties du micro-ordinateur. À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effectuer une lecture ou écriture en mémoire. :example: >>> test = IO(modBus.Bus())"""
def __init__(self, bus):
"""Constr... | the_stack_v2_python_sparse | Modules/04-05-IO.py | MarcAndreJean/PCONC | train | 0 |
219fe56326a795e8d12c015ec5f57b499df51462 | [
"note = self.get_object()\nif not note.is_public and note.user != self.request.user:\n return redirect('notes')\nself.object = note\nreturn super().dispatch(request, *args, **kwargs)",
"initial = super().get_initial()\nnote = self.get_object()\ninitial['title'] = note.title\ninitial['content'] = note.content\n... | <|body_start_0|>
note = self.get_object()
if not note.is_public and note.user != self.request.user:
return redirect('notes')
self.object = note
return super().dispatch(request, *args, **kwargs)
<|end_body_0|>
<|body_start_1|>
initial = super().get_initial()
n... | View for User to make a clone of another Note. The Note's num_clones is incremented upon a sucessful clone. | CloneNoteView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloneNoteView:
"""View for User to make a clone of another Note. The Note's num_clones is incremented upon a sucessful clone."""
def dispatch(self, request, *args, **kwargs):
"""Can only clone Note if it is public or the requesting User is the creator of the Note."""
<|body_0... | stack_v2_sparse_classes_36k_train_026546 | 4,866 | no_license | [
{
"docstring": "Can only clone Note if it is public or the requesting User is the creator of the Note.",
"name": "dispatch",
"signature": "def dispatch(self, request, *args, **kwargs)"
},
{
"docstring": "Add the cloned Note's data to the form.",
"name": "get_initial",
"signature": "def g... | 3 | stack_v2_sparse_classes_30k_train_006553 | Implement the Python class `CloneNoteView` described below.
Class description:
View for User to make a clone of another Note. The Note's num_clones is incremented upon a sucessful clone.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Can only clone Note if it is public or the reques... | Implement the Python class `CloneNoteView` described below.
Class description:
View for User to make a clone of another Note. The Note's num_clones is incremented upon a sucessful clone.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Can only clone Note if it is public or the reques... | 8476643e12548ac797c6e18e23b9654c43cebe77 | <|skeleton|>
class CloneNoteView:
"""View for User to make a clone of another Note. The Note's num_clones is incremented upon a sucessful clone."""
def dispatch(self, request, *args, **kwargs):
"""Can only clone Note if it is public or the requesting User is the creator of the Note."""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloneNoteView:
"""View for User to make a clone of another Note. The Note's num_clones is incremented upon a sucessful clone."""
def dispatch(self, request, *args, **kwargs):
"""Can only clone Note if it is public or the requesting User is the creator of the Note."""
note = self.get_objec... | the_stack_v2_python_sparse | notes/views.py | gurupratap-matharu/code-atlas | train | 0 |
4acf368b530be055abad166700eea9f066af7e8e | [
"try:\n where_clause = ''\n for i in range(0, len(companies)):\n if i < len(companies) - 1:\n where_clause = where_clause + '(Title LIKE %' + str(companies[i]) + '%) or '\n else:\n where_clause = where_clause + '(Title LIKE %' + str(companies[i]) + '%)'\n query = 'SELECT... | <|body_start_0|>
try:
where_clause = ''
for i in range(0, len(companies)):
if i < len(companies) - 1:
where_clause = where_clause + '(Title LIKE %' + str(companies[i]) + '%) or '
else:
where_clause = where_clause + '... | PartialArticleDAO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartialArticleDAO:
def getArticlesByCompanyInTitle(self, companies):
"""Returns a list of articles that mention at least one company presents in company."""
<|body_0|>
def getArticlesByNewsPaper(self, newspaper):
"""Returns every articles published by a certain sourc... | stack_v2_sparse_classes_36k_train_026547 | 6,200 | no_license | [
{
"docstring": "Returns a list of articles that mention at least one company presents in company.",
"name": "getArticlesByCompanyInTitle",
"signature": "def getArticlesByCompanyInTitle(self, companies)"
},
{
"docstring": "Returns every articles published by a certain source",
"name": "getArt... | 3 | stack_v2_sparse_classes_30k_train_007816 | Implement the Python class `PartialArticleDAO` described below.
Class description:
Implement the PartialArticleDAO class.
Method signatures and docstrings:
- def getArticlesByCompanyInTitle(self, companies): Returns a list of articles that mention at least one company presents in company.
- def getArticlesByNewsPaper... | Implement the Python class `PartialArticleDAO` described below.
Class description:
Implement the PartialArticleDAO class.
Method signatures and docstrings:
- def getArticlesByCompanyInTitle(self, companies): Returns a list of articles that mention at least one company presents in company.
- def getArticlesByNewsPaper... | 83b622ab161e27bf36d77ac4754184ccf68a90ba | <|skeleton|>
class PartialArticleDAO:
def getArticlesByCompanyInTitle(self, companies):
"""Returns a list of articles that mention at least one company presents in company."""
<|body_0|>
def getArticlesByNewsPaper(self, newspaper):
"""Returns every articles published by a certain sourc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PartialArticleDAO:
def getArticlesByCompanyInTitle(self, companies):
"""Returns a list of articles that mention at least one company presents in company."""
try:
where_clause = ''
for i in range(0, len(companies)):
if i < len(companies) - 1:
... | the_stack_v2_python_sparse | analysis/utilities/articlesDAO.py | tangtang95/mercurio_project | train | 0 | |
2645f710df68b335f7985f6567067055440cd2ac | [
"prefix_list_entry = []\nif entries:\n for entry in entries:\n subnet, min_len, max_len, action = entry\n prefix_list_entry.append({'{}_entry'.format(cls.typeof): {'action': action, 'max_prefix_length': max_len, 'min_prefix_length': min_len, 'subnet': subnet}})\ncls.json = {'name': name, 'entries':... | <|body_start_0|>
prefix_list_entry = []
if entries:
for entry in entries:
subnet, min_len, max_len, action = entry
prefix_list_entry.append({'{}_entry'.format(cls.typeof): {'action': action, 'max_prefix_length': max_len, 'min_prefix_length': min_len, 'subnet':... | PrefixList provides common methods utilized by all prefix list operations | PrefixList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrefixList:
"""PrefixList provides common methods utilized by all prefix list operations"""
def create(cls, name, entries=None):
"""Create an IPv4 or IPv6 Prefix List Entries should be a 4-tuple consisting of (subnet, min_prefix_len, max_prefix_len, action). Action values are 'permit... | stack_v2_sparse_classes_36k_train_026548 | 4,764 | permissive | [
{
"docstring": "Create an IPv4 or IPv6 Prefix List Entries should be a 4-tuple consisting of (subnet, min_prefix_len, max_prefix_len, action). Action values are 'permit' or 'deny'. For example:: IPPrefixList.create( name='poo', entries=[('10.0.0.0/8', 16, 32, 'deny'), ('192.16.1.0/24', 25, 32, 'permit')]) IPv6P... | 4 | stack_v2_sparse_classes_30k_train_012276 | Implement the Python class `PrefixList` described below.
Class description:
PrefixList provides common methods utilized by all prefix list operations
Method signatures and docstrings:
- def create(cls, name, entries=None): Create an IPv4 or IPv6 Prefix List Entries should be a 4-tuple consisting of (subnet, min_prefi... | Implement the Python class `PrefixList` described below.
Class description:
PrefixList provides common methods utilized by all prefix list operations
Method signatures and docstrings:
- def create(cls, name, entries=None): Create an IPv4 or IPv6 Prefix List Entries should be a 4-tuple consisting of (subnet, min_prefi... | ae9894648787f7e81dca05de6b697c94e0f17d32 | <|skeleton|>
class PrefixList:
"""PrefixList provides common methods utilized by all prefix list operations"""
def create(cls, name, entries=None):
"""Create an IPv4 or IPv6 Prefix List Entries should be a 4-tuple consisting of (subnet, min_prefix_len, max_prefix_len, action). Action values are 'permit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrefixList:
"""PrefixList provides common methods utilized by all prefix list operations"""
def create(cls, name, entries=None):
"""Create an IPv4 or IPv6 Prefix List Entries should be a 4-tuple consisting of (subnet, min_prefix_len, max_prefix_len, action). Action values are 'permit' or 'deny'. ... | the_stack_v2_python_sparse | smc/routing/prefix_list.py | m4h3/smc-python | train | 0 |
1db502042c35527194bcbcd7cb402454fdf77eaf | [
"self.savepath = savepath\nself.fig = fig\nself.ax = ax\nself.loss = loss",
"self.ax.plot(train)\nself.ax.plot(validation)\nself.ax.set_xlabel('epochs')\nif self.loss:\n self.ax.set_ylabel('loss')\nelse:\n self.ax.set_ylabel('accuracy')\nself.ax.legend(['train', 'validation'])",
"graph = 'loss' if self.lo... | <|body_start_0|>
self.savepath = savepath
self.fig = fig
self.ax = ax
self.loss = loss
<|end_body_0|>
<|body_start_1|>
self.ax.plot(train)
self.ax.plot(validation)
self.ax.set_xlabel('epochs')
if self.loss:
self.ax.set_ylabel('loss')
e... | Graph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graph:
def __init__(self, savepath: str, fig: matplotlib.figure.Figure, ax: matplotlib.figure.Axes, loss: bool=True):
"""represents a graph to show the evolution of the loss and accuracy during training. :param savepath: path to save the images. :param fig: matplotlib figure object. :par... | stack_v2_sparse_classes_36k_train_026549 | 1,544 | permissive | [
{
"docstring": "represents a graph to show the evolution of the loss and accuracy during training. :param savepath: path to save the images. :param fig: matplotlib figure object. :param ax: matplotlib axis object. :param loss: whether the graph is a loss one or not.",
"name": "__init__",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_008182 | Implement the Python class `Graph` described below.
Class description:
Implement the Graph class.
Method signatures and docstrings:
- def __init__(self, savepath: str, fig: matplotlib.figure.Figure, ax: matplotlib.figure.Axes, loss: bool=True): represents a graph to show the evolution of the loss and accuracy during ... | Implement the Python class `Graph` described below.
Class description:
Implement the Graph class.
Method signatures and docstrings:
- def __init__(self, savepath: str, fig: matplotlib.figure.Figure, ax: matplotlib.figure.Axes, loss: bool=True): represents a graph to show the evolution of the loss and accuracy during ... | 583e6868864582f081f18689124e74e9ca169f28 | <|skeleton|>
class Graph:
def __init__(self, savepath: str, fig: matplotlib.figure.Figure, ax: matplotlib.figure.Axes, loss: bool=True):
"""represents a graph to show the evolution of the loss and accuracy during training. :param savepath: path to save the images. :param fig: matplotlib figure object. :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Graph:
def __init__(self, savepath: str, fig: matplotlib.figure.Figure, ax: matplotlib.figure.Axes, loss: bool=True):
"""represents a graph to show the evolution of the loss and accuracy during training. :param savepath: path to save the images. :param fig: matplotlib figure object. :param ax: matplot... | the_stack_v2_python_sparse | utils/graphs.py | beaupreda/domain-networks | train | 1 | |
6cb4d0b6f841d67a1c2db122b373533917f7531b | [
"user_prof = UserProfile.objects.get(user=request.user)\ntry:\n about_person = AboutPerson.objects.get(slug=str(slug))\n form = AboutFunderForm(initial={'name': about_person.name, 'content': about_person.content, 'image': about_person.image, 'funder_or_adviser': about_person.funder_or_adviser})\n user_prof... | <|body_start_0|>
user_prof = UserProfile.objects.get(user=request.user)
try:
about_person = AboutPerson.objects.get(slug=str(slug))
form = AboutFunderForm(initial={'name': about_person.name, 'content': about_person.content, 'image': about_person.image, 'funder_or_adviser': about_... | A class that represents the update page for an about page entry | AboutUpdateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AboutUpdateView:
"""A class that represents the update page for an about page entry"""
def get(self, request, slug):
"""The get request to view the update page for an entry on the about page :return: an http response showing the aboutPerson form for creating new about entry"""
... | stack_v2_sparse_classes_36k_train_026550 | 11,714 | no_license | [
{
"docstring": "The get request to view the update page for an entry on the about page :return: an http response showing the aboutPerson form for creating new about entry",
"name": "get",
"signature": "def get(self, request, slug)"
},
{
"docstring": "The post request for updating an existing ent... | 2 | stack_v2_sparse_classes_30k_train_006610 | Implement the Python class `AboutUpdateView` described below.
Class description:
A class that represents the update page for an about page entry
Method signatures and docstrings:
- def get(self, request, slug): The get request to view the update page for an entry on the about page :return: an http response showing th... | Implement the Python class `AboutUpdateView` described below.
Class description:
A class that represents the update page for an about page entry
Method signatures and docstrings:
- def get(self, request, slug): The get request to view the update page for an entry on the about page :return: an http response showing th... | 8296c49dfa8771b47965c24b6b49a2b6e8ace6cf | <|skeleton|>
class AboutUpdateView:
"""A class that represents the update page for an about page entry"""
def get(self, request, slug):
"""The get request to view the update page for an entry on the about page :return: an http response showing the aboutPerson form for creating new about entry"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AboutUpdateView:
"""A class that represents the update page for an about page entry"""
def get(self, request, slug):
"""The get request to view the update page for an entry on the about page :return: an http response showing the aboutPerson form for creating new about entry"""
user_prof =... | the_stack_v2_python_sparse | relevate_web_app/apps/contribution/views/about_views.py | jhock/Relevate | train | 1 |
5d326c04f0315f3db4226fb1f8d9ccb7f32ac371 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ListItem()",
"from .base_item import BaseItem\nfrom .content_type_info import ContentTypeInfo\nfrom .document_set_version import DocumentSetVersion\nfrom .drive_item import DriveItem\nfrom .field_value_set import FieldValueSet\nfrom .i... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ListItem()
<|end_body_0|>
<|body_start_1|>
from .base_item import BaseItem
from .content_type_info import ContentTypeInfo
from .document_set_version import DocumentSetVersion
... | ListItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ListItem:
"""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: ListItem... | stack_v2_sparse_classes_36k_train_026551 | 4,909 | 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: ListItem",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(pars... | 3 | null | Implement the Python class `ListItem` described below.
Class description:
Implement the ListItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ListItem: Creates a new instance of the appropriate class based on discriminator value Args: parse_no... | Implement the Python class `ListItem` described below.
Class description:
Implement the ListItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ListItem: Creates a new instance of the appropriate class based on discriminator value Args: parse_no... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ListItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ListItem:
"""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: ListItem... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ListItem:
"""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: ListItem"""
if... | the_stack_v2_python_sparse | msgraph/generated/models/list_item.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
57306ecdfaf3aa610f81dae6b4c488a6adf14178 | [
"rslt = super(StockMove, self)._generate_valuation_lines_data(partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id)\nif self.picking_id.currency_rate1 > 0:\n purchase_currency = self.purchase_line_id.currency_id\n purchase_price_unit = self.purchase_line_id.price_unit\n if self.p... | <|body_start_0|>
rslt = super(StockMove, self)._generate_valuation_lines_data(partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id)
if self.picking_id.currency_rate1 > 0:
purchase_currency = self.purchase_line_id.currency_id
purchase_price_unit = self.p... | StockMove | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StockMove:
def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id):
"""Overridden from stock_account to support amount_currency on valuation lines generated from po"""
<|body_0|>
def _prepare_account_move_line... | stack_v2_sparse_classes_36k_train_026552 | 5,257 | no_license | [
{
"docstring": "Overridden from stock_account to support amount_currency on valuation lines generated from po",
"name": "_generate_valuation_lines_data",
"signature": "def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id)"
},
{
... | 2 | null | Implement the Python class `StockMove` described below.
Class description:
Implement the StockMove class.
Method signatures and docstrings:
- def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id): Overridden from stock_account to support amount_curre... | Implement the Python class `StockMove` described below.
Class description:
Implement the StockMove class.
Method signatures and docstrings:
- def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id): Overridden from stock_account to support amount_curre... | 5ed668bda8177586695f5dc2e68a48806eccf976 | <|skeleton|>
class StockMove:
def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id):
"""Overridden from stock_account to support amount_currency on valuation lines generated from po"""
<|body_0|>
def _prepare_account_move_line... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StockMove:
def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id):
"""Overridden from stock_account to support amount_currency on valuation lines generated from po"""
rslt = super(StockMove, self)._generate_valuation_lines_data... | the_stack_v2_python_sparse | purchase_exchange_currency_rate/models/stock.py | akradore/ACC_12 | train | 0 | |
6c4a959aed6520b8d4a77d3f63b2ffd843e83ec9 | [
"dumb = TreeNode(0)\nfor node in self.preOrderTraversalNodes(root):\n dumb.right = node\n dumb = dumb.right\n dumb.left = None",
"if not root:\n return []\nreturn [root] + self.preOrderTraversalNodes(root.left) + self.preOrderTraversalNodes(root.right)"
] | <|body_start_0|>
dumb = TreeNode(0)
for node in self.preOrderTraversalNodes(root):
dumb.right = node
dumb = dumb.right
dumb.left = None
<|end_body_0|>
<|body_start_1|>
if not root:
return []
return [root] + self.preOrderTraversalNodes(root... | Solution_A | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_A:
def flatten(self, root: TreeNode) -> None:
"""Use a preOrderTraversal helper to keep the TreeNode in order Then assign to a dumb head to the right with iteration"""
<|body_0|>
def preOrderTraversalNodes(self, root: TreeNode) -> List[TreeNode]:
"""Modified... | stack_v2_sparse_classes_36k_train_026553 | 2,886 | permissive | [
{
"docstring": "Use a preOrderTraversal helper to keep the TreeNode in order Then assign to a dumb head to the right with iteration",
"name": "flatten",
"signature": "def flatten(self, root: TreeNode) -> None"
},
{
"docstring": "Modified preOrder traversal to get nodes instead of the values",
... | 2 | null | Implement the Python class `Solution_A` described below.
Class description:
Implement the Solution_A class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: Use a preOrderTraversal helper to keep the TreeNode in order Then assign to a dumb head to the right with iteration
- def preOrderT... | Implement the Python class `Solution_A` described below.
Class description:
Implement the Solution_A class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: Use a preOrderTraversal helper to keep the TreeNode in order Then assign to a dumb head to the right with iteration
- def preOrderT... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_A:
def flatten(self, root: TreeNode) -> None:
"""Use a preOrderTraversal helper to keep the TreeNode in order Then assign to a dumb head to the right with iteration"""
<|body_0|>
def preOrderTraversalNodes(self, root: TreeNode) -> List[TreeNode]:
"""Modified... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution_A:
def flatten(self, root: TreeNode) -> None:
"""Use a preOrderTraversal helper to keep the TreeNode in order Then assign to a dumb head to the right with iteration"""
dumb = TreeNode(0)
for node in self.preOrderTraversalNodes(root):
dumb.right = node
d... | the_stack_v2_python_sparse | LeetCode/LC114_flatten_binary_tree_to_linked_list.py | jxie0755/Learning_Python | train | 0 | |
6bf9dfec5216fa5e858d22a6e5f19e0f9b4a7ca8 | [
"result = []\nqueue = deque()\nqueue.append(root)\nwhile queue:\n node = queue.popleft()\n if node is None:\n result.append('N')\n continue\n result.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\nreturn ','.join(result).rstrip(',N')",
"if not data:\n re... | <|body_start_0|>
result = []
queue = deque()
queue.append(root)
while queue:
node = queue.popleft()
if node is None:
result.append('N')
continue
result.append(str(node.val))
queue.append(node.left)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_026554 | 1,902 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 7f8145f0c7ffdf18c557f01d221087b10443156e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
result = []
queue = deque()
queue.append(root)
while queue:
node = queue.popleft()
if node is None:
result.append('N')
... | the_stack_v2_python_sparse | tree/297 Serialize and Deserialize Binary Tree.py | mofei952/leetcode_python | train | 0 | |
0997cbfe2fffabd45e55f0b7662f5485ba8ad9ec | [
"def post(root, t):\n if not root:\n return\n for c in root.children:\n post(c, t)\n t += [root.val]\nt = []\npost(root, t)\nreturn t",
"if not root:\n return []\nsta = [root]\nlast = root\nres = []\nwhile len(sta):\n t = sta[-1]\n if len(t.children) == 0 or last == t.children[-1]:... | <|body_start_0|>
def post(root, t):
if not root:
return
for c in root.children:
post(c, t)
t += [root.val]
t = []
post(root, t)
return t
<|end_body_0|>
<|body_start_1|>
if not root:
return []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def postorder(self, root):
""":type root: Node :rtype: List[int]"""
<|body_0|>
def postorder(self, root):
""":type root: Node :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def post(root, t):
if not root:
... | stack_v2_sparse_classes_36k_train_026555 | 1,299 | no_license | [
{
"docstring": ":type root: Node :rtype: List[int]",
"name": "postorder",
"signature": "def postorder(self, root)"
},
{
"docstring": ":type root: Node :rtype: List[int]",
"name": "postorder",
"signature": "def postorder(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000152 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorder(self, root): :type root: Node :rtype: List[int]
- def postorder(self, root): :type root: Node :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorder(self, root): :type root: Node :rtype: List[int]
- def postorder(self, root): :type root: Node :rtype: List[int]
<|skeleton|>
class Solution:
def postorder(sel... | 160de27c1222ff31e0b4f22d78c278a3906d29c0 | <|skeleton|>
class Solution:
def postorder(self, root):
""":type root: Node :rtype: List[int]"""
<|body_0|>
def postorder(self, root):
""":type root: Node :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def postorder(self, root):
""":type root: Node :rtype: List[int]"""
def post(root, t):
if not root:
return
for c in root.children:
post(c, t)
t += [root.val]
t = []
post(root, t)
return t
... | the_stack_v2_python_sparse | LeetCode/Python/E590_N-aryTreePostorderTraversal.py | hughian/OJ | train | 0 | |
dc9242ee420a6691b8c50ddae8286278cdeb2eab | [
"query = None\nif '-' in accession:\n accession = accession.split('-')[0]\ntry:\n service = Service('http://www.mousemine.org/mousemine/service')\n query = service.new_query('Gene')\n query.add_view('primaryIdentifier', 'ncbiGeneNumber', 'proteins.primaryAccession', 'symbol', 'proteins.synonyms.value', ... | <|body_start_0|>
query = None
if '-' in accession:
accession = accession.split('-')[0]
try:
service = Service('http://www.mousemine.org/mousemine/service')
query = service.new_query('Gene')
query.add_view('primaryIdentifier', 'ncbiGeneNumber', 'pro... | IntermineTools | [
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntermineTools:
def mousemine_accession_lookup(accession, verbose=False):
"""Return an intermine query object for a given protien accession number. The query is design to find Entrez gene IDs for proetiens of a given accession number. It only considers the cannonical isoform of whole mou... | stack_v2_sparse_classes_36k_train_026556 | 9,507 | permissive | [
{
"docstring": "Return an intermine query object for a given protien accession number. The query is design to find Entrez gene IDs for proetiens of a given accession number. It only considers the cannonical isoform of whole mouse proteins(not fragments) presnt in the Swiss-Prot or TrEMBL databases. Parameters -... | 5 | stack_v2_sparse_classes_30k_train_019601 | Implement the Python class `IntermineTools` described below.
Class description:
Implement the IntermineTools class.
Method signatures and docstrings:
- def mousemine_accession_lookup(accession, verbose=False): Return an intermine query object for a given protien accession number. The query is design to find Entrez ge... | Implement the Python class `IntermineTools` described below.
Class description:
Implement the IntermineTools class.
Method signatures and docstrings:
- def mousemine_accession_lookup(accession, verbose=False): Return an intermine query object for a given protien accession number. The query is design to find Entrez ge... | bedb36eafe681401c11d562f8d7117aad3d758d7 | <|skeleton|>
class IntermineTools:
def mousemine_accession_lookup(accession, verbose=False):
"""Return an intermine query object for a given protien accession number. The query is design to find Entrez gene IDs for proetiens of a given accession number. It only considers the cannonical isoform of whole mou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IntermineTools:
def mousemine_accession_lookup(accession, verbose=False):
"""Return an intermine query object for a given protien accession number. The query is design to find Entrez gene IDs for proetiens of a given accession number. It only considers the cannonical isoform of whole mouse proteins(no... | the_stack_v2_python_sparse | omin/utils/network_tools.py | dmpio/omin | train | 0 | |
7626ba95a9ff034172a89b7f887250d385dd263c | [
"self.submitted_targets = submitted_targets\nself.real_targets = real_targets\nif self.submitted_targets:\n self.user = self.submitted_targets[0].user\n for t in self.submitted_targets:\n if t.user != self.user:\n raise AssertionError('All submitted targets must be from the same user')\n ... | <|body_start_0|>
self.submitted_targets = submitted_targets
self.real_targets = real_targets
if self.submitted_targets:
self.user = self.submitted_targets[0].user
for t in self.submitted_targets:
if t.user != self.user:
raise AssertionE... | Evaluates submitted targets against real judge-made targets. | TargetEvaluator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TargetEvaluator:
"""Evaluates submitted targets against real judge-made targets."""
def __init__(self, submitted_targets, real_targets):
"""Creates an evaluation of submitted targets against real targets. Args: submitted_targets: List of submitted Target objects, all from the same us... | stack_v2_sparse_classes_36k_train_026557 | 17,186 | permissive | [
{
"docstring": "Creates an evaluation of submitted targets against real targets. Args: submitted_targets: List of submitted Target objects, all from the same user. real_targets: List of real Target objects made by judges. Raises: AssertionError: not all submitted targets are from the same user.",
"name": "_... | 6 | stack_v2_sparse_classes_30k_train_001717 | Implement the Python class `TargetEvaluator` described below.
Class description:
Evaluates submitted targets against real judge-made targets.
Method signatures and docstrings:
- def __init__(self, submitted_targets, real_targets): Creates an evaluation of submitted targets against real targets. Args: submitted_target... | Implement the Python class `TargetEvaluator` described below.
Class description:
Evaluates submitted targets against real judge-made targets.
Method signatures and docstrings:
- def __init__(self, submitted_targets, real_targets): Creates an evaluation of submitted targets against real targets. Args: submitted_target... | 509f36562fc895433fcd01da755a35dd04581025 | <|skeleton|>
class TargetEvaluator:
"""Evaluates submitted targets against real judge-made targets."""
def __init__(self, submitted_targets, real_targets):
"""Creates an evaluation of submitted targets against real targets. Args: submitted_targets: List of submitted Target objects, all from the same us... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TargetEvaluator:
"""Evaluates submitted targets against real judge-made targets."""
def __init__(self, submitted_targets, real_targets):
"""Creates an evaluation of submitted targets against real targets. Args: submitted_targets: List of submitted Target objects, all from the same user. real_targ... | the_stack_v2_python_sparse | server/auvsi_suas/models/target.py | matcheydj/interop | train | 1 |
6d7e1f8a1a096364cc493ba82661ee7184ab62a9 | [
"super().__init__()\nif out_channels is None:\n out_channels = in_channels\nself.in_channels, self.out_channels = (in_channels, out_channels)\nself.map = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation)",
"x = self.map(input)\nx_gate = torch.sigmo... | <|body_start_0|>
super().__init__()
if out_channels is None:
out_channels = in_channels
self.in_channels, self.out_channels = (in_channels, out_channels)
self.map = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation... | Sigmoid Linear Units for 2D inputs | SiLU2d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiLU2d:
"""Sigmoid Linear Units for 2D inputs"""
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)):
"""Args: in_channels <int> out_channels <int>"""
<|body_0|>
def forward(self, input):
"""Args: input (batc... | stack_v2_sparse_classes_36k_train_026558 | 2,967 | no_license | [
{
"docstring": "Args: in_channels <int> out_channels <int>",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1))"
},
{
"docstring": "Args: input (batch_size, in_channels, H, W) Returns: output (batch_size, o... | 2 | stack_v2_sparse_classes_30k_train_014548 | Implement the Python class `SiLU2d` described below.
Class description:
Sigmoid Linear Units for 2D inputs
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)): Args: in_channels <int> out_channels <int>
- def forward(self, inpu... | Implement the Python class `SiLU2d` described below.
Class description:
Sigmoid Linear Units for 2D inputs
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)): Args: in_channels <int> out_channels <int>
- def forward(self, inpu... | 4f7f77406cf580785ebf932d78069e7d6e35b765 | <|skeleton|>
class SiLU2d:
"""Sigmoid Linear Units for 2D inputs"""
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)):
"""Args: in_channels <int> out_channels <int>"""
<|body_0|>
def forward(self, input):
"""Args: input (batc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SiLU2d:
"""Sigmoid Linear Units for 2D inputs"""
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)):
"""Args: in_channels <int> out_channels <int>"""
super().__init__()
if out_channels is None:
out_channels = in_c... | the_stack_v2_python_sparse | src/models/silu.py | shelly-tang/DNN-based_source_separation | train | 0 |
74cf2663c72e62fd7acaea89e5afe5b93977d1ae | [
"try:\n obj = QueryPlansAcquired.objects.filter(queryplansclient__client=pk).values('id', 'plan_name', 'queryplansclient__is_chosen', 'is_active', 'status', 'validity_months', 'query_quantity', 'queries_to_pay', 'activation_date', 'available_queries', 'expiration_date', 'queryplansclient__transfer', 'queryplansc... | <|body_start_0|>
try:
obj = QueryPlansAcquired.objects.filter(queryplansclient__client=pk).values('id', 'plan_name', 'queryplansclient__is_chosen', 'is_active', 'status', 'validity_months', 'query_quantity', 'queries_to_pay', 'activation_date', 'available_queries', 'expiration_date', 'queryplansclie... | Vista para obetener todos los planes de un cliente. | ClientAllPlansView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientAllPlansView:
"""Vista para obetener todos los planes de un cliente."""
def get_object(self, pk):
"""Obtener lista de planes."""
<|body_0|>
def get(self, request):
"""Obtener la lista con todos los planes del cliente."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_026559 | 44,248 | no_license | [
{
"docstring": "Obtener lista de planes.",
"name": "get_object",
"signature": "def get_object(self, pk)"
},
{
"docstring": "Obtener la lista con todos los planes del cliente.",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010103 | Implement the Python class `ClientAllPlansView` described below.
Class description:
Vista para obetener todos los planes de un cliente.
Method signatures and docstrings:
- def get_object(self, pk): Obtener lista de planes.
- def get(self, request): Obtener la lista con todos los planes del cliente. | Implement the Python class `ClientAllPlansView` described below.
Class description:
Vista para obetener todos los planes de un cliente.
Method signatures and docstrings:
- def get_object(self, pk): Obtener lista de planes.
- def get(self, request): Obtener la lista con todos los planes del cliente.
<|skeleton|>
clas... | 3135a4142c38f367a152e1fc79fee8af8fca4bcc | <|skeleton|>
class ClientAllPlansView:
"""Vista para obetener todos los planes de un cliente."""
def get_object(self, pk):
"""Obtener lista de planes."""
<|body_0|>
def get(self, request):
"""Obtener la lista con todos los planes del cliente."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClientAllPlansView:
"""Vista para obetener todos los planes de un cliente."""
def get_object(self, pk):
"""Obtener lista de planes."""
try:
obj = QueryPlansAcquired.objects.filter(queryplansclient__client=pk).values('id', 'plan_name', 'queryplansclient__is_chosen', 'is_active'... | the_stack_v2_python_sparse | api/views/plan.py | darwinv/api-chat-lnk | train | 0 |
10179b3207eccee4fbf8ce52da1e16c416cbe919 | [
"self._body._dirty.discard('id')\nid_mapping_name = self._body_mapping()['id']\nself._body._dirty.discard(id_mapping_name)\nif not any([self._body.dirty, self._header.dirty]):\n return self\nif not self.allow_update:\n raise exceptions.MethodNotSupported(self, 'update')\nrequest = self._prepare_request(prepen... | <|body_start_0|>
self._body._dirty.discard('id')
id_mapping_name = self._body_mapping()['id']
self._body._dirty.discard(id_mapping_name)
if not any([self._body.dirty, self._header.dirty]):
return self
if not self.allow_update:
raise exceptions.MethodNotSup... | Subnet | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subnet:
def update(self, session, prepend_key=True, has_body=True):
"""Update information about a subnet. :param session: The session to use for this request. :type session: :class:`~openstack.session.Session` :param bool prepend_key: A boolean indicating whether the resource_key should ... | stack_v2_sparse_classes_36k_train_026560 | 6,415 | permissive | [
{
"docstring": "Update information about a subnet. :param session: The session to use for this request. :type session: :class:`~openstack.session.Session` :param bool prepend_key: A boolean indicating whether the resource_key should be prepended in a resource update request. Default to True. :param bool has_bod... | 3 | null | Implement the Python class `Subnet` described below.
Class description:
Implement the Subnet class.
Method signatures and docstrings:
- def update(self, session, prepend_key=True, has_body=True): Update information about a subnet. :param session: The session to use for this request. :type session: :class:`~openstack.... | Implement the Python class `Subnet` described below.
Class description:
Implement the Subnet class.
Method signatures and docstrings:
- def update(self, session, prepend_key=True, has_body=True): Update information about a subnet. :param session: The session to use for this request. :type session: :class:`~openstack.... | 227cd7f68a07974b16794c371f110d1927571fd0 | <|skeleton|>
class Subnet:
def update(self, session, prepend_key=True, has_body=True):
"""Update information about a subnet. :param session: The session to use for this request. :type session: :class:`~openstack.session.Session` :param bool prepend_key: A boolean indicating whether the resource_key should ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Subnet:
def update(self, session, prepend_key=True, has_body=True):
"""Update information about a subnet. :param session: The session to use for this request. :type session: :class:`~openstack.session.Session` :param bool prepend_key: A boolean indicating whether the resource_key should be prepended i... | the_stack_v2_python_sparse | openstack/vpc/v1/subnet.py | ArvinSong/huaweicloud-sdk-python | train | 1 | |
c460b4586b14b2b6a15d3fd87b2c83bdbcb3188d | [
"shapefile = os.path.join(os.path.expanduser('~'), 'data_pool/U-TMP/TILE/MRGS-CHN', 'MRGS_Grid.shp')\nself.shapefile = ogr.Open(shapefile)\nif not os.path.exists(shapefile):\n raise Exception('path-row file was not found and check out the file dir!')\nself.layer = self.shapefile.GetLayer(0)\nself.polygons = []\n... | <|body_start_0|>
shapefile = os.path.join(os.path.expanduser('~'), 'data_pool/U-TMP/TILE/MRGS-CHN', 'MRGS_Grid.shp')
self.shapefile = ogr.Open(shapefile)
if not os.path.exists(shapefile):
raise Exception('path-row file was not found and check out the file dir!')
self.layer = ... | Class which performs conversion between latitude/longitude co-ordinates and Sentinel paths and rows. Requirements: * OGR (in the GDAL suite) * Shapely * Sentinel Path/Row Shapefiles Usage: 1. Create an instance of the class: conv = ConvertToMRGS() (This will take a while to run, as it loads the shapefiles in to memory)... | ConvertToMRGS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvertToMRGS:
"""Class which performs conversion between latitude/longitude co-ordinates and Sentinel paths and rows. Requirements: * OGR (in the GDAL suite) * Shapely * Sentinel Path/Row Shapefiles Usage: 1. Create an instance of the class: conv = ConvertToMRGS() (This will take a while to run,... | stack_v2_sparse_classes_36k_train_026561 | 4,182 | no_license | [
{
"docstring": "Create a new instance of the ConvertToMRGS class, and load the shapefiles into memory. If it can't find the shapefile then specify the path using the shapefile keyword - but it should work if the shapefile is in the same directory.",
"name": "__init__",
"signature": "def __init__(self, s... | 2 | stack_v2_sparse_classes_30k_train_012799 | Implement the Python class `ConvertToMRGS` described below.
Class description:
Class which performs conversion between latitude/longitude co-ordinates and Sentinel paths and rows. Requirements: * OGR (in the GDAL suite) * Shapely * Sentinel Path/Row Shapefiles Usage: 1. Create an instance of the class: conv = ConvertT... | Implement the Python class `ConvertToMRGS` described below.
Class description:
Class which performs conversion between latitude/longitude co-ordinates and Sentinel paths and rows. Requirements: * OGR (in the GDAL suite) * Shapely * Sentinel Path/Row Shapefiles Usage: 1. Create an instance of the class: conv = ConvertT... | 43854cd50edf69fa7f7c1159fa4aa644adc53ecd | <|skeleton|>
class ConvertToMRGS:
"""Class which performs conversion between latitude/longitude co-ordinates and Sentinel paths and rows. Requirements: * OGR (in the GDAL suite) * Shapely * Sentinel Path/Row Shapefiles Usage: 1. Create an instance of the class: conv = ConvertToMRGS() (This will take a while to run,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvertToMRGS:
"""Class which performs conversion between latitude/longitude co-ordinates and Sentinel paths and rows. Requirements: * OGR (in the GDAL suite) * Shapely * Sentinel Path/Row Shapefiles Usage: 1. Create an instance of the class: conv = ConvertToMRGS() (This will take a while to run, as it loads ... | the_stack_v2_python_sparse | sample_points/sentinel_index.py | Aaayue/SAMPLE-EXTRACTOR | train | 0 |
fcaf528c6354af5a366cb4a11dd8c1e1e9f6a976 | [
"self.timeToSpawn = timeToSpawn\nself.timer = timeToSpawn\nself.map = map\nself.currBonusId = 0",
"if self.timer == 0:\n if len(self.map.bonuses) < self.map.maxNoOfBonuses:\n bonus = None\n rand = randint(0, len(self.BONUSES) - 1)\n if rand == 0:\n bonus = WeaponBonus(self.currB... | <|body_start_0|>
self.timeToSpawn = timeToSpawn
self.timer = timeToSpawn
self.map = map
self.currBonusId = 0
<|end_body_0|>
<|body_start_1|>
if self.timer == 0:
if len(self.map.bonuses) < self.map.maxNoOfBonuses:
bonus = None
rand = ra... | A class that represents a bonus spawner. | BonusSpawner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BonusSpawner:
"""A class that represents a bonus spawner."""
def __init__(self, map, timeToSpawn):
"""The constructor"""
<|body_0|>
def process(self):
"""This method checks wether the number of bonuses on the map has not exceeded the maximum number of bonuses all... | stack_v2_sparse_classes_36k_train_026562 | 1,318 | no_license | [
{
"docstring": "The constructor",
"name": "__init__",
"signature": "def __init__(self, map, timeToSpawn)"
},
{
"docstring": "This method checks wether the number of bonuses on the map has not exceeded the maximum number of bonuses allowed. If not it creates a new random one and adds it to the ma... | 2 | stack_v2_sparse_classes_30k_train_003368 | Implement the Python class `BonusSpawner` described below.
Class description:
A class that represents a bonus spawner.
Method signatures and docstrings:
- def __init__(self, map, timeToSpawn): The constructor
- def process(self): This method checks wether the number of bonuses on the map has not exceeded the maximum ... | Implement the Python class `BonusSpawner` described below.
Class description:
A class that represents a bonus spawner.
Method signatures and docstrings:
- def __init__(self, map, timeToSpawn): The constructor
- def process(self): This method checks wether the number of bonuses on the map has not exceeded the maximum ... | eec95e28603b3a55c1df4f39e98ef9978881df73 | <|skeleton|>
class BonusSpawner:
"""A class that represents a bonus spawner."""
def __init__(self, map, timeToSpawn):
"""The constructor"""
<|body_0|>
def process(self):
"""This method checks wether the number of bonuses on the map has not exceeded the maximum number of bonuses all... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BonusSpawner:
"""A class that represents a bonus spawner."""
def __init__(self, map, timeToSpawn):
"""The constructor"""
self.timeToSpawn = timeToSpawn
self.timer = timeToSpawn
self.map = map
self.currBonusId = 0
def process(self):
"""This method check... | the_stack_v2_python_sparse | game/BonusSpawner.py | eatrunner/tank-game | train | 0 |
afb56ce2864fb14579beda356238f2d3c34d755d | [
"if root == None:\n return '[]'\nque = []\nque.append(root)\nres = []\nwhile any(que):\n next_level = []\n while len(que) > 0:\n cur = que.pop(0)\n if cur == None:\n res.append(None)\n next_level.append(None)\n next_level.append(None)\n else:\n ... | <|body_start_0|>
if root == None:
return '[]'
que = []
que.append(root)
res = []
while any(que):
next_level = []
while len(que) > 0:
cur = que.pop(0)
if cur == None:
res.append(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: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_026563 | 3,172 | 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_021628 | 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:... | 0d6f414e7610fedb2ec4818ecf88d51aa69e1355 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root == None:
return '[]'
que = []
que.append(root)
res = []
while any(que):
next_level = []
while len(que) > 0:
... | the_stack_v2_python_sparse | 0449_Serialize_and_Deserialize_BST.py | chien-wei/LeetCode | train | 0 | |
597b1d2e98a7ec1dbf7cec6655f6169114c70831 | [
"work_pool = await models.workers.read_work_pool_by_name(session=session, work_pool_name=work_pool_name)\nif not work_pool:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Worker pool \"{work_pool_name}\" not found.')\nreturn work_pool.id",
"work_pool = await models.workers.read_work_pool... | <|body_start_0|>
work_pool = await models.workers.read_work_pool_by_name(session=session, work_pool_name=work_pool_name)
if not work_pool:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Worker pool "{work_pool_name}" not found.')
return work_pool.id
<|end_body_0|... | WorkerLookups | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkerLookups:
async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID:
"""Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
<|body_0|>
async d... | stack_v2_sparse_classes_36k_train_026564 | 16,683 | permissive | [
{
"docstring": "Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).",
"name": "_get_work_pool_id_from_name",
"signature": "async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUI... | 3 | stack_v2_sparse_classes_30k_test_000581 | Implement the Python class `WorkerLookups` described below.
Class description:
Implement the WorkerLookups class.
Method signatures and docstrings:
- async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: Given a work pool name, return its ID. Used for translating user-facing... | Implement the Python class `WorkerLookups` described below.
Class description:
Implement the WorkerLookups class.
Method signatures and docstrings:
- async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: Given a work pool name, return its ID. Used for translating user-facing... | 355d5de4b29720d9a81c12fd77ef734fc2c1733b | <|skeleton|>
class WorkerLookups:
async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID:
"""Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
<|body_0|>
async d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkerLookups:
async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID:
"""Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
work_pool = await models.workers.read... | the_stack_v2_python_sparse | src/prefect/orion/api/workers.py | Clearcover/prefect | train | 1 | |
804c5c6a5c1dcfb1003dd8f70a4e285a6648a125 | [
"maxNum = 0\nstack = []\nstack.append(-1)\nfor idx, val in enumerate(s):\n if val == '(':\n stack.append(idx)\n else:\n stack.pop()\n if not stack:\n stack.append(idx)\n else:\n maxNum = max(maxNum, idx - stack[-1])\nreturn maxNum",
"stack = []\nmaxNum = 0\n... | <|body_start_0|>
maxNum = 0
stack = []
stack.append(-1)
for idx, val in enumerate(s):
if val == '(':
stack.append(idx)
else:
stack.pop()
if not stack:
stack.append(idx)
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestValidParenthesesBetter(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
maxNum = 0
stack = []
s... | stack_v2_sparse_classes_36k_train_026565 | 1,273 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "longestValidParenthesesBetter",
"signature": "def longestValidParenthesesBetter(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "longestValidParentheses",
"signature": "def longestValidParentheses(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParenthesesBetter(self, s): :type s: str :rtype: int
- def longestValidParentheses(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParenthesesBetter(self, s): :type s: str :rtype: int
- def longestValidParentheses(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def longe... | be2bf7c78aaf2628419be4a6ff34817dac719a57 | <|skeleton|>
class Solution:
def longestValidParenthesesBetter(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestValidParenthesesBetter(self, s):
""":type s: str :rtype: int"""
maxNum = 0
stack = []
stack.append(-1)
for idx, val in enumerate(s):
if val == '(':
stack.append(idx)
else:
stack.pop()
... | the_stack_v2_python_sparse | Solutions/LongestValidParentheses.py | sherld/LeetCodeForPython | train | 0 | |
bbdaea12a663570e0a24047c8a882d95e4c899d3 | [
"self.rulesFuzzyDisplay = rulesFuzzyDisplay\nself.fuzzy_sets = rulesFuzzyDisplay.fuzzy_sets\nself.new_rule_root = Toplevel()\nself.new_rule_root.title(\"Création d'une nouvelle règle\")\nLabel(self.new_rule_root, text='Conditions :').grid(row=0, padx='0.3c')\nLabel(self.new_rule_root, text='Nom du fait').grid(row=1... | <|body_start_0|>
self.rulesFuzzyDisplay = rulesFuzzyDisplay
self.fuzzy_sets = rulesFuzzyDisplay.fuzzy_sets
self.new_rule_root = Toplevel()
self.new_rule_root.title("Création d'une nouvelle règle")
Label(self.new_rule_root, text='Conditions :').grid(row=0, padx='0.3c')
Lab... | RuleCreation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RuleCreation:
def __init__(self, rulesFuzzyDisplay):
"""Allows the user to create a new rule. a description is automatically generated"""
<|body_0|>
def validate(self):
"""This function is called when the button "creer" is pressed in the creation form. It saves the n... | stack_v2_sparse_classes_36k_train_026566 | 8,831 | no_license | [
{
"docstring": "Allows the user to create a new rule. a description is automatically generated",
"name": "__init__",
"signature": "def __init__(self, rulesFuzzyDisplay)"
},
{
"docstring": "This function is called when the button \"creer\" is pressed in the creation form. It saves the new rule in... | 2 | stack_v2_sparse_classes_30k_train_021004 | Implement the Python class `RuleCreation` described below.
Class description:
Implement the RuleCreation class.
Method signatures and docstrings:
- def __init__(self, rulesFuzzyDisplay): Allows the user to create a new rule. a description is automatically generated
- def validate(self): This function is called when t... | Implement the Python class `RuleCreation` described below.
Class description:
Implement the RuleCreation class.
Method signatures and docstrings:
- def __init__(self, rulesFuzzyDisplay): Allows the user to create a new rule. a description is automatically generated
- def validate(self): This function is called when t... | 989f4050816d1241e41e36e4e6d95784ff4dff1c | <|skeleton|>
class RuleCreation:
def __init__(self, rulesFuzzyDisplay):
"""Allows the user to create a new rule. a description is automatically generated"""
<|body_0|>
def validate(self):
"""This function is called when the button "creer" is pressed in the creation form. It saves the n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RuleCreation:
def __init__(self, rulesFuzzyDisplay):
"""Allows the user to create a new rule. a description is automatically generated"""
self.rulesFuzzyDisplay = rulesFuzzyDisplay
self.fuzzy_sets = rulesFuzzyDisplay.fuzzy_sets
self.new_rule_root = Toplevel()
self.new_r... | the_stack_v2_python_sparse | User_interface/UI_Rules_Fuzzy.py | brieglhostis/ExpertSystems | train | 0 | |
ac29afa47da058381d4669c8ec3359d232ef54cd | [
"title = ['ID', '接口描述', '请求方式', 'API', '参数', '执行时间', '状态码', '执行结果']\nif not os.path.exists('%s' % self.report_path):\n workbook = xlwt.Workbook(encoding='utf-8')\n worksheet = workbook.add_sheet(self.sheet_name)\n self.col_width(title, worksheet)\n workbook.save('%s' % self.report_path)\nelse:\n open... | <|body_start_0|>
title = ['ID', '接口描述', '请求方式', 'API', '参数', '执行时间', '状态码', '执行结果']
if not os.path.exists('%s' % self.report_path):
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet(self.sheet_name)
self.col_width(title, worksheet)
... | 日志文件相关操作 | GetReport | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetReport:
"""日志文件相关操作"""
def get_report(self):
"""生成xls文件 :param sheet_name:工作表名称"""
<|body_0|>
def col_width(self, title, worksheet):
"""设置表格列宽、表头内容 :param title: 表头 :param worksheet: 工作表"""
<|body_1|>
def style(self):
"""设置单元格格式 :return:[s... | stack_v2_sparse_classes_36k_train_026567 | 5,047 | no_license | [
{
"docstring": "生成xls文件 :param sheet_name:工作表名称",
"name": "get_report",
"signature": "def get_report(self)"
},
{
"docstring": "设置表格列宽、表头内容 :param title: 表头 :param worksheet: 工作表",
"name": "col_width",
"signature": "def col_width(self, title, worksheet)"
},
{
"docstring": "设置单元格格式... | 5 | stack_v2_sparse_classes_30k_train_017133 | Implement the Python class `GetReport` described below.
Class description:
日志文件相关操作
Method signatures and docstrings:
- def get_report(self): 生成xls文件 :param sheet_name:工作表名称
- def col_width(self, title, worksheet): 设置表格列宽、表头内容 :param title: 表头 :param worksheet: 工作表
- def style(self): 设置单元格格式 :return:[style_title, sty... | Implement the Python class `GetReport` described below.
Class description:
日志文件相关操作
Method signatures and docstrings:
- def get_report(self): 生成xls文件 :param sheet_name:工作表名称
- def col_width(self, title, worksheet): 设置表格列宽、表头内容 :param title: 表头 :param worksheet: 工作表
- def style(self): 设置单元格格式 :return:[style_title, sty... | c47c157d7b96b6182ae7e885d5f940af3d56e69e | <|skeleton|>
class GetReport:
"""日志文件相关操作"""
def get_report(self):
"""生成xls文件 :param sheet_name:工作表名称"""
<|body_0|>
def col_width(self, title, worksheet):
"""设置表格列宽、表头内容 :param title: 表头 :param worksheet: 工作表"""
<|body_1|>
def style(self):
"""设置单元格格式 :return:[s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetReport:
"""日志文件相关操作"""
def get_report(self):
"""生成xls文件 :param sheet_name:工作表名称"""
title = ['ID', '接口描述', '请求方式', 'API', '参数', '执行时间', '状态码', '执行结果']
if not os.path.exists('%s' % self.report_path):
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = w... | the_stack_v2_python_sparse | Scripts/GetReport.py | AbigaleLiu/WuKongDianJing | train | 0 |
d30b470e4a85426f9466269f5dc90980267a1fcc | [
"ret = []\np_counter = collections.Counter(p)\ns_counter = collections.Counter(s[:len(p) - 1])\nfor i in range(len(p) - 1, len(s)):\n s_counter[s[i]] += 1\n pre_i = i - len(p) + 1\n if s_counter == p_counter:\n ret.append(pre_i)\n s_counter[s[pre_i]] -= 1\n if s_counter[s[pre_i]] == 0:\n ... | <|body_start_0|>
ret = []
p_counter = collections.Counter(p)
s_counter = collections.Counter(s[:len(p) - 1])
for i in range(len(p) - 1, len(s)):
s_counter[s[i]] += 1
pre_i = i - len(p) + 1
if s_counter == p_counter:
ret.append(pre_i)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = []
p_coun... | stack_v2_sparse_classes_36k_train_026568 | 1,384 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams",
"signature": "def findAnagrams(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams",
"signature": "def findAnagrams(self, s, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020800 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
<|skeleton|>
class Solution... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
ret = []
p_counter = collections.Counter(p)
s_counter = collections.Counter(s[:len(p) - 1])
for i in range(len(p) - 1, len(s)):
s_counter[s[i]] += 1
pre_i =... | the_stack_v2_python_sparse | problems/findAnagrams.py | joddiy/leetcode | train | 1 | |
a89021bfbc7ba91d665dc548b8bd850efbf2393d | [
"self.num_classes = num_classes\nself.num_models = num_models\nif class_names is None:\n class_names = map(str, range(num_classes))\nassert len(class_names) == num_classes, 'ERROR! No. of classes in class_names \\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tshould be equal to num_classes.'\nif isinstance(class_names, np.nd... | <|body_start_0|>
self.num_classes = num_classes
self.num_models = num_models
if class_names is None:
class_names = map(str, range(num_classes))
assert len(class_names) == num_classes, 'ERROR! No. of classes in class_names \t\t\t\t\t\t\t\t\t\t\t\tshould be equal to num_classes... | the class of Dempster-Shafer Theory (DST) and Dempster's Rule of Combination (DRC) | DST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DST:
"""the class of Dempster-Shafer Theory (DST) and Dempster's Rule of Combination (DRC)"""
def __init__(self, num_models, num_classes, class_names=None):
"""Description: * class names are present in class_names Input arguments: * num_models: no. of models * num_classes: no. of cla... | stack_v2_sparse_classes_36k_train_026569 | 6,507 | no_license | [
{
"docstring": "Description: * class names are present in class_names Input arguments: * num_models: no. of models * num_classes: no. of classes * class_names: actual class names Return: * self",
"name": "__init__",
"signature": "def __init__(self, num_models, num_classes, class_names=None)"
},
{
... | 6 | null | Implement the Python class `DST` described below.
Class description:
the class of Dempster-Shafer Theory (DST) and Dempster's Rule of Combination (DRC)
Method signatures and docstrings:
- def __init__(self, num_models, num_classes, class_names=None): Description: * class names are present in class_names Input argumen... | Implement the Python class `DST` described below.
Class description:
the class of Dempster-Shafer Theory (DST) and Dempster's Rule of Combination (DRC)
Method signatures and docstrings:
- def __init__(self, num_models, num_classes, class_names=None): Description: * class names are present in class_names Input argumen... | 80a89e8ab8a457433b5bde4a7d254bc66e663df0 | <|skeleton|>
class DST:
"""the class of Dempster-Shafer Theory (DST) and Dempster's Rule of Combination (DRC)"""
def __init__(self, num_models, num_classes, class_names=None):
"""Description: * class names are present in class_names Input arguments: * num_models: no. of models * num_classes: no. of cla... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DST:
"""the class of Dempster-Shafer Theory (DST) and Dempster's Rule of Combination (DRC)"""
def __init__(self, num_models, num_classes, class_names=None):
"""Description: * class names are present in class_names Input arguments: * num_models: no. of models * num_classes: no. of classes * class_... | the_stack_v2_python_sparse | Naveen/Backup/DST.py | nmadapan/AHRQ_Gesture_Recognition | train | 2 |
7470740510f1e5513510c2f6dc9230c7bb2e0eae | [
"if db_field.name == 'ldap_bind_cred':\n kwargs['queryset'] = models.LDAPBindCred.active\n kwargs['initial'] = models.LDAPBindCred.default()\nelif db_field.name == 'ad_orion_node':\n kwargs['queryset'] = models.OrionADNode.active\nelif db_field.name == 'ad_node':\n kwargs['queryset'] = models.NonOrionAD... | <|body_start_0|>
if db_field.name == 'ldap_bind_cred':
kwargs['queryset'] = models.LDAPBindCred.active
kwargs['initial'] = models.LDAPBindCred.default()
elif db_field.name == 'ad_orion_node':
kwargs['queryset'] = models.OrionADNode.active
elif db_field.name ==... | Base class for other :class:`Django admin classes <django.contrib.admin.ModelAdmin>` in this module | LdapProbeBaseAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LdapProbeBaseAdmin:
"""Base class for other :class:`Django admin classes <django.contrib.admin.ModelAdmin>` in this module"""
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""override :meth:`django.contrib.admin.ModelAdmin.formfield_for_foreignkey` provide speciali... | stack_v2_sparse_classes_36k_train_026570 | 13,168 | no_license | [
{
"docstring": "override :meth:`django.contrib.admin.ModelAdmin.formfield_for_foreignkey` provide specialized drop-down values for 'ldap_bind_cred`, `ad_orion_node`, and `ad_node` `ForeignKey` fields.",
"name": "formfield_for_foreignkey",
"signature": "def formfield_for_foreignkey(self, db_field, reques... | 4 | stack_v2_sparse_classes_30k_val_001141 | Implement the Python class `LdapProbeBaseAdmin` described below.
Class description:
Base class for other :class:`Django admin classes <django.contrib.admin.ModelAdmin>` in this module
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): override :meth:`django.contrib.ad... | Implement the Python class `LdapProbeBaseAdmin` described below.
Class description:
Base class for other :class:`Django admin classes <django.contrib.admin.ModelAdmin>` in this module
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): override :meth:`django.contrib.ad... | 08bf0cc90e4d63a84fcd4e35bf5d196430c43319 | <|skeleton|>
class LdapProbeBaseAdmin:
"""Base class for other :class:`Django admin classes <django.contrib.admin.ModelAdmin>` in this module"""
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""override :meth:`django.contrib.admin.ModelAdmin.formfield_for_foreignkey` provide speciali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LdapProbeBaseAdmin:
"""Base class for other :class:`Django admin classes <django.contrib.admin.ModelAdmin>` in this module"""
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""override :meth:`django.contrib.admin.ModelAdmin.formfield_for_foreignkey` provide specialized drop-down... | the_stack_v2_python_sparse | ldap_probe/admin.py | PHSAServiceOperationsCenter/PHSA-SOC | train | 0 |
35ddd38d6826e00069c13ed51297f8659f19ee58 | [
"primary_controller = self.env.primary_controller\nprimary_node = devops_env.get_node_by_fuel_node(primary_controller)\nself.env.warm_shutdown_nodes([primary_node])\nname = 'Test_{}'.format(suffix[:6])\ncmd = 'image-create --name {name} --container-format bare --disk-format qcow2 --file {file}'.format(name=name, fi... | <|body_start_0|>
primary_controller = self.env.primary_controller
primary_node = devops_env.get_node_by_fuel_node(primary_controller)
self.env.warm_shutdown_nodes([primary_node])
name = 'Test_{}'.format(suffix[:6])
cmd = 'image-create --name {name} --container-format bare --disk-... | TestGlanceHA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGlanceHA:
def test_shutdown_primary_controller(self, glance, image_file, suffix, devops_env, timeout=60):
"""Check creating image after shutdown primary controller Steps: 1. Shutdown primary controller 2. Create image from `image_file` 3. Check that image is present in list and image... | stack_v2_sparse_classes_36k_train_026571 | 7,990 | no_license | [
{
"docstring": "Check creating image after shutdown primary controller Steps: 1. Shutdown primary controller 2. Create image from `image_file` 3. Check that image is present in list and image status is `active` 4. Delete created image 5. Check that image deleted",
"name": "test_shutdown_primary_controller",... | 3 | null | Implement the Python class `TestGlanceHA` described below.
Class description:
Implement the TestGlanceHA class.
Method signatures and docstrings:
- def test_shutdown_primary_controller(self, glance, image_file, suffix, devops_env, timeout=60): Check creating image after shutdown primary controller Steps: 1. Shutdown ... | Implement the Python class `TestGlanceHA` described below.
Class description:
Implement the TestGlanceHA class.
Method signatures and docstrings:
- def test_shutdown_primary_controller(self, glance, image_file, suffix, devops_env, timeout=60): Check creating image after shutdown primary controller Steps: 1. Shutdown ... | 8aced2855b78b5f123195d188c80e27b43888a2e | <|skeleton|>
class TestGlanceHA:
def test_shutdown_primary_controller(self, glance, image_file, suffix, devops_env, timeout=60):
"""Check creating image after shutdown primary controller Steps: 1. Shutdown primary controller 2. Create image from `image_file` 3. Check that image is present in list and image... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestGlanceHA:
def test_shutdown_primary_controller(self, glance, image_file, suffix, devops_env, timeout=60):
"""Check creating image after shutdown primary controller Steps: 1. Shutdown primary controller 2. Create image from `image_file` 3. Check that image is present in list and image status is `ac... | the_stack_v2_python_sparse | mos_tests/glance/ha_test.py | Mirantis/mos-integration-tests | train | 16 | |
bd1733748dd9b82f4766d6ca9c63593826e991b7 | [
"threading.Thread.__init__(self)\nself.hass = hass\nself.stopped = threading.Event()\nself.on_receive = on_receive\nself.client = client\nself.events = events\nself.started = False\nself.channel = channel",
"self.started = True\n_LOGGER.info('Starting DahuaEventThread')\nwhile True:\n if not self.started:\n ... | <|body_start_0|>
threading.Thread.__init__(self)
self.hass = hass
self.stopped = threading.Event()
self.on_receive = on_receive
self.client = client
self.events = events
self.started = False
self.channel = channel
<|end_body_0|>
<|body_start_1|>
s... | Connects to device and subscribes to events. Mainly to capture motion detection events. | DahuaEventThread | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DahuaEventThread:
"""Connects to device and subscribes to events. Mainly to capture motion detection events."""
def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive, events: list, channel: int):
"""Construct a thread listening for events."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_026572 | 5,648 | permissive | [
{
"docstring": "Construct a thread listening for events.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive, events: list, channel: int)"
},
{
"docstring": "Fetch events",
"name": "run",
"signature": "def run(self)"
},
{
"d... | 3 | null | Implement the Python class `DahuaEventThread` described below.
Class description:
Connects to device and subscribes to events. Mainly to capture motion detection events.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive, events: list, channel: int): Construct ... | Implement the Python class `DahuaEventThread` described below.
Class description:
Connects to device and subscribes to events. Mainly to capture motion detection events.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive, events: list, channel: int): Construct ... | 1048a33ab025208228ca2b99375f052577514e42 | <|skeleton|>
class DahuaEventThread:
"""Connects to device and subscribes to events. Mainly to capture motion detection events."""
def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive, events: list, channel: int):
"""Construct a thread listening for events."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DahuaEventThread:
"""Connects to device and subscribes to events. Mainly to capture motion detection events."""
def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive, events: list, channel: int):
"""Construct a thread listening for events."""
threading.Thread.__init__(se... | the_stack_v2_python_sparse | custom_components/dahua/thread.py | rohankapoorcom/homeassistant-config | train | 1 |
c81df7ae8a54fa15aaf1be9db65731de7e489823 | [
"subject = loader.render_to_string(subject_template_name, context)\nsubject = ''.join(subject.splitlines())\nbody = loader.render_to_string(email_template_name, context)\nemail_message = EmailMultiAlternatives(subject, body, from_email, [to_email])\nif html_email_template_name is not None:\n html_email = loader.... | <|body_start_0|>
subject = loader.render_to_string(subject_template_name, context)
subject = ''.join(subject.splitlines())
body = loader.render_to_string(email_template_name, context)
email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
if html_email_temp... | PasswordResetForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResetForm:
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None):
"""Send a django.core.mail.EmailMultiAlternatives to `to_email`."""
<|body_0|>
def get_users(self, email, user_type):
"""... | stack_v2_sparse_classes_36k_train_026573 | 10,968 | no_license | [
{
"docstring": "Send a django.core.mail.EmailMultiAlternatives to `to_email`.",
"name": "send_mail",
"signature": "def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None)"
},
{
"docstring": "Given an email, return matching use... | 3 | stack_v2_sparse_classes_30k_train_017442 | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): Send a django.core.mail.EmailMult... | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): Send a django.core.mail.EmailMult... | 97a524bfae0b490d6e1f58dd7e825eb76d984749 | <|skeleton|>
class PasswordResetForm:
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None):
"""Send a django.core.mail.EmailMultiAlternatives to `to_email`."""
<|body_0|>
def get_users(self, email, user_type):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PasswordResetForm:
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None):
"""Send a django.core.mail.EmailMultiAlternatives to `to_email`."""
subject = loader.render_to_string(subject_template_name, context)
subjec... | the_stack_v2_python_sparse | core/forms.py | Kartikjin/HMS | train | 0 | |
a57637e13030d2d006ca9a225a2765a675b9785e | [
"self.discount = discount\nself.tau = tau\nself.target_update_period = target_update_period\nself.critic = Critic(state_dim, action_dim, cross_norm=True)\nself.critic_optimizer = tf.keras.optimizers.Adam(learning_rate=critic_lr, beta_1=0.0)",
"with tf.GradientTape(watch_accessed_variables=False) as tape:\n tap... | <|body_start_0|>
self.discount = discount
self.tau = tau
self.target_update_period = target_update_period
self.critic = Critic(state_dim, action_dim, cross_norm=True)
self.critic_optimizer = tf.keras.optimizers.Adam(learning_rate=critic_lr, beta_1=0.0)
<|end_body_0|>
<|body_star... | Class performing cross norm critic fitting. | CrossNormCriticLearner | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossNormCriticLearner:
"""Class performing cross norm critic fitting."""
def __init__(self, state_dim, action_dim, critic_lr=0.0003, discount=0.99, tau=0.005, target_update_period=1):
"""Initializes critic learner. Args: state_dim: State size. action_dim: Action size. critic_lr: Cri... | stack_v2_sparse_classes_36k_train_026574 | 10,984 | permissive | [
{
"docstring": "Initializes critic learner. Args: state_dim: State size. action_dim: Action size. critic_lr: Critic learning rate. discount: MDP discount. tau: Soft target update parameter. target_update_period: Target network update period.",
"name": "__init__",
"signature": "def __init__(self, state_d... | 2 | null | Implement the Python class `CrossNormCriticLearner` described below.
Class description:
Class performing cross norm critic fitting.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, critic_lr=0.0003, discount=0.99, tau=0.005, target_update_period=1): Initializes critic learner. Args: state... | Implement the Python class `CrossNormCriticLearner` described below.
Class description:
Class performing cross norm critic fitting.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, critic_lr=0.0003, discount=0.99, tau=0.005, target_update_period=1): Initializes critic learner. Args: state... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class CrossNormCriticLearner:
"""Class performing cross norm critic fitting."""
def __init__(self, state_dim, action_dim, critic_lr=0.0003, discount=0.99, tau=0.005, target_update_period=1):
"""Initializes critic learner. Args: state_dim: State size. action_dim: Action size. critic_lr: Cri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrossNormCriticLearner:
"""Class performing cross norm critic fitting."""
def __init__(self, state_dim, action_dim, critic_lr=0.0003, discount=0.99, tau=0.005, target_update_period=1):
"""Initializes critic learner. Args: state_dim: State size. action_dim: Action size. critic_lr: Critic learning ... | the_stack_v2_python_sparse | rl_repr/batch_rl/critic.py | Jimmy-INL/google-research | train | 1 |
13f5c8ee890238f1972d00540019d43b61dfeb0e | [
"def get_depth_sum(nested_list, depth):\n for x in nested_list:\n if x.isInteger():\n result[0] += depth * x.getInteger()\n else:\n get_depth_sum(x.getList(), depth + 1)\nif not nestedList:\n return 0\nresult = [0]\nget_depth_sum(nestedList, 1)\nreturn result[0]",
"from c... | <|body_start_0|>
def get_depth_sum(nested_list, depth):
for x in nested_list:
if x.isInteger():
result[0] += depth * x.getInteger()
else:
get_depth_sum(x.getList(), depth + 1)
if not nestedList:
return 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def depthSum(self, nestedList):
""":type nestedList: List[NestedInteger] :rtype: int"""
<|body_0|>
def depthSum2(self, nestedList):
""":type nestedList: List[NestedInteger] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def ge... | stack_v2_sparse_classes_36k_train_026575 | 2,554 | no_license | [
{
"docstring": ":type nestedList: List[NestedInteger] :rtype: int",
"name": "depthSum",
"signature": "def depthSum(self, nestedList)"
},
{
"docstring": ":type nestedList: List[NestedInteger] :rtype: int",
"name": "depthSum2",
"signature": "def depthSum2(self, nestedList)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001128 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def depthSum(self, nestedList): :type nestedList: List[NestedInteger] :rtype: int
- def depthSum2(self, nestedList): :type nestedList: List[NestedInteger] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def depthSum(self, nestedList): :type nestedList: List[NestedInteger] :rtype: int
- def depthSum2(self, nestedList): :type nestedList: List[NestedInteger] :rtype: int
<|skeleton... | 18ed31a3edf20a3e5a0b7a0b56acca5b98939693 | <|skeleton|>
class Solution:
def depthSum(self, nestedList):
""":type nestedList: List[NestedInteger] :rtype: int"""
<|body_0|>
def depthSum2(self, nestedList):
""":type nestedList: List[NestedInteger] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def depthSum(self, nestedList):
""":type nestedList: List[NestedInteger] :rtype: int"""
def get_depth_sum(nested_list, depth):
for x in nested_list:
if x.isInteger():
result[0] += depth * x.getInteger()
else:
... | the_stack_v2_python_sparse | exercises/array/nested_list_weight_sum_i.py | nahgnaw/data-structure | train | 0 | |
caf083eb67f04310670b050b0707ef54be1b9537 | [
"n = len(nums)\ndp = [0] * n\ndp[-1] = 1\nfor i in range(n - 2, -1, -1):\n for j in range(i + 1, n):\n if dp[j] == 1 and nums[i] >= j - i:\n dp[i] = 1\n break\nreturn dp[0]",
"n = len(nums)\ndp = [False] * n\ndp[-1] = True\nindex = n - 1\nfor i in range(n - 2, -1, -1):\n if inde... | <|body_start_0|>
n = len(nums)
dp = [0] * n
dp[-1] = 1
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if dp[j] == 1 and nums[i] >= j - i:
dp[i] = 1
break
return dp[0]
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_2... | stack_v2_sparse_classes_36k_train_026576 | 1,572 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump",
"signature": "def canJump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump",
"signature": "def canJump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",... | 4 | stack_v2_sparse_classes_30k_test_000515 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def canJump(self, nums): :type nums: List[int] :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def canJump(self, nums): :type nums: List[int] :rtype:... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
n = len(nums)
dp = [0] * n
dp[-1] = 1
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if dp[j] == 1 and nums[i] >= j - i:
dp[i] = 1
... | the_stack_v2_python_sparse | 0055_Jump_Game.py | bingli8802/leetcode | train | 0 | |
26aff93bc0df9aa22e1b2e111b25105004d5a7c8 | [
"self._DebugPrintValue('Unknown1', f'0x{user_assist_entry.unknown1:08x}')\nself._DebugPrintDecimalValue('Number of executions', user_assist_entry.number_of_executions)\nif format_version == 5:\n self._DebugPrintDecimalValue('Application focus count', user_assist_entry.application_focus_count)\n self._DebugPri... | <|body_start_0|>
self._DebugPrintValue('Unknown1', f'0x{user_assist_entry.unknown1:08x}')
self._DebugPrintDecimalValue('Number of executions', user_assist_entry.number_of_executions)
if format_version == 5:
self._DebugPrintDecimalValue('Application focus count', user_assist_entry.app... | UserAssist data parser. | UserAssistDataParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAssistDataParser:
"""UserAssist data parser."""
def _DebugPrintEntry(self, format_version, user_assist_entry):
"""Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entry (user_assist_entry_v3|user_assist_entry_v5): UserAssist... | stack_v2_sparse_classes_36k_train_026577 | 7,377 | permissive | [
{
"docstring": "Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entry (user_assist_entry_v3|user_assist_entry_v5): UserAssist entry.",
"name": "_DebugPrintEntry",
"signature": "def _DebugPrintEntry(self, format_version, user_assist_entry)"
},
... | 2 | stack_v2_sparse_classes_30k_train_007099 | Implement the Python class `UserAssistDataParser` described below.
Class description:
UserAssist data parser.
Method signatures and docstrings:
- def _DebugPrintEntry(self, format_version, user_assist_entry): Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entr... | Implement the Python class `UserAssistDataParser` described below.
Class description:
UserAssist data parser.
Method signatures and docstrings:
- def _DebugPrintEntry(self, format_version, user_assist_entry): Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entr... | d149aff1b8ff97e1cc8d7416fc583b964bad4ccd | <|skeleton|>
class UserAssistDataParser:
"""UserAssist data parser."""
def _DebugPrintEntry(self, format_version, user_assist_entry):
"""Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entry (user_assist_entry_v3|user_assist_entry_v5): UserAssist... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserAssistDataParser:
"""UserAssist data parser."""
def _DebugPrintEntry(self, format_version, user_assist_entry):
"""Prints UserAssist entry value debug information. Args: format_version (int): format version. user_assist_entry (user_assist_entry_v3|user_assist_entry_v5): UserAssist entry."""
... | the_stack_v2_python_sparse | winregrc/userassist.py | libyal/winreg-kb | train | 129 |
37c55f55754b8506b8d570c0c109b4e154eeee2c | [
"model = super(CompileImageFactory, cls).create(**settings)\nif not model.time_stamp:\n cls.set_time_stamp_from_path(model)\nif model.index < 0:\n cls.set_index_from_path(model)\nreturn model",
"if model.index >= 0:\n return True\nreturn model.FIELD_TYPES.index",
"if os.path.abspath(model.path) == mode... | <|body_start_0|>
model = super(CompileImageFactory, cls).create(**settings)
if not model.time_stamp:
cls.set_time_stamp_from_path(model)
if model.index < 0:
cls.set_index_from_path(model)
return model
<|end_body_0|>
<|body_start_1|>
if model.index >= 0:
... | CompileImageFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompileImageFactory:
def create(cls, **settings):
""":rtype : scanomatic.models.compile_project_model.CompileImageModel"""
<|body_0|>
def _validate_index(cls, model):
""":type model: scanomatic.models.compile_project_model.CompileImageModel"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_026578 | 7,881 | no_license | [
{
"docstring": ":rtype : scanomatic.models.compile_project_model.CompileImageModel",
"name": "create",
"signature": "def create(cls, **settings)"
},
{
"docstring": ":type model: scanomatic.models.compile_project_model.CompileImageModel",
"name": "_validate_index",
"signature": "def _vali... | 6 | null | Implement the Python class `CompileImageFactory` described below.
Class description:
Implement the CompileImageFactory class.
Method signatures and docstrings:
- def create(cls, **settings): :rtype : scanomatic.models.compile_project_model.CompileImageModel
- def _validate_index(cls, model): :type model: scanomatic.m... | Implement the Python class `CompileImageFactory` described below.
Class description:
Implement the CompileImageFactory class.
Method signatures and docstrings:
- def create(cls, **settings): :rtype : scanomatic.models.compile_project_model.CompileImageModel
- def _validate_index(cls, model): :type model: scanomatic.m... | db5dd2e8501d9db8fb0fd8fbf5c9ddd652ae8fdf | <|skeleton|>
class CompileImageFactory:
def create(cls, **settings):
""":rtype : scanomatic.models.compile_project_model.CompileImageModel"""
<|body_0|>
def _validate_index(cls, model):
""":type model: scanomatic.models.compile_project_model.CompileImageModel"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompileImageFactory:
def create(cls, **settings):
""":rtype : scanomatic.models.compile_project_model.CompileImageModel"""
model = super(CompileImageFactory, cls).create(**settings)
if not model.time_stamp:
cls.set_time_stamp_from_path(model)
if model.index < 0:
... | the_stack_v2_python_sparse | scanomatic/models/factories/compile_project_factory.py | StenbergSimon/scanomatic | train | 0 | |
fd5b7ad897b16403c7985e92e02f6de39e926b65 | [
"for child in self.children:\n if hasattr(child, attr):\n if value is not None and getattr(child, attr) == value or value is None:\n return child\n result = Searchable.find_by(child, attr, value)\n if result is not None:\n return result\nreturn None",
"result = []\nfor child in s... | <|body_start_0|>
for child in self.children:
if hasattr(child, attr):
if value is not None and getattr(child, attr) == value or value is None:
return child
result = Searchable.find_by(child, attr, value)
if result is not None:
... | Allows classes that have a "children" array to be searched by using some convenience methods. | Searchable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Searchable:
"""Allows classes that have a "children" array to be searched by using some convenience methods."""
def find_by(self, attr, value=None):
"""Returns the first child that has an attr that is equal to value. If value is not defined, then it will return the first child that h... | stack_v2_sparse_classes_36k_train_026579 | 2,593 | permissive | [
{
"docstring": "Returns the first child that has an attr that is equal to value. If value is not defined, then it will return the first child that has that attribute defined.",
"name": "find_by",
"signature": "def find_by(self, attr, value=None)"
},
{
"docstring": "Returns all the children that ... | 4 | stack_v2_sparse_classes_30k_train_011733 | Implement the Python class `Searchable` described below.
Class description:
Allows classes that have a "children" array to be searched by using some convenience methods.
Method signatures and docstrings:
- def find_by(self, attr, value=None): Returns the first child that has an attr that is equal to value. If value i... | Implement the Python class `Searchable` described below.
Class description:
Allows classes that have a "children" array to be searched by using some convenience methods.
Method signatures and docstrings:
- def find_by(self, attr, value=None): Returns the first child that has an attr that is equal to value. If value i... | 31773128238830d3d335c1915877dc0db56836cd | <|skeleton|>
class Searchable:
"""Allows classes that have a "children" array to be searched by using some convenience methods."""
def find_by(self, attr, value=None):
"""Returns the first child that has an attr that is equal to value. If value is not defined, then it will return the first child that h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Searchable:
"""Allows classes that have a "children" array to be searched by using some convenience methods."""
def find_by(self, attr, value=None):
"""Returns the first child that has an attr that is equal to value. If value is not defined, then it will return the first child that has that attri... | the_stack_v2_python_sparse | fp_py/src/main/fruitpunch/searchable.py | leolimasa/fruitpunch | train | 0 |
3724d6f00822427e3252c6c4eadfc53cd90bdc30 | [
"m = len(y)\nsum_of_square_errors = np.square(np.dot(X, self.w) - y).sum()\ncost = sum_of_square_errors / (2 * m)\nreturn cost",
"tic = time.time()\nif self.train_type == 'Parallel':\n self.w = self.w_hat\n count = 0\n tic = time.time()\n for i in range(self.torque):\n count += 1\n loss ... | <|body_start_0|>
m = len(y)
sum_of_square_errors = np.square(np.dot(X, self.w) - y).sum()
cost = sum_of_square_errors / (2 * m)
return cost
<|end_body_0|>
<|body_start_1|>
tic = time.time()
if self.train_type == 'Parallel':
self.w = self.w_hat
cou... | LinearRegression | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearRegression:
def compute_loss(self, X, y):
"""Computing loss according to OLS Args: X: Features, shape = (# of samples, # of features) y: Target, shape = (1, # of samples) Returns: loss"""
<|body_0|>
def fit(self, X, y):
"""Implement l2-linear regression by Grad... | stack_v2_sparse_classes_36k_train_026580 | 2,582 | no_license | [
{
"docstring": "Computing loss according to OLS Args: X: Features, shape = (# of samples, # of features) y: Target, shape = (1, # of samples) Returns: loss",
"name": "compute_loss",
"signature": "def compute_loss(self, X, y)"
},
{
"docstring": "Implement l2-linear regression by Gradient descent.... | 2 | stack_v2_sparse_classes_30k_train_014439 | Implement the Python class `LinearRegression` described below.
Class description:
Implement the LinearRegression class.
Method signatures and docstrings:
- def compute_loss(self, X, y): Computing loss according to OLS Args: X: Features, shape = (# of samples, # of features) y: Target, shape = (1, # of samples) Return... | Implement the Python class `LinearRegression` described below.
Class description:
Implement the LinearRegression class.
Method signatures and docstrings:
- def compute_loss(self, X, y): Computing loss according to OLS Args: X: Features, shape = (# of samples, # of features) y: Target, shape = (1, # of samples) Return... | 4d1e09ddbb84b7fdc23e030edd8cd833824c1b9f | <|skeleton|>
class LinearRegression:
def compute_loss(self, X, y):
"""Computing loss according to OLS Args: X: Features, shape = (# of samples, # of features) y: Target, shape = (1, # of samples) Returns: loss"""
<|body_0|>
def fit(self, X, y):
"""Implement l2-linear regression by Grad... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearRegression:
def compute_loss(self, X, y):
"""Computing loss according to OLS Args: X: Features, shape = (# of samples, # of features) y: Target, shape = (1, # of samples) Returns: loss"""
m = len(y)
sum_of_square_errors = np.square(np.dot(X, self.w) - y).sum()
cost = sum_... | the_stack_v2_python_sparse | classifier/linearRegression.py | BiggyBing/Parallel | train | 2 | |
0479d29589366db6eb55c5277df3a19f5146280d | [
"query = object_session(self).query(self.__class__)\nquery = query.order_by(self.__class__.order_within_agency)\nquery = query.filter(self.__class__.agency == self.agency)\nreturn query",
"query = object_session(self).query(self.__class__)\nquery = query.order_by(self.__class__.order_within_person)\nquery = query... | <|body_start_0|>
query = object_session(self).query(self.__class__)
query = query.order_by(self.__class__.order_within_agency)
query = query.filter(self.__class__.agency == self.agency)
return query
<|end_body_0|>
<|body_start_1|>
query = object_session(self).query(self.__class_... | A membership to an agency. | AgencyMembership | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgencyMembership:
"""A membership to an agency."""
def siblings_by_agency(self):
"""Returns a query that includes all siblings by agency, including the item itself ordered by `order_within_agency`."""
<|body_0|>
def siblings_by_person(self):
"""Returns a query th... | stack_v2_sparse_classes_36k_train_026581 | 4,034 | permissive | [
{
"docstring": "Returns a query that includes all siblings by agency, including the item itself ordered by `order_within_agency`.",
"name": "siblings_by_agency",
"signature": "def siblings_by_agency(self)"
},
{
"docstring": "Returns a query that includes all siblings by person, including the ite... | 3 | null | Implement the Python class `AgencyMembership` described below.
Class description:
A membership to an agency.
Method signatures and docstrings:
- def siblings_by_agency(self): Returns a query that includes all siblings by agency, including the item itself ordered by `order_within_agency`.
- def siblings_by_person(self... | Implement the Python class `AgencyMembership` described below.
Class description:
A membership to an agency.
Method signatures and docstrings:
- def siblings_by_agency(self): Returns a query that includes all siblings by agency, including the item itself ordered by `order_within_agency`.
- def siblings_by_person(self... | c706b38d5b67692b4146cdf14ef24d971a32c6b8 | <|skeleton|>
class AgencyMembership:
"""A membership to an agency."""
def siblings_by_agency(self):
"""Returns a query that includes all siblings by agency, including the item itself ordered by `order_within_agency`."""
<|body_0|>
def siblings_by_person(self):
"""Returns a query th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgencyMembership:
"""A membership to an agency."""
def siblings_by_agency(self):
"""Returns a query that includes all siblings by agency, including the item itself ordered by `order_within_agency`."""
query = object_session(self).query(self.__class__)
query = query.order_by(self._... | the_stack_v2_python_sparse | src/onegov/people/models/membership.py | OneGov/onegov-cloud | train | 17 |
4d8703ab469b53407c3e2000c50416251ace5eed | [
"dummy_head = ListNode(0)\ndummy_head.next = head\nif n == m:\n return dummy_head.next\ni = 1\npre = dummy_head\nwhile i < m:\n pre = pre.next\n i += 1\ntemp_head = None\ntail = pre.next\nwhile i < n:\n cur = pre.next\n pre.next = cur.next\n cur.next = temp_head\n temp_head = cur\n i += 1\nn... | <|body_start_0|>
dummy_head = ListNode(0)
dummy_head.next = head
if n == m:
return dummy_head.next
i = 1
pre = dummy_head
while i < m:
pre = pre.next
i += 1
temp_head = None
tail = pre.next
while i < n:
... | ReverseLinkedList2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReverseLinkedList2:
def reverse_between(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_0|>
def reverse_between_dj(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_... | stack_v2_sparse_classes_36k_train_026582 | 2,382 | no_license | [
{
"docstring": ":type head: ListNode :type m: int :type n: int :rtype: ListNode",
"name": "reverse_between",
"signature": "def reverse_between(self, head, m, n)"
},
{
"docstring": ":type head: ListNode :type m: int :type n: int :rtype: ListNode",
"name": "reverse_between_dj",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_008953 | Implement the Python class `ReverseLinkedList2` described below.
Class description:
Implement the ReverseLinkedList2 class.
Method signatures and docstrings:
- def reverse_between(self, head, m, n): :type head: ListNode :type m: int :type n: int :rtype: ListNode
- def reverse_between_dj(self, head, m, n): :type head:... | Implement the Python class `ReverseLinkedList2` described below.
Class description:
Implement the ReverseLinkedList2 class.
Method signatures and docstrings:
- def reverse_between(self, head, m, n): :type head: ListNode :type m: int :type n: int :rtype: ListNode
- def reverse_between_dj(self, head, m, n): :type head:... | e41f4ac9e99b9272ed4718680f4d12fd7443db03 | <|skeleton|>
class ReverseLinkedList2:
def reverse_between(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_0|>
def reverse_between_dj(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReverseLinkedList2:
def reverse_between(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
dummy_head = ListNode(0)
dummy_head.next = head
if n == m:
return dummy_head.next
i = 1
pre = dummy_head
while i ... | the_stack_v2_python_sparse | tags/linked_list/reverse_linked_list2.py | jied314/IQs | train | 0 | |
caf0cefc987a3c08109cf8ff88999f5e1878a698 | [
"if len(s) < 1:\n return 0\ni, max_len = (0, 0)\nc = 0\nfor i in range(len(s)):\n j = 0\n while i - j >= 0 and i + j < len(s):\n if s[i - j] != s[i + j]:\n break\n c = 2 * j + 1\n j += 1\n max_len = max(max_len, c)\n j = 0\n while i - j >= 0 and i + j + 1 < len(s):\... | <|body_start_0|>
if len(s) < 1:
return 0
i, max_len = (0, 0)
c = 0
for i in range(len(s)):
j = 0
while i - j >= 0 and i + j < len(s):
if s[i - j] != s[i + j]:
break
c = 2 * j + 1
j += ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def LPS_basic(self, s):
"""枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度 :param s: :return:"""
<|body_0|>
def manacher(self, s):
"""manacher算法 step 1: 令RL[i]=min(RL[2*pos-i], MaxRight-i) step 2: 以i为中心扩展回文串,直到左右两边字符不同,或者到达边界。 step 3: 更新MaxRight和pos reference:https://s... | stack_v2_sparse_classes_36k_train_026583 | 2,050 | no_license | [
{
"docstring": "枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度 :param s: :return:",
"name": "LPS_basic",
"signature": "def LPS_basic(self, s)"
},
{
"docstring": "manacher算法 step 1: 令RL[i]=min(RL[2*pos-i], MaxRight-i) step 2: 以i为中心扩展回文串,直到左右两边字符不同,或者到达边界。 step 3: 更新MaxRight和pos reference:https://segmentfaul... | 2 | stack_v2_sparse_classes_30k_val_000507 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def LPS_basic(self, s): 枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度 :param s: :return:
- def manacher(self, s): manacher算法 step 1: 令RL[i]=min(RL[2*pos-i], MaxRight-i) step 2: 以i为中心扩展回文串,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def LPS_basic(self, s): 枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度 :param s: :return:
- def manacher(self, s): manacher算法 step 1: 令RL[i]=min(RL[2*pos-i], MaxRight-i) step 2: 以i为中心扩展回文串,... | 215d513b3564a7a76db3d2b29e4acc341a68e8ee | <|skeleton|>
class Solution:
def LPS_basic(self, s):
"""枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度 :param s: :return:"""
<|body_0|>
def manacher(self, s):
"""manacher算法 step 1: 令RL[i]=min(RL[2*pos-i], MaxRight-i) step 2: 以i为中心扩展回文串,直到左右两边字符不同,或者到达边界。 step 3: 更新MaxRight和pos reference:https://s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def LPS_basic(self, s):
"""枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度 :param s: :return:"""
if len(s) < 1:
return 0
i, max_len = (0, 0)
c = 0
for i in range(len(s)):
j = 0
while i - j >= 0 and i + j < len(s):
if s[i... | the_stack_v2_python_sparse | python/dp/longest-palindrome-substring.py | euxuoh/leetcode | train | 0 | |
b584c2df4b677e43de1b1bfa77e51f7b47fee9b4 | [
"self.name = buffer_name\nself.poligons = []\ncur = con.cursor()\ncur.execute('select id from acumulos.buffers where nome=%s', (self.name,))\nids = cur.fetchall()\nself.id = ids[0][0]",
"cur = con.cursor()\ncur.execute('select id,st_astext(poligono) from acumulos.poligonos where id_buffer=%s', (self.id,))\nrespos... | <|body_start_0|>
self.name = buffer_name
self.poligons = []
cur = con.cursor()
cur.execute('select id from acumulos.buffers where nome=%s', (self.name,))
ids = cur.fetchall()
self.id = ids[0][0]
<|end_body_0|>
<|body_start_1|>
cur = con.cursor()
cur.execu... | Clase Buffer | Buffer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Buffer:
"""Clase Buffer"""
def __init__(self, con, buffer_name):
"""Inicializa o buffer dando un nome :param con: conexión activa :param buffer_name: Nome de buffer na base de datos"""
<|body_0|>
def fill_poligons(self, con):
"""Enche unha lista cos polígonos :pa... | stack_v2_sparse_classes_36k_train_026584 | 2,140 | no_license | [
{
"docstring": "Inicializa o buffer dando un nome :param con: conexión activa :param buffer_name: Nome de buffer na base de datos",
"name": "__init__",
"signature": "def __init__(self, con, buffer_name)"
},
{
"docstring": "Enche unha lista cos polígonos :param con: conexión :return:",
"name"... | 3 | stack_v2_sparse_classes_30k_train_000367 | Implement the Python class `Buffer` described below.
Class description:
Clase Buffer
Method signatures and docstrings:
- def __init__(self, con, buffer_name): Inicializa o buffer dando un nome :param con: conexión activa :param buffer_name: Nome de buffer na base de datos
- def fill_poligons(self, con): Enche unha li... | Implement the Python class `Buffer` described below.
Class description:
Clase Buffer
Method signatures and docstrings:
- def __init__(self, con, buffer_name): Inicializa o buffer dando un nome :param con: conexión activa :param buffer_name: Nome de buffer na base de datos
- def fill_poligons(self, con): Enche unha li... | e3c577e6048d546706df0c6191a0d0d10a58d3d8 | <|skeleton|>
class Buffer:
"""Clase Buffer"""
def __init__(self, con, buffer_name):
"""Inicializa o buffer dando un nome :param con: conexión activa :param buffer_name: Nome de buffer na base de datos"""
<|body_0|>
def fill_poligons(self, con):
"""Enche unha lista cos polígonos :pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Buffer:
"""Clase Buffer"""
def __init__(self, con, buffer_name):
"""Inicializa o buffer dando un nome :param con: conexión activa :param buffer_name: Nome de buffer na base de datos"""
self.name = buffer_name
self.poligons = []
cur = con.cursor()
cur.execute('selec... | the_stack_v2_python_sparse | cleanatlantic/buffer.py | pedromontero/CLEANATLANTIC | train | 1 |
e34e31f941b5e0cb939b7b8e9a1e51d6a1af2a2c | [
"self.attributes = attributes\nself.end_of_range = end_of_range\nself.range_type = range_type\nself.start_of_range = start_of_range",
"if dictionary is None:\n return None\nattributes = cohesity_management_sdk.models.oracle_archive_log_info_oracle_archive_log_range_range_attributes.OracleArchiveLogInfo_OracleA... | <|body_start_0|>
self.attributes = attributes
self.end_of_range = end_of_range
self.range_type = range_type
self.start_of_range = start_of_range
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
attributes = cohesity_management_sdk.models.ora... | Implementation of the 'OracleArchiveLogInfo_OracleArchiveLogRange' model. TODO: type description here. Attributes: attributes (OracleArchiveLogInfo_OracleArchiveLogRange_RangeAttributes): TODO: Type description here. end_of_range (long|int): End value of the range range_type (int): Type of range provided. start_of_rang... | OracleArchiveLogInfo_OracleArchiveLogRange | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OracleArchiveLogInfo_OracleArchiveLogRange:
"""Implementation of the 'OracleArchiveLogInfo_OracleArchiveLogRange' model. TODO: type description here. Attributes: attributes (OracleArchiveLogInfo_OracleArchiveLogRange_RangeAttributes): TODO: Type description here. end_of_range (long|int): End valu... | stack_v2_sparse_classes_36k_train_026585 | 2,708 | permissive | [
{
"docstring": "Constructor for the OracleArchiveLogInfo_OracleArchiveLogRange class",
"name": "__init__",
"signature": "def __init__(self, attributes=None, end_of_range=None, range_type=None, start_of_range=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dict... | 2 | null | Implement the Python class `OracleArchiveLogInfo_OracleArchiveLogRange` described below.
Class description:
Implementation of the 'OracleArchiveLogInfo_OracleArchiveLogRange' model. TODO: type description here. Attributes: attributes (OracleArchiveLogInfo_OracleArchiveLogRange_RangeAttributes): TODO: Type description ... | Implement the Python class `OracleArchiveLogInfo_OracleArchiveLogRange` described below.
Class description:
Implementation of the 'OracleArchiveLogInfo_OracleArchiveLogRange' model. TODO: type description here. Attributes: attributes (OracleArchiveLogInfo_OracleArchiveLogRange_RangeAttributes): TODO: Type description ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class OracleArchiveLogInfo_OracleArchiveLogRange:
"""Implementation of the 'OracleArchiveLogInfo_OracleArchiveLogRange' model. TODO: type description here. Attributes: attributes (OracleArchiveLogInfo_OracleArchiveLogRange_RangeAttributes): TODO: Type description here. end_of_range (long|int): End valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OracleArchiveLogInfo_OracleArchiveLogRange:
"""Implementation of the 'OracleArchiveLogInfo_OracleArchiveLogRange' model. TODO: type description here. Attributes: attributes (OracleArchiveLogInfo_OracleArchiveLogRange_RangeAttributes): TODO: Type description here. end_of_range (long|int): End value of the rang... | the_stack_v2_python_sparse | cohesity_management_sdk/models/oracle_archive_log_info_oracle_archive_log_range.py | cohesity/management-sdk-python | train | 24 |
02fbfaea4130980ae66479416096ab1480c88f49 | [
"self.cur_idx = 0\nself.next_idx = -1\nself.seats = [False] * N\nself.max_dis = [-1] * N\nself.N = N\nself.count = 0",
"if self.count == 0 or self.next_idx == -1:\n self.next_idx = self.N - 1\n self.seats[self.cur_idx] = True\n for i in range(self.N):\n self.max_dis[i] = i\n self.count += 1\n ... | <|body_start_0|>
self.cur_idx = 0
self.next_idx = -1
self.seats = [False] * N
self.max_dis = [-1] * N
self.N = N
self.count = 0
<|end_body_0|>
<|body_start_1|>
if self.count == 0 or self.next_idx == -1:
self.next_idx = self.N - 1
self.seat... | ExamRoom | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExamRoom:
def __init__(self, N):
""":type N: int"""
<|body_0|>
def seat(self):
""":rtype: int"""
<|body_1|>
def leave(self, p):
""":type p: int :rtype: void"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.cur_idx = 0
... | stack_v2_sparse_classes_36k_train_026586 | 2,951 | no_license | [
{
"docstring": ":type N: int",
"name": "__init__",
"signature": "def __init__(self, N)"
},
{
"docstring": ":rtype: int",
"name": "seat",
"signature": "def seat(self)"
},
{
"docstring": ":type p: int :rtype: void",
"name": "leave",
"signature": "def leave(self, p)"
}
] | 3 | stack_v2_sparse_classes_30k_val_000311 | Implement the Python class `ExamRoom` described below.
Class description:
Implement the ExamRoom class.
Method signatures and docstrings:
- def __init__(self, N): :type N: int
- def seat(self): :rtype: int
- def leave(self, p): :type p: int :rtype: void | Implement the Python class `ExamRoom` described below.
Class description:
Implement the ExamRoom class.
Method signatures and docstrings:
- def __init__(self, N): :type N: int
- def seat(self): :rtype: int
- def leave(self, p): :type p: int :rtype: void
<|skeleton|>
class ExamRoom:
def __init__(self, N):
... | c08fdd1556b6dbbdda8ad6210aa0eaa97074ae3b | <|skeleton|>
class ExamRoom:
def __init__(self, N):
""":type N: int"""
<|body_0|>
def seat(self):
""":rtype: int"""
<|body_1|>
def leave(self, p):
""":type p: int :rtype: void"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExamRoom:
def __init__(self, N):
""":type N: int"""
self.cur_idx = 0
self.next_idx = -1
self.seats = [False] * N
self.max_dis = [-1] * N
self.N = N
self.count = 0
def seat(self):
""":rtype: int"""
if self.count == 0 or self.next_idx ... | the_stack_v2_python_sparse | python/misc/problem3.py | sumitkrm/lang-1 | train | 0 | |
0eadfbfa1e83c474a949ac72b99f3851e324c0f4 | [
"is_app_engine_target_set = app_engine_http_queue is not None and app_engine_http_queue.appEngineRoutingOverride is not None\nis_http_target_set = http_target is not None\nif is_app_engine_target_set and is_http_target_set:\n raise CreatingHttpAndAppEngineQueueError('Attempting to send multiple queue target type... | <|body_start_0|>
is_app_engine_target_set = app_engine_http_queue is not None and app_engine_http_queue.appEngineRoutingOverride is not None
is_http_target_set = http_target is not None
if is_app_engine_target_set and is_http_target_set:
raise CreatingHttpAndAppEngineQueueError('Atte... | Client for queues service in the Cloud Tasks API. | BetaQueues | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BetaQueues:
"""Client for queues service in the Cloud Tasks API."""
def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_http_queue=None, stackdriver_logging_config=None, queue_type=None, http_target=None):
"""Prepares and sends a Create request for... | stack_v2_sparse_classes_36k_train_026587 | 19,528 | permissive | [
{
"docstring": "Prepares and sends a Create request for creating a queue.",
"name": "Create",
"signature": "def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_http_queue=None, stackdriver_logging_config=None, queue_type=None, http_target=None)"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_train_002542 | Implement the Python class `BetaQueues` described below.
Class description:
Client for queues service in the Cloud Tasks API.
Method signatures and docstrings:
- def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_http_queue=None, stackdriver_logging_config=None, queue_type=None, h... | Implement the Python class `BetaQueues` described below.
Class description:
Client for queues service in the Cloud Tasks API.
Method signatures and docstrings:
- def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_http_queue=None, stackdriver_logging_config=None, queue_type=None, h... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class BetaQueues:
"""Client for queues service in the Cloud Tasks API."""
def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_http_queue=None, stackdriver_logging_config=None, queue_type=None, http_target=None):
"""Prepares and sends a Create request for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BetaQueues:
"""Client for queues service in the Cloud Tasks API."""
def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_http_queue=None, stackdriver_logging_config=None, queue_type=None, http_target=None):
"""Prepares and sends a Create request for creating a q... | the_stack_v2_python_sparse | lib/googlecloudsdk/api_lib/tasks/queues.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
520386c909e26ad2d139e961a3a2d02ad3e1db31 | [
"user = request.user\nclassroom_id = request.GET.get('classrm_id', None)\nklass_id = request.GET.get('klass_id', None)\nif classroom_id is None:\n classroom = Classroom.objects.filter(opener=user, klass_id=klass_id).order_by('-finish_time').first()\nelse:\n try:\n classroom = Classroom.objects.get(id=c... | <|body_start_0|>
user = request.user
classroom_id = request.GET.get('classrm_id', None)
klass_id = request.GET.get('klass_id', None)
if classroom_id is None:
classroom = Classroom.objects.filter(opener=user, klass_id=klass_id).order_by('-finish_time').first()
else:
... | ActivityDetailReportViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivityDetailReportViewSet:
def study_detail_abstractpage(self, request):
"""学情统计首页信息 :param request: { "classroom_id": 1 不传显示最近一堂课内容 "klass_id": 1 } :return:"""
<|body_0|>
def nearest_class(self, request):
"""最近课程学情列表 :param request: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_026588 | 21,391 | no_license | [
{
"docstring": "学情统计首页信息 :param request: { \"classroom_id\": 1 不传显示最近一堂课内容 \"klass_id\": 1 } :return:",
"name": "study_detail_abstractpage",
"signature": "def study_detail_abstractpage(self, request)"
},
{
"docstring": "最近课程学情列表 :param request: :return:",
"name": "nearest_class",
"signat... | 2 | stack_v2_sparse_classes_30k_train_005519 | Implement the Python class `ActivityDetailReportViewSet` described below.
Class description:
Implement the ActivityDetailReportViewSet class.
Method signatures and docstrings:
- def study_detail_abstractpage(self, request): 学情统计首页信息 :param request: { "classroom_id": 1 不传显示最近一堂课内容 "klass_id": 1 } :return:
- def neares... | Implement the Python class `ActivityDetailReportViewSet` described below.
Class description:
Implement the ActivityDetailReportViewSet class.
Method signatures and docstrings:
- def study_detail_abstractpage(self, request): 学情统计首页信息 :param request: { "classroom_id": 1 不传显示最近一堂课内容 "klass_id": 1 } :return:
- def neares... | 4189fdcacc20795a4778b53c9d47d6fdd3e71811 | <|skeleton|>
class ActivityDetailReportViewSet:
def study_detail_abstractpage(self, request):
"""学情统计首页信息 :param request: { "classroom_id": 1 不传显示最近一堂课内容 "klass_id": 1 } :return:"""
<|body_0|>
def nearest_class(self, request):
"""最近课程学情列表 :param request: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActivityDetailReportViewSet:
def study_detail_abstractpage(self, request):
"""学情统计首页信息 :param request: { "classroom_id": 1 不传显示最近一堂课内容 "klass_id": 1 } :return:"""
user = request.user
classroom_id = request.GET.get('classrm_id', None)
klass_id = request.GET.get('klass_id', None)... | the_stack_v2_python_sparse | bigfish/apps/classrooms/views.py | hyu9999/bigfish | train | 0 | |
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_36k_train_026589 | 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 | null | 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_36k | data/stack_v2_sparse_classes_30k | 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 |
d50b86f7bc198dc08788662906e4ffc9e9d3c61c | [
"self.ans = 0\n\ndef depth(p):\n if not p:\n return 0\n left, right = (depth(p.left), depth(p.right))\n self.ans = max(self.ans, left + right)\n return 1 + max(left, right)\ndepth(root)\nreturn self.ans",
"def depth(p):\n global ans\n if not p:\n return 0\n left, right = (depth(... | <|body_start_0|>
self.ans = 0
def depth(p):
if not p:
return 0
left, right = (depth(p.left), depth(p.right))
self.ans = max(self.ans, left + right)
return 1 + max(left, right)
depth(root)
return self.ans
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def diameterOfBinaryTree2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.ans = 0
def de... | stack_v2_sparse_classes_36k_train_026590 | 1,788 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "diameterOfBinaryTree",
"signature": "def diameterOfBinaryTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "diameterOfBinaryTree2",
"signature": "def diameterOfBinaryTree2(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int
- def diameterOfBinaryTree2(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int
- def diameterOfBinaryTree2(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def diameterOfBinaryTree2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int"""
self.ans = 0
def depth(p):
if not p:
return 0
left, right = (depth(p.left), depth(p.right))
self.ans = max(self.ans, left + right)
ret... | the_stack_v2_python_sparse | D/DiameterofBinaryTree.py | bssrdf/pyleet | train | 2 | |
ab311a003b4166b2dcbf63bb49b2e480b7add91f | [
"l = len(nums)\nfor i in range(l):\n if nums[i] == 0:\n zero_pos = i\n for j in range(zero_pos + 1, l):\n if nums[j] != 0:\n nums[zero_pos], nums[j] = (nums[j], nums[zero_pos])\n break",
"s = 0\ni = 0\nfor k in nums:\n if k == 0:\n s += 1\nwhile ... | <|body_start_0|>
l = len(nums)
for i in range(l):
if nums[i] == 0:
zero_pos = i
for j in range(zero_pos + 1, l):
if nums[j] != 0:
nums[zero_pos], nums[j] = (nums[j], nums[zero_pos])
break
<|en... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
def mo... | stack_v2_sparse_classes_36k_train_026591 | 1,806 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes1",
"signature": "def moveZeroes1(self, nums: List[int]) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes2",
"signature": "def moveZeroes2(sel... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes1(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes2(self, nums: List[int]) -> None: Do not return anything, mo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes1(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes2(self, nums: List[int]) -> None: Do not return anything, mo... | 0c5e686ecc543405083714604c231a40ac786e07 | <|skeleton|>
class Solution:
def moveZeroes1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
def mo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def moveZeroes1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
l = len(nums)
for i in range(l):
if nums[i] == 0:
zero_pos = i
for j in range(zero_pos + 1, l):
if nums[... | the_stack_v2_python_sparse | 283. Move Zeroes.py | xulzee/LeetCodeProjectPython | train | 4 | |
b4f8fed26db62b207444d916c3ae8440d9c6590d | [
"super().__init__()\nassert kernel_sizes is not None and isinstance(kernel_sizes, list)\nself.kernel_sizes = kernel_sizes\nself.embedding_dim = embedding_dim\nself.output_dim = self.embedding_dim if output_dim is None else output_dim\nself.sentence_cnn_conv = nn.ModuleList([nn.Sequential(nn.Conv1d(self.embedding_di... | <|body_start_0|>
super().__init__()
assert kernel_sizes is not None and isinstance(kernel_sizes, list)
self.kernel_sizes = kernel_sizes
self.embedding_dim = embedding_dim
self.output_dim = self.embedding_dim if output_dim is None else output_dim
self.sentence_cnn_conv = n... | SentenceEmbeddingCNN (for each text). | SentenceEmbeddingCNN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SentenceEmbeddingCNN:
"""SentenceEmbeddingCNN (for each text)."""
def __init__(self, embedding_dim, output_dim=None, kernel_sizes=None):
"""Args: embedding_dim (int): dim of input features output_dim (int or None): dim of output features, if not specified, use embedding_dim as defaul... | stack_v2_sparse_classes_36k_train_026592 | 3,272 | permissive | [
{
"docstring": "Args: embedding_dim (int): dim of input features output_dim (int or None): dim of output features, if not specified, use embedding_dim as default kernel_sizes (list(int): multiple kernels used in CNN to extract sentence embeddings",
"name": "__init__",
"signature": "def __init__(self, em... | 3 | stack_v2_sparse_classes_30k_train_004068 | Implement the Python class `SentenceEmbeddingCNN` described below.
Class description:
SentenceEmbeddingCNN (for each text).
Method signatures and docstrings:
- def __init__(self, embedding_dim, output_dim=None, kernel_sizes=None): Args: embedding_dim (int): dim of input features output_dim (int or None): dim of outpu... | Implement the Python class `SentenceEmbeddingCNN` described below.
Class description:
SentenceEmbeddingCNN (for each text).
Method signatures and docstrings:
- def __init__(self, embedding_dim, output_dim=None, kernel_sizes=None): Args: embedding_dim (int): dim of input features output_dim (int or None): dim of outpu... | fb47a96d1a38f5ce634c6f12d710ed5300cc89fc | <|skeleton|>
class SentenceEmbeddingCNN:
"""SentenceEmbeddingCNN (for each text)."""
def __init__(self, embedding_dim, output_dim=None, kernel_sizes=None):
"""Args: embedding_dim (int): dim of input features output_dim (int or None): dim of output features, if not specified, use embedding_dim as defaul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SentenceEmbeddingCNN:
"""SentenceEmbeddingCNN (for each text)."""
def __init__(self, embedding_dim, output_dim=None, kernel_sizes=None):
"""Args: embedding_dim (int): dim of input features output_dim (int or None): dim of output features, if not specified, use embedding_dim as default kernel_size... | the_stack_v2_python_sparse | davarocr/davarocr/davar_ie/models/embedding/sentence_embedding.py | OCRWorld/DAVAR-Lab-OCR | train | 0 |
101d3caeadb4f95760aabd2b2398c14f26804141 | [
"set_custom_attribute('course_import_init', True)\nset_custom_attributes_for_course_key(course_key)\ntry:\n if 'course_data' not in request.FILES:\n raise self.api_error(status_code=status.HTTP_400_BAD_REQUEST, developer_message='Missing required parameter', error_code='internal_error')\n filename = re... | <|body_start_0|>
set_custom_attribute('course_import_init', True)
set_custom_attributes_for_course_key(course_key)
try:
if 'course_data' not in request.FILES:
raise self.api_error(status_code=status.HTTP_400_BAD_REQUEST, developer_message='Missing required parameter',... | **Use Case** * Start an asynchronous task to import a course from a .tar.gz file into the specified course ID, overwriting the existing course * Get a status on an asynchronous task import **Example Requests** POST /api/courses/v0/import/{course_id}/ GET /api/courses/v0/import/{course_id}/?task_id={task_id} **POST Para... | CourseImportView | [
"MIT",
"AGPL-3.0-only",
"AGPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseImportView:
"""**Use Case** * Start an asynchronous task to import a course from a .tar.gz file into the specified course ID, overwriting the existing course * Get a status on an asynchronous task import **Example Requests** POST /api/courses/v0/import/{course_id}/ GET /api/courses/v0/impor... | stack_v2_sparse_classes_36k_train_026593 | 6,376 | permissive | [
{
"docstring": "Kicks off an asynchronous course import and returns an ID to be used to check the task's status",
"name": "post",
"signature": "def post(self, request, course_key)"
},
{
"docstring": "Check the status of the specified task",
"name": "get",
"signature": "def get(self, requ... | 2 | stack_v2_sparse_classes_30k_train_009638 | Implement the Python class `CourseImportView` described below.
Class description:
**Use Case** * Start an asynchronous task to import a course from a .tar.gz file into the specified course ID, overwriting the existing course * Get a status on an asynchronous task import **Example Requests** POST /api/courses/v0/import... | Implement the Python class `CourseImportView` described below.
Class description:
**Use Case** * Start an asynchronous task to import a course from a .tar.gz file into the specified course ID, overwriting the existing course * Get a status on an asynchronous task import **Example Requests** POST /api/courses/v0/import... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class CourseImportView:
"""**Use Case** * Start an asynchronous task to import a course from a .tar.gz file into the specified course ID, overwriting the existing course * Get a status on an asynchronous task import **Example Requests** POST /api/courses/v0/import/{course_id}/ GET /api/courses/v0/impor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CourseImportView:
"""**Use Case** * Start an asynchronous task to import a course from a .tar.gz file into the specified course ID, overwriting the existing course * Get a status on an asynchronous task import **Example Requests** POST /api/courses/v0/import/{course_id}/ GET /api/courses/v0/import/{course_id}... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/cms/djangoapps/contentstore/api/views/course_import.py | luque/better-ways-of-thinking-about-software | train | 3 |
71eac08b32ec3c6481db3863b601ac6e6ca60599 | [
"super().__init__(game, neural_net, args, MuZeroMCTS, DefaultMuZeroPlayer)\nif run_name is None:\n run_name = datetime.now().strftime('%Y%m%d-%H%M%S')\nself.log_dir = f'out/logs/MuZero/{self.neural_net.architecture}/' + run_name\nself.file_writer = tf.summary.create_file_writer(self.log_dir + '/metrics')\nself.f... | <|body_start_0|>
super().__init__(game, neural_net, args, MuZeroMCTS, DefaultMuZeroPlayer)
if run_name is None:
run_name = datetime.now().strftime('%Y%m%d-%H%M%S')
self.log_dir = f'out/logs/MuZero/{self.neural_net.architecture}/' + run_name
self.file_writer = tf.summary.creat... | Implement base Coach class to define proper data-batch sampling procedures and logging objects. | MuZeroCoach | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MuZeroCoach:
"""Implement base Coach class to define proper data-batch sampling procedures and logging objects."""
def __init__(self, game, neural_net, args: DotDict, run_name: typing.Optional[str]=None) -> None:
"""Initialize the class for self-play. This inherited method initialize... | stack_v2_sparse_classes_36k_train_026594 | 7,090 | permissive | [
{
"docstring": "Initialize the class for self-play. This inherited method initializes tensorboard logging and defines helper variables for data batch sampling. The super class is initialized with the proper search engine and agent-interface. (MuZeroMCTS, MuZeroPlayer) :param game: Game Implementation of Game cl... | 3 | stack_v2_sparse_classes_30k_train_005807 | Implement the Python class `MuZeroCoach` described below.
Class description:
Implement base Coach class to define proper data-batch sampling procedures and logging objects.
Method signatures and docstrings:
- def __init__(self, game, neural_net, args: DotDict, run_name: typing.Optional[str]=None) -> None: Initialize ... | Implement the Python class `MuZeroCoach` described below.
Class description:
Implement base Coach class to define proper data-batch sampling procedures and logging objects.
Method signatures and docstrings:
- def __init__(self, game, neural_net, args: DotDict, run_name: typing.Optional[str]=None) -> None: Initialize ... | 78478c6a8a0f0e0e740159236d6cbb30a9396f5a | <|skeleton|>
class MuZeroCoach:
"""Implement base Coach class to define proper data-batch sampling procedures and logging objects."""
def __init__(self, game, neural_net, args: DotDict, run_name: typing.Optional[str]=None) -> None:
"""Initialize the class for self-play. This inherited method initialize... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MuZeroCoach:
"""Implement base Coach class to define proper data-batch sampling procedures and logging objects."""
def __init__(self, game, neural_net, args: DotDict, run_name: typing.Optional[str]=None) -> None:
"""Initialize the class for self-play. This inherited method initializes tensorboard... | the_stack_v2_python_sparse | MuZero/MuCoach.py | frankbryce/muzero | train | 1 |
9bbcfacac476bb9d2befb82a33afdf2436de95e9 | [
"try:\n user_id = request.user.id\n data = redis_obj.get('label' + str(label_id))\n if data is None:\n label_obj = Label.objects.get(id=label_id, user_id=user_id)\n serializer = LabelSerializer(label_obj)\n label_data = serializer.data\n else:\n label_data = data\n smd = s... | <|body_start_0|>
try:
user_id = request.user.id
data = redis_obj.get('label' + str(label_id))
if data is None:
label_obj = Label.objects.get(id=label_id, user_id=user_id)
serializer = LabelSerializer(label_obj)
label_data = seri... | LabelShareView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelShareView:
def get(self, request, label_id):
""":param request: GET :param label_id: The name parameter is for accessing a label with the label id as given by the user :return: returns an SMD response accordingly if the label with the name is present/not present in the database with... | stack_v2_sparse_classes_36k_train_026595 | 22,405 | no_license | [
{
"docstring": ":param request: GET :param label_id: The name parameter is for accessing a label with the label id as given by the user :return: returns an SMD response accordingly if the label with the name is present/not present in the database with the serialized data of the label",
"name": "get",
"s... | 3 | stack_v2_sparse_classes_30k_train_003293 | Implement the Python class `LabelShareView` described below.
Class description:
Implement the LabelShareView class.
Method signatures and docstrings:
- def get(self, request, label_id): :param request: GET :param label_id: The name parameter is for accessing a label with the label id as given by the user :return: ret... | Implement the Python class `LabelShareView` described below.
Class description:
Implement the LabelShareView class.
Method signatures and docstrings:
- def get(self, request, label_id): :param request: GET :param label_id: The name parameter is for accessing a label with the label id as given by the user :return: ret... | 97e5870e9af3f5c6dab75f9bf336c05045a5fea8 | <|skeleton|>
class LabelShareView:
def get(self, request, label_id):
""":param request: GET :param label_id: The name parameter is for accessing a label with the label id as given by the user :return: returns an SMD response accordingly if the label with the name is present/not present in the database with... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelShareView:
def get(self, request, label_id):
""":param request: GET :param label_id: The name parameter is for accessing a label with the label id as given by the user :return: returns an SMD response accordingly if the label with the name is present/not present in the database with the serialize... | the_stack_v2_python_sparse | notes/views.py | addyp1911/FundooNotes | train | 0 | |
d8385f7be7a23757ba8bef74da256a154fe640f0 | [
"try:\n output = subprocess.check_output([sys.executable, idf_py_path, '--version', '@file_args_expansion_inputs/args_a'], env=os.environ, stderr=subprocess.STDOUT).decode('utf-8', 'ignore')\n self.assertIn('Running: idf.py --version DAAA DBBB', output)\nexcept subprocess.CalledProcessError as e:\n self.fa... | <|body_start_0|>
try:
output = subprocess.check_output([sys.executable, idf_py_path, '--version', '@file_args_expansion_inputs/args_a'], env=os.environ, stderr=subprocess.STDOUT).decode('utf-8', 'ignore')
self.assertIn('Running: idf.py --version DAAA DBBB', output)
except subproc... | TestFileArgumentExpansion | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFileArgumentExpansion:
def test_file_expansion(self):
"""Test @filename expansion functionality"""
<|body_0|>
def test_multiple_file_arguments(self):
"""Test multiple @filename arguments"""
<|body_1|>
def test_recursive_expansion(self):
"""Te... | stack_v2_sparse_classes_36k_train_026596 | 14,442 | permissive | [
{
"docstring": "Test @filename expansion functionality",
"name": "test_file_expansion",
"signature": "def test_file_expansion(self)"
},
{
"docstring": "Test multiple @filename arguments",
"name": "test_multiple_file_arguments",
"signature": "def test_multiple_file_arguments(self)"
},
... | 5 | stack_v2_sparse_classes_30k_train_019889 | Implement the Python class `TestFileArgumentExpansion` described below.
Class description:
Implement the TestFileArgumentExpansion class.
Method signatures and docstrings:
- def test_file_expansion(self): Test @filename expansion functionality
- def test_multiple_file_arguments(self): Test multiple @filename argument... | Implement the Python class `TestFileArgumentExpansion` described below.
Class description:
Implement the TestFileArgumentExpansion class.
Method signatures and docstrings:
- def test_file_expansion(self): Test @filename expansion functionality
- def test_multiple_file_arguments(self): Test multiple @filename argument... | 3befd5fff72aa6980514454a50233037718b611f | <|skeleton|>
class TestFileArgumentExpansion:
def test_file_expansion(self):
"""Test @filename expansion functionality"""
<|body_0|>
def test_multiple_file_arguments(self):
"""Test multiple @filename arguments"""
<|body_1|>
def test_recursive_expansion(self):
"""Te... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFileArgumentExpansion:
def test_file_expansion(self):
"""Test @filename expansion functionality"""
try:
output = subprocess.check_output([sys.executable, idf_py_path, '--version', '@file_args_expansion_inputs/args_a'], env=os.environ, stderr=subprocess.STDOUT).decode('utf-8', '... | the_stack_v2_python_sparse | tools/test_idf_py/test_idf_py.py | KollarRichard/esp-idf | train | 1 | |
7b5c5532bed0fef752e4969eb0a32c2f04c4082e | [
"lnmu = np.zeros_like(sites.vs30)\nstddev_types = self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\nlnsd2 = [np.zeros_like(sites.vs30) for a in stddev_types]\nfor i in range(len(self.GMPEs)):\n gmpe = self.GMPEs[i]\n if gmpe == 'AbrahamsonEtAl2014()':\n sites.z1pt0 = sites.z1pt0ask14\n if gmpe == 'BooreEtA... | <|body_start_0|>
lnmu = np.zeros_like(sites.vs30)
stddev_types = self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
lnsd2 = [np.zeros_like(sites.vs30) for a in stddev_types]
for i in range(len(self.GMPEs)):
gmpe = self.GMPEs[i]
if gmpe == 'AbrahamsonEtAl2014()':
... | Implements a GMPE that is the combination of multiple GMPEs. To do * Update IMT conversion to account for additional uncertainty. * Develop a method to include GMPEs that don't have a site term. * Add a check that the lenght of the weights match the length of the GMPE list. | MultiGMPE | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiGMPE:
"""Implements a GMPE that is the combination of multiple GMPEs. To do * Update IMT conversion to account for additional uncertainty. * Develop a method to include GMPEs that don't have a site term. * Add a check that the lenght of the weights match the length of the GMPE list."""
... | stack_v2_sparse_classes_36k_train_026597 | 11,067 | permissive | [
{
"docstring": "See superclass `method <http://docs.openquake.org/oq-hazardlib/master/gsim/index.html#openquake.hazardlib.gsim.base.GroundShakingIntensityModel.get_mean_and_stddevs>`__.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
... | 2 | stack_v2_sparse_classes_30k_train_000591 | Implement the Python class `MultiGMPE` described below.
Class description:
Implements a GMPE that is the combination of multiple GMPEs. To do * Update IMT conversion to account for additional uncertainty. * Develop a method to include GMPEs that don't have a site term. * Add a check that the lenght of the weights matc... | Implement the Python class `MultiGMPE` described below.
Class description:
Implements a GMPE that is the combination of multiple GMPEs. To do * Update IMT conversion to account for additional uncertainty. * Develop a method to include GMPEs that don't have a site term. * Add a check that the lenght of the weights matc... | a55f488bbe19c45c6375c7102160dbc0a353d661 | <|skeleton|>
class MultiGMPE:
"""Implements a GMPE that is the combination of multiple GMPEs. To do * Update IMT conversion to account for additional uncertainty. * Develop a method to include GMPEs that don't have a site term. * Add a check that the lenght of the weights match the length of the GMPE list."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiGMPE:
"""Implements a GMPE that is the combination of multiple GMPEs. To do * Update IMT conversion to account for additional uncertainty. * Develop a method to include GMPEs that don't have a site term. * Add a check that the lenght of the weights match the length of the GMPE list."""
def get_mean_... | the_stack_v2_python_sparse | shakemap/grind/multigmpe.py | kallstadt-usgs/shakemap | train | 0 |
41e6260b57448ad08a207a1993e53a94d9002d75 | [
"self.queue = []\nself.cap = size\nself.avg = 0",
"self.queue.append(val)\nif len(self.queue) > self.cap:\n self.avg = self.avg + (val - self.queue.pop(0)) / float(self.cap)\nelse:\n n = len(self.queue)\n self.avg = (self.avg * (n - 1) + val) / float(n)\nreturn self.avg"
] | <|body_start_0|>
self.queue = []
self.cap = size
self.avg = 0
<|end_body_0|>
<|body_start_1|>
self.queue.append(val)
if len(self.queue) > self.cap:
self.avg = self.avg + (val - self.queue.pop(0)) / float(self.cap)
else:
n = len(self.queue)
... | 95%. | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
"""95%."""
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.queue = []
... | stack_v2_sparse_classes_36k_train_026598 | 1,648 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005589 | Implement the Python class `MovingAverage` described below.
Class description:
95%.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
95%.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
"""95%."""
def __init__... | d634941087bc51869f43c0d8044db09b7bdbaf58 | <|skeleton|>
class MovingAverage:
"""95%."""
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
"""95%."""
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.queue = []
self.cap = size
self.avg = 0
def next(self, val):
""":type val: int :rtype: float"""
self.queue.append(val)
if len(se... | the_stack_v2_python_sparse | 346_Moving_Average_from_Data_Stream.py | susunini/leetcode | train | 1 |
d8a27c8ecacd6d6c983ab807a9cdcc471b726370 | [
"method = 'chart.gettopartists'\nurl_params = {'method': method}\nif page is not None:\n url_params['page'] = page\nif limit is not None:\n url_params['limit'] = limit\nquery = parse.urlencode(url_params)\nreturn query",
"method = 'chart.gettoptags'\nurl_params = {'method': method}\nif page is not None:\n ... | <|body_start_0|>
method = 'chart.gettopartists'
url_params = {'method': method}
if page is not None:
url_params['page'] = page
if limit is not None:
url_params['limit'] = limit
query = parse.urlencode(url_params)
return query
<|end_body_0|>
<|body... | ChartClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChartClient:
def get_top_artists(self, page=None, limit=10):
"""Get the top artists chart Params: page (Optional) : The page number to fetch. Defaults to first page. limit (Optional) : The number of results to fetch per page."""
<|body_0|>
def get_top_tags(self, page=None, l... | stack_v2_sparse_classes_36k_train_026599 | 1,751 | no_license | [
{
"docstring": "Get the top artists chart Params: page (Optional) : The page number to fetch. Defaults to first page. limit (Optional) : The number of results to fetch per page.",
"name": "get_top_artists",
"signature": "def get_top_artists(self, page=None, limit=10)"
},
{
"docstring": "Get the ... | 3 | stack_v2_sparse_classes_30k_train_005287 | Implement the Python class `ChartClient` described below.
Class description:
Implement the ChartClient class.
Method signatures and docstrings:
- def get_top_artists(self, page=None, limit=10): Get the top artists chart Params: page (Optional) : The page number to fetch. Defaults to first page. limit (Optional) : The... | Implement the Python class `ChartClient` described below.
Class description:
Implement the ChartClient class.
Method signatures and docstrings:
- def get_top_artists(self, page=None, limit=10): Get the top artists chart Params: page (Optional) : The page number to fetch. Defaults to first page. limit (Optional) : The... | 5311236c98274d4e4a6f2c09c6bf021b3f195e66 | <|skeleton|>
class ChartClient:
def get_top_artists(self, page=None, limit=10):
"""Get the top artists chart Params: page (Optional) : The page number to fetch. Defaults to first page. limit (Optional) : The number of results to fetch per page."""
<|body_0|>
def get_top_tags(self, page=None, l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChartClient:
def get_top_artists(self, page=None, limit=10):
"""Get the top artists chart Params: page (Optional) : The page number to fetch. Defaults to first page. limit (Optional) : The number of results to fetch per page."""
method = 'chart.gettopartists'
url_params = {'method': me... | the_stack_v2_python_sparse | apiClients/chart_client.py | zflake1208/last-fm-analyzer | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.