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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6b9cd1baa5c498e9d33c91a262fb2e77df3625e5 | [
"if Log.createdLog == 0:\n Log.driver = driver\n logName = path.basename(sys.modules['__main__'].__file__).split('.')[0]\n logFolderPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, os.pardir, 'Logs')\n if any((x.startswith(logName) for x in os.listdir(logFolderPath))):\n ... | <|body_start_0|>
if Log.createdLog == 0:
Log.driver = driver
logName = path.basename(sys.modules['__main__'].__file__).split('.')[0]
logFolderPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, os.pardir, 'Logs')
if any((x.startswith(logName... | Log | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Log:
def __init__(self, driver):
"""Creates Log instance with given driver. (Driver is used to generate screenshots) :param driver: Driver :type driver: WebDriver"""
<|body_0|>
def info(self, msg):
"""Log info message in log :param msg: Message to log :type msg: str"... | stack_v2_sparse_classes_36k_train_018700 | 3,526 | no_license | [
{
"docstring": "Creates Log instance with given driver. (Driver is used to generate screenshots) :param driver: Driver :type driver: WebDriver",
"name": "__init__",
"signature": "def __init__(self, driver)"
},
{
"docstring": "Log info message in log :param msg: Message to log :type msg: str",
... | 4 | stack_v2_sparse_classes_30k_train_006527 | Implement the Python class `Log` described below.
Class description:
Implement the Log class.
Method signatures and docstrings:
- def __init__(self, driver): Creates Log instance with given driver. (Driver is used to generate screenshots) :param driver: Driver :type driver: WebDriver
- def info(self, msg): Log info m... | Implement the Python class `Log` described below.
Class description:
Implement the Log class.
Method signatures and docstrings:
- def __init__(self, driver): Creates Log instance with given driver. (Driver is used to generate screenshots) :param driver: Driver :type driver: WebDriver
- def info(self, msg): Log info m... | 5cc54ad6dd379b34da9f318ea4a08f65aedf03c1 | <|skeleton|>
class Log:
def __init__(self, driver):
"""Creates Log instance with given driver. (Driver is used to generate screenshots) :param driver: Driver :type driver: WebDriver"""
<|body_0|>
def info(self, msg):
"""Log info message in log :param msg: Message to log :type msg: str"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Log:
def __init__(self, driver):
"""Creates Log instance with given driver. (Driver is used to generate screenshots) :param driver: Driver :type driver: WebDriver"""
if Log.createdLog == 0:
Log.driver = driver
logName = path.basename(sys.modules['__main__'].__file__).sp... | the_stack_v2_python_sparse | Lib/common/Log.py | smirad91/AutoTestingFramework | train | 0 | |
650e979cfbab39b3967d92e537f44eba7ae54420 | [
"try:\n platform = self.get_argument('platform', 'iOS')\n username = self.get_argument('username')\nexcept Exception as e:\n logging.error(e)\n raise utils.APIError(errcode=100)\nuser = ctrl.web.get_user_info_ctl(username)\nif user:\n return self.send_json(user)\ndt_7days_after = datetime.datetime.no... | <|body_start_0|>
try:
platform = self.get_argument('platform', 'iOS')
username = self.get_argument('username')
except Exception as e:
logging.error(e)
raise utils.APIError(errcode=100)
user = ctrl.web.get_user_info_ctl(username)
if user:
... | UserHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserHandler:
def post(self):
"""进入app后就会掉的接口, username是设备相关的,如果没有账号则创建,返回账号信息"""
<|body_0|>
def get(self):
"""获取用户信息: email, timelimit, password, sim_online"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
platform = self.get_argumen... | stack_v2_sparse_classes_36k_train_018701 | 3,027 | no_license | [
{
"docstring": "进入app后就会掉的接口, username是设备相关的,如果没有账号则创建,返回账号信息",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "获取用户信息: email, timelimit, password, sim_online",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013778 | Implement the Python class `UserHandler` described below.
Class description:
Implement the UserHandler class.
Method signatures and docstrings:
- def post(self): 进入app后就会掉的接口, username是设备相关的,如果没有账号则创建,返回账号信息
- def get(self): 获取用户信息: email, timelimit, password, sim_online | Implement the Python class `UserHandler` described below.
Class description:
Implement the UserHandler class.
Method signatures and docstrings:
- def post(self): 进入app后就会掉的接口, username是设备相关的,如果没有账号则创建,返回账号信息
- def get(self): 获取用户信息: email, timelimit, password, sim_online
<|skeleton|>
class UserHandler:
def post... | 7fd1b320a0ed33fbe428599b432bb4d0bfeb12f4 | <|skeleton|>
class UserHandler:
def post(self):
"""进入app后就会掉的接口, username是设备相关的,如果没有账号则创建,返回账号信息"""
<|body_0|>
def get(self):
"""获取用户信息: email, timelimit, password, sim_online"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserHandler:
def post(self):
"""进入app后就会掉的接口, username是设备相关的,如果没有账号则创建,返回账号信息"""
try:
platform = self.get_argument('platform', 'iOS')
username = self.get_argument('username')
except Exception as e:
logging.error(e)
raise utils.APIError(er... | the_stack_v2_python_sparse | apiv2/handler/user.py | onlywsx/FreeVPN | train | 0 | |
5f45935372d3cb33d0e21d88a390bcc90e986189 | [
"super(YoloDetector, self).__init__()\nkernel_depth = num_anchors * (4 + 1 + num_classes)\nself.in_channels = in_ch\nself.mid_channels = round(in_ch / 2)\nself.out_channels = kernel_depth\nself.batch_norm = batch_norm\nself.num_anchors = num_anchors\nself.num_classes = num_classes\nself.index_in = index\nself.conv_... | <|body_start_0|>
super(YoloDetector, self).__init__()
kernel_depth = num_anchors * (4 + 1 + num_classes)
self.in_channels = in_ch
self.mid_channels = round(in_ch / 2)
self.out_channels = kernel_depth
self.batch_norm = batch_norm
self.num_anchors = num_anchors
... | Output Dimensions of each detection kernel is 1 x 1 x (B x (4 + 1 + C)) - B: Number of bounding boxes a cell on the feature map can predic; - 4: Bounding box attributes; - 1: Object confidence; - C: Number of classes. Kernel depth arrangement: [t_x ,t_y, t_w, t_h], [p_o], [p_1, p+2, ..., p_C] x B | YoloDetector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YoloDetector:
"""Output Dimensions of each detection kernel is 1 x 1 x (B x (4 + 1 + C)) - B: Number of bounding boxes a cell on the feature map can predic; - 4: Bounding box attributes; - 1: Object confidence; - C: Number of classes. Kernel depth arrangement: [t_x ,t_y, t_w, t_h], [p_o], [p_1, p... | stack_v2_sparse_classes_36k_train_018702 | 28,014 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, in_ch, num_classes=3, num_anchors=3, batch_norm=True, index=0)"
},
{
"docstring": "Foward method",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001112 | Implement the Python class `YoloDetector` described below.
Class description:
Output Dimensions of each detection kernel is 1 x 1 x (B x (4 + 1 + C)) - B: Number of bounding boxes a cell on the feature map can predic; - 4: Bounding box attributes; - 1: Object confidence; - C: Number of classes. Kernel depth arrangemen... | Implement the Python class `YoloDetector` described below.
Class description:
Output Dimensions of each detection kernel is 1 x 1 x (B x (4 + 1 + C)) - B: Number of bounding boxes a cell on the feature map can predic; - 4: Bounding box attributes; - 1: Object confidence; - C: Number of classes. Kernel depth arrangemen... | 69edb5ecd569395086cf610df9c8aa345284259a | <|skeleton|>
class YoloDetector:
"""Output Dimensions of each detection kernel is 1 x 1 x (B x (4 + 1 + C)) - B: Number of bounding boxes a cell on the feature map can predic; - 4: Bounding box attributes; - 1: Object confidence; - C: Number of classes. Kernel depth arrangement: [t_x ,t_y, t_w, t_h], [p_o], [p_1, p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YoloDetector:
"""Output Dimensions of each detection kernel is 1 x 1 x (B x (4 + 1 + C)) - B: Number of bounding boxes a cell on the feature map can predic; - 4: Bounding box attributes; - 1: Object confidence; - C: Number of classes. Kernel depth arrangement: [t_x ,t_y, t_w, t_h], [p_o], [p_1, p+2, ..., p_C]... | the_stack_v2_python_sparse | python/models/modules.py | dswanderley/detntorch | train | 2 |
9f72499ff4beedce04619d5976746a58bd000945 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ResponseStatus()",
"from .response_type import ResponseType\nfrom .response_type import ResponseType\nfields: Dict[str, Callable[[Any], None]] = {'@odata.type': lambda n: setattr(self, 'odata_type', n.get_str_value()), 'response': lamb... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ResponseStatus()
<|end_body_0|>
<|body_start_1|>
from .response_type import ResponseType
from .response_type import ResponseType
fields: Dict[str, Callable[[Any], None]] = {'@oda... | ResponseStatus | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResponseStatus:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ResponseStatus:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | stack_v2_sparse_classes_36k_train_018703 | 3,761 | 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: ResponseStatus",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | stack_v2_sparse_classes_30k_train_016748 | Implement the Python class `ResponseStatus` described below.
Class description:
Implement the ResponseStatus class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ResponseStatus: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `ResponseStatus` described below.
Class description:
Implement the ResponseStatus class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ResponseStatus: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ResponseStatus:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ResponseStatus:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResponseStatus:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ResponseStatus:
"""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: ResponseSt... | the_stack_v2_python_sparse | msgraph/generated/models/response_status.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
c532fbbfdde307a35d233e4084d03c5f605ea7d7 | [
"test_node = class_dependency.JavaClass(self.TEST_PKG, self.TEST_CLS)\nself.assertEqual(test_node.name, f'{self.TEST_PKG}.{self.TEST_CLS}')\nself.assertEqual(test_node.package, self.TEST_PKG)\nself.assertEqual(test_node.class_name, self.TEST_CLS)",
"test_node = class_dependency.JavaClass(self.TEST_PKG, self.TEST_... | <|body_start_0|>
test_node = class_dependency.JavaClass(self.TEST_PKG, self.TEST_CLS)
self.assertEqual(test_node.name, f'{self.TEST_PKG}.{self.TEST_CLS}')
self.assertEqual(test_node.package, self.TEST_PKG)
self.assertEqual(test_node.class_name, self.TEST_CLS)
<|end_body_0|>
<|body_start... | Unit tests for dependency_analysis.class_dependency.JavaClass. | TestJavaClass | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestJavaClass:
"""Unit tests for dependency_analysis.class_dependency.JavaClass."""
def test_initialization(self):
"""Tests that JavaClass is initialized correctly."""
<|body_0|>
def test_equality(self):
"""Tests that two JavaClasses with the same package+class a... | stack_v2_sparse_classes_36k_train_018704 | 4,801 | permissive | [
{
"docstring": "Tests that JavaClass is initialized correctly.",
"name": "test_initialization",
"signature": "def test_initialization(self)"
},
{
"docstring": "Tests that two JavaClasses with the same package+class are equal.",
"name": "test_equality",
"signature": "def test_equality(sel... | 5 | stack_v2_sparse_classes_30k_train_009079 | Implement the Python class `TestJavaClass` described below.
Class description:
Unit tests for dependency_analysis.class_dependency.JavaClass.
Method signatures and docstrings:
- def test_initialization(self): Tests that JavaClass is initialized correctly.
- def test_equality(self): Tests that two JavaClasses with the... | Implement the Python class `TestJavaClass` described below.
Class description:
Unit tests for dependency_analysis.class_dependency.JavaClass.
Method signatures and docstrings:
- def test_initialization(self): Tests that JavaClass is initialized correctly.
- def test_equality(self): Tests that two JavaClasses with the... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class TestJavaClass:
"""Unit tests for dependency_analysis.class_dependency.JavaClass."""
def test_initialization(self):
"""Tests that JavaClass is initialized correctly."""
<|body_0|>
def test_equality(self):
"""Tests that two JavaClasses with the same package+class a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestJavaClass:
"""Unit tests for dependency_analysis.class_dependency.JavaClass."""
def test_initialization(self):
"""Tests that JavaClass is initialized correctly."""
test_node = class_dependency.JavaClass(self.TEST_PKG, self.TEST_CLS)
self.assertEqual(test_node.name, f'{self.TES... | the_stack_v2_python_sparse | tools/android/dependency_analysis/class_dependency_unittest.py | chromium/chromium | train | 17,408 |
4ee9b97a2e29075cfaa31b686d2a8023f7b47dbd | [
"if not head or not head.next:\n return head\ncur = head.next\nlast = head\nwhile cur:\n t = head\n last_t = None\n while t.val < cur.val:\n last_t = t\n t = t.next\n if cur == t:\n last = cur\n cur = cur.next\n else:\n last.next = cur.next\n if last_t:\n ... | <|body_start_0|>
if not head or not head.next:
return head
cur = head.next
last = head
while cur:
t = head
last_t = None
while t.val < cur.val:
last_t = t
t = t.next
if cur == t:
l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
"""链表插入排序"""
<|body_0|>
def insertionSortList2(self, head: ListNode) -> ListNode:
"""链表插入排序 优化后"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or not head.next:
... | stack_v2_sparse_classes_36k_train_018705 | 2,451 | no_license | [
{
"docstring": "链表插入排序",
"name": "insertionSortList",
"signature": "def insertionSortList(self, head: ListNode) -> ListNode"
},
{
"docstring": "链表插入排序 优化后",
"name": "insertionSortList2",
"signature": "def insertionSortList2(self, head: ListNode) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_018043 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertionSortList(self, head: ListNode) -> ListNode: 链表插入排序
- def insertionSortList2(self, head: ListNode) -> ListNode: 链表插入排序 优化后 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertionSortList(self, head: ListNode) -> ListNode: 链表插入排序
- def insertionSortList2(self, head: ListNode) -> ListNode: 链表插入排序 优化后
<|skeleton|>
class Solution:
def inse... | 7f8145f0c7ffdf18c557f01d221087b10443156e | <|skeleton|>
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
"""链表插入排序"""
<|body_0|>
def insertionSortList2(self, head: ListNode) -> ListNode:
"""链表插入排序 优化后"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
"""链表插入排序"""
if not head or not head.next:
return head
cur = head.next
last = head
while cur:
t = head
last_t = None
while t.val < cur.val:
... | the_stack_v2_python_sparse | linked_list/147 Insertion Sort List.py | mofei952/leetcode_python | train | 0 | |
d178d30106276ed713d76afe79af8f3802451c1e | [
"self.pump = Pump('127.0.0.1', 8000)\nself.sensor = Sensor('127.1.1.3', 9000)\nself.decider = Decider(100, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)",
"self.sensor.measure = MagicMock(return_value=110)\nself.pump.get_state = MagicMock(return_value='PUMP_OFF')\nself.controller.tick ... | <|body_start_0|>
self.pump = Pump('127.0.0.1', 8000)
self.sensor = Sensor('127.1.1.3', 9000)
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
<|end_body_0|>
<|body_start_1|>
self.sensor.measure = MagicMock(return_value=110)
... | Unit tests for the Controller class | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""setup :return:"""
<|body_0|>
def test_tick(self):
"""test tick of Controller class :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pump = Pump('127.0.0.... | stack_v2_sparse_classes_36k_train_018706 | 3,198 | no_license | [
{
"docstring": "setup :return:",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test tick of Controller class :return:",
"name": "test_tick",
"signature": "def test_tick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014901 | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): setup :return:
- def test_tick(self): test tick of Controller class :return: | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): setup :return:
- def test_tick(self): test tick of Controller class :return:
<|skeleton|>
class ControllerTests:
"""Unit tests for the Controll... | 263685ca90110609bfd05d621516727f8cd0028f | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""setup :return:"""
<|body_0|>
def test_tick(self):
"""test tick of Controller class :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""setup :return:"""
self.pump = Pump('127.0.0.1', 8000)
self.sensor = Sensor('127.1.1.3', 9000)
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump, self.... | the_stack_v2_python_sparse | students/marc_charbo/assignment_6/assign_6/waterregulation/test.py | aurel1212/Sp2018-Online | train | 0 |
28243be8f2d9fbe71fc8494db51bc3d143920a58 | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\ntimestamp = int(timestamp)\nreturn dfdatetime_posix_time.PosixTime(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = IOSTwitterContactEventData()\nevent_data.creation_time = self._GetDateTimeRowValue(... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
timestamp = int(timestamp)
return dfdatetime_posix_time.PosixTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event... | SQLite parser plugin for Twitter on iOS 8+ database files. The Twitter on iOS 8+ database file is typically stored in: /private/var/mobile/Containers/Data/Application/Library/Caches/databases/ twitter.db | IOSTwitterPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOSTwitterPlugin:
"""SQLite parser plugin for Twitter on iOS 8+ database files. The Twitter on iOS 8+ database file is typically stored in: /private/var/mobile/Containers/Data/Application/Library/Caches/databases/ twitter.db"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
... | stack_v2_sparse_classes_36k_train_018707 | 12,718 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.PosixTime: date and time value or None if not available.",
"name... | 3 | null | Implement the Python class `IOSTwitterPlugin` described below.
Class description:
SQLite parser plugin for Twitter on iOS 8+ database files. The Twitter on iOS 8+ database file is typically stored in: /private/var/mobile/Containers/Data/Application/Library/Caches/databases/ twitter.db
Method signatures and docstrings... | Implement the Python class `IOSTwitterPlugin` described below.
Class description:
SQLite parser plugin for Twitter on iOS 8+ database files. The Twitter on iOS 8+ database file is typically stored in: /private/var/mobile/Containers/Data/Application/Library/Caches/databases/ twitter.db
Method signatures and docstrings... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class IOSTwitterPlugin:
"""SQLite parser plugin for Twitter on iOS 8+ database files. The Twitter on iOS 8+ database file is typically stored in: /private/var/mobile/Containers/Data/Application/Library/Caches/databases/ twitter.db"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IOSTwitterPlugin:
"""SQLite parser plugin for Twitter on iOS 8+ database files. The Twitter on iOS 8+ database file is typically stored in: /private/var/mobile/Containers/Data/Application/Library/Caches/databases/ twitter.db"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retri... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/ios_twitter.py | log2timeline/plaso | train | 1,506 |
e6ecc5c8c7c3564f856df069ccbf0fe72cb6edda | [
"model = LibraryGaussianNumeric.create_test_instance()\nmodel.error_msg = 'Gaussian mixture'\nyield model",
"model = LibraryGaussianBase.create_test_instance()\nc_means = model.concentration_means\nfor i, c_mean in enumerate(c_means):\n mean_calc = model.get_concentration_distribution(i).mean()\n self.asser... | <|body_start_0|>
model = LibraryGaussianNumeric.create_test_instance()
model.error_msg = 'Gaussian mixture'
yield model
<|end_body_0|>
<|body_start_1|>
model = LibraryGaussianBase.create_test_instance()
c_means = model.concentration_means
for i, c_mean in enumerate(c_mea... | unit tests for the Gaussian mixtures | TestLibraryGaussian | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLibraryGaussian:
"""unit tests for the Gaussian mixtures"""
def _create_test_models(self):
"""helper method for creating test models"""
<|body_0|>
def test_base(self):
"""consistency tests on the base class"""
<|body_1|>
def test_estimates(self):... | stack_v2_sparse_classes_36k_train_018708 | 2,335 | permissive | [
{
"docstring": "helper method for creating test models",
"name": "_create_test_models",
"signature": "def _create_test_models(self)"
},
{
"docstring": "consistency tests on the base class",
"name": "test_base",
"signature": "def test_base(self)"
},
{
"docstring": "tests the estim... | 3 | stack_v2_sparse_classes_30k_train_008349 | Implement the Python class `TestLibraryGaussian` described below.
Class description:
unit tests for the Gaussian mixtures
Method signatures and docstrings:
- def _create_test_models(self): helper method for creating test models
- def test_base(self): consistency tests on the base class
- def test_estimates(self): tes... | Implement the Python class `TestLibraryGaussian` described below.
Class description:
unit tests for the Gaussian mixtures
Method signatures and docstrings:
- def _create_test_models(self): helper method for creating test models
- def test_base(self): consistency tests on the base class
- def test_estimates(self): tes... | 7f53127f66fe3525c2843901de6caa537ff8800c | <|skeleton|>
class TestLibraryGaussian:
"""unit tests for the Gaussian mixtures"""
def _create_test_models(self):
"""helper method for creating test models"""
<|body_0|>
def test_base(self):
"""consistency tests on the base class"""
<|body_1|>
def test_estimates(self):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLibraryGaussian:
"""unit tests for the Gaussian mixtures"""
def _create_test_models(self):
"""helper method for creating test models"""
model = LibraryGaussianNumeric.create_test_instance()
model.error_msg = 'Gaussian mixture'
yield model
def test_base(self):
... | the_stack_v2_python_sparse | sensing/binary_response/gaussian_mixtures/tests.py | david-zwicker/sensing | train | 0 |
7360adda5d8607c2abe59635521d999d501126f2 | [
"examples, metadata = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True, as_supervised=True)\nself.data_train = examples['train']\nself.data_valid = examples['validation']\nPT, EN = self.tokenize_dataset(self.data_train)\nself.tokenizer_pt, self.tokenizer_en = (PT, EN)",
"tokenizer_en = tfds.features.text.S... | <|body_start_0|>
examples, metadata = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True, as_supervised=True)
self.data_train = examples['train']
self.data_valid = examples['validation']
PT, EN = self.tokenize_dataset(self.data_train)
self.tokenizer_pt, self.tokenizer_en = (... | Class Dataset | Dataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""Class Dataset"""
def __init__(self):
"""* data_train, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided * data_valid, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded as_supervided * token... | stack_v2_sparse_classes_36k_train_018709 | 1,982 | no_license | [
{
"docstring": "* data_train, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided * data_valid, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded as_supervided * tokenizer_pt is the Portuguese tokenizer created from the training se... | 2 | null | Implement the Python class `Dataset` described below.
Class description:
Class Dataset
Method signatures and docstrings:
- def __init__(self): * data_train, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided * data_valid, which contains the ted_hrlr_translate/pt_to_en tf.... | Implement the Python class `Dataset` described below.
Class description:
Class Dataset
Method signatures and docstrings:
- def __init__(self): * data_train, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided * data_valid, which contains the ted_hrlr_translate/pt_to_en tf.... | 8ad4c2594ff78b345dbd92e9d54d2a143ac4071a | <|skeleton|>
class Dataset:
"""Class Dataset"""
def __init__(self):
"""* data_train, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided * data_valid, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded as_supervided * token... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset:
"""Class Dataset"""
def __init__(self):
"""* data_train, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided * data_valid, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded as_supervided * tokenizer_pt is th... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/0-dataset.py | jorgezafra94/holbertonschool-machine_learning | train | 1 |
98c9cb5882414af086513717f3a4f881c8997674 | [
"self.d = collections.defaultdict(set)\nfor word in dictionary:\n temp = word\n if len(word) > 2:\n word = word[0] + str(len(word) - 2) + word[-1]\n self.d[word].add(temp)",
"temp = word\nif len(word) > 2:\n word = word[0] + str(len(word) - 2) + word[-1]\nreturn len(self.d[word]) == 0 or (len(s... | <|body_start_0|>
self.d = collections.defaultdict(set)
for word in dictionary:
temp = word
if len(word) > 2:
word = word[0] + str(len(word) - 2) + word[-1]
self.d[word].add(temp)
<|end_body_0|>
<|body_start_1|>
temp = word
if len(word)... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.d = collections.defaultdict(set)
for w... | stack_v2_sparse_classes_36k_train_018710 | 948 | no_license | [
{
"docstring": ":type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": ":type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002180 | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool
<|skeleton|>
class ValidWordAbbr:
def __init_... | 0297c0d8d06f0282f866d2e90b65a2cf65b87395 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
self.d = collections.defaultdict(set)
for word in dictionary:
temp = word
if len(word) > 2:
word = word[0] + str(len(word) - 2) + word[-1]
self.d[word].a... | the_stack_v2_python_sparse | unique_word_abb.py | prathy16/LeetCode | train | 0 | |
ec3866cec08471e03bec4059ad89725643ebe1f4 | [
"assert relpos.is_contiguous()\nassert attn_weight.is_contiguous()\nassert value_features.is_contiguous()\nassert query_batch_cnt.is_contiguous()\nassert key_batch_cnt.is_contiguous()\nassert index_pair_batch.is_contiguous()\nassert index_pair.is_contiguous()\nassert lookup_table.is_contiguous()\nb = query_batch_cn... | <|body_start_0|>
assert relpos.is_contiguous()
assert attn_weight.is_contiguous()
assert value_features.is_contiguous()
assert query_batch_cnt.is_contiguous()
assert key_batch_cnt.is_contiguous()
assert index_pair_batch.is_contiguous()
assert index_pair.is_contigu... | Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size, nhead) | RelativePositionalEmbeddingValueIndex | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelativePositionalEmbeddingValueIndex:
"""Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size, nhead)"""
... | stack_v2_sparse_classes_36k_train_018711 | 11,582 | no_license | [
{
"docstring": ":param ctx: :param relpos: A float tensor with shape [total_query_num, local_size] :param attn_weight: A float tensor with shape [total_query_num, local_size, nhead] :param value_features: A float tensor with shape [total_key_num, nhead, hdim] :param query_batch_cnt: A integer tensor with shape ... | 2 | stack_v2_sparse_classes_30k_train_000107 | Implement the Python class `RelativePositionalEmbeddingValueIndex` described below.
Class description:
Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total... | Implement the Python class `RelativePositionalEmbeddingValueIndex` described below.
Class description:
Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total... | bbc78ca91e851f0f04459b1a8bbe96ab44bf41bc | <|skeleton|>
class RelativePositionalEmbeddingValueIndex:
"""Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size, nhead)"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelativePositionalEmbeddingValueIndex:
"""Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size, nhead)"""
def forward(c... | the_stack_v2_python_sparse | EQNet/eqnet/ops/crpe/crpe_utils_v2.py | dvlab-research/DeepVision3D | train | 94 |
650b4f796c789b285ffcfc4d7f200983e97a084b | [
"self.x = np.zeros((dim_x, 1))\nself.P = np.zeros(dim_x)\nself.Q = np.zeros(dim_x)\nself.u = np.zeros((dim_x, 1))\nself.B = 0\nself.F = 0\nself.H = 0\nself.R = np.zeros(dim_x)\nself._I = np.eye(dim_x)\nif use_short_form:\n self.update = self.update_short_form",
"if Z is None:\n return\nif R is None:\n R ... | <|body_start_0|>
self.x = np.zeros((dim_x, 1))
self.P = np.zeros(dim_x)
self.Q = np.zeros(dim_x)
self.u = np.zeros((dim_x, 1))
self.B = 0
self.F = 0
self.H = 0
self.R = np.zeros(dim_x)
self._I = np.eye(dim_x)
if use_short_form:
... | KalmanFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KalmanFilter:
def __init__(self, dim_x, dim_z, dim_u=0):
"""Create a Kalman filter. You are responsible for setting the various state variables to reasonable values; the defaults below will not give you a functional filter. Parameters ---------- dim_x : int Number of state variables for ... | stack_v2_sparse_classes_36k_train_018712 | 2,843 | no_license | [
{
"docstring": "Create a Kalman filter. You are responsible for setting the various state variables to reasonable values; the defaults below will not give you a functional filter. Parameters ---------- dim_x : int Number of state variables for the Kalman filter. For example, if you are tracking the position and... | 2 | null | Implement the Python class `KalmanFilter` described below.
Class description:
Implement the KalmanFilter class.
Method signatures and docstrings:
- def __init__(self, dim_x, dim_z, dim_u=0): Create a Kalman filter. You are responsible for setting the various state variables to reasonable values; the defaults below wi... | Implement the Python class `KalmanFilter` described below.
Class description:
Implement the KalmanFilter class.
Method signatures and docstrings:
- def __init__(self, dim_x, dim_z, dim_u=0): Create a Kalman filter. You are responsible for setting the various state variables to reasonable values; the defaults below wi... | a3ebaab52f8af813a95f8fc03ee725f2f071dd52 | <|skeleton|>
class KalmanFilter:
def __init__(self, dim_x, dim_z, dim_u=0):
"""Create a Kalman filter. You are responsible for setting the various state variables to reasonable values; the defaults below will not give you a functional filter. Parameters ---------- dim_x : int Number of state variables for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KalmanFilter:
def __init__(self, dim_x, dim_z, dim_u=0):
"""Create a Kalman filter. You are responsible for setting the various state variables to reasonable values; the defaults below will not give you a functional filter. Parameters ---------- dim_x : int Number of state variables for the Kalman fil... | the_stack_v2_python_sparse | kalman_filter_multivariate_v2.py | ChuChuIgbokwe/Python-2.7-code | train | 0 | |
2fc65772b90a27673e6d01d877fa8cb5bea60810 | [
"if source == destination:\n return True\nuf = UnionFind(n)\nfor edge in edges:\n uf.union(edge[0], edge[1])\n if uf.connected(source, destination):\n return True\nreturn uf.connected(source, destination)",
"if source == destination:\n return True\nedge_dict = defaultdict(list)\nfor edge in edg... | <|body_start_0|>
if source == destination:
return True
uf = UnionFind(n)
for edge in edges:
uf.union(edge[0], edge[1])
if uf.connected(source, destination):
return True
return uf.connected(source, destination)
<|end_body_0|>
<|body_sta... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
"""CREATED AT: 2022/1/28 25 / 25 test cases passed. Status: Accepted Runtime: 3405 ms, faster than 15.86% Memory Usage: 103.6 MB, less than 99.46% After add the code: >>> if uf.connected... | stack_v2_sparse_classes_36k_train_018713 | 4,213 | permissive | [
{
"docstring": "CREATED AT: 2022/1/28 25 / 25 test cases passed. Status: Accepted Runtime: 3405 ms, faster than 15.86% Memory Usage: 103.6 MB, less than 99.46% After add the code: >>> if uf.connected(source, destination): >>> return True 25 / 25 test cases passed. Status: Accepted Runtime: 1828 ms, faster than ... | 2 | stack_v2_sparse_classes_30k_train_018044 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: CREATED AT: 2022/1/28 25 / 25 test cases passed. Status: Accepted Runtime: 3405 ms, fa... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: CREATED AT: 2022/1/28 25 / 25 test cases passed. Status: Accepted Runtime: 3405 ms, fa... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
"""CREATED AT: 2022/1/28 25 / 25 test cases passed. Status: Accepted Runtime: 3405 ms, faster than 15.86% Memory Usage: 103.6 MB, less than 99.46% After add the code: >>> if uf.connected... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
"""CREATED AT: 2022/1/28 25 / 25 test cases passed. Status: Accepted Runtime: 3405 ms, faster than 15.86% Memory Usage: 103.6 MB, less than 99.46% After add the code: >>> if uf.connected(source, desti... | the_stack_v2_python_sparse | src/1971-FindIfPathExistsInGraph.py | Jiezhi/myleetcode | train | 1 | |
b9e28ccf14b2f6e3eb95428417ffd1946db8fae2 | [
"Whh = np.random.randn(h, h)\nWhx = np.random.randn(i, h)\nself.Wh = np.concatenate((Whh, Whx), axis=0)\nself.Wy = np.random.randn(h, o)\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"x_max = np.max(x, axis=-1, keepdims=True)\ne_x = np.exp(x - x_max)\nreturn e_x / e_x.sum(axis=-1, keepdims=True)",
"... | <|body_start_0|>
Whh = np.random.randn(h, h)
Whx = np.random.randn(i, h)
self.Wh = np.concatenate((Whh, Whx), axis=0)
self.Wy = np.random.randn(h, o)
self.bh = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
x_max = np.max(x, axis=-1, ... | RNNCell class, vanila model | RNNCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNCell:
"""RNNCell class, vanila model"""
def __init__(self, i, h, o):
"""initialized the variables Arg: - i: is the dimensionality of the data - h: is the dimensionality of the hidden state - o: is the dimensionality of the outputs - Public instance attributes Wh, Wy, bh, by that r... | stack_v2_sparse_classes_36k_train_018714 | 1,721 | no_license | [
{
"docstring": "initialized the variables Arg: - i: is the dimensionality of the data - h: is the dimensionality of the hidden state - o: is the dimensionality of the outputs - Public instance attributes Wh, Wy, bh, by that represent the weights and biases of the cell - Wh and bh: for the concat hidden state an... | 3 | stack_v2_sparse_classes_30k_val_000661 | Implement the Python class `RNNCell` described below.
Class description:
RNNCell class, vanila model
Method signatures and docstrings:
- def __init__(self, i, h, o): initialized the variables Arg: - i: is the dimensionality of the data - h: is the dimensionality of the hidden state - o: is the dimensionality of the o... | Implement the Python class `RNNCell` described below.
Class description:
RNNCell class, vanila model
Method signatures and docstrings:
- def __init__(self, i, h, o): initialized the variables Arg: - i: is the dimensionality of the data - h: is the dimensionality of the hidden state - o: is the dimensionality of the o... | 5aff923277cfe9f2b5324a773e4e5c3cac810a0c | <|skeleton|>
class RNNCell:
"""RNNCell class, vanila model"""
def __init__(self, i, h, o):
"""initialized the variables Arg: - i: is the dimensionality of the data - h: is the dimensionality of the hidden state - o: is the dimensionality of the outputs - Public instance attributes Wh, Wy, bh, by that r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNCell:
"""RNNCell class, vanila model"""
def __init__(self, i, h, o):
"""initialized the variables Arg: - i: is the dimensionality of the data - h: is the dimensionality of the hidden state - o: is the dimensionality of the outputs - Public instance attributes Wh, Wy, bh, by that represent the ... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/0-rnn_cell.py | cmmolanos1/holbertonschool-machine_learning | train | 1 |
31992966e5b7060b3b25752f22042bc13fa28e00 | [
"rng = random.PRNGKey(0)\nsamples = sampling.multinomial(rng=rng, logits=jnp.array(logits))\nself.assertAllEqual(samples, expected_samples)",
"seqs = ['abab', 'baba'] * 64\ndomain = domains.VariableLengthDiscreteDomain(vocab=domains.Vocabulary(tokens=['a', 'b'], include_bos=True, include_eos=True), length=len(seq... | <|body_start_0|>
rng = random.PRNGKey(0)
samples = sampling.multinomial(rng=rng, logits=jnp.array(logits))
self.assertAllEqual(samples, expected_samples)
<|end_body_0|>
<|body_start_1|>
seqs = ['abab', 'baba'] * 64
domain = domains.VariableLengthDiscreteDomain(vocab=domains.Voca... | SamplingTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SamplingTest:
def test_multinomial(self, logits, expected_samples):
"""Tests that multinomial works as expected_samples."""
<|body_0|>
def _make_pretrained_transformer(self, **kwargs):
"""Trains a transformer to produce strings of alternating a's and b's."""
... | stack_v2_sparse_classes_36k_train_018715 | 3,262 | permissive | [
{
"docstring": "Tests that multinomial works as expected_samples.",
"name": "test_multinomial",
"signature": "def test_multinomial(self, logits, expected_samples)"
},
{
"docstring": "Trains a transformer to produce strings of alternating a's and b's.",
"name": "_make_pretrained_transformer",... | 4 | null | Implement the Python class `SamplingTest` described below.
Class description:
Implement the SamplingTest class.
Method signatures and docstrings:
- def test_multinomial(self, logits, expected_samples): Tests that multinomial works as expected_samples.
- def _make_pretrained_transformer(self, **kwargs): Trains a trans... | Implement the Python class `SamplingTest` described below.
Class description:
Implement the SamplingTest class.
Method signatures and docstrings:
- def test_multinomial(self, logits, expected_samples): Tests that multinomial works as expected_samples.
- def _make_pretrained_transformer(self, **kwargs): Trains a trans... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class SamplingTest:
def test_multinomial(self, logits, expected_samples):
"""Tests that multinomial works as expected_samples."""
<|body_0|>
def _make_pretrained_transformer(self, **kwargs):
"""Trains a transformer to produce strings of alternating a's and b's."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SamplingTest:
def test_multinomial(self, logits, expected_samples):
"""Tests that multinomial works as expected_samples."""
rng = random.PRNGKey(0)
samples = sampling.multinomial(rng=rng, logits=jnp.array(logits))
self.assertAllEqual(samples, expected_samples)
def _make_pr... | the_stack_v2_python_sparse | protein_lm/sampling_test.py | Jimmy-INL/google-research | train | 1 | |
c8c422668bde104a1fd2e7525a44ecd2406dcf52 | [
"if 'form.button.Cancel' in self.request.form.keys():\n return self.doReturn(_('migration_error_cancel', default=u'Migration canceled.'), 'info')\nif not 'form.button.Migrate' in self.request.form.keys():\n return self.index()\nif not self.request.form.get('src_type', '') and (not self.request.form.get('dst_t... | <|body_start_0|>
if 'form.button.Cancel' in self.request.form.keys():
return self.doReturn(_('migration_error_cancel', default=u'Migration canceled.'), 'info')
if not 'form.button.Migrate' in self.request.form.keys():
return self.index()
if not self.request.form.get('src_... | A view that allows to migrate a portal-type into another | MigrateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MigrateView:
"""A view that allows to migrate a portal-type into another"""
def __call__(self):
"""Check values in the request, and make the right action"""
<|body_0|>
def doMigration(self):
"""handle migration from a portal_type to anther, and log all outputs gi... | stack_v2_sparse_classes_36k_train_018716 | 3,781 | no_license | [
{
"docstring": "Check values in the request, and make the right action",
"name": "__call__",
"signature": "def __call__(self)"
},
{
"docstring": "handle migration from a portal_type to anther, and log all outputs given",
"name": "doMigration",
"signature": "def doMigration(self)"
},
... | 4 | null | Implement the Python class `MigrateView` described below.
Class description:
A view that allows to migrate a portal-type into another
Method signatures and docstrings:
- def __call__(self): Check values in the request, and make the right action
- def doMigration(self): handle migration from a portal_type to anther, a... | Implement the Python class `MigrateView` described below.
Class description:
A view that allows to migrate a portal-type into another
Method signatures and docstrings:
- def __call__(self): Check values in the request, and make the right action
- def doMigration(self): handle migration from a portal_type to anther, a... | 99f1e99d7fe7335eb97aac21a46eb2a0cc3c3a48 | <|skeleton|>
class MigrateView:
"""A view that allows to migrate a portal-type into another"""
def __call__(self):
"""Check values in the request, and make the right action"""
<|body_0|>
def doMigration(self):
"""handle migration from a portal_type to anther, and log all outputs gi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MigrateView:
"""A view that allows to migrate a portal-type into another"""
def __call__(self):
"""Check values in the request, and make the right action"""
if 'form.button.Cancel' in self.request.form.keys():
return self.doReturn(_('migration_error_cancel', default=u'Migratio... | the_stack_v2_python_sparse | src/rt.atmigrator/rt/atmigrator/browser/migrate_types.py | Proteus-tech/ejn-buildout | train | 0 |
d034f1931851f04fe8d1df1fde9fec3f629f3300 | [
"self._limit = limit\nself._current_batch: List[BatchPlanner[_T].BatchPart] = []\nself._current_batch_size = 0\nself._batches: List[BatchPlanner[_T].Batch] = []",
"if self._current_batch_size + count > self._limit:\n delta = self._limit - self._current_batch_size\n self._current_batch.append((key, offset, d... | <|body_start_0|>
self._limit = limit
self._current_batch: List[BatchPlanner[_T].BatchPart] = []
self._current_batch_size = 0
self._batches: List[BatchPlanner[_T].Batch] = []
<|end_body_0|>
<|body_start_1|>
if self._current_batch_size + count > self._limit:
delta = se... | Helper class to batch operations based on affected rows limit. Typical example: batching delete operations. Database backends often have limits on number of rows to be modified within a single transaction. These can be hard limits imposed by the DB design or practical limits that have to be respected for optimal perfor... | BatchPlanner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchPlanner:
"""Helper class to batch operations based on affected rows limit. Typical example: batching delete operations. Database backends often have limits on number of rows to be modified within a single transaction. These can be hard limits imposed by the DB design or practical limits that... | stack_v2_sparse_classes_36k_train_018717 | 10,610 | permissive | [
{
"docstring": "Constructor. Args: limit: Maximum limit of rows that an operation can be performed on in a single batch.",
"name": "__init__",
"signature": "def __init__(self, limit: int)"
},
{
"docstring": "An utility method to plan a single operation. Args: key: Any value identifying a group o... | 4 | null | Implement the Python class `BatchPlanner` described below.
Class description:
Helper class to batch operations based on affected rows limit. Typical example: batching delete operations. Database backends often have limits on number of rows to be modified within a single transaction. These can be hard limits imposed by... | Implement the Python class `BatchPlanner` described below.
Class description:
Helper class to batch operations based on affected rows limit. Typical example: batching delete operations. Database backends often have limits on number of rows to be modified within a single transaction. These can be hard limits imposed by... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class BatchPlanner:
"""Helper class to batch operations based on affected rows limit. Typical example: batching delete operations. Database backends often have limits on number of rows to be modified within a single transaction. These can be hard limits imposed by the DB design or practical limits that... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchPlanner:
"""Helper class to batch operations based on affected rows limit. Typical example: batching delete operations. Database backends often have limits on number of rows to be modified within a single transaction. These can be hard limits imposed by the DB design or practical limits that have to be r... | the_stack_v2_python_sparse | grr/server/grr_response_server/databases/db_utils.py | google/grr | train | 4,683 |
27052a245422609bf5b10c68b41dd6ef786f510f | [
"self.A = array([[10.161209, 1.2196541, -3.1371353], [1.2196541, 7.7162264, 0.72990862], [-3.1371353, 0.72990862, 6.1225643]], dtype=float)\nself.b = array([9.8826956, -6.7155449, -5.7038132], dtype=float)\nself.x0 = zeros(self.A.shape[0])\nself.eps = 1 / 10 ** 5",
"x = approximate_Jacobi(self.A, self.b, self.x0,... | <|body_start_0|>
self.A = array([[10.161209, 1.2196541, -3.1371353], [1.2196541, 7.7162264, 0.72990862], [-3.1371353, 0.72990862, 6.1225643]], dtype=float)
self.b = array([9.8826956, -6.7155449, -5.7038132], dtype=float)
self.x0 = zeros(self.A.shape[0])
self.eps = 1 / 10 ** 5
<|end_body_... | IterativeMethodTestCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IterativeMethodTestCase:
def setUp(self):
"""initial set up"""
<|body_0|>
def test_approximate_Jacobi(self):
"""Verify the correctness of the solution of the system"""
<|body_1|>
def test_approximate_Nekrasov(self):
"""Verify the correctness of t... | stack_v2_sparse_classes_36k_train_018718 | 1,756 | permissive | [
{
"docstring": "initial set up",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Verify the correctness of the solution of the system",
"name": "test_approximate_Jacobi",
"signature": "def test_approximate_Jacobi(self)"
},
{
"docstring": "Verify the correctness... | 4 | stack_v2_sparse_classes_30k_train_019066 | Implement the Python class `IterativeMethodTestCase` described below.
Class description:
Implement the IterativeMethodTestCase class.
Method signatures and docstrings:
- def setUp(self): initial set up
- def test_approximate_Jacobi(self): Verify the correctness of the solution of the system
- def test_approximate_Nek... | Implement the Python class `IterativeMethodTestCase` described below.
Class description:
Implement the IterativeMethodTestCase class.
Method signatures and docstrings:
- def setUp(self): initial set up
- def test_approximate_Jacobi(self): Verify the correctness of the solution of the system
- def test_approximate_Nek... | 65d6386f18e96a528b90b22130045e8349b82a98 | <|skeleton|>
class IterativeMethodTestCase:
def setUp(self):
"""initial set up"""
<|body_0|>
def test_approximate_Jacobi(self):
"""Verify the correctness of the solution of the system"""
<|body_1|>
def test_approximate_Nekrasov(self):
"""Verify the correctness of t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IterativeMethodTestCase:
def setUp(self):
"""initial set up"""
self.A = array([[10.161209, 1.2196541, -3.1371353], [1.2196541, 7.7162264, 0.72990862], [-3.1371353, 0.72990862, 6.1225643]], dtype=float)
self.b = array([9.8826956, -6.7155449, -5.7038132], dtype=float)
self.x0 = z... | the_stack_v2_python_sparse | IterativeMethod_SLE/test_iterative.py | AlbertMukhammadiev/NumericalAnalysis_Labworks | train | 0 | |
bac482190b131501460ef4b85db5547897848935 | [
"super().__init__()\nself.encoder = NMTEncoder(num_embeddings=source_vocab_size, embedding_size=source_embedding_size, rnn_hidden_size=encoding_size)\ndecoding_size = encoding_size * 2\nself.decoder = NMTDecoder(num_embedding=target_vocab_size, embedding_size=target_embedding_size, rnn_hidden_size=decoding_size, bo... | <|body_start_0|>
super().__init__()
self.encoder = NMTEncoder(num_embeddings=source_vocab_size, embedding_size=source_embedding_size, rnn_hidden_size=encoding_size)
decoding_size = encoding_size * 2
self.decoder = NMTDecoder(num_embedding=target_vocab_size, embedding_size=target_embeddin... | A Neural Machine Translation Model | NMTModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NMTModel:
"""A Neural Machine Translation Model"""
def __init__(self, source_vocab_size, source_embedding_size, target_vocab_size, target_embedding_size, encoding_size, target_bos_index):
"""Args :param source_vocab_size: int, number of unique words in source language :param source_e... | stack_v2_sparse_classes_36k_train_018719 | 9,631 | permissive | [
{
"docstring": "Args :param source_vocab_size: int, number of unique words in source language :param source_embedding_size: int, size of the source embedding vectors :param target_vocab_size: int, number of unique words in target language :param target_embedding_size: int, size of the target embedding vectors :... | 2 | stack_v2_sparse_classes_30k_train_004795 | Implement the Python class `NMTModel` described below.
Class description:
A Neural Machine Translation Model
Method signatures and docstrings:
- def __init__(self, source_vocab_size, source_embedding_size, target_vocab_size, target_embedding_size, encoding_size, target_bos_index): Args :param source_vocab_size: int, ... | Implement the Python class `NMTModel` described below.
Class description:
A Neural Machine Translation Model
Method signatures and docstrings:
- def __init__(self, source_vocab_size, source_embedding_size, target_vocab_size, target_embedding_size, encoding_size, target_bos_index): Args :param source_vocab_size: int, ... | c360e81624296c9243fd662dea618042164e0aa7 | <|skeleton|>
class NMTModel:
"""A Neural Machine Translation Model"""
def __init__(self, source_vocab_size, source_embedding_size, target_vocab_size, target_embedding_size, encoding_size, target_bos_index):
"""Args :param source_vocab_size: int, number of unique words in source language :param source_e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NMTModel:
"""A Neural Machine Translation Model"""
def __init__(self, source_vocab_size, source_embedding_size, target_vocab_size, target_embedding_size, encoding_size, target_bos_index):
"""Args :param source_vocab_size: int, number of unique words in source language :param source_embedding_size... | the_stack_v2_python_sparse | Tempermonkey-vue3-tfjs/torch/ml/mnt_model.py | flashlin/Samples | train | 3 |
07347fdf52d32af836753f5292dd4102a51a740b | [
"if len(s) < k:\n return 0\ncharDic = {}\nfor x in s:\n if x not in charDic:\n charDic[x] = 1\n else:\n charDic[x] += 1\nminChar = min(charDic, key=charDic.get)\nprint(minChar)\nif s.count(minChar) >= k:\n return len(s)\nmaxSubstring = 0\nfor t in s.split(minChar):\n maxSubstring = max(... | <|body_start_0|>
if len(s) < k:
return 0
charDic = {}
for x in s:
if x not in charDic:
charDic[x] = 1
else:
charDic[x] += 1
minChar = min(charDic, key=charDic.get)
print(minChar)
if s.count(minChar) >= k:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def longestSubstring2(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
def longestSubstring_rec(self, s, k):
""":type s: str :ty... | stack_v2_sparse_classes_36k_train_018720 | 4,375 | no_license | [
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "longestSubstring",
"signature": "def longestSubstring(self, s, k)"
},
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "longestSubstring2",
"signature": "def longestSubstring2(self, s, k)"
},
{
"docst... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstring2(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstring_rec(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstring2(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstring_rec(self... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def longestSubstring2(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
def longestSubstring_rec(self, s, k):
""":type s: str :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
if len(s) < k:
return 0
charDic = {}
for x in s:
if x not in charDic:
charDic[x] = 1
else:
charDic[x] += 1
minChar... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00395.Longest Substring with At Least K Repeating Characters.py | roger6blog/LeetCode | train | 0 | |
c7906a841ce1fee46eb9ae5fb3a22ce35c7fb388 | [
"super().__init__()\nself.self_attention = self_attention\nself.feed_forward = feed_forward\nself.norm1 = LayerNorm(hdim)\nself.norm2 = LayerNorm(hdim)\nself.dropout = torch.nn.Dropout(dropout_rate)\nself.hdim = hdim",
"residual = sequence\nsequence = self.norm1(sequence)\nif cache is None:\n sequence_q = sequ... | <|body_start_0|>
super().__init__()
self.self_attention = self_attention
self.feed_forward = feed_forward
self.norm1 = LayerNorm(hdim)
self.norm2 = LayerNorm(hdim)
self.dropout = torch.nn.Dropout(dropout_rate)
self.hdim = hdim
<|end_body_0|>
<|body_start_1|>
... | Transformer decoder layer module for custom Transducer model. Args: hdim: Hidden dimension. self_attention: Self-attention module. feed_forward: Feed forward module. dropout_rate: Dropout rate. | TransformerDecoderLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerDecoderLayer:
"""Transformer decoder layer module for custom Transducer model. Args: hdim: Hidden dimension. self_attention: Self-attention module. feed_forward: Feed forward module. dropout_rate: Dropout rate."""
def __init__(self, hdim: int, self_attention: MultiHeadedAttention,... | stack_v2_sparse_classes_36k_train_018721 | 2,702 | permissive | [
{
"docstring": "Construct an DecoderLayer object.",
"name": "__init__",
"signature": "def __init__(self, hdim: int, self_attention: MultiHeadedAttention, feed_forward: PositionwiseFeedForward, dropout_rate: float)"
},
{
"docstring": "Compute previous decoder output sequences. Args: sequence: Tra... | 2 | null | Implement the Python class `TransformerDecoderLayer` described below.
Class description:
Transformer decoder layer module for custom Transducer model. Args: hdim: Hidden dimension. self_attention: Self-attention module. feed_forward: Feed forward module. dropout_rate: Dropout rate.
Method signatures and docstrings:
-... | Implement the Python class `TransformerDecoderLayer` described below.
Class description:
Transformer decoder layer module for custom Transducer model. Args: hdim: Hidden dimension. self_attention: Self-attention module. feed_forward: Feed forward module. dropout_rate: Dropout rate.
Method signatures and docstrings:
-... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class TransformerDecoderLayer:
"""Transformer decoder layer module for custom Transducer model. Args: hdim: Hidden dimension. self_attention: Self-attention module. feed_forward: Feed forward module. dropout_rate: Dropout rate."""
def __init__(self, hdim: int, self_attention: MultiHeadedAttention,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerDecoderLayer:
"""Transformer decoder layer module for custom Transducer model. Args: hdim: Hidden dimension. self_attention: Self-attention module. feed_forward: Feed forward module. dropout_rate: Dropout rate."""
def __init__(self, hdim: int, self_attention: MultiHeadedAttention, feed_forward... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transducer/transformer_decoder_layer.py | espnet/espnet | train | 7,242 |
8e90ccbc1d636dbbc6ad35c03bf49577bbbdde39 | [
"cls = self.model\nattr_list = cls._meta.get_all_field_names()\nreturn attr_list",
"cls = self.model\nattr_list = cls._meta.get_fields()\nattr_str_list = []\nfor attr in attr_list:\n if isinstance(attr, models.ForeignKey):\n attr_str = '%s_id' % attr.name\n attr_str_list.append(attr_str)\n els... | <|body_start_0|>
cls = self.model
attr_list = cls._meta.get_all_field_names()
return attr_list
<|end_body_0|>
<|body_start_1|>
cls = self.model
attr_list = cls._meta.get_fields()
attr_str_list = []
for attr in attr_list:
if isinstance(attr, models.For... | 模型管理器类抽象基类 | BaseModelManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseModelManager:
"""模型管理器类抽象基类"""
def get_all_valid_fields(self):
"""获取模型管理器对象所在模型类的属性列表"""
<|body_0|>
def get_all_valid_fields2(self):
"""获取模型管理器对象所在模型类的属性列表"""
<|body_1|>
def create_one_object(self, **kwargs):
"""往数据库中插入一条模型管理器对象所在的模型类数据""... | stack_v2_sparse_classes_36k_train_018722 | 2,914 | no_license | [
{
"docstring": "获取模型管理器对象所在模型类的属性列表",
"name": "get_all_valid_fields",
"signature": "def get_all_valid_fields(self)"
},
{
"docstring": "获取模型管理器对象所在模型类的属性列表",
"name": "get_all_valid_fields2",
"signature": "def get_all_valid_fields2(self)"
},
{
"docstring": "往数据库中插入一条模型管理器对象所在的模型类数据... | 5 | stack_v2_sparse_classes_30k_train_015043 | Implement the Python class `BaseModelManager` described below.
Class description:
模型管理器类抽象基类
Method signatures and docstrings:
- def get_all_valid_fields(self): 获取模型管理器对象所在模型类的属性列表
- def get_all_valid_fields2(self): 获取模型管理器对象所在模型类的属性列表
- def create_one_object(self, **kwargs): 往数据库中插入一条模型管理器对象所在的模型类数据
- def get_one_ob... | Implement the Python class `BaseModelManager` described below.
Class description:
模型管理器类抽象基类
Method signatures and docstrings:
- def get_all_valid_fields(self): 获取模型管理器对象所在模型类的属性列表
- def get_all_valid_fields2(self): 获取模型管理器对象所在模型类的属性列表
- def create_one_object(self, **kwargs): 往数据库中插入一条模型管理器对象所在的模型类数据
- def get_one_ob... | ac01a1cba0e0068cd33d30bfd60d2a5df6bc5114 | <|skeleton|>
class BaseModelManager:
"""模型管理器类抽象基类"""
def get_all_valid_fields(self):
"""获取模型管理器对象所在模型类的属性列表"""
<|body_0|>
def get_all_valid_fields2(self):
"""获取模型管理器对象所在模型类的属性列表"""
<|body_1|>
def create_one_object(self, **kwargs):
"""往数据库中插入一条模型管理器对象所在的模型类数据""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseModelManager:
"""模型管理器类抽象基类"""
def get_all_valid_fields(self):
"""获取模型管理器对象所在模型类的属性列表"""
cls = self.model
attr_list = cls._meta.get_all_field_names()
return attr_list
def get_all_valid_fields2(self):
"""获取模型管理器对象所在模型类的属性列表"""
cls = self.model
... | the_stack_v2_python_sparse | salesmindData/db/base_manager.py | piaoxue85/salesmindData | train | 0 |
90c429e552d5a516231a8a4794c595ccf1b645fd | [
"timestamp = self._GetDecimalValueFromStructure(structure, 'timestamp')\nevent_data = BashHistoryEventData()\nevent_data.command = self._GetValueFromStructure(structure, 'command')\nevent_data.written_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)\nparser_mediator.ProduceEventData(event_data)",
"try:... | <|body_start_0|>
timestamp = self._GetDecimalValueFromStructure(structure, 'timestamp')
event_data = BashHistoryEventData()
event_data.command = self._GetValueFromStructure(structure, 'command')
event_data.written_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)
parser... | Text parser plugin for bash history files. | BashHistoryTextPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BashHistoryTextPlugin:
"""Text parser plugin for bash history files."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and df... | stack_v2_sparse_classes_36k_train_018723 | 2,889 | permissive | [
{
"docstring": "Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. key (str): name of the parsed structure. structure (pyparsing.ParseResults): tokens from a parsed log line. Raises: ParseError: if the stru... | 2 | null | Implement the Python class `BashHistoryTextPlugin` described below.
Class description:
Text parser plugin for bash history files.
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions bet... | Implement the Python class `BashHistoryTextPlugin` described below.
Class description:
Text parser plugin for bash history files.
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions bet... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class BashHistoryTextPlugin:
"""Text parser plugin for bash history files."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and df... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BashHistoryTextPlugin:
"""Text parser plugin for bash history files."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. key (str... | the_stack_v2_python_sparse | plaso/parsers/text_plugins/bash_history.py | log2timeline/plaso | train | 1,506 |
bf902f72d626e008e5d3ec43c39409035d5521d2 | [
"self.ls = []\nself.k2v = {}\nself.cap = capacity",
"if key in self.k2v:\n self.ls.remove(key)\n self.ls.append(key)\n return self.k2v[key]\nreturn -1",
"if key in self.k2v:\n self.ls.remove(key)\nelif len(self.ls) >= self.cap:\n del self.k2v[self.ls.pop(0)]\nself.k2v[key] = value\nself.ls.append... | <|body_start_0|>
self.ls = []
self.k2v = {}
self.cap = capacity
<|end_body_0|>
<|body_start_1|>
if key in self.k2v:
self.ls.remove(key)
self.ls.append(key)
return self.k2v[key]
return -1
<|end_body_1|>
<|body_start_2|>
if key in self.... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_018724 | 1,307 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | 737b9bac5a73c319e46cda8c3e9d729f734d7792 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.ls = []
self.k2v = {}
self.cap = capacity
def get(self, key):
""":rtype: int"""
if key in self.k2v:
self.ls.remove(key)
self.ls.append(key)
return sel... | the_stack_v2_python_sparse | leetcode/python/passedProblems/146-lru-cache.py | iampkuhz/OnlineJudge_cpp | train | 0 | |
51f17ffa5fdc037560df22a267e783b7a6bba3ef | [
"logger.info('%s initialization' % obj.name)\nsuper(self.__class__, self).__init__(obj, parent)\nself.local_data['x'] = 0.0\nself.local_data['y'] = 0.0\nself.local_data['z'] = 0.0\nself.local_data['yaw'] = 0.0\nself.local_data['pitch'] = 0.0\nself.local_data['roll'] = 0.0\nlogger.info('Component initialized')",
"... | <|body_start_0|>
logger.info('%s initialization' % obj.name)
super(self.__class__, self).__init__(obj, parent)
self.local_data['x'] = 0.0
self.local_data['y'] = 0.0
self.local_data['z'] = 0.0
self.local_data['yaw'] = 0.0
self.local_data['pitch'] = 0.0
self... | Robot pose sensor, including position and orientation | PoseClass | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoseClass:
"""Robot pose sensor, including position and orientation"""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
<|body_0|>
def default_act... | stack_v2_sparse_classes_36k_train_018725 | 1,814 | permissive | [
{
"docstring": "Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent.",
"name": "__init__",
"signature": "def __init__(self, obj, parent=None)"
},
{
"docstring": "Get the x, y, z, yaw, pitch and roll of the blender objec... | 2 | stack_v2_sparse_classes_30k_train_015870 | Implement the Python class `PoseClass` described below.
Class description:
Robot pose sensor, including position and orientation
Method signatures and docstrings:
- def __init__(self, obj, parent=None): Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the ob... | Implement the Python class `PoseClass` described below.
Class description:
Robot pose sensor, including position and orientation
Method signatures and docstrings:
- def __init__(self, obj, parent=None): Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the ob... | 07fcb64fea3b58b258e917eb1aed0a585f863418 | <|skeleton|>
class PoseClass:
"""Robot pose sensor, including position and orientation"""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
<|body_0|>
def default_act... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PoseClass:
"""Robot pose sensor, including position and orientation"""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
logger.info('%s initialization' % obj.name)
... | the_stack_v2_python_sparse | src/morse/sensors/pose.py | DefaultUser/morse | train | 2 |
accf9cf443b0fbe99a239f23f27fbc03809718cb | [
"def preorder(root, string):\n if root == None:\n string += 'None,'\n else:\n string += str(root.val) + ','\n string = preorder(root.left, string)\n string = preorder(root.right, string)\n return string\nreturn preorder(root, '')",
"def reconstructTree(data):\n if data[0] =... | <|body_start_0|>
def preorder(root, string):
if root == None:
string += 'None,'
else:
string += str(root.val) + ','
string = preorder(root.left, string)
string = preorder(root.right, string)
return string
... | Solution Method 参考答案给的解法是将二叉树DFS序列化,然后对其反序列化 这里我最关键的是每想到这样去反序列化,因为python传参是引用传参,通过这种先左后右虽然传 的都是同一个data,但是其实在左子树和右子树的建立中所看到的data是不一样的,而序列化的建立过程中 又是先左后右的,所以对一个序列用data[0]去建立节点反序列化是可以构造出原来的树的,而且这种DFS的 方法不会像我用层次遍历一样建立很多none的空节点,效率相对来说高 ❗️❗️❗️: 其实第105题根据先序和中序构造二叉树也是巧妙地利用了这种传参就是传引用的特点,对二叉树进行的 处理,可以回顾一下 再一个是序列化的过程中要注意参数传递的意义和值... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""Solution Method 参考答案给的解法是将二叉树DFS序列化,然后对其反序列化 这里我最关键的是每想到这样去反序列化,因为python传参是引用传参,通过这种先左后右虽然传 的都是同一个data,但是其实在左子树和右子树的建立中所看到的data是不一样的,而序列化的建立过程中 又是先左后右的,所以对一个序列用data[0]去建立节点反序列化是可以构造出原来的树的,而且这种DFS的 方法不会像我用层次遍历一样建立很多none的空节点,效率相对来说高 ❗️❗️❗️: 其实第105题根据先序和中序构造二叉树也是巧妙地利用了这种传参就是传引用的特点,对二叉树进行的 ... | stack_v2_sparse_classes_36k_train_018726 | 2,554 | 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_012832 | Implement the Python class `Codec` described below.
Class description:
Solution Method 参考答案给的解法是将二叉树DFS序列化,然后对其反序列化 这里我最关键的是每想到这样去反序列化,因为python传参是引用传参,通过这种先左后右虽然传 的都是同一个data,但是其实在左子树和右子树的建立中所看到的data是不一样的,而序列化的建立过程中 又是先左后右的,所以对一个序列用data[0]去建立节点反序列化是可以构造出原来的树的,而且这种DFS的 方法不会像我用层次遍历一样建立很多none的空节点,效率相对来说高 ❗️❗️❗️: 其实第105题根据... | Implement the Python class `Codec` described below.
Class description:
Solution Method 参考答案给的解法是将二叉树DFS序列化,然后对其反序列化 这里我最关键的是每想到这样去反序列化,因为python传参是引用传参,通过这种先左后右虽然传 的都是同一个data,但是其实在左子树和右子树的建立中所看到的data是不一样的,而序列化的建立过程中 又是先左后右的,所以对一个序列用data[0]去建立节点反序列化是可以构造出原来的树的,而且这种DFS的 方法不会像我用层次遍历一样建立很多none的空节点,效率相对来说高 ❗️❗️❗️: 其实第105题根据... | a1c074ff0d542f7ef0e5e01e280b16e52fa7a33d | <|skeleton|>
class Codec:
"""Solution Method 参考答案给的解法是将二叉树DFS序列化,然后对其反序列化 这里我最关键的是每想到这样去反序列化,因为python传参是引用传参,通过这种先左后右虽然传 的都是同一个data,但是其实在左子树和右子树的建立中所看到的data是不一样的,而序列化的建立过程中 又是先左后右的,所以对一个序列用data[0]去建立节点反序列化是可以构造出原来的树的,而且这种DFS的 方法不会像我用层次遍历一样建立很多none的空节点,效率相对来说高 ❗️❗️❗️: 其实第105题根据先序和中序构造二叉树也是巧妙地利用了这种传参就是传引用的特点,对二叉树进行的 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
"""Solution Method 参考答案给的解法是将二叉树DFS序列化,然后对其反序列化 这里我最关键的是每想到这样去反序列化,因为python传参是引用传参,通过这种先左后右虽然传 的都是同一个data,但是其实在左子树和右子树的建立中所看到的data是不一样的,而序列化的建立过程中 又是先左后右的,所以对一个序列用data[0]去建立节点反序列化是可以构造出原来的树的,而且这种DFS的 方法不会像我用层次遍历一样建立很多none的空节点,效率相对来说高 ❗️❗️❗️: 其实第105题根据先序和中序构造二叉树也是巧妙地利用了这种传参就是传引用的特点,对二叉树进行的 处理,可以回顾一下 再一个... | the_stack_v2_python_sparse | 297_Serialize and Deserialize Binary Tree.py | xhwupup/xhw_project | train | 0 |
2bb76b879c283eefc51750ffa292312b2bbef3c5 | [
"self.start_time = get_start_time(run_history)\nself.metric = metric\nself.search_results = SearchResults(metric=metric, run_history=run_history, scoring_functions=[], order_by_endtime=True)\nself.ensemble_results = EnsembleResults(metric=metric, ensemble_performance_history=ensemble_performance_history, order_by_e... | <|body_start_0|>
self.start_time = get_start_time(run_history)
self.metric = metric
self.search_results = SearchResults(metric=metric, run_history=run_history, scoring_functions=[], order_by_endtime=True)
self.ensemble_results = EnsembleResults(metric=metric, ensemble_performance_history... | MetricResults | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-philippe-de-muyter"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricResults:
def __init__(self, metric: autoPyTorchMetric, run_history: RunHistory, ensemble_performance_history: List[Dict[str, Any]]):
"""The wrapper class for ensemble_performance_history. This class extracts the information from ensemble_performance_history and allows other class t... | stack_v2_sparse_classes_36k_train_018727 | 30,202 | permissive | [
{
"docstring": "The wrapper class for ensemble_performance_history. This class extracts the information from ensemble_performance_history and allows other class to easily handle the history. Note that all the data is sorted by endtime! Attributes: start_time (float): The timestamp at the very beginning of the o... | 3 | stack_v2_sparse_classes_30k_train_008048 | Implement the Python class `MetricResults` described below.
Class description:
Implement the MetricResults class.
Method signatures and docstrings:
- def __init__(self, metric: autoPyTorchMetric, run_history: RunHistory, ensemble_performance_history: List[Dict[str, Any]]): The wrapper class for ensemble_performance_h... | Implement the Python class `MetricResults` described below.
Class description:
Implement the MetricResults class.
Method signatures and docstrings:
- def __init__(self, metric: autoPyTorchMetric, run_history: RunHistory, ensemble_performance_history: List[Dict[str, Any]]): The wrapper class for ensemble_performance_h... | 56a2ac1d69c7c61a847c678879a67f5d3672b3e8 | <|skeleton|>
class MetricResults:
def __init__(self, metric: autoPyTorchMetric, run_history: RunHistory, ensemble_performance_history: List[Dict[str, Any]]):
"""The wrapper class for ensemble_performance_history. This class extracts the information from ensemble_performance_history and allows other class t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetricResults:
def __init__(self, metric: autoPyTorchMetric, run_history: RunHistory, ensemble_performance_history: List[Dict[str, Any]]):
"""The wrapper class for ensemble_performance_history. This class extracts the information from ensemble_performance_history and allows other class to easily handl... | the_stack_v2_python_sparse | autoPyTorch/utils/results_manager.py | automl/Auto-PyTorch | train | 2,214 | |
b2949d5231c56a45587b301ce96e405745632199 | [
"cluster = self.get_object_or_404(objects.Cluster, cluster_id)\nattrs = objects.Cluster.get_default_editable_attributes(cluster)\nif not attrs:\n raise self.http(500, 'No attributes found!')\nreturn {'editable': attrs}",
"cluster = self.get_object_or_404(objects.Cluster, cluster_id, log_404=('error', \"There i... | <|body_start_0|>
cluster = self.get_object_or_404(objects.Cluster, cluster_id)
attrs = objects.Cluster.get_default_editable_attributes(cluster)
if not attrs:
raise self.http(500, 'No attributes found!')
return {'editable': attrs}
<|end_body_0|>
<|body_start_1|>
clust... | Cluster default attributes handler | ClusterAttributesDefaultsHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterAttributesDefaultsHandler:
"""Cluster default attributes handler"""
def GET(self, cluster_id):
""":returns: JSONized default Cluster attributes. :http: * 200 (OK) * 404 (cluster not found in db) * 500 (cluster has no attributes)"""
<|body_0|>
def PUT(self, cluster... | stack_v2_sparse_classes_36k_train_018728 | 16,652 | permissive | [
{
"docstring": ":returns: JSONized default Cluster attributes. :http: * 200 (OK) * 404 (cluster not found in db) * 500 (cluster has no attributes)",
"name": "GET",
"signature": "def GET(self, cluster_id)"
},
{
"docstring": ":returns: JSONized Cluster attributes. :http: * 200 (OK) * 400 (wrong at... | 2 | stack_v2_sparse_classes_30k_train_012287 | Implement the Python class `ClusterAttributesDefaultsHandler` described below.
Class description:
Cluster default attributes handler
Method signatures and docstrings:
- def GET(self, cluster_id): :returns: JSONized default Cluster attributes. :http: * 200 (OK) * 404 (cluster not found in db) * 500 (cluster has no att... | Implement the Python class `ClusterAttributesDefaultsHandler` described below.
Class description:
Cluster default attributes handler
Method signatures and docstrings:
- def GET(self, cluster_id): :returns: JSONized default Cluster attributes. :http: * 200 (OK) * 404 (cluster not found in db) * 500 (cluster has no att... | 768ac74a420f822261c4eb8da72f1d8af3c6bbff | <|skeleton|>
class ClusterAttributesDefaultsHandler:
"""Cluster default attributes handler"""
def GET(self, cluster_id):
""":returns: JSONized default Cluster attributes. :http: * 200 (OK) * 404 (cluster not found in db) * 500 (cluster has no attributes)"""
<|body_0|>
def PUT(self, cluster... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClusterAttributesDefaultsHandler:
"""Cluster default attributes handler"""
def GET(self, cluster_id):
""":returns: JSONized default Cluster attributes. :http: * 200 (OK) * 404 (cluster not found in db) * 500 (cluster has no attributes)"""
cluster = self.get_object_or_404(objects.Cluster, ... | the_stack_v2_python_sparse | nailgun/nailgun/api/v1/handlers/cluster.py | dis-xcom/fuel-web | train | 0 |
a7b6fa09182ed79244a86c8925762b58ad12de9d | [
"identity = (yield gen.Task(Identity.Query, self._client, identity_key, None))\ntry:\n yield identity.VerifyAccessToken(self._client, identity.access_token)\nexcept Exception as ex:\n logging.info('error during access token verification: %s', ex)\n raise ExpiredError(EXPIRED_EMAIL_LINK_ERROR)\nself.render(... | <|body_start_0|>
identity = (yield gen.Task(Identity.Query, self._client, identity_key, None))
try:
yield identity.VerifyAccessToken(self._client, identity.access_token)
except Exception as ex:
logging.info('error during access token verification: %s', ex)
rai... | This web request handler is invoked when a user clicks an identity verification link in an email that was triggered by a web site page. It renders a page that guides the user through the completion of the auth action. This may include confirmation of the user's password, and ends with a "well done" kind of page to noti... | VerifyIdWebHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerifyIdWebHandler:
"""This web request handler is invoked when a user clicks an identity verification link in an email that was triggered by a web site page. It renders a page that guides the user through the completion of the auth action. This may include confirmation of the user's password, an... | stack_v2_sparse_classes_36k_train_018729 | 34,668 | permissive | [
{
"docstring": "This handler is invoked when the user clicks a ShortURL link in a verification email that was sent to them. Returns a page that guides the user through the completion of the operation.",
"name": "_HandleGet",
"signature": "def _HandleGet(self, short_url, action, identity_key, user_name, ... | 2 | null | Implement the Python class `VerifyIdWebHandler` described below.
Class description:
This web request handler is invoked when a user clicks an identity verification link in an email that was triggered by a web site page. It renders a page that guides the user through the completion of the auth action. This may include ... | Implement the Python class `VerifyIdWebHandler` described below.
Class description:
This web request handler is invoked when a user clicks an identity verification link in an email that was triggered by a web site page. It renders a page that guides the user through the completion of the auth action. This may include ... | 992209086d01be0ef6506f325cf89b84d374f969 | <|skeleton|>
class VerifyIdWebHandler:
"""This web request handler is invoked when a user clicks an identity verification link in an email that was triggered by a web site page. It renders a page that guides the user through the completion of the auth action. This may include confirmation of the user's password, an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VerifyIdWebHandler:
"""This web request handler is invoked when a user clicks an identity verification link in an email that was triggered by a web site page. It renders a page that guides the user through the completion of the auth action. This may include confirmation of the user's password, and ends with a... | the_stack_v2_python_sparse | backend/www/auth_viewfinder.py | xuantan/viewfinder | train | 0 |
b552f04c5b924fdabd6779c0894a87f0be04f186 | [
"import bisect as bi\nif not points:\n return 0\nend_s = sorted([p[1] for p in points])\nstart_s = sorted(points, key=lambda x: x[0])\narrow = 0\ncurr_min_end = end_s[0]\nfor st in start_s:\n if st[0] <= curr_min_end:\n idx = bi.bisect_left(end_s, st[1])\n end_s.pop(idx)\n else:\n arro... | <|body_start_0|>
import bisect as bi
if not points:
return 0
end_s = sorted([p[1] for p in points])
start_s = sorted(points, key=lambda x: x[0])
arrow = 0
curr_min_end = end_s[0]
for st in start_s:
if st[0] <= curr_min_end:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int 類似 253. 先做 end/start sort 概念建立: 最小的end 是跟 start走 即唯一個pair 此pair的start為箭穿過的min point."""
<|body_0|>
def fast(self, points):
""":type points: List[List[int]] :rtype: int 類似 253.... | stack_v2_sparse_classes_36k_train_018730 | 3,818 | no_license | [
{
"docstring": ":type points: List[List[int]] :rtype: int 類似 253. 先做 end/start sort 概念建立: 最小的end 是跟 start走 即唯一個pair 此pair的start為箭穿過的min point.",
"name": "findMinArrowShots",
"signature": "def findMinArrowShots(self, points)"
},
{
"docstring": ":type points: List[List[int]] :rtype: int 類似 253. 先做... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int 類似 253. 先做 end/start sort 概念建立: 最小的end 是跟 start走 即唯一個pair 此pair的start為箭穿過的min point.
- def fast(sel... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int 類似 253. 先做 end/start sort 概念建立: 最小的end 是跟 start走 即唯一個pair 此pair的start為箭穿過的min point.
- def fast(sel... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int 類似 253. 先做 end/start sort 概念建立: 最小的end 是跟 start走 即唯一個pair 此pair的start為箭穿過的min point."""
<|body_0|>
def fast(self, points):
""":type points: List[List[int]] :rtype: int 類似 253.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int 類似 253. 先做 end/start sort 概念建立: 最小的end 是跟 start走 即唯一個pair 此pair的start為箭穿過的min point."""
import bisect as bi
if not points:
return 0
end_s = sorted([p[1] for p in points])
... | the_stack_v2_python_sparse | co_ms/452_Minimum_Number_of_Arrows_to_Burst_Balloons.py | vsdrun/lc_public | train | 6 | |
d2b3d469189b6f2ca163caf888abf16853232af6 | [
"super(IPAssociationsClient, self).__init__(serialize_format, deserialize_format)\nself.auth_token = auth_token\nself.default_headers['X-Auth-Token'] = auth_token\nct = '{content_type}/{content_subtype}'.format(content_type='application', content_subtype=self.serialize_format)\naccept = '{content_type}/{content_sub... | <|body_start_0|>
super(IPAssociationsClient, self).__init__(serialize_format, deserialize_format)
self.auth_token = auth_token
self.default_headers['X-Auth-Token'] = auth_token
ct = '{content_type}/{content_subtype}'.format(content_type='application', content_subtype=self.serialize_forma... | IPAssociationsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPAssociationsClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None):
"""@summary: Rackspace Compute API IP Associations extension client @param url: Base URL for the compute service @type url: string @param auth_token: Auth token to be used for all r... | stack_v2_sparse_classes_36k_train_018731 | 6,302 | permissive | [
{
"docstring": "@summary: Rackspace Compute API IP Associations extension client @param url: Base URL for the compute service @type url: string @param auth_token: Auth token to be used for all requests @type auth_token: string @param serialize_format: Format for serializing requests @type serialize_format: stri... | 5 | stack_v2_sparse_classes_30k_train_018977 | Implement the Python class `IPAssociationsClient` described below.
Class description:
Implement the IPAssociationsClient class.
Method signatures and docstrings:
- def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None): @summary: Rackspace Compute API IP Associations extension client @par... | Implement the Python class `IPAssociationsClient` described below.
Class description:
Implement the IPAssociationsClient class.
Method signatures and docstrings:
- def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None): @summary: Rackspace Compute API IP Associations extension client @par... | 1a62bf21adfb047829c7b8c79cfee1f55f9ca350 | <|skeleton|>
class IPAssociationsClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None):
"""@summary: Rackspace Compute API IP Associations extension client @param url: Base URL for the compute service @type url: string @param auth_token: Auth token to be used for all r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IPAssociationsClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None):
"""@summary: Rackspace Compute API IP Associations extension client @param url: Base URL for the compute service @type url: string @param auth_token: Auth token to be used for all requests @type ... | the_stack_v2_python_sparse | cloudcafe/compute/extensions/ip_associations_api/client.py | sajuptpm/cloudcafe | train | 0 | |
519cb248c55b1e7cfcd9306e208c8df24942b6cd | [
"gph = [[[], []] for _ in range(n)]\nres = [[n * 2] * 2 for _ in range(n)]\nres[0] = [0, 0]\nlen_res = n << 1\nqueue = [(0, 0), (0, 1)]\nfor s, e in red_edges:\n gph[s][0].append(e)\nfor s, e in blue_edges:\n gph[s][1].append(e)\nfor si, c in queue:\n for ei in gph[si][c]:\n if res[ei][c] == len_res... | <|body_start_0|>
gph = [[[], []] for _ in range(n)]
res = [[n * 2] * 2 for _ in range(n)]
res[0] = [0, 0]
len_res = n << 1
queue = [(0, 0), (0, 1)]
for s, e in red_edges:
gph[s][0].append(e)
for s, e in blue_edges:
gph[s][1].append(e)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortestAlternatingPaths(self, n, red_edges, blue_edges):
""":type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def shortestAlternatingPaths2(self, n, red_edges, blue_edges):
""":type n: int :... | stack_v2_sparse_classes_36k_train_018732 | 6,587 | no_license | [
{
"docstring": ":type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int]",
"name": "shortestAlternatingPaths",
"signature": "def shortestAlternatingPaths(self, n, red_edges, blue_edges)"
},
{
"docstring": ":type n: int :type red_edges: List[List[int]] :ty... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestAlternatingPaths(self, n, red_edges, blue_edges): :type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int]
- def shortestAlte... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestAlternatingPaths(self, n, red_edges, blue_edges): :type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int]
- def shortestAlte... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class Solution:
def shortestAlternatingPaths(self, n, red_edges, blue_edges):
""":type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def shortestAlternatingPaths2(self, n, red_edges, blue_edges):
""":type n: int :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def shortestAlternatingPaths(self, n, red_edges, blue_edges):
""":type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int]"""
gph = [[[], []] for _ in range(n)]
res = [[n * 2] * 2 for _ in range(n)]
res[0] = [0, 0]
len_r... | the_stack_v2_python_sparse | LC1129.py | Qiao-Liang/LeetCode | train | 0 | |
e42a16a8d6f07839c8f8ddb707d52e4da6449ebf | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ArchivedPrintJob()",
"from .print_job_processing_state import PrintJobProcessingState\nfrom .user_identity import UserIdentity\nfrom .print_job_processing_state import PrintJobProcessingState\nfrom .user_identity import UserIdentity\nf... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ArchivedPrintJob()
<|end_body_0|>
<|body_start_1|>
from .print_job_processing_state import PrintJobProcessingState
from .user_identity import UserIdentity
from .print_job_process... | ArchivedPrintJob | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArchivedPrintJob:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ArchivedPrintJob:
"""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 R... | stack_v2_sparse_classes_36k_train_018733 | 5,408 | 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: ArchivedPrintJob",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_008094 | Implement the Python class `ArchivedPrintJob` described below.
Class description:
Implement the ArchivedPrintJob class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ArchivedPrintJob: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `ArchivedPrintJob` described below.
Class description:
Implement the ArchivedPrintJob class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ArchivedPrintJob: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ArchivedPrintJob:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ArchivedPrintJob:
"""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 R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArchivedPrintJob:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ArchivedPrintJob:
"""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: Archiv... | the_stack_v2_python_sparse | msgraph/generated/models/archived_print_job.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
e5dca98e7a5b7f6df5f89689eb4ebcb9f8bcb929 | [
"if len(s) > len(t):\n return False\nindices = {}\nfor index, char in enumerate(t):\n if char not in indices:\n indices[char] = []\n indices[char].append(index)\nprevIndex = -1\nfor index, char in enumerate(s):\n if char not in indices:\n return False\n found = False\n for numAppeara... | <|body_start_0|>
if len(s) > len(t):
return False
indices = {}
for index, char in enumerate(t):
if char not in indices:
indices[char] = []
indices[char].append(index)
prevIndex = -1
for index, char in enumerate(s):
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def betterSolution(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(s) > len(t):
... | stack_v2_sparse_classes_36k_train_018734 | 1,670 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isSubsequence",
"signature": "def isSubsequence(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "betterSolution",
"signature": "def betterSolution(self, s, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009550 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s, t): :type s: str :type t: str :rtype: bool
- def betterSolution(self, s, t): :type s: str :type t: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s, t): :type s: str :type t: str :rtype: bool
- def betterSolution(self, s, t): :type s: str :type t: str :rtype: bool
<|skeleton|>
class Solution:
... | ed904cbca90e7b9004cc4a0f9662c8e498847e07 | <|skeleton|>
class Solution:
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def betterSolution(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
if len(s) > len(t):
return False
indices = {}
for index, char in enumerate(t):
if char not in indices:
indices[char] = []
indices[char].appe... | the_stack_v2_python_sparse | isSubsequence.py | sergeichestakov/InterviewPrep | train | 0 | |
1cfa58eb3c2ce4ffcc8b347603fdd842979abbee | [
"Parametre.__init__(self, 'voir', 'view')\nself.schema = '<cle>'\nself.aide_courte = 'visionne un banc particulier'\nself.aide_longue = \"Cette commande offre un affichage détaillé d'un banc de poisson.\"",
"cle = dic_masques['cle'].cle\nif cle not in importeur.peche.bancs:\n personnage << \"|err|Ce banc n'exi... | <|body_start_0|>
Parametre.__init__(self, 'voir', 'view')
self.schema = '<cle>'
self.aide_courte = 'visionne un banc particulier'
self.aide_longue = "Cette commande offre un affichage détaillé d'un banc de poisson."
<|end_body_0|>
<|body_start_1|>
cle = dic_masques['cle'].cle
... | Commande 'banc voir'. | PrmVoir | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmVoir:
"""Commande 'banc voir'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre.__init__... | stack_v2_sparse_classes_36k_train_018735 | 3,205 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmVoir` described below.
Class description:
Commande 'banc voir'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmVoir` described below.
Class description:
Commande 'banc voir'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmVoir:
"""Commande 'banc voir'."""
... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmVoir:
"""Commande 'banc voir'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmVoir:
"""Commande 'banc voir'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'voir', 'view')
self.schema = '<cle>'
self.aide_courte = 'visionne un banc particulier'
self.aide_longue = "Cette commande offre un affichage détaillé ... | the_stack_v2_python_sparse | src/secondaires/peche/commandes/banc/voir.py | vincent-lg/tsunami | train | 5 |
e22ae7dc3509bcc83bc3460f23623bd8363e271c | [
"if 'password' in lookup:\n return False\nreturn True",
"search_fields = self.get_search_fields(request)\nif '=' in search_term:\n fields = {field.split('__')[0]: field for field in search_fields}\n new_search_term = []\n for part in search_term.split():\n field = None\n if '=' in part:\... | <|body_start_0|>
if 'password' in lookup:
return False
return True
<|end_body_0|>
<|body_start_1|>
search_fields = self.get_search_fields(request)
if '=' in search_term:
fields = {field.split('__')[0]: field for field in search_fields}
new_search_term... | EnhaceSearchMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnhaceSearchMixin:
def lookup_allowed(self, lookup, value):
"""allows any lookup"""
<|body_0|>
def get_search_results(self, request, queryset, search_term):
"""allows to specify field <field_name>:<search_term>"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_018736 | 14,024 | permissive | [
{
"docstring": "allows any lookup",
"name": "lookup_allowed",
"signature": "def lookup_allowed(self, lookup, value)"
},
{
"docstring": "allows to specify field <field_name>:<search_term>",
"name": "get_search_results",
"signature": "def get_search_results(self, request, queryset, search_... | 2 | null | Implement the Python class `EnhaceSearchMixin` described below.
Class description:
Implement the EnhaceSearchMixin class.
Method signatures and docstrings:
- def lookup_allowed(self, lookup, value): allows any lookup
- def get_search_results(self, request, queryset, search_term): allows to specify field <field_name>:... | Implement the Python class `EnhaceSearchMixin` described below.
Class description:
Implement the EnhaceSearchMixin class.
Method signatures and docstrings:
- def lookup_allowed(self, lookup, value): allows any lookup
- def get_search_results(self, request, queryset, search_term): allows to specify field <field_name>:... | 49c84f13a8f92427b01231615136549fb5be3a78 | <|skeleton|>
class EnhaceSearchMixin:
def lookup_allowed(self, lookup, value):
"""allows any lookup"""
<|body_0|>
def get_search_results(self, request, queryset, search_term):
"""allows to specify field <field_name>:<search_term>"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnhaceSearchMixin:
def lookup_allowed(self, lookup, value):
"""allows any lookup"""
if 'password' in lookup:
return False
return True
def get_search_results(self, request, queryset, search_term):
"""allows to specify field <field_name>:<search_term>"""
... | the_stack_v2_python_sparse | orchestra/admin/options.py | Ro9ueAdmin/django-orchestra | train | 0 | |
1d5e8c1aed8fca029bb79de412e54c937e8ed5ec | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.aadUserConversationMember'.casefold():\n ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | ConversationMember | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConversationMember:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConversationMember:
"""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 obje... | stack_v2_sparse_classes_36k_train_018737 | 6,677 | 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: ConversationMember",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_017043 | Implement the Python class `ConversationMember` described below.
Class description:
Implement the ConversationMember class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConversationMember: Creates a new instance of the appropriate class based on disc... | Implement the Python class `ConversationMember` described below.
Class description:
Implement the ConversationMember class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConversationMember: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ConversationMember:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConversationMember:
"""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 obje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConversationMember:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConversationMember:
"""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: Co... | the_stack_v2_python_sparse | msgraph/generated/models/conversation_member.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
f5419253bc0a0fa138ca6d1ca677636103925e3e | [
"self.restore_task_id = restore_task_id\nself.allow_empty_dest_guids = allow_empty_dest_guids\nself.exclude_sys_attributes = exclude_sys_attributes\nself.filter_null_value_attributes = filter_null_value_attributes\nself.filter_same_value_attributes = filter_same_value_attributes\nself.guid_pairs = guid_pairs\nself.... | <|body_start_0|>
self.restore_task_id = restore_task_id
self.allow_empty_dest_guids = allow_empty_dest_guids
self.exclude_sys_attributes = exclude_sys_attributes
self.filter_null_value_attributes = filter_null_value_attributes
self.filter_same_value_attributes = filter_same_value... | Implementation of the 'CompareAdObjectsRequest' model. Specifies the request to compare AD objects from Snapshot and Production AD. Attributes: restore_task_id (long|int, required): Specifies the Restore Task Id corresponding to which we need to compare the AD objects. allow_empty_dest_guids (bool): Specifies the optio... | CompareAdObjectsRequest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompareAdObjectsRequest:
"""Implementation of the 'CompareAdObjectsRequest' model. Specifies the request to compare AD objects from Snapshot and Production AD. Attributes: restore_task_id (long|int, required): Specifies the Restore Task Id corresponding to which we need to compare the AD objects.... | stack_v2_sparse_classes_36k_train_018738 | 4,925 | permissive | [
{
"docstring": "Constructor for the CompareAdObjectsRequest class",
"name": "__init__",
"signature": "def __init__(self, restore_task_id=None, allow_empty_dest_guids=None, exclude_sys_attributes=None, filter_null_value_attributes=None, filter_same_value_attributes=None, guid_pairs=None, quick_compare=No... | 2 | null | Implement the Python class `CompareAdObjectsRequest` described below.
Class description:
Implementation of the 'CompareAdObjectsRequest' model. Specifies the request to compare AD objects from Snapshot and Production AD. Attributes: restore_task_id (long|int, required): Specifies the Restore Task Id corresponding to w... | Implement the Python class `CompareAdObjectsRequest` described below.
Class description:
Implementation of the 'CompareAdObjectsRequest' model. Specifies the request to compare AD objects from Snapshot and Production AD. Attributes: restore_task_id (long|int, required): Specifies the Restore Task Id corresponding to w... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CompareAdObjectsRequest:
"""Implementation of the 'CompareAdObjectsRequest' model. Specifies the request to compare AD objects from Snapshot and Production AD. Attributes: restore_task_id (long|int, required): Specifies the Restore Task Id corresponding to which we need to compare the AD objects.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompareAdObjectsRequest:
"""Implementation of the 'CompareAdObjectsRequest' model. Specifies the request to compare AD objects from Snapshot and Production AD. Attributes: restore_task_id (long|int, required): Specifies the Restore Task Id corresponding to which we need to compare the AD objects. allow_empty_... | the_stack_v2_python_sparse | cohesity_management_sdk/models/compare_ad_objects_request.py | cohesity/management-sdk-python | train | 24 |
d6508d909d9da78ebf9728c295a7d38e159ac53f | [
"self.set_header('content-type', 'application/json')\ntry:\n user = UserDao().get_user_detail_by_id(id)\n manage_groups = GroupDao().get_manage_groups(self.group.id)\n if user['group_id'] not in manage_groups:\n user = {}\n self.finish(json_dumps({'status': 200, 'msg': 'ok', 'values': user}))\nex... | <|body_start_0|>
self.set_header('content-type', 'application/json')
try:
user = UserDao().get_user_detail_by_id(id)
manage_groups = GroupDao().get_manage_groups(self.group.id)
if user['group_id'] not in manage_groups:
user = {}
self.finish... | UserQueryHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserQueryHandler:
def get(self, id):
"""get a specific user detail @API summary: get a specific user detail notes: get a specific user detail tags: - auth parameters: - name: id in: path required: true type: integer description: id of the user"""
<|body_0|>
def post(self, id... | stack_v2_sparse_classes_36k_train_018739 | 6,245 | permissive | [
{
"docstring": "get a specific user detail @API summary: get a specific user detail notes: get a specific user detail tags: - auth parameters: - name: id in: path required: true type: integer description: id of the user",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "modify ... | 2 | null | Implement the Python class `UserQueryHandler` described below.
Class description:
Implement the UserQueryHandler class.
Method signatures and docstrings:
- def get(self, id): get a specific user detail @API summary: get a specific user detail notes: get a specific user detail tags: - auth parameters: - name: id in: p... | Implement the Python class `UserQueryHandler` described below.
Class description:
Implement the UserQueryHandler class.
Method signatures and docstrings:
- def get(self, id): get a specific user detail @API summary: get a specific user detail notes: get a specific user detail tags: - auth parameters: - name: id in: p... | 2e32e6e7b225e0bd87ee8c847c22862f12c51bb1 | <|skeleton|>
class UserQueryHandler:
def get(self, id):
"""get a specific user detail @API summary: get a specific user detail notes: get a specific user detail tags: - auth parameters: - name: id in: path required: true type: integer description: id of the user"""
<|body_0|>
def post(self, id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserQueryHandler:
def get(self, id):
"""get a specific user detail @API summary: get a specific user detail notes: get a specific user detail tags: - auth parameters: - name: id in: path required: true type: integer description: id of the user"""
self.set_header('content-type', 'application/js... | the_stack_v2_python_sparse | nebula/views/user.py | threathunterX/nebula_web | train | 2 | |
e2ff69ec6a016706c22add2f2480536e1bfe98e1 | [
"if n == 0:\n return []\nelif n == 1:\n return [TreeNode(1)]\nresult = list()\nfor x in range(1, n + 1):\n if x == 1:\n right_children = self.gen_SBT(2, n)\n for child in right_children:\n root = TreeNode(1)\n root.right = child\n result.append(root)\n elif... | <|body_start_0|>
if n == 0:
return []
elif n == 1:
return [TreeNode(1)]
result = list()
for x in range(1, n + 1):
if x == 1:
right_children = self.gen_SBT(2, n)
for child in right_children:
root = Tre... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_0|>
def gen_SBT(self, left, right):
""":type left: int :type right: int :rtype: List[TreeNode] returns the roots of BSTs"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_018740 | 2,618 | no_license | [
{
"docstring": ":type n: int :rtype: List[TreeNode]",
"name": "generateTrees",
"signature": "def generateTrees(self, n)"
},
{
"docstring": ":type left: int :type right: int :rtype: List[TreeNode] returns the roots of BSTs",
"name": "gen_SBT",
"signature": "def gen_SBT(self, left, right)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateTrees(self, n): :type n: int :rtype: List[TreeNode]
- def gen_SBT(self, left, right): :type left: int :type right: int :rtype: List[TreeNode] returns the roots of BST... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateTrees(self, n): :type n: int :rtype: List[TreeNode]
- def gen_SBT(self, left, right): :type left: int :type right: int :rtype: List[TreeNode] returns the roots of BST... | 78ed11f34fd03e9a188c9c6cb352e883016d05d9 | <|skeleton|>
class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_0|>
def gen_SBT(self, left, right):
""":type left: int :type right: int :rtype: List[TreeNode] returns the roots of BSTs"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
if n == 0:
return []
elif n == 1:
return [TreeNode(1)]
result = list()
for x in range(1, n + 1):
if x == 1:
right_children = self.gen_SBT(... | the_stack_v2_python_sparse | 95_unique_binary_search_trees_2.py | 26XINXIN/leetcode | train | 0 | |
81c6013775667f080ebc67d00df95d6b39eeeecd | [
"print(' Starting job: %s\\nExecuting command: %s\\n' % (jobnum, command))\nrv = os.system(command)\nif rv:\n print('Problem running job...\\nFile: %s\\n Job: %d\\nLine: %d\\n...dieing!' % (batchfile, jobnum, linenum))\n sys.exit(rv)",
"if not os.path.isfile(batchfile):\n print('Cannot find batch fil... | <|body_start_0|>
print(' Starting job: %s\nExecuting command: %s\n' % (jobnum, command))
rv = os.system(command)
if rv:
print('Problem running job...\nFile: %s\n Job: %d\nLine: %d\n...dieing!' % (batchfile, jobnum, linenum))
sys.exit(rv)
<|end_body_0|>
<|body_start_1... | This is the main class Instantiate it then call run() | SimpleBatchFile | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleBatchFile:
"""This is the main class Instantiate it then call run()"""
def _exec(self, command, jobnum, linenum, batchfile):
"""Execute a command in a subshell, die on errors"""
<|body_0|>
def __init__(self, batchfile):
"""Start the fun"""
<|body_1|... | stack_v2_sparse_classes_36k_train_018741 | 4,414 | permissive | [
{
"docstring": "Execute a command in a subshell, die on errors",
"name": "_exec",
"signature": "def _exec(self, command, jobnum, linenum, batchfile)"
},
{
"docstring": "Start the fun",
"name": "__init__",
"signature": "def __init__(self, batchfile)"
},
{
"docstring": "List jobs a... | 4 | stack_v2_sparse_classes_30k_val_000735 | Implement the Python class `SimpleBatchFile` described below.
Class description:
This is the main class Instantiate it then call run()
Method signatures and docstrings:
- def _exec(self, command, jobnum, linenum, batchfile): Execute a command in a subshell, die on errors
- def __init__(self, batchfile): Start the fun... | Implement the Python class `SimpleBatchFile` described below.
Class description:
This is the main class Instantiate it then call run()
Method signatures and docstrings:
- def _exec(self, command, jobnum, linenum, batchfile): Execute a command in a subshell, die on errors
- def __init__(self, batchfile): Start the fun... | d097ca0ad6a6aee2180d32dce6a3322621f655fd | <|skeleton|>
class SimpleBatchFile:
"""This is the main class Instantiate it then call run()"""
def _exec(self, command, jobnum, linenum, batchfile):
"""Execute a command in a subshell, die on errors"""
<|body_0|>
def __init__(self, batchfile):
"""Start the fun"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleBatchFile:
"""This is the main class Instantiate it then call run()"""
def _exec(self, command, jobnum, linenum, batchfile):
"""Execute a command in a subshell, die on errors"""
print(' Starting job: %s\nExecuting command: %s\n' % (jobnum, command))
rv = os.system(comman... | the_stack_v2_python_sparse | recipes/Python/496897_Running_Batch_Commands/recipe-496897.py | betty29/code-1 | train | 0 |
3e58ef187a05e00ec9a3af9d15dfbeae6472187d | [
"self.group_member_vec = group_member_vec\nself.member_prefix = member_prefix\nself.num_groups = num_groups\nself.size_mb = size_mb",
"if dictionary is None:\n return None\ngroup_member_vec = dictionary.get('groupMemberVec')\nmember_prefix = dictionary.get('memberPrefix')\nnum_groups = dictionary.get('numGroup... | <|body_start_0|>
self.group_member_vec = group_member_vec
self.member_prefix = member_prefix
self.num_groups = num_groups
self.size_mb = size_mb
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
group_member_vec = dictionary.get('groupMemberV... | Implementation of the 'OracleDBConfig_RedoLogGroupConf' model. GROUP1 : {DST1/CH1.log, DST2/CH1.log} GROUP2 : {DST1/CH2.log, DST2/CH2.log} GROUP3 : {DST1/CH3.log, DST2/CH3.log} Attributes: group_member_vec (list of string): List of members of this redo log group. member_prefix (string): Log member name prefix. num_grou... | OracleDBConfig_RedoLogGroupConf | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OracleDBConfig_RedoLogGroupConf:
"""Implementation of the 'OracleDBConfig_RedoLogGroupConf' model. GROUP1 : {DST1/CH1.log, DST2/CH1.log} GROUP2 : {DST1/CH2.log, DST2/CH2.log} GROUP3 : {DST1/CH3.log, DST2/CH3.log} Attributes: group_member_vec (list of string): List of members of this redo log grou... | stack_v2_sparse_classes_36k_train_018742 | 2,224 | permissive | [
{
"docstring": "Constructor for the OracleDBConfig_RedoLogGroupConf class",
"name": "__init__",
"signature": "def __init__(self, group_member_vec=None, member_prefix=None, num_groups=None, size_mb=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dic... | 2 | null | Implement the Python class `OracleDBConfig_RedoLogGroupConf` described below.
Class description:
Implementation of the 'OracleDBConfig_RedoLogGroupConf' model. GROUP1 : {DST1/CH1.log, DST2/CH1.log} GROUP2 : {DST1/CH2.log, DST2/CH2.log} GROUP3 : {DST1/CH3.log, DST2/CH3.log} Attributes: group_member_vec (list of string)... | Implement the Python class `OracleDBConfig_RedoLogGroupConf` described below.
Class description:
Implementation of the 'OracleDBConfig_RedoLogGroupConf' model. GROUP1 : {DST1/CH1.log, DST2/CH1.log} GROUP2 : {DST1/CH2.log, DST2/CH2.log} GROUP3 : {DST1/CH3.log, DST2/CH3.log} Attributes: group_member_vec (list of string)... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class OracleDBConfig_RedoLogGroupConf:
"""Implementation of the 'OracleDBConfig_RedoLogGroupConf' model. GROUP1 : {DST1/CH1.log, DST2/CH1.log} GROUP2 : {DST1/CH2.log, DST2/CH2.log} GROUP3 : {DST1/CH3.log, DST2/CH3.log} Attributes: group_member_vec (list of string): List of members of this redo log grou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OracleDBConfig_RedoLogGroupConf:
"""Implementation of the 'OracleDBConfig_RedoLogGroupConf' model. GROUP1 : {DST1/CH1.log, DST2/CH1.log} GROUP2 : {DST1/CH2.log, DST2/CH2.log} GROUP3 : {DST1/CH3.log, DST2/CH3.log} Attributes: group_member_vec (list of string): List of members of this redo log group. member_pre... | the_stack_v2_python_sparse | cohesity_management_sdk/models/oracle_db_config_redo_log_group_conf.py | cohesity/management-sdk-python | train | 24 |
9a2e3ec46e565c30ec121349ae78b06f15b3e245 | [
"key = ndb.Key(models.InstanceGroupManager, 'fake-key')\ninstance_group_managers.update_url(key, 'url')\nself.failIf(key.get())",
"key = models.InstanceGroupManager(key=instance_group_managers.get_instance_group_manager_key('base-name', 'revision', 'zone'), url='url').put()\ninstance_group_managers.update_url(key... | <|body_start_0|>
key = ndb.Key(models.InstanceGroupManager, 'fake-key')
instance_group_managers.update_url(key, 'url')
self.failIf(key.get())
<|end_body_0|>
<|body_start_1|>
key = models.InstanceGroupManager(key=instance_group_managers.get_instance_group_manager_key('base-name', 'revisi... | Tests for instance_group_managers.update_url. | UpdateURLTest | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateURLTest:
"""Tests for instance_group_managers.update_url."""
def test_entity_doesnt_exist(self):
"""Ensures nothing happens when the entity doesn't exist."""
<|body_0|>
def test_url_matches(self):
"""Ensures nothing happens when the URL already matches."""
... | stack_v2_sparse_classes_36k_train_018743 | 34,211 | permissive | [
{
"docstring": "Ensures nothing happens when the entity doesn't exist.",
"name": "test_entity_doesnt_exist",
"signature": "def test_entity_doesnt_exist(self)"
},
{
"docstring": "Ensures nothing happens when the URL already matches.",
"name": "test_url_matches",
"signature": "def test_url... | 4 | null | Implement the Python class `UpdateURLTest` described below.
Class description:
Tests for instance_group_managers.update_url.
Method signatures and docstrings:
- def test_entity_doesnt_exist(self): Ensures nothing happens when the entity doesn't exist.
- def test_url_matches(self): Ensures nothing happens when the URL... | Implement the Python class `UpdateURLTest` described below.
Class description:
Tests for instance_group_managers.update_url.
Method signatures and docstrings:
- def test_entity_doesnt_exist(self): Ensures nothing happens when the entity doesn't exist.
- def test_url_matches(self): Ensures nothing happens when the URL... | 0a4fdfc25f89833026be6a8b29c0a27b8f3c5fc4 | <|skeleton|>
class UpdateURLTest:
"""Tests for instance_group_managers.update_url."""
def test_entity_doesnt_exist(self):
"""Ensures nothing happens when the entity doesn't exist."""
<|body_0|>
def test_url_matches(self):
"""Ensures nothing happens when the URL already matches."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateURLTest:
"""Tests for instance_group_managers.update_url."""
def test_entity_doesnt_exist(self):
"""Ensures nothing happens when the entity doesn't exist."""
key = ndb.Key(models.InstanceGroupManager, 'fake-key')
instance_group_managers.update_url(key, 'url')
self.fa... | the_stack_v2_python_sparse | appengine/gce-backend/instance_group_managers_test.py | Swift1313/luci-py | train | 0 |
8eccf0e5cf8e669b0ab4df4a7084aa00f6db75bc | [
"for name, config_value in self.__dict__.items():\n if name in override_parameters:\n override_value = override_parameters[name]\n if override_value is not None:\n if isinstance(config_value, OutputLists):\n config_value.update(override_value)\n else:\n ... | <|body_start_0|>
for name, config_value in self.__dict__.items():
if name in override_parameters:
override_value = override_parameters[name]
if override_value is not None:
if isinstance(config_value, OutputLists):
config_val... | Parameters common to both RT-Alignment and Targeted notebooks | BaseNotebookParameters | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseNotebookParameters:
"""Parameters common to both RT-Alignment and Targeted notebooks"""
def update(self, override_parameters: Dict) -> None:
"""update all parameters with any non-None values in override_parameters"""
<|body_0|>
def distribute_always_values(self) -> N... | stack_v2_sparse_classes_36k_train_018744 | 12,746 | permissive | [
{
"docstring": "update all parameters with any non-None values in override_parameters",
"name": "update",
"signature": "def update(self, override_parameters: Dict) -> None"
},
{
"docstring": "distribute always values within each OutputLists attribute",
"name": "distribute_always_values",
... | 2 | stack_v2_sparse_classes_30k_train_019511 | Implement the Python class `BaseNotebookParameters` described below.
Class description:
Parameters common to both RT-Alignment and Targeted notebooks
Method signatures and docstrings:
- def update(self, override_parameters: Dict) -> None: update all parameters with any non-None values in override_parameters
- def dis... | Implement the Python class `BaseNotebookParameters` described below.
Class description:
Parameters common to both RT-Alignment and Targeted notebooks
Method signatures and docstrings:
- def update(self, override_parameters: Dict) -> None: update all parameters with any non-None values in override_parameters
- def dis... | 909ede3d1fe75fa5d64c6ff1b4c6016dc3df6746 | <|skeleton|>
class BaseNotebookParameters:
"""Parameters common to both RT-Alignment and Targeted notebooks"""
def update(self, override_parameters: Dict) -> None:
"""update all parameters with any non-None values in override_parameters"""
<|body_0|>
def distribute_always_values(self) -> N... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseNotebookParameters:
"""Parameters common to both RT-Alignment and Targeted notebooks"""
def update(self, override_parameters: Dict) -> None:
"""update all parameters with any non-None values in override_parameters"""
for name, config_value in self.__dict__.items():
if name... | the_stack_v2_python_sparse | metatlas/tools/config.py | biorack/metatlas | train | 10 |
e52f61ccf821fec7130dfa09cb9073306f4bacb5 | [
"self.filters = filters\nself.num_layers = num_layers\nself.activation = activation\nself.dropout_rate = dropout_rate\nself.dropout_layer = custom_layers.ConcreteDropout\nself.build_layers(input_shape, output_shape)",
"inputs, outputs = self.build_input(input_shape)\nfor power in range(1, self.num_layers):\n o... | <|body_start_0|>
self.filters = filters
self.num_layers = num_layers
self.activation = activation
self.dropout_rate = dropout_rate
self.dropout_layer = custom_layers.ConcreteDropout
self.build_layers(input_shape, output_shape)
<|end_body_0|>
<|body_start_1|>
inpu... | Extends keras.models.Model object. Implementation of WaveNet-like topology for multivariate time series. This architecture is built on the idea of causal convolutions that can extract features from time series. :param input_shape: Shape of input example. :type input_shape: tuple :param output_shape: Shape of output con... | WaveNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WaveNet:
"""Extends keras.models.Model object. Implementation of WaveNet-like topology for multivariate time series. This architecture is built on the idea of causal convolutions that can extract features from time series. :param input_shape: Shape of input example. :type input_shape: tuple :para... | stack_v2_sparse_classes_36k_train_018745 | 7,749 | no_license | [
{
"docstring": "Initialize attributes.",
"name": "__init__",
"signature": "def __init__(self, input_shape, output_shape, filters=32, num_layers=1, dropout_rate=(0.1, 0.3), activation='relu', *args, **kwargs)"
},
{
"docstring": "Build layers of the network. :param input_shape: Length and dimensio... | 5 | stack_v2_sparse_classes_30k_train_009667 | Implement the Python class `WaveNet` described below.
Class description:
Extends keras.models.Model object. Implementation of WaveNet-like topology for multivariate time series. This architecture is built on the idea of causal convolutions that can extract features from time series. :param input_shape: Shape of input ... | Implement the Python class `WaveNet` described below.
Class description:
Extends keras.models.Model object. Implementation of WaveNet-like topology for multivariate time series. This architecture is built on the idea of causal convolutions that can extract features from time series. :param input_shape: Shape of input ... | b6943406fa4a094b7dbe7fe7c5378f0116749f56 | <|skeleton|>
class WaveNet:
"""Extends keras.models.Model object. Implementation of WaveNet-like topology for multivariate time series. This architecture is built on the idea of causal convolutions that can extract features from time series. :param input_shape: Shape of input example. :type input_shape: tuple :para... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WaveNet:
"""Extends keras.models.Model object. Implementation of WaveNet-like topology for multivariate time series. This architecture is built on the idea of causal convolutions that can extract features from time series. :param input_shape: Shape of input example. :type input_shape: tuple :param output_shap... | the_stack_v2_python_sparse | hybrid4cast/cnn/models.py | Aspriter/Hybrid4Cast | train | 1 |
0c947d2de390f62ebf5d9cba02a9bffba8063935 | [
"q = Queue()\nq.enqueue(3)\nself.assertEqual(q.head, q.tail)\nself.assertEqual(q.head.value, 3)",
"q = Queue()\nq.enqueue(3)\nresult = q.dequeue()\nself.assertEqual(result, 3)\nself.assertIsNone(q.head)",
"q = Queue()\nq.enqueue(3)\nq.enqueue(4)\nq.enqueue(5)\nself.assertEqual(q.head.value, 3)\nself.assertEqual... | <|body_start_0|>
q = Queue()
q.enqueue(3)
self.assertEqual(q.head, q.tail)
self.assertEqual(q.head.value, 3)
<|end_body_0|>
<|body_start_1|>
q = Queue()
q.enqueue(3)
result = q.dequeue()
self.assertEqual(result, 3)
self.assertIsNone(q.head)
<|end_... | test_queue_implementation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_queue_implementation:
def test_first_elemnt_of_queue(self):
"""test that after initial enqueue, the head of the Queue is correct"""
<|body_0|>
def test_enqueue_then_dequeue(self):
"""test that after an enqueue a dequeue gives what is expected"""
<|body_1... | stack_v2_sparse_classes_36k_train_018746 | 1,023 | no_license | [
{
"docstring": "test that after initial enqueue, the head of the Queue is correct",
"name": "test_first_elemnt_of_queue",
"signature": "def test_first_elemnt_of_queue(self)"
},
{
"docstring": "test that after an enqueue a dequeue gives what is expected",
"name": "test_enqueue_then_dequeue",
... | 4 | stack_v2_sparse_classes_30k_train_004563 | Implement the Python class `test_queue_implementation` described below.
Class description:
Implement the test_queue_implementation class.
Method signatures and docstrings:
- def test_first_elemnt_of_queue(self): test that after initial enqueue, the head of the Queue is correct
- def test_enqueue_then_dequeue(self): t... | Implement the Python class `test_queue_implementation` described below.
Class description:
Implement the test_queue_implementation class.
Method signatures and docstrings:
- def test_first_elemnt_of_queue(self): test that after initial enqueue, the head of the Queue is correct
- def test_enqueue_then_dequeue(self): t... | 7e884adb19b84a2e5960d1b6e81cd926f0b46705 | <|skeleton|>
class test_queue_implementation:
def test_first_elemnt_of_queue(self):
"""test that after initial enqueue, the head of the Queue is correct"""
<|body_0|>
def test_enqueue_then_dequeue(self):
"""test that after an enqueue a dequeue gives what is expected"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_queue_implementation:
def test_first_elemnt_of_queue(self):
"""test that after initial enqueue, the head of the Queue is correct"""
q = Queue()
q.enqueue(3)
self.assertEqual(q.head, q.tail)
self.assertEqual(q.head.value, 3)
def test_enqueue_then_dequeue(self):... | the_stack_v2_python_sparse | questions/linked_lists/queue_test.py | qdonnellan/random_questions | train | 0 | |
c45931b6822566d5ab3f70c3c2b836d420352207 | [
"from ArmisEventCollector import fetch_events\nmocker.patch.object(Client, 'fetch_by_aql_query', return_value=response)\nmocker.patch.dict(EVENT_TYPES, {'Events': EVENT_TYPE('unique_id', 'events_query', 'events')})\nassert fetch_events(dummy_client, max_fetch, last_run, fetch_start_time, event_types_to_fetch) == (e... | <|body_start_0|>
from ArmisEventCollector import fetch_events
mocker.patch.object(Client, 'fetch_by_aql_query', return_value=response)
mocker.patch.dict(EVENT_TYPES, {'Events': EVENT_TYPE('unique_id', 'events_query', 'events')})
assert fetch_events(dummy_client, max_fetch, last_run, fetc... | TestFetchFlow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFetchFlow:
def test_fetch_flow_cases(self, mocker, dummy_client, max_fetch, last_run, fetch_start_time, event_types_to_fetch, response, events, next_run):
"""Given: - Case 1: First fetch, response has 3 events with different timestamps. - Case 2: Second fetch, response has 3 events w... | stack_v2_sparse_classes_36k_train_018747 | 18,429 | permissive | [
{
"docstring": "Given: - Case 1: First fetch, response has 3 events with different timestamps. - Case 2: Second fetch, response has 3 events with different timestamps. - Case 3: Second fetch with duplicated, some events in the response have same timestamps as last fetch. - Case 4: Second fetch with empty respon... | 2 | null | Implement the Python class `TestFetchFlow` described below.
Class description:
Implement the TestFetchFlow class.
Method signatures and docstrings:
- def test_fetch_flow_cases(self, mocker, dummy_client, max_fetch, last_run, fetch_start_time, event_types_to_fetch, response, events, next_run): Given: - Case 1: First f... | Implement the Python class `TestFetchFlow` described below.
Class description:
Implement the TestFetchFlow class.
Method signatures and docstrings:
- def test_fetch_flow_cases(self, mocker, dummy_client, max_fetch, last_run, fetch_start_time, event_types_to_fetch, response, events, next_run): Given: - Case 1: First f... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestFetchFlow:
def test_fetch_flow_cases(self, mocker, dummy_client, max_fetch, last_run, fetch_start_time, event_types_to_fetch, response, events, next_run):
"""Given: - Case 1: First fetch, response has 3 events with different timestamps. - Case 2: Second fetch, response has 3 events w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFetchFlow:
def test_fetch_flow_cases(self, mocker, dummy_client, max_fetch, last_run, fetch_start_time, event_types_to_fetch, response, events, next_run):
"""Given: - Case 1: First fetch, response has 3 events with different timestamps. - Case 2: Second fetch, response has 3 events with different ... | the_stack_v2_python_sparse | Packs/Armis/Integrations/ArmisEventCollector/ArmisEventCollector_test.py | demisto/content | train | 1,023 | |
384a982f027e9b91e29be99ea587e51cd2b1c027 | [
"HistogramSeries.__init__(self, *args, **kwargs)\nself.__display = self.displayCtx.getDisplay(self.overlay)\nself.__opts = self.displayCtx.getOpts(self.overlay)\nself.__display.addListener('overlayType', self.name, self.__overlayTypeChanged)\nself.__opts.addListener('volume', self.name, self.__volumeChanged)\nself.... | <|body_start_0|>
HistogramSeries.__init__(self, *args, **kwargs)
self.__display = self.displayCtx.getDisplay(self.overlay)
self.__opts = self.displayCtx.getOpts(self.overlay)
self.__display.addListener('overlayType', self.name, self.__overlayTypeChanged)
self.__opts.addListener('... | An ``ImageHistogramSeries`` instance manages generation of histogram data for an :class:`.Image` overlay. | ImageHistogramSeries | [
"BSD-3-Clause",
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageHistogramSeries:
"""An ``ImageHistogramSeries`` instance manages generation of histogram data for an :class:`.Image` overlay."""
def __init__(self, *args, **kwargs):
"""Create an ``ImageHistogramSeries``. All arguments are passed through to :meth:`HistogramSeries.__init__`."""
... | stack_v2_sparse_classes_36k_train_018748 | 19,944 | permissive | [
{
"docstring": "Create an ``ImageHistogramSeries``. All arguments are passed through to :meth:`HistogramSeries.__init__`.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Must be called when this ``ImageHistogramSeries`` is no longer needed. Removes som... | 6 | stack_v2_sparse_classes_30k_test_000055 | Implement the Python class `ImageHistogramSeries` described below.
Class description:
An ``ImageHistogramSeries`` instance manages generation of histogram data for an :class:`.Image` overlay.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create an ``ImageHistogramSeries``. All arguments are... | Implement the Python class `ImageHistogramSeries` described below.
Class description:
An ``ImageHistogramSeries`` instance manages generation of histogram data for an :class:`.Image` overlay.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create an ``ImageHistogramSeries``. All arguments are... | 46ccb4fe2b2346eb57576247f49714032b61307a | <|skeleton|>
class ImageHistogramSeries:
"""An ``ImageHistogramSeries`` instance manages generation of histogram data for an :class:`.Image` overlay."""
def __init__(self, *args, **kwargs):
"""Create an ``ImageHistogramSeries``. All arguments are passed through to :meth:`HistogramSeries.__init__`."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageHistogramSeries:
"""An ``ImageHistogramSeries`` instance manages generation of histogram data for an :class:`.Image` overlay."""
def __init__(self, *args, **kwargs):
"""Create an ``ImageHistogramSeries``. All arguments are passed through to :meth:`HistogramSeries.__init__`."""
Histog... | the_stack_v2_python_sparse | fsleyes/plotting/histogramseries.py | sanjayankur31/fsleyes | train | 1 |
3d60905f84269173c91d16aa4f0cd3d3f5b58cae | [
"self.id = id\nself.requested_amount = requested_amount\nself.approved_amount = approved_amount\nself.recipient = recipient\nself.pgid = pgid\nself.created_at = APIHelper.RFC3339DateTime(created_at) if created_at else None\nself.updated_at = APIHelper.RFC3339DateTime(updated_at) if updated_at else None\nself.paymen... | <|body_start_0|>
self.id = id
self.requested_amount = requested_amount
self.approved_amount = approved_amount
self.recipient = recipient
self.pgid = pgid
self.created_at = APIHelper.RFC3339DateTime(created_at) if created_at else None
self.updated_at = APIHelper.RF... | Implementation of the 'Recipients Anticipations Response' model. TODO: type model description here. Attributes: id (string): Id requested_amount (int): Requested amount approved_amount (int): Approved amount recipient (Recipient): TODO: type description here. pgid (string): Anticipation id on the gateway created_at (da... | RecipientsAnticipationsResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecipientsAnticipationsResponse:
"""Implementation of the 'Recipients Anticipations Response' model. TODO: type model description here. Attributes: id (string): Id requested_amount (int): Requested amount approved_amount (int): Approved amount recipient (Recipient): TODO: type description here. p... | stack_v2_sparse_classes_36k_train_018749 | 4,138 | permissive | [
{
"docstring": "Constructor for the RecipientsAnticipationsResponse class",
"name": "__init__",
"signature": "def __init__(self, id=None, requested_amount=None, approved_amount=None, pgid=None, created_at=None, updated_at=None, payment_date=None, status=None, timeframe=None, recipient=None)"
},
{
... | 2 | null | Implement the Python class `RecipientsAnticipationsResponse` described below.
Class description:
Implementation of the 'Recipients Anticipations Response' model. TODO: type model description here. Attributes: id (string): Id requested_amount (int): Requested amount approved_amount (int): Approved amount recipient (Rec... | Implement the Python class `RecipientsAnticipationsResponse` described below.
Class description:
Implementation of the 'Recipients Anticipations Response' model. TODO: type model description here. Attributes: id (string): Id requested_amount (int): Requested amount approved_amount (int): Approved amount recipient (Rec... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class RecipientsAnticipationsResponse:
"""Implementation of the 'Recipients Anticipations Response' model. TODO: type model description here. Attributes: id (string): Id requested_amount (int): Requested amount approved_amount (int): Approved amount recipient (Recipient): TODO: type description here. p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecipientsAnticipationsResponse:
"""Implementation of the 'Recipients Anticipations Response' model. TODO: type model description here. Attributes: id (string): Id requested_amount (int): Requested amount approved_amount (int): Approved amount recipient (Recipient): TODO: type description here. pgid (string):... | the_stack_v2_python_sparse | mundiapi/models/recipients_anticipations_response.py | mundipagg/MundiAPI-PYTHON | train | 10 |
1d15d04ddb9a348eb4a69084d02be739e36f17e6 | [
"super(cls, DeployCommand).AddParser(parser)\ncls.AddDeviceArgument(parser)\nparser.add_argument('packages', help='Packages to install. You can specify [category/]package[:slot] or the path to the binary package. Use @installed to update all installed packages (requires --update).', nargs='+')\nparser.add_argument(... | <|body_start_0|>
super(cls, DeployCommand).AddParser(parser)
cls.AddDeviceArgument(parser)
parser.add_argument('packages', help='Packages to install. You can specify [category/]package[:slot] or the path to the binary package. Use @installed to update all installed packages (requires --update).'... | Deploy the requested packages to the target device. This command assumes the requested packages are already built in the chroot. This command needs to run inside the chroot for inspecting the installed packages. Note: If the rootfs on your device is read-only, this command remounts it as read-write. If the rootfs verif... | DeployCommand | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeployCommand:
"""Deploy the requested packages to the target device. This command assumes the requested packages are already built in the chroot. This command needs to run inside the chroot for inspecting the installed packages. Note: If the rootfs on your device is read-only, this command remou... | stack_v2_sparse_classes_36k_train_018750 | 4,560 | permissive | [
{
"docstring": "Add a parser.",
"name": "AddParser",
"signature": "def AddParser(cls, parser)"
},
{
"docstring": "Run cros deploy.",
"name": "Run",
"signature": "def Run(self)"
}
] | 2 | null | Implement the Python class `DeployCommand` described below.
Class description:
Deploy the requested packages to the target device. This command assumes the requested packages are already built in the chroot. This command needs to run inside the chroot for inspecting the installed packages. Note: If the rootfs on your ... | Implement the Python class `DeployCommand` described below.
Class description:
Deploy the requested packages to the target device. This command assumes the requested packages are already built in the chroot. This command needs to run inside the chroot for inspecting the installed packages. Note: If the rootfs on your ... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class DeployCommand:
"""Deploy the requested packages to the target device. This command assumes the requested packages are already built in the chroot. This command needs to run inside the chroot for inspecting the installed packages. Note: If the rootfs on your device is read-only, this command remou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeployCommand:
"""Deploy the requested packages to the target device. This command assumes the requested packages are already built in the chroot. This command needs to run inside the chroot for inspecting the installed packages. Note: If the rootfs on your device is read-only, this command remounts it as rea... | the_stack_v2_python_sparse | third_party/chromite/cli/cros/cros_deploy.py | metux/chromium-suckless | train | 5 |
c15a66ff2bca285cb18224bba16de8b7533b1d4b | [
"self.loginpage.openLoginPage()\nself.log('PO-gjs:打开浏览器进入到项目首页')\nself.loginpage.login_gjs_pro(self.readusername(2), self.readpassword(2))\nself.log('PO-gjs:输入正确用户名和密码为空')\nself.assertEqual(self.loginpage.get_passwordNullText(), self.exceptText(2))\nself.log('PO-gjs:登录失败获取信息进行断言')\nSaveImage(self.dr, 'loginpasswdNu... | <|body_start_0|>
self.loginpage.openLoginPage()
self.log('PO-gjs:打开浏览器进入到项目首页')
self.loginpage.login_gjs_pro(self.readusername(2), self.readpassword(2))
self.log('PO-gjs:输入正确用户名和密码为空')
self.assertEqual(self.loginpage.get_passwordNullText(), self.exceptText(2))
self.log('P... | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
def test_user_null(self):
"""测试密码为空"""
<|body_0|>
def test_username_null(self):
"""测试用户名为空"""
<|body_1|>
def test_user_passwd_null(self):
"""测试用户名/密码为空"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.loginpage.op... | stack_v2_sparse_classes_36k_train_018751 | 4,917 | no_license | [
{
"docstring": "测试密码为空",
"name": "test_user_null",
"signature": "def test_user_null(self)"
},
{
"docstring": "测试用户名为空",
"name": "test_username_null",
"signature": "def test_username_null(self)"
},
{
"docstring": "测试用户名/密码为空",
"name": "test_user_passwd_null",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_013485 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_user_null(self): 测试密码为空
- def test_username_null(self): 测试用户名为空
- def test_user_passwd_null(self): 测试用户名/密码为空 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_user_null(self): 测试密码为空
- def test_username_null(self): 测试用户名为空
- def test_user_passwd_null(self): 测试用户名/密码为空
<|skeleton|>
class TestLogin:
def test_user_null(se... | 910bcf91dacb8ef699c700709b42dec771b504d0 | <|skeleton|>
class TestLogin:
def test_user_null(self):
"""测试密码为空"""
<|body_0|>
def test_username_null(self):
"""测试用户名为空"""
<|body_1|>
def test_user_passwd_null(self):
"""测试用户名/密码为空"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLogin:
def test_user_null(self):
"""测试密码为空"""
self.loginpage.openLoginPage()
self.log('PO-gjs:打开浏览器进入到项目首页')
self.loginpage.login_gjs_pro(self.readusername(2), self.readpassword(2))
self.log('PO-gjs:输入正确用户名和密码为空')
self.assertEqual(self.loginpage.get_password... | the_stack_v2_python_sparse | 2.15章节源码/page/test_Login.py | luruifeng/myBookCode | train | 3 | |
314aba23446bc9511891adc25df151613f77257c | [
"Frame.__init__(self, *args, **kwargs)\nself.download = fdw.FrameDownload(self)\nself.process = fp.FrameProcess(self)\nself.display = fds.FrameDisplay(self)\nself.create_buttons()\nself.create_container()",
"button_frame = Frame(self)\nbutton_frame.place(relx=0.5, rely=0.5, anchor='c')\nbutton_frame.pack(side='to... | <|body_start_0|>
Frame.__init__(self, *args, **kwargs)
self.download = fdw.FrameDownload(self)
self.process = fp.FrameProcess(self)
self.display = fds.FrameDisplay(self)
self.create_buttons()
self.create_container()
<|end_body_0|>
<|body_start_1|>
button_frame = ... | Main frame class. | MainView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainView:
"""Main frame class."""
def __init__(self, *args, **kwargs):
"""Set the button frame and the container frame for the Main frame. :param args: Any arguments :param kwargs: Aby arguments"""
<|body_0|>
def create_buttons(self) -> None:
"""Create buttons fo... | stack_v2_sparse_classes_36k_train_018752 | 3,025 | no_license | [
{
"docstring": "Set the button frame and the container frame for the Main frame. :param args: Any arguments :param kwargs: Aby arguments",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Create buttons for the Main frame. :return: None",
"name": "cre... | 3 | stack_v2_sparse_classes_30k_val_000963 | Implement the Python class `MainView` described below.
Class description:
Main frame class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set the button frame and the container frame for the Main frame. :param args: Any arguments :param kwargs: Aby arguments
- def create_buttons(self) -> No... | Implement the Python class `MainView` described below.
Class description:
Main frame class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set the button frame and the container frame for the Main frame. :param args: Any arguments :param kwargs: Aby arguments
- def create_buttons(self) -> No... | 271390668c0dcc9d85ad78c757bda7456d46f877 | <|skeleton|>
class MainView:
"""Main frame class."""
def __init__(self, *args, **kwargs):
"""Set the button frame and the container frame for the Main frame. :param args: Any arguments :param kwargs: Aby arguments"""
<|body_0|>
def create_buttons(self) -> None:
"""Create buttons fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MainView:
"""Main frame class."""
def __init__(self, *args, **kwargs):
"""Set the button frame and the container frame for the Main frame. :param args: Any arguments :param kwargs: Aby arguments"""
Frame.__init__(self, *args, **kwargs)
self.download = fdw.FrameDownload(self)
... | the_stack_v2_python_sparse | data_displaying/gui.py | BabyCakes13/Glacier-Analyser | train | 5 |
e688e235226bef00ac82b0e5806b081bbf580c3e | [
"index1 = self._select_index(population=population)\nindex2 = index1\nwhile index2 == index1:\n index2 = self._select_index(population=population)\nreturn (population.get(index1), population.get(index2))",
"total_fitness = 0\nfor solution in population.solutions:\n total_fitness += solution.fitness\nwheel_p... | <|body_start_0|>
index1 = self._select_index(population=population)
index2 = index1
while index2 == index1:
index2 = self._select_index(population=population)
return (population.get(index1), population.get(index2))
<|end_body_0|>
<|body_start_1|>
total_fitness = 0
... | Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individuals REMARK: This implementation does not consider minimization problem | RouletteWheelSelection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouletteWheelSelection:
"""Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individuals REMARK: This implementation does no... | stack_v2_sparse_classes_36k_train_018753 | 10,268 | no_license | [
{
"docstring": "select two different parents using roulette wheel",
"name": "select",
"signature": "def select(self, population, objective, params)"
},
{
"docstring": "This is the roullete wheel itself",
"name": "_select_index",
"signature": "def _select_index(self, population)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010977 | Implement the Python class `RouletteWheelSelection` described below.
Class description:
Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individu... | Implement the Python class `RouletteWheelSelection` described below.
Class description:
Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individu... | 4dd77d5d72186f446fead55371c9941c4020f431 | <|skeleton|>
class RouletteWheelSelection:
"""Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individuals REMARK: This implementation does no... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RouletteWheelSelection:
"""Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individuals REMARK: This implementation does not consider mi... | the_stack_v2_python_sparse | Customer Segmentation for Insurance Dataset/Extra Code/GA for ML/algorithm/ga_operators.py | apanchot/Projects | train | 1 |
05f4b5a2eb9e0b9004e3088ef049a1b2f5d0118b | [
"if 'id' in request.GET:\n project_id = 'new_app:scanlottery:%s' % request.GET.get('related_page_id', 0)\n try:\n scanlottery = app_models.Scanlottery.objects.get(id=request.GET['id'])\n except:\n c = RequestContext(request, {'first_nav_name': FIRST_NAV, 'second_navs': mall_export.get_promoti... | <|body_start_0|>
if 'id' in request.GET:
project_id = 'new_app:scanlottery:%s' % request.GET.get('related_page_id', 0)
try:
scanlottery = app_models.Scanlottery.objects.get(id=request.GET['id'])
except:
c = RequestContext(request, {'first_nav_n... | Scanlottery | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scanlottery:
def get(request):
"""响应GET"""
<|body_0|>
def api_put(request):
"""响应PUT"""
<|body_1|>
def api_post(request):
"""响应POST"""
<|body_2|>
def api_delete(request):
"""响应DELETE"""
<|body_3|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_018754 | 4,033 | no_license | [
{
"docstring": "响应GET",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "响应PUT",
"name": "api_put",
"signature": "def api_put(request)"
},
{
"docstring": "响应POST",
"name": "api_post",
"signature": "def api_post(request)"
},
{
"docstring": "响应DELET... | 4 | null | Implement the Python class `Scanlottery` described below.
Class description:
Implement the Scanlottery class.
Method signatures and docstrings:
- def get(request): 响应GET
- def api_put(request): 响应PUT
- def api_post(request): 响应POST
- def api_delete(request): 响应DELETE | Implement the Python class `Scanlottery` described below.
Class description:
Implement the Scanlottery class.
Method signatures and docstrings:
- def get(request): 响应GET
- def api_put(request): 响应PUT
- def api_post(request): 响应POST
- def api_delete(request): 响应DELETE
<|skeleton|>
class Scanlottery:
def get(requ... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class Scanlottery:
def get(request):
"""响应GET"""
<|body_0|>
def api_put(request):
"""响应PUT"""
<|body_1|>
def api_post(request):
"""响应POST"""
<|body_2|>
def api_delete(request):
"""响应DELETE"""
<|body_3|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scanlottery:
def get(request):
"""响应GET"""
if 'id' in request.GET:
project_id = 'new_app:scanlottery:%s' % request.GET.get('related_page_id', 0)
try:
scanlottery = app_models.Scanlottery.objects.get(id=request.GET['id'])
except:
... | the_stack_v2_python_sparse | weapp/apps/customerized_apps/scanlottery/scanlottery.py | chengdg/weizoom | train | 1 | |
c6bd06c206e535163c297d72e5ab047fcb3cde9a | [
"user = self.model(username=username, personal=personal, family=family, email=self.normalize_email(email), is_superuser=False)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.model(username=username, personal=personal, family=family, email=self.normalize_email(email), is_superu... | <|body_start_0|>
user = self.model(username=username, personal=personal, family=family, email=self.normalize_email(email), is_superuser=False)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.model(username=username, p... | Create users and superusers from command line. For example: $ python manage.py createsuperuser | PersonManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonManager:
"""Create users and superusers from command line. For example: $ python manage.py createsuperuser"""
def create_user(self, username, personal, family, email, password=None):
"""Create and save a normal (not-super) user."""
<|body_0|>
def create_superuser(s... | stack_v2_sparse_classes_36k_train_018755 | 33,077 | permissive | [
{
"docstring": "Create and save a normal (not-super) user.",
"name": "create_user",
"signature": "def create_user(self, username, personal, family, email, password=None)"
},
{
"docstring": "Create and save a superuser.",
"name": "create_superuser",
"signature": "def create_superuser(self... | 2 | stack_v2_sparse_classes_30k_train_010038 | Implement the Python class `PersonManager` described below.
Class description:
Create users and superusers from command line. For example: $ python manage.py createsuperuser
Method signatures and docstrings:
- def create_user(self, username, personal, family, email, password=None): Create and save a normal (not-super... | Implement the Python class `PersonManager` described below.
Class description:
Create users and superusers from command line. For example: $ python manage.py createsuperuser
Method signatures and docstrings:
- def create_user(self, username, personal, family, email, password=None): Create and save a normal (not-super... | bb8a5d065930542bb378fea133851200aa58058a | <|skeleton|>
class PersonManager:
"""Create users and superusers from command line. For example: $ python manage.py createsuperuser"""
def create_user(self, username, personal, family, email, password=None):
"""Create and save a normal (not-super) user."""
<|body_0|>
def create_superuser(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersonManager:
"""Create users and superusers from command line. For example: $ python manage.py createsuperuser"""
def create_user(self, username, personal, family, email, password=None):
"""Create and save a normal (not-super) user."""
user = self.model(username=username, personal=perso... | the_stack_v2_python_sparse | workshops/models.py | wking/swc-amy | train | 0 |
455912b33abc587b0bd4ea135ce2da724d12d645 | [
"r = station_diameter / 2\nfor i in range(strings_per_station):\n if i == 0:\n x_str = x\n y_str = y\n else:\n angle = 0 if i == 1 else 2 * np.pi * (i - 1) / (strings_per_station - 1)\n x_str = x + r * np.cos(angle)\n y_str = y + r * np.sin(angle)\n self.subsets.append(st... | <|body_start_0|>
r = station_diameter / 2
for i in range(strings_per_station):
if i == 0:
x_str = x
y_str = y
else:
angle = 0 if i == 1 else 2 * np.pi * (i - 1) / (strings_per_station - 1)
x_str = x + r * np.cos(angl... | Station geometry with one string at the station center and the rest of the strings evenly spaced radially around the station center. Supports any string type and passes extra keyword arguments on to the string class. | CoxeterStation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoxeterStation:
"""Station geometry with one string at the station center and the rest of the strings evenly spaced radially around the station center. Supports any string type and passes extra keyword arguments on to the string class."""
def set_positions(self, x, y, strings_per_station=4, ... | stack_v2_sparse_classes_36k_train_018756 | 6,416 | permissive | [
{
"docstring": "Generates string positions around the station.",
"name": "set_positions",
"signature": "def set_positions(self, x, y, strings_per_station=4, station_diameter=50, string_type=IREXString, **string_kwargs)"
},
{
"docstring": "Test whether the number of hit antennas meets the given a... | 2 | stack_v2_sparse_classes_30k_test_000687 | Implement the Python class `CoxeterStation` described below.
Class description:
Station geometry with one string at the station center and the rest of the strings evenly spaced radially around the station center. Supports any string type and passes extra keyword arguments on to the string class.
Method signatures and... | Implement the Python class `CoxeterStation` described below.
Class description:
Station geometry with one string at the station center and the rest of the strings evenly spaced radially around the station center. Supports any string type and passes extra keyword arguments on to the string class.
Method signatures and... | 80798ec2c4fd2e27f40843e37013765ee6a4e551 | <|skeleton|>
class CoxeterStation:
"""Station geometry with one string at the station center and the rest of the strings evenly spaced radially around the station center. Supports any string type and passes extra keyword arguments on to the string class."""
def set_positions(self, x, y, strings_per_station=4, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CoxeterStation:
"""Station geometry with one string at the station center and the rest of the strings evenly spaced radially around the station center. Supports any string type and passes extra keyword arguments on to the string class."""
def set_positions(self, x, y, strings_per_station=4, station_diame... | the_stack_v2_python_sparse | pyrex/custom/irex/detector.py | shrishabh/pyrex | train | 0 |
fad880e928937a6e4c537c2bf66e62120d904775 | [
"self.device_name = None\nself.device_type = None\nself.device_name_abbrev = None\nself.compatible = None\nself.device_address = None\nself.vendor = 'al'\nself.device_attributes = None\nself.attrWriteCommBytes = None\nself.attrWriteComm = None\nself.attributeWriteOffsets = None\nself.initComm = None\nself.initCommB... | <|body_start_0|>
self.device_name = None
self.device_type = None
self.device_name_abbrev = None
self.compatible = None
self.device_address = None
self.vendor = 'al'
self.device_attributes = None
self.attrWriteCommBytes = None
self.attrWriteComm = N... | The configuration for the driver being generated. | DriverConfig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DriverConfig:
"""The configuration for the driver being generated."""
def __init__(self):
"""Initialize driver configuration."""
<|body_0|>
def parse_json(json_filepath):
"""Parse JSON file into driver configuration. Parameters ---------- json_filepath : str file... | stack_v2_sparse_classes_36k_train_018757 | 4,564 | permissive | [
{
"docstring": "Initialize driver configuration.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Parse JSON file into driver configuration. Parameters ---------- json_filepath : str file path to JSON configuration file Returns ------- DriverConfig Returns an instance o... | 2 | stack_v2_sparse_classes_30k_train_006267 | Implement the Python class `DriverConfig` described below.
Class description:
The configuration for the driver being generated.
Method signatures and docstrings:
- def __init__(self): Initialize driver configuration.
- def parse_json(json_filepath): Parse JSON file into driver configuration. Parameters ---------- jso... | Implement the Python class `DriverConfig` described below.
Class description:
The configuration for the driver being generated.
Method signatures and docstrings:
- def __init__(self): Initialize driver configuration.
- def parse_json(json_filepath): Parse JSON file into driver configuration. Parameters ---------- jso... | 090576504c721ea18d1cc09fadfe9873c0e1f96c | <|skeleton|>
class DriverConfig:
"""The configuration for the driver being generated."""
def __init__(self):
"""Initialize driver configuration."""
<|body_0|>
def parse_json(json_filepath):
"""Parse JSON file into driver configuration. Parameters ---------- json_filepath : str file... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DriverConfig:
"""The configuration for the driver being generated."""
def __init__(self):
"""Initialize driver configuration."""
self.device_name = None
self.device_type = None
self.device_name_abbrev = None
self.compatible = None
self.device_address = None... | the_stack_v2_python_sparse | device_drivers/driver_config.py | fpga-open-speech-tools/simulink_codegen | train | 2 |
7d815e9da803285f6e5e9ebf4467e0f08c76fb20 | [
"super().__init__()\nimport sklearn\nimport sklearn.discriminant_analysis\nself.model = sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis",
"specs = super(QuadraticDiscriminantAnalysisClassifier, cls).getInputSpecification()\nspecs.description = \"The \\\\xmlNode{QuadraticDiscriminantAnalysisClassifier}... | <|body_start_0|>
super().__init__()
import sklearn
import sklearn.discriminant_analysis
self.model = sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis
<|end_body_0|>
<|body_start_1|>
specs = super(QuadraticDiscriminantAnalysisClassifier, cls).getInputSpecification()
... | KNeighborsClassifier Classifier implementing the k-nearest neighbors vote. | QuadraticDiscriminantAnalysisClassifier | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuadraticDiscriminantAnalysisClassifier:
"""KNeighborsClassifier Classifier implementing the k-nearest neighbors vote."""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputS... | stack_v2_sparse_classes_36k_train_018758 | 5,236 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 3 | stack_v2_sparse_classes_30k_train_018547 | Implement the Python class `QuadraticDiscriminantAnalysisClassifier` described below.
Class description:
KNeighborsClassifier Classifier implementing the k-nearest neighbors vote.
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, ... | Implement the Python class `QuadraticDiscriminantAnalysisClassifier` described below.
Class description:
KNeighborsClassifier Classifier implementing the k-nearest neighbors vote.
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, ... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class QuadraticDiscriminantAnalysisClassifier:
"""KNeighborsClassifier Classifier implementing the k-nearest neighbors vote."""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputS... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuadraticDiscriminantAnalysisClassifier:
"""KNeighborsClassifier Classifier implementing the k-nearest neighbors vote."""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
import sklearn
... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/DiscriminantAnalysis/QuadraticDiscriminantAnalysis.py | idaholab/raven | train | 201 |
b3351e565ab7f8f534a647d41008a0f639abeb0a | [
"self.cmd = cmd\nself.content = content\nself.stdout = None\nself.returncode = 0\nself.stderr = None\nthreading.Thread.__init__(self)",
"read, write = os.pipe()\nos.write(write, str.encode(self.content))\nos.close(write)\ntry:\n output = subprocess.check_output(self.cmd, shell=sublime.platform() == 'windows', ... | <|body_start_0|>
self.cmd = cmd
self.content = content
self.stdout = None
self.returncode = 0
self.stderr = None
threading.Thread.__init__(self)
<|end_body_0|>
<|body_start_1|>
read, write = os.pipe()
os.write(write, str.encode(self.content))
os.c... | Threaded class used for running flow commands in a different thread. The subprocess must be threaded so we don't lockup the UI. | ExecFlowCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecFlowCommand:
"""Threaded class used for running flow commands in a different thread. The subprocess must be threaded so we don't lockup the UI."""
def __init__(self, cmd, content):
"""Initialize with the command and the file content to send."""
<|body_0|>
def run(sel... | stack_v2_sparse_classes_36k_train_018759 | 1,493 | permissive | [
{
"docstring": "Initialize with the command and the file content to send.",
"name": "__init__",
"signature": "def __init__(self, cmd, content)"
},
{
"docstring": "Execute the command in a subprocess.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007845 | Implement the Python class `ExecFlowCommand` described below.
Class description:
Threaded class used for running flow commands in a different thread. The subprocess must be threaded so we don't lockup the UI.
Method signatures and docstrings:
- def __init__(self, cmd, content): Initialize with the command and the fil... | Implement the Python class `ExecFlowCommand` described below.
Class description:
Threaded class used for running flow commands in a different thread. The subprocess must be threaded so we don't lockup the UI.
Method signatures and docstrings:
- def __init__(self, cmd, content): Initialize with the command and the fil... | d1f95f22fb698029d09771dfe0959eb2d7f0c722 | <|skeleton|>
class ExecFlowCommand:
"""Threaded class used for running flow commands in a different thread. The subprocess must be threaded so we don't lockup the UI."""
def __init__(self, cmd, content):
"""Initialize with the command and the file content to send."""
<|body_0|>
def run(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExecFlowCommand:
"""Threaded class used for running flow commands in a different thread. The subprocess must be threaded so we don't lockup the UI."""
def __init__(self, cmd, content):
"""Initialize with the command and the file content to send."""
self.cmd = cmd
self.content = co... | the_stack_v2_python_sparse | flowtype/commands/exec_flow.py | Pegase745/sublime-flowtype | train | 32 |
93e5989775c1779db6095dc63156b6743d503b4e | [
"author = g.user\ntag = TagModel.query.get(tag_id)\nif not tag:\n abort(404, error=f'Tag with id={tag_id} not found')\nif tag.author != author:\n abort(403, error=f'Access denied to tag with id={tag_id}')\nreturn (tag, 200)",
"author = g.user\ntag = TagModel.query.get(tag_id)\nif not tag:\n abort(404, er... | <|body_start_0|>
author = g.user
tag = TagModel.query.get(tag_id)
if not tag:
abort(404, error=f'Tag with id={tag_id} not found')
if tag.author != author:
abort(403, error=f'Access denied to tag with id={tag_id}')
return (tag, 200)
<|end_body_0|>
<|body_s... | TagResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagResource:
def get(self, tag_id):
"""Возвращает тег по id. Требуется аутентификация. :param tag_id: id тега :return: тег"""
<|body_0|>
def put(self, tag_id, **kwargs):
"""Изменяет тег по id. Требуется аутентификация. :param tag_id: id тега :param kwargs: параметры ... | stack_v2_sparse_classes_36k_train_018760 | 3,928 | no_license | [
{
"docstring": "Возвращает тег по id. Требуется аутентификация. :param tag_id: id тега :return: тег",
"name": "get",
"signature": "def get(self, tag_id)"
},
{
"docstring": "Изменяет тег по id. Требуется аутентификация. :param tag_id: id тега :param kwargs: параметры для изменения тега :return: т... | 3 | stack_v2_sparse_classes_30k_train_010622 | Implement the Python class `TagResource` described below.
Class description:
Implement the TagResource class.
Method signatures and docstrings:
- def get(self, tag_id): Возвращает тег по id. Требуется аутентификация. :param tag_id: id тега :return: тег
- def put(self, tag_id, **kwargs): Изменяет тег по id. Требуется ... | Implement the Python class `TagResource` described below.
Class description:
Implement the TagResource class.
Method signatures and docstrings:
- def get(self, tag_id): Возвращает тег по id. Требуется аутентификация. :param tag_id: id тега :return: тег
- def put(self, tag_id, **kwargs): Изменяет тег по id. Требуется ... | adb9a3f4524ab76e8ba656344e2ed452e87b577c | <|skeleton|>
class TagResource:
def get(self, tag_id):
"""Возвращает тег по id. Требуется аутентификация. :param tag_id: id тега :return: тег"""
<|body_0|>
def put(self, tag_id, **kwargs):
"""Изменяет тег по id. Требуется аутентификация. :param tag_id: id тега :param kwargs: параметры ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TagResource:
def get(self, tag_id):
"""Возвращает тег по id. Требуется аутентификация. :param tag_id: id тега :return: тег"""
author = g.user
tag = TagModel.query.get(tag_id)
if not tag:
abort(404, error=f'Tag with id={tag_id} not found')
if tag.author != au... | the_stack_v2_python_sparse | api/resources/tag.py | UshakovAleksandr/Blog | train | 1 | |
22fe7cd59df87cbf8f01d07a113adcd6cd550126 | [
"if description is not None and len(description) > constants.DESC_MAX_LENGTH:\n raise forms.ValidationError({'description': [_(constants.DESC_SIZE)]})\nelif description is not None and len(description) < constants.DESC_MIN_LENGTH:\n raise forms.ValidationError({'description': [_(constants.DESC_SIZE)]})",
"n... | <|body_start_0|>
if description is not None and len(description) > constants.DESC_MAX_LENGTH:
raise forms.ValidationError({'description': [_(constants.DESC_SIZE)]})
elif description is not None and len(description) < constants.DESC_MIN_LENGTH:
raise forms.ValidationError({'descri... | Validating Custom Exam fields. | CustomExamValidator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomExamValidator:
"""Validating Custom Exam fields."""
def validator_description(self, description):
"""Validating description."""
<|body_0|>
def validator_name(self, name):
"""Validating name."""
<|body_1|>
def validator_name_update(self, name):
... | stack_v2_sparse_classes_36k_train_018761 | 1,637 | permissive | [
{
"docstring": "Validating description.",
"name": "validator_description",
"signature": "def validator_description(self, description)"
},
{
"docstring": "Validating name.",
"name": "validator_name",
"signature": "def validator_name(self, name)"
},
{
"docstring": "Validating name.... | 3 | null | Implement the Python class `CustomExamValidator` described below.
Class description:
Validating Custom Exam fields.
Method signatures and docstrings:
- def validator_description(self, description): Validating description.
- def validator_name(self, name): Validating name.
- def validator_name_update(self, name): Vali... | Implement the Python class `CustomExamValidator` described below.
Class description:
Validating Custom Exam fields.
Method signatures and docstrings:
- def validator_description(self, description): Validating description.
- def validator_name(self, name): Validating name.
- def validator_name_update(self, name): Vali... | 5387eb80dfb354e948abe64f7d8bbe087fc4f136 | <|skeleton|>
class CustomExamValidator:
"""Validating Custom Exam fields."""
def validator_description(self, description):
"""Validating description."""
<|body_0|>
def validator_name(self, name):
"""Validating name."""
<|body_1|>
def validator_name_update(self, name):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomExamValidator:
"""Validating Custom Exam fields."""
def validator_description(self, description):
"""Validating description."""
if description is not None and len(description) > constants.DESC_MAX_LENGTH:
raise forms.ValidationError({'description': [_(constants.DESC_SIZE... | the_stack_v2_python_sparse | medical_prescription/exam/validators/customexamvalidator.py | ristovao/2017.2-Receituario-Medico | train | 0 |
4ffe6b92d6d24f1fecb74a43cdf54a1ba52d04e5 | [
"for item in list_target:\n if func_condition(item):\n yield item",
"for item in list_target:\n if func_condition(item):\n return item",
"number = 0\nfor item in list_target:\n if func_condition(item):\n number += 1\nreturn number",
"for item in list_target:\n if func_conditio... | <|body_start_0|>
for item in list_target:
if func_condition(item):
yield item
<|end_body_0|>
<|body_start_1|>
for item in list_target:
if func_condition(item):
return item
<|end_body_1|>
<|body_start_2|>
number = 0
for item in lis... | 列表助手类 | ListHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListHelper:
"""列表助手类"""
def find_all(list_target, func_condition):
"""通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型."""
<|body_0|>
def find_single_condition(list_target, func_condition):
"... | stack_v2_sparse_classes_36k_train_018762 | 2,479 | no_license | [
{
"docstring": "通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型.",
"name": "find_all",
"signature": "def find_all(list_target, func_condition)"
},
{
"docstring": "通用的查找某个条件的单个元素的方法 :param list_target: 需要查找的列表 :param func_co... | 4 | stack_v2_sparse_classes_30k_train_020319 | Implement the Python class `ListHelper` described below.
Class description:
列表助手类
Method signatures and docstrings:
- def find_all(list_target, func_condition): 通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型.
- def find_single_condition(list_ta... | Implement the Python class `ListHelper` described below.
Class description:
列表助手类
Method signatures and docstrings:
- def find_all(list_target, func_condition): 通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型.
- def find_single_condition(list_ta... | 55e6681da1a9faf9c0ec618ed60f5da9ecc6beb6 | <|skeleton|>
class ListHelper:
"""列表助手类"""
def find_all(list_target, func_condition):
"""通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型."""
<|body_0|>
def find_single_condition(list_target, func_condition):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListHelper:
"""列表助手类"""
def find_all(list_target, func_condition):
"""通用的查找某个条件的所有元素方法 :param list_target: 需要查找的列表 :param func_condition: 需要查找的条件,函数类型 函数名(参数) --> bool :return: 需要查找的元素,生成器类型."""
for item in list_target:
if func_condition(item):
yield item
... | the_stack_v2_python_sparse | MyNotes_01/Step01/4-CORE/day04_17/common/list_helper.py | ZimingGuo/MyNotes01 | train | 0 |
16d2159a79e1bf886a49d7db52e067aa0a2b22f3 | [
"self._caffe = kwargs.pop('caffe')\nkwargs.setdefault('label_suffix', '')\nsuper(ProductForm, self).__init__(*args, **kwargs)\nself.fields['name'].label = 'Nazwa'\nself.fields['category'].label = 'Kategoria'\nself.fields['unit'].label = 'Jednostka'\nself.fields['category'].empty_label = None\nself.fields['unit'].em... | <|body_start_0|>
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['name'].label = 'Nazwa'
self.fields['category'].label = 'Kategoria'
self.fields['unit'].label = 'Jednostka'
self... | Responsible for setting up a Product. | ProductForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductForm:
"""Responsible for setting up a Product."""
def __init__(self, *args, **kwargs):
"""Initialize all Product's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commit=True):
"""Override ... | stack_v2_sparse_classes_36k_train_018763 | 5,569 | permissive | [
{
"docstring": "Initialize all Product's fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check name field.",
"name": "clean_name",
"signature": "def clean_name(self)"
},
{
"docstring": "Override of save method, to add Caffe rela... | 3 | stack_v2_sparse_classes_30k_train_020953 | Implement the Python class `ProductForm` described below.
Class description:
Responsible for setting up a Product.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Product's fields.
- def clean_name(self): Check name field.
- def save(self, commit=True): Override of save method,... | Implement the Python class `ProductForm` described below.
Class description:
Responsible for setting up a Product.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Product's fields.
- def clean_name(self): Check name field.
- def save(self, commit=True): Override of save method,... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class ProductForm:
"""Responsible for setting up a Product."""
def __init__(self, *args, **kwargs):
"""Initialize all Product's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commit=True):
"""Override ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductForm:
"""Responsible for setting up a Product."""
def __init__(self, *args, **kwargs):
"""Initialize all Product's fields."""
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(ProductForm, self).__init__(*args, **kwargs)
self.fiel... | the_stack_v2_python_sparse | caffe/reports/forms.py | VirrageS/io-kawiarnie | train | 3 |
579f88719470322c795e58bef8a1e3db137f9628 | [
"super().__init__()\nself.threshold = threshold\nself.pitch_weight = pitch_weight\nself.ioi_weight = ioi_weight\nself.rest_weight = rest_weight",
"track: MidiTrack = mid.tracks[track_index]\nchord_track_ind = None\nchord_track = None\nif 'chord_track' in kwargs.keys() and kwargs['chord_track'] is not None:\n c... | <|body_start_0|>
super().__init__()
self.threshold = threshold
self.pitch_weight = pitch_weight
self.ioi_weight = ioi_weight
self.rest_weight = rest_weight
<|end_body_0|>
<|body_start_1|>
track: MidiTrack = mid.tracks[track_index]
chord_track_ind = None
c... | LbdmSegmenter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LbdmSegmenter:
def __init__(self, threshold: float=0.5, pitch_weight: float=0.25, ioi_weight: float=0.5, rest_weight: float=0.25):
"""A Segmenter which creates segments of music based on the LBDM algorithm (Cambouropoulos, 2001). See lbdm.py for how the segmentation works. In short the o... | stack_v2_sparse_classes_36k_train_018764 | 3,812 | no_license | [
{
"docstring": "A Segmenter which creates segments of music based on the LBDM algorithm (Cambouropoulos, 2001). See lbdm.py for how the segmentation works. In short the output of the LBDM algorithm is a boundary profile. This Segmenter splits the input MIDI file at places where the boundary value is > ``thresho... | 2 | stack_v2_sparse_classes_30k_train_009468 | Implement the Python class `LbdmSegmenter` described below.
Class description:
Implement the LbdmSegmenter class.
Method signatures and docstrings:
- def __init__(self, threshold: float=0.5, pitch_weight: float=0.25, ioi_weight: float=0.5, rest_weight: float=0.25): A Segmenter which creates segments of music based on... | Implement the Python class `LbdmSegmenter` described below.
Class description:
Implement the LbdmSegmenter class.
Method signatures and docstrings:
- def __init__(self, threshold: float=0.5, pitch_weight: float=0.25, ioi_weight: float=0.5, rest_weight: float=0.25): A Segmenter which creates segments of music based on... | f78b35274f49f6ae54ca7bc02691ab5db45eda36 | <|skeleton|>
class LbdmSegmenter:
def __init__(self, threshold: float=0.5, pitch_weight: float=0.25, ioi_weight: float=0.5, rest_weight: float=0.25):
"""A Segmenter which creates segments of music based on the LBDM algorithm (Cambouropoulos, 2001). See lbdm.py for how the segmentation works. In short the o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LbdmSegmenter:
def __init__(self, threshold: float=0.5, pitch_weight: float=0.25, ioi_weight: float=0.5, rest_weight: float=0.25):
"""A Segmenter which creates segments of music based on the LBDM algorithm (Cambouropoulos, 2001). See lbdm.py for how the segmentation works. In short the output of the L... | the_stack_v2_python_sparse | project/algorithms/graph_based/lbdm_segmenter.py | jamesb456/final-year-project | train | 0 | |
1c30e177e19b9845715f0ad9a2e0f01622919a2d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RiskDetection()",
"from .activity_type import ActivityType\nfrom .entity import Entity\nfrom .risk_detail import RiskDetail\nfrom .risk_detection_timing_type import RiskDetectionTimingType\nfrom .risk_level import RiskLevel\nfrom .risk... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return RiskDetection()
<|end_body_0|>
<|body_start_1|>
from .activity_type import ActivityType
from .entity import Entity
from .risk_detail import RiskDetail
from .risk_detectio... | RiskDetection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RiskDetection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskDetection:
"""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... | stack_v2_sparse_classes_36k_train_018765 | 10,613 | 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: RiskDetection",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | stack_v2_sparse_classes_30k_train_008888 | Implement the Python class `RiskDetection` described below.
Class description:
Implement the RiskDetection class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskDetection: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `RiskDetection` described below.
Class description:
Implement the RiskDetection class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskDetection: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class RiskDetection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskDetection:
"""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... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RiskDetection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskDetection:
"""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: RiskDetectio... | the_stack_v2_python_sparse | msgraph/generated/models/risk_detection.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
da814904d40b66b3e6bd2b8a43af2e420a90ad77 | [
"super(Decoder, self).__init__()\nself.d_model = d_model\nself.number_of_layers = number_of_layers\nself.embedding = tf.keras.layers.Embedding(target_vocabulary_size, d_model)\nself.positional_encoding = positional_encoding(maximum_position_encoding, d_model)\nself.decoder_layers = [DecoderLayer(d_model, number_of_... | <|body_start_0|>
super(Decoder, self).__init__()
self.d_model = d_model
self.number_of_layers = number_of_layers
self.embedding = tf.keras.layers.Embedding(target_vocabulary_size, d_model)
self.positional_encoding = positional_encoding(maximum_position_encoding, d_model)
... | Decoder class contains of word embedding, positional encoding and several numbers of decoder layers to represent an decoder of transformer model | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Decoder class contains of word embedding, positional encoding and several numbers of decoder layers to represent an decoder of transformer model"""
def __init__(self, number_of_layers, d_model, number_of_heads, dff, target_vocabulary_size, maximum_position_encoding, rate=0.1):
... | stack_v2_sparse_classes_36k_train_018766 | 11,425 | no_license | [
{
"docstring": "Constructor for the Decoder :param number_of_layers: number of decoder layers :param d_model: dimension of the word embedding vector :param number_of_heads: number of heads to work in parallel :param dff: inner-layer dimensionality :param target_vocabulary_size: size of the target vocabulary :pa... | 2 | stack_v2_sparse_classes_30k_train_008788 | Implement the Python class `Decoder` described below.
Class description:
Decoder class contains of word embedding, positional encoding and several numbers of decoder layers to represent an decoder of transformer model
Method signatures and docstrings:
- def __init__(self, number_of_layers, d_model, number_of_heads, d... | Implement the Python class `Decoder` described below.
Class description:
Decoder class contains of word embedding, positional encoding and several numbers of decoder layers to represent an decoder of transformer model
Method signatures and docstrings:
- def __init__(self, number_of_layers, d_model, number_of_heads, d... | f164c21ed852dfd10a4701f4050d72dc87bd302a | <|skeleton|>
class Decoder:
"""Decoder class contains of word embedding, positional encoding and several numbers of decoder layers to represent an decoder of transformer model"""
def __init__(self, number_of_layers, d_model, number_of_heads, dff, target_vocabulary_size, maximum_position_encoding, rate=0.1):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""Decoder class contains of word embedding, positional encoding and several numbers of decoder layers to represent an decoder of transformer model"""
def __init__(self, number_of_layers, d_model, number_of_heads, dff, target_vocabulary_size, maximum_position_encoding, rate=0.1):
"""Cons... | the_stack_v2_python_sparse | backend/code/transformer_model.py | sovaso/NewsHeadlineGenerator | train | 3 |
98ced64d138522af568b25a5ad61d7073e9eb5aa | [
"queryset = Relationship.objects.filter(user_one=user_one)\nif not queryset.count() == 0:\n relationship = queryset[0]\nelse:\n relationship = cls(user_one=user_one)\n relationship.save()\nreturn relationship",
"friends = json.loads(facebook_data).get('data')\nfor friend in friends:\n try:\n us... | <|body_start_0|>
queryset = Relationship.objects.filter(user_one=user_one)
if not queryset.count() == 0:
relationship = queryset[0]
else:
relationship = cls(user_one=user_one)
relationship.save()
return relationship
<|end_body_0|>
<|body_start_1|>
... | Relationship | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Relationship:
def get_instance(cls, user_one):
"""Tenta localizar um Relationship entity para o usuário. Se não for encontrado o método criar um e retorna para o cliente."""
<|body_0|>
def find_friends(self, facebook_data):
"""Parse json data from facebook and map cu... | stack_v2_sparse_classes_36k_train_018767 | 33,206 | no_license | [
{
"docstring": "Tenta localizar um Relationship entity para o usuário. Se não for encontrado o método criar um e retorna para o cliente.",
"name": "get_instance",
"signature": "def get_instance(cls, user_one)"
},
{
"docstring": "Parse json data from facebook and map current friends on Relationsh... | 2 | stack_v2_sparse_classes_30k_train_008244 | Implement the Python class `Relationship` described below.
Class description:
Implement the Relationship class.
Method signatures and docstrings:
- def get_instance(cls, user_one): Tenta localizar um Relationship entity para o usuário. Se não for encontrado o método criar um e retorna para o cliente.
- def find_frien... | Implement the Python class `Relationship` described below.
Class description:
Implement the Relationship class.
Method signatures and docstrings:
- def get_instance(cls, user_one): Tenta localizar um Relationship entity para o usuário. Se não for encontrado o método criar um e retorna para o cliente.
- def find_frien... | 0c2fbdee78e481b66bc66e630ecd794f3d92885f | <|skeleton|>
class Relationship:
def get_instance(cls, user_one):
"""Tenta localizar um Relationship entity para o usuário. Se não for encontrado o método criar um e retorna para o cliente."""
<|body_0|>
def find_friends(self, facebook_data):
"""Parse json data from facebook and map cu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Relationship:
def get_instance(cls, user_one):
"""Tenta localizar um Relationship entity para o usuário. Se não for encontrado o método criar um e retorna para o cliente."""
queryset = Relationship.objects.filter(user_one=user_one)
if not queryset.count() == 0:
relationship... | the_stack_v2_python_sparse | core/models.py | Indikko/indikko | train | 0 | |
47e158c247d92c986cf5f63200aad703e1af6a85 | [
"if not head:\n return head\nindex = 0\nm = {}\ncur = head\ncopy_nodes = []\nwhile cur:\n m[hash(cur)] = index\n node = Node(cur.val, None, None)\n if copy_nodes:\n copy_nodes[-1].next = node\n copy_nodes.append(node)\n index += 1\n cur = cur.next\ncur = head\ncopy_node = copy_nodes[0]\n... | <|body_start_0|>
if not head:
return head
index = 0
m = {}
cur = head
copy_nodes = []
while cur:
m[hash(cur)] = index
node = Node(cur.val, None, None)
if copy_nodes:
copy_nodes[-1].next = node
cop... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def copyRandomList(self, head):
""":type head: Node :rtype: Node"""
<|body_0|>
def copyRandomList1(self, head):
""":type head: Node :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head:
return head
i... | stack_v2_sparse_classes_36k_train_018768 | 2,036 | no_license | [
{
"docstring": ":type head: Node :rtype: Node",
"name": "copyRandomList",
"signature": "def copyRandomList(self, head)"
},
{
"docstring": ":type head: Node :rtype: Node",
"name": "copyRandomList1",
"signature": "def copyRandomList1(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def copyRandomList(self, head): :type head: Node :rtype: Node
- def copyRandomList1(self, head): :type head: Node :rtype: Node | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def copyRandomList(self, head): :type head: Node :rtype: Node
- def copyRandomList1(self, head): :type head: Node :rtype: Node
<|skeleton|>
class Solution:
def copyRandomLi... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def copyRandomList(self, head):
""":type head: Node :rtype: Node"""
<|body_0|>
def copyRandomList1(self, head):
""":type head: Node :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def copyRandomList(self, head):
""":type head: Node :rtype: Node"""
if not head:
return head
index = 0
m = {}
cur = head
copy_nodes = []
while cur:
m[hash(cur)] = index
node = Node(cur.val, None, None)
... | the_stack_v2_python_sparse | python/leetcode/138_Copy_List_with_Random_Pointer.py | bobcaoge/my-code | train | 0 | |
495913fb1c6aaf5639afa60fe74ffd09d85b5854 | [
"self.elements = []\nself.currentMinStack = []\nself.elementsLength = 0\nself.currentMinLength = 0",
"self.elements.append(x)\nself.elementsLength += 1\nif self.currentMinLength == 0 or x <= self.currentMinStack[-1]:\n self.currentMinStack.append(x)\n self.currentMinLength += 1",
"if self.elementsLength =... | <|body_start_0|>
self.elements = []
self.currentMinStack = []
self.elementsLength = 0
self.currentMinLength = 0
<|end_body_0|>
<|body_start_1|>
self.elements.append(x)
self.elementsLength += 1
if self.currentMinLength == 0 or x <= self.currentMinStack[-1]:
... | MinStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinStack:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def push(self, x):
""":type x: int :rtype: void"""
<|body_1|>
def pop(self):
""":rtype: void"""
<|body_2|>
def top(self):
""":rtype: int"""
... | stack_v2_sparse_classes_36k_train_018769 | 1,424 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type x: int :rtype: void",
"name": "push",
"signature": "def push(self, x)"
},
{
"docstring": ":rtype: void",
"name": "pop",
"signature": "def ... | 5 | null | Implement the Python class `MinStack` described below.
Class description:
Implement the MinStack class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def push(self, x): :type x: int :rtype: void
- def pop(self): :rtype: void
- def top(self): :rtype: int
- def getMin(se... | Implement the Python class `MinStack` described below.
Class description:
Implement the MinStack class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def push(self, x): :type x: int :rtype: void
- def pop(self): :rtype: void
- def top(self): :rtype: int
- def getMin(se... | dae0a5e6e688a34e6b870a93ecb210416a54d67a | <|skeleton|>
class MinStack:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def push(self, x):
""":type x: int :rtype: void"""
<|body_1|>
def pop(self):
""":rtype: void"""
<|body_2|>
def top(self):
""":rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MinStack:
def __init__(self):
"""initialize your data structure here."""
self.elements = []
self.currentMinStack = []
self.elementsLength = 0
self.currentMinLength = 0
def push(self, x):
""":type x: int :rtype: void"""
self.elements.append(x)
... | the_stack_v2_python_sparse | python/algorithms/design/min_stack.py | nathanle89/interview | train | 0 | |
7ab7303db9ca1d69ac18f3c0a73adc5e4c7f21ba | [
"labels_queryset = NodeLabel.objects.filter(project_id=project_id)\nif cluster_id != node_constants.PROJECT_ALL_CLUSTER:\n labels_queryset = labels_queryset.filter(cluster_id=cluster_id)\nreturn labels_queryset",
"data = set([])\nfor info in labels_queryset:\n labels = info.node_labels\n if not key_name:... | <|body_start_0|>
labels_queryset = NodeLabel.objects.filter(project_id=project_id)
if cluster_id != node_constants.PROJECT_ALL_CLUSTER:
labels_queryset = labels_queryset.filter(cluster_id=cluster_id)
return labels_queryset
<|end_body_0|>
<|body_start_1|>
data = set([])
... | QueryNodeLabelKeys | [
"BSD-3-Clause",
"LicenseRef-scancode-unicode",
"ICU",
"LicenseRef-scancode-unknown-license-reference",
"Artistic-2.0",
"Zlib",
"LicenseRef-scancode-openssl",
"NAIST-2003",
"ISC",
"NTP",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueryNodeLabelKeys:
def get_queryset(self, project_id, cluster_id):
"""filter the labels record"""
<|body_0|>
def compose_data(self, labels_queryset, key_name=None):
"""compose the label keys or values"""
<|body_1|>
def label_keys(self, request, project_... | stack_v2_sparse_classes_36k_train_018770 | 2,901 | permissive | [
{
"docstring": "filter the labels record",
"name": "get_queryset",
"signature": "def get_queryset(self, project_id, cluster_id)"
},
{
"docstring": "compose the label keys or values",
"name": "compose_data",
"signature": "def compose_data(self, labels_queryset, key_name=None)"
},
{
... | 4 | null | Implement the Python class `QueryNodeLabelKeys` described below.
Class description:
Implement the QueryNodeLabelKeys class.
Method signatures and docstrings:
- def get_queryset(self, project_id, cluster_id): filter the labels record
- def compose_data(self, labels_queryset, key_name=None): compose the label keys or v... | Implement the Python class `QueryNodeLabelKeys` described below.
Class description:
Implement the QueryNodeLabelKeys class.
Method signatures and docstrings:
- def get_queryset(self, project_id, cluster_id): filter the labels record
- def compose_data(self, labels_queryset, key_name=None): compose the label keys or v... | 96373cda9d87038aceb0b4858ce89e7873c8e149 | <|skeleton|>
class QueryNodeLabelKeys:
def get_queryset(self, project_id, cluster_id):
"""filter the labels record"""
<|body_0|>
def compose_data(self, labels_queryset, key_name=None):
"""compose the label keys or values"""
<|body_1|>
def label_keys(self, request, project_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QueryNodeLabelKeys:
def get_queryset(self, project_id, cluster_id):
"""filter the labels record"""
labels_queryset = NodeLabel.objects.filter(project_id=project_id)
if cluster_id != node_constants.PROJECT_ALL_CLUSTER:
labels_queryset = labels_queryset.filter(cluster_id=clus... | the_stack_v2_python_sparse | bcs-app/backend/apps/cluster/views/node_views/query_apis.py | freyzheng/bk-bcs-saas | train | 0 | |
69c5fefceeed4a89ebd2bf8fee07365340f4f3bd | [
"self.rows, self.cols = (height, width)\nself.food = [tuple(f) for f in food]\nself.snake = {(0, 0): None}\nself.head, self.tail = ((0, 0), (0, 0))\nself.moves = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}",
"new_head = (self.head[0] + self.moves[direction][0], self.head[1] + self.moves[direction][1])\... | <|body_start_0|>
self.rows, self.cols = (height, width)
self.food = [tuple(f) for f in food]
self.snake = {(0, 0): None}
self.head, self.tail = ((0, 0), (0, 0))
self.moves = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}
<|end_body_0|>
<|body_start_1|>
new_head =... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_36k_train_018771 | 2,966 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]",
... | 2 | stack_v2_sparse_classes_30k_val_000469 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | 05e0beff0047f0ad399d0b46d625bb8d3459814e | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :... | the_stack_v2_python_sparse | python_1_to_1000/353_Design_Snake_Game.py | jakehoare/leetcode | train | 58 | |
6806e0d3dcfae4849b8586447c1c77d7c28763f6 | [
"exp_value = 3.14\nobj = Double(exp_value)\nself.assertEqual(exp_value, obj.icpw_value)",
"exp_value = 123.456\nobj0 = Double(exp_value)\nobj1 = Double(exp_value)\nself.assertEqual(obj0, obj1)",
"exp_value = 123.456\nobj0 = Double(exp_value)\nobj1 = Double(exp_value)\nself.assertEqual(obj0, obj1)",
"exp_value... | <|body_start_0|>
exp_value = 3.14
obj = Double(exp_value)
self.assertEqual(exp_value, obj.icpw_value)
<|end_body_0|>
<|body_start_1|>
exp_value = 123.456
obj0 = Double(exp_value)
obj1 = Double(exp_value)
self.assertEqual(obj0, obj1)
<|end_body_1|>
<|body_start_2... | DoubleTester | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoubleTester:
def test_value(self):
"""Test retrieving the value of a Double."""
<|body_0|>
def test_eq(self):
"""Test that two Double's with the same value compare equal."""
<|body_1|>
def test_ne(self):
"""Test that two Double's with the same v... | stack_v2_sparse_classes_36k_train_018772 | 42,194 | permissive | [
{
"docstring": "Test retrieving the value of a Double.",
"name": "test_value",
"signature": "def test_value(self)"
},
{
"docstring": "Test that two Double's with the same value compare equal.",
"name": "test_eq",
"signature": "def test_eq(self)"
},
{
"docstring": "Test that two D... | 4 | stack_v2_sparse_classes_30k_train_016045 | Implement the Python class `DoubleTester` described below.
Class description:
Implement the DoubleTester class.
Method signatures and docstrings:
- def test_value(self): Test retrieving the value of a Double.
- def test_eq(self): Test that two Double's with the same value compare equal.
- def test_ne(self): Test that... | Implement the Python class `DoubleTester` described below.
Class description:
Implement the DoubleTester class.
Method signatures and docstrings:
- def test_value(self): Test retrieving the value of a Double.
- def test_eq(self): Test that two Double's with the same value compare equal.
- def test_ne(self): Test that... | a626f881d55c307bd857d0ff980cc526f2b18de2 | <|skeleton|>
class DoubleTester:
def test_value(self):
"""Test retrieving the value of a Double."""
<|body_0|>
def test_eq(self):
"""Test that two Double's with the same value compare equal."""
<|body_1|>
def test_ne(self):
"""Test that two Double's with the same v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DoubleTester:
def test_value(self):
"""Test retrieving the value of a Double."""
exp_value = 3.14
obj = Double(exp_value)
self.assertEqual(exp_value, obj.icpw_value)
def test_eq(self):
"""Test that two Double's with the same value compare equal."""
exp_valu... | the_stack_v2_python_sparse | icypaw/test_types.py | sandialabs/IcyPaw | train | 0 | |
80d599a72b2874f7c907b3cc362274669670f885 | [
"super().__init__(input_key, output_key or input_key)\nself.dtype = dtype\nself.default_value = default_value\nself.one_hot_classes = one_hot_classes\nself.smoothing = smoothing\nif self.one_hot_classes is not None and self.smoothing is not None:\n assert 0.0 < smoothing < 1.0, 'If smoothing is specified it must... | <|body_start_0|>
super().__init__(input_key, output_key or input_key)
self.dtype = dtype
self.default_value = default_value
self.one_hot_classes = one_hot_classes
self.smoothing = smoothing
if self.one_hot_classes is not None and self.smoothing is not None:
as... | Numeric data reader abstraction. Reads a single float, int, str or other from data | ScalarReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalarReader:
"""Numeric data reader abstraction. Reads a single float, int, str or other from data"""
def __init__(self, input_key: str, output_key: Optional[str]=None, dtype: Type=np.float32, default_value: float=None, one_hot_classes: int=None, smoothing: float=None):
"""Args: inp... | stack_v2_sparse_classes_36k_train_018773 | 5,229 | permissive | [
{
"docstring": "Args: input_key: input key to use from annotation dict output_key: output key to use to store the result, default: ``input_key`` dtype: datatype of scalar values to use default_value: default value to use if something goes wrong one_hot_classes: number of one-hot classes smoothing (float, option... | 2 | stack_v2_sparse_classes_30k_train_002981 | Implement the Python class `ScalarReader` described below.
Class description:
Numeric data reader abstraction. Reads a single float, int, str or other from data
Method signatures and docstrings:
- def __init__(self, input_key: str, output_key: Optional[str]=None, dtype: Type=np.float32, default_value: float=None, one... | Implement the Python class `ScalarReader` described below.
Class description:
Numeric data reader abstraction. Reads a single float, int, str or other from data
Method signatures and docstrings:
- def __init__(self, input_key: str, output_key: Optional[str]=None, dtype: Type=np.float32, default_value: float=None, one... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class ScalarReader:
"""Numeric data reader abstraction. Reads a single float, int, str or other from data"""
def __init__(self, input_key: str, output_key: Optional[str]=None, dtype: Type=np.float32, default_value: float=None, one_hot_classes: int=None, smoothing: float=None):
"""Args: inp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScalarReader:
"""Numeric data reader abstraction. Reads a single float, int, str or other from data"""
def __init__(self, input_key: str, output_key: Optional[str]=None, dtype: Type=np.float32, default_value: float=None, one_hot_classes: int=None, smoothing: float=None):
"""Args: input_key: input... | the_stack_v2_python_sparse | catalyst/contrib/data/reader.py | catalyst-team/catalyst | train | 3,038 |
e95597e1994587cf9ce83131016915ae184582ed | [
"include = option.search if option.search else include\nif include:\n match = True if self.isIp(include, True) else match\nahost, nhost = ({}, {})\nhost_key = ['name', 'ip', 'user', 'passwd', 'port', 'sudo']\nkey, ikey = (1, 1)\nincludes = self.getArgs(include)\nwith open(self.sshfile) as rhost:\n for line in... | <|body_start_0|>
include = option.search if option.search else include
if include:
match = True if self.isIp(include, True) else match
ahost, nhost = ({}, {})
host_key = ['name', 'ip', 'user', 'passwd', 'port', 'sudo']
key, ikey = (1, 1)
includes = self.getArg... | 暂时保留 | BaseHandle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseHandle:
"""暂时保留"""
def oldGetHost(self, include=None, pattern=False, match=False):
"""获取主机信息,old数据 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) match : 开启精确匹配模式,默认False(模糊匹配)"""
<|body_0|>
def searchHost(self, include=None, pattern=False, match=False):
"""... | stack_v2_sparse_classes_36k_train_018774 | 5,633 | no_license | [
{
"docstring": "获取主机信息,old数据 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) match : 开启精确匹配模式,默认False(模糊匹配)",
"name": "oldGetHost",
"signature": "def oldGetHost(self, include=None, pattern=False, match=False)"
},
{
"docstring": "获取主机信息, 基于sqlite3 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) m... | 2 | stack_v2_sparse_classes_30k_train_011045 | Implement the Python class `BaseHandle` described below.
Class description:
暂时保留
Method signatures and docstrings:
- def oldGetHost(self, include=None, pattern=False, match=False): 获取主机信息,old数据 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) match : 开启精确匹配模式,默认False(模糊匹配)
- def searchHost(self, include=None, pattern=... | Implement the Python class `BaseHandle` described below.
Class description:
暂时保留
Method signatures and docstrings:
- def oldGetHost(self, include=None, pattern=False, match=False): 获取主机信息,old数据 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) match : 开启精确匹配模式,默认False(模糊匹配)
- def searchHost(self, include=None, pattern=... | 2a4e1e71c9ac3ad3fceeaf9828a0f39d8f205bd8 | <|skeleton|>
class BaseHandle:
"""暂时保留"""
def oldGetHost(self, include=None, pattern=False, match=False):
"""获取主机信息,old数据 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) match : 开启精确匹配模式,默认False(模糊匹配)"""
<|body_0|>
def searchHost(self, include=None, pattern=False, match=False):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseHandle:
"""暂时保留"""
def oldGetHost(self, include=None, pattern=False, match=False):
"""获取主机信息,old数据 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) match : 开启精确匹配模式,默认False(模糊匹配)"""
include = option.search if option.search else include
if include:
match = True if se... | the_stack_v2_python_sparse | build/lib/antshell/install.py | ooppwwqq0/AntShell | train | 5 |
c1253c9e71cc696834db3147a020706933e24840 | [
"if not email:\n raise ValueError('User must have an email address!')\nif not phone:\n raise ValueError('User must have an phone number!')\nemail = self.normalize_email(email)\nuser = self.model(email=email, phone=phone)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.cre... | <|body_start_0|>
if not email:
raise ValueError('User must have an email address!')
if not phone:
raise ValueError('User must have an phone number!')
email = self.normalize_email(email)
user = self.model(email=email, phone=phone)
user.set_password(password... | Helps django work with our custom user model | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
"""Helps django work with our custom user model"""
def create_user(self, email, phone=None, password=None, **kwargs):
"""creates a new user profile objecs"""
<|body_0|>
def create_superuser(self, email, phone, password):
"""creates and saves a... | stack_v2_sparse_classes_36k_train_018775 | 3,088 | no_license | [
{
"docstring": "creates a new user profile objecs",
"name": "create_user",
"signature": "def create_user(self, email, phone=None, password=None, **kwargs)"
},
{
"docstring": "creates and saves a new super user with given details",
"name": "create_superuser",
"signature": "def create_supe... | 2 | stack_v2_sparse_classes_30k_train_015378 | Implement the Python class `UserProfileManager` described below.
Class description:
Helps django work with our custom user model
Method signatures and docstrings:
- def create_user(self, email, phone=None, password=None, **kwargs): creates a new user profile objecs
- def create_superuser(self, email, phone, password)... | Implement the Python class `UserProfileManager` described below.
Class description:
Helps django work with our custom user model
Method signatures and docstrings:
- def create_user(self, email, phone=None, password=None, **kwargs): creates a new user profile objecs
- def create_superuser(self, email, phone, password)... | 1f6a43b49d0a7cdcc4bee35fe0f7e2d9f4ac80fd | <|skeleton|>
class UserProfileManager:
"""Helps django work with our custom user model"""
def create_user(self, email, phone=None, password=None, **kwargs):
"""creates a new user profile objecs"""
<|body_0|>
def create_superuser(self, email, phone, password):
"""creates and saves a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
"""Helps django work with our custom user model"""
def create_user(self, email, phone=None, password=None, **kwargs):
"""creates a new user profile objecs"""
if not email:
raise ValueError('User must have an email address!')
if not phone:
... | the_stack_v2_python_sparse | accounts/models.py | Moshiurmamun/online-booking | train | 1 |
828ea4c327f398c497a4b81e774d0ee9d887bd1d | [
"rand = randint(1, 100)\nprint(rand)\ntmp = set()\nfor data, trip_id in zip(self.trainSet['TERMINALNO'], self.trainSet['TRIP_ID']):\n if data == rand:\n tmp.add(trip_id)\ncnt = len(tmp)\nvalue = self.trainData.iloc[rand - 1].values[0]\nself.assertEqual(cnt, value)",
"rand = randint(1, 100)\nprint(rand)\... | <|body_start_0|>
rand = randint(1, 100)
print(rand)
tmp = set()
for data, trip_id in zip(self.trainSet['TERMINALNO'], self.trainSet['TRIP_ID']):
if data == rand:
tmp.add(trip_id)
cnt = len(tmp)
value = self.trainData.iloc[rand - 1].values[0]
... | TestTripIdCount | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTripIdCount:
def test1(self):
"""test trip :return:"""
<|body_0|>
def test2(self):
"""test trip :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rand = randint(1, 100)
print(rand)
tmp = set()
for data, trip_id in ... | stack_v2_sparse_classes_36k_train_018776 | 1,322 | permissive | [
{
"docstring": "test trip :return:",
"name": "test1",
"signature": "def test1(self)"
},
{
"docstring": "test trip :return:",
"name": "test2",
"signature": "def test2(self)"
}
] | 2 | null | Implement the Python class `TestTripIdCount` described below.
Class description:
Implement the TestTripIdCount class.
Method signatures and docstrings:
- def test1(self): test trip :return:
- def test2(self): test trip :return: | Implement the Python class `TestTripIdCount` described below.
Class description:
Implement the TestTripIdCount class.
Method signatures and docstrings:
- def test1(self): test trip :return:
- def test2(self): test trip :return:
<|skeleton|>
class TestTripIdCount:
def test1(self):
"""test trip :return:""... | a372a2051a2a1580feb280ce6842a785459cf8d1 | <|skeleton|>
class TestTripIdCount:
def test1(self):
"""test trip :return:"""
<|body_0|>
def test2(self):
"""test trip :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestTripIdCount:
def test1(self):
"""test trip :return:"""
rand = randint(1, 100)
print(rand)
tmp = set()
for data, trip_id in zip(self.trainSet['TERMINALNO'], self.trainSet['TRIP_ID']):
if data == rand:
tmp.add(trip_id)
cnt = len(tmp... | the_stack_v2_python_sparse | 驾驶行为预测驾驶风险/team3_48,2749/unittests/functions_trip_id_count.py | moonlight1776/competitions | train | 0 | |
9997586f3652df7b0bfbb50b4708e5fecc8345fb | [
"input_json = request.data\noutput_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'Payload'], [request.data['AvailabilityDetails'], request.data['AuthenticationDetails'], None]))\nif 'APIParams' not in input_json or 'user_ip' not in input_json['APIParams']:\n user_ip_var = None\nelse:\n user... | <|body_start_0|>
input_json = request.data
output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'Payload'], [request.data['AvailabilityDetails'], request.data['AuthenticationDetails'], None]))
if 'APIParams' not in input_json or 'user_ip' not in input_json['APIParams']:
... | This covers the API for fetching all support centre tickets raised by the user | GetUserGeosAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetUserGeosAPI:
"""This covers the API for fetching all support centre tickets raised by the user"""
def post(self, request):
"""Post Function to fetching common questions based on ticket type."""
<|body_0|>
def get_user_geos_json(self, request):
"""this function... | stack_v2_sparse_classes_36k_train_018777 | 4,683 | no_license | [
{
"docstring": "Post Function to fetching common questions based on ticket type.",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "this function calls third party API to get user's country from ip_address in case user_ip is provided in the input. If user_ip is not provi... | 2 | stack_v2_sparse_classes_30k_train_018356 | Implement the Python class `GetUserGeosAPI` described below.
Class description:
This covers the API for fetching all support centre tickets raised by the user
Method signatures and docstrings:
- def post(self, request): Post Function to fetching common questions based on ticket type.
- def get_user_geos_json(self, re... | Implement the Python class `GetUserGeosAPI` described below.
Class description:
This covers the API for fetching all support centre tickets raised by the user
Method signatures and docstrings:
- def post(self, request): Post Function to fetching common questions based on ticket type.
- def get_user_geos_json(self, re... | 36eb9931f330e64902354c6fc471be2adf4b7049 | <|skeleton|>
class GetUserGeosAPI:
"""This covers the API for fetching all support centre tickets raised by the user"""
def post(self, request):
"""Post Function to fetching common questions based on ticket type."""
<|body_0|>
def get_user_geos_json(self, request):
"""this function... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetUserGeosAPI:
"""This covers the API for fetching all support centre tickets raised by the user"""
def post(self, request):
"""Post Function to fetching common questions based on ticket type."""
input_json = request.data
output_json = dict(zip(['AvailabilityDetails', 'Authentica... | the_stack_v2_python_sparse | Generic/common/location/api/get_user_geos/views_get_user_geos.py | archiemb303/common_backend_django | train | 0 |
264030f531868fca69de0d639290b7cdd98302ac | [
"json_dict = json.loads(request.body.decode())\nreceiver = json_dict.get('receiver')\nprovince_id = json_dict.get('province_id')\ncity_id = json_dict.get('city_id')\ndistrict_id = json_dict.get('district_id')\nplace = json_dict.get('place')\nmobile = json_dict.get('mobile')\ntel = json_dict.get('tel')\nemail = json... | <|body_start_0|>
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('province_id')
city_id = json_dict.get('city_id')
district_id = json_dict.get('district_id')
place = json_dict.get('place')
mobile = jso... | 修改和删除地址 | UpdateDestroyAddressView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
<|body_0|>
def delete(self, request, address_id):
"""删除地址"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
json_dict = json.loads(request.body.decode())
... | stack_v2_sparse_classes_36k_train_018778 | 18,106 | no_license | [
{
"docstring": "修改地址",
"name": "put",
"signature": "def put(self, request, address_id)"
},
{
"docstring": "删除地址",
"name": "delete",
"signature": "def delete(self, request, address_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012651 | Implement the Python class `UpdateDestroyAddressView` described below.
Class description:
修改和删除地址
Method signatures and docstrings:
- def put(self, request, address_id): 修改地址
- def delete(self, request, address_id): 删除地址 | Implement the Python class `UpdateDestroyAddressView` described below.
Class description:
修改和删除地址
Method signatures and docstrings:
- def put(self, request, address_id): 修改地址
- def delete(self, request, address_id): 删除地址
<|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, addre... | 41ab7838dd5b1e5616febd9d6d299a9cf60d3f5d | <|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
<|body_0|>
def delete(self, request, address_id):
"""删除地址"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('province_id')
city_id = json_dict.get('city_id')
district_... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/users/views.py | xzlee2020/- | train | 0 |
5b3d31405bf7e32431b5a43d8a6822a0bc4d0007 | [
"request = self.context.get('request')\ndata['poster'] = request.user\nreturn validate_complete_address(data)",
"response = super().to_representation(instance)\nresponse['poster'] = {'id': instance.poster.id}\nreturn response"
] | <|body_start_0|>
request = self.context.get('request')
data['poster'] = request.user
return validate_complete_address(data)
<|end_body_0|>
<|body_start_1|>
response = super().to_representation(instance)
response['poster'] = {'id': instance.poster.id}
return response
<|en... | Serializer handles creation of a new listing | CreateListingSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateListingSerializer:
"""Serializer handles creation of a new listing"""
def validate(self, data):
"""Validate creation of new listing - Check complete address listing is valid"""
<|body_0|>
def to_representation(self, instance):
"""Return only id of poster wh... | stack_v2_sparse_classes_36k_train_018779 | 3,983 | no_license | [
{
"docstring": "Validate creation of new listing - Check complete address listing is valid",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Return only id of poster when creating listing",
"name": "to_representation",
"signature": "def to_representation(se... | 2 | stack_v2_sparse_classes_30k_train_015983 | Implement the Python class `CreateListingSerializer` described below.
Class description:
Serializer handles creation of a new listing
Method signatures and docstrings:
- def validate(self, data): Validate creation of new listing - Check complete address listing is valid
- def to_representation(self, instance): Return... | Implement the Python class `CreateListingSerializer` described below.
Class description:
Serializer handles creation of a new listing
Method signatures and docstrings:
- def validate(self, data): Validate creation of new listing - Check complete address listing is valid
- def to_representation(self, instance): Return... | 1f2c8c232372de6a40089c8b867ce1798d2296c7 | <|skeleton|>
class CreateListingSerializer:
"""Serializer handles creation of a new listing"""
def validate(self, data):
"""Validate creation of new listing - Check complete address listing is valid"""
<|body_0|>
def to_representation(self, instance):
"""Return only id of poster wh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateListingSerializer:
"""Serializer handles creation of a new listing"""
def validate(self, data):
"""Validate creation of new listing - Check complete address listing is valid"""
request = self.context.get('request')
data['poster'] = request.user
return validate_comple... | the_stack_v2_python_sparse | core/roommates_api/serializers/listing_serializers.py | harmanT23/yournextroommates | train | 1 |
1a7c66eed58c3019f4e47dbdef190ad3e3ebb54b | [
"if e in self.vals:\n self.vals[e] -= 1\nelse:\n pass",
"if e in self.vals:\n return self.vals[e]\nelse:\n return 0",
"for o in other.vals:\n if o in self.vals:\n self.vals[o] += other.count(o)\n else:\n self.vals[o] = other.count(o)\nreturn self"
] | <|body_start_0|>
if e in self.vals:
self.vals[e] -= 1
else:
pass
<|end_body_0|>
<|body_start_1|>
if e in self.vals:
return self.vals[e]
else:
return 0
<|end_body_1|>
<|body_start_2|>
for o in other.vals:
if o in self.v... | Bag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bag:
def remove(self, e):
"""assumes e is hashable If e occurs in self, reduces the number of times it occurs in self by 1. Otherwise does nothing."""
<|body_0|>
def count(self, e):
"""assumes e is hashable Returns the number of times e occurs in self."""
<|b... | stack_v2_sparse_classes_36k_train_018780 | 5,303 | no_license | [
{
"docstring": "assumes e is hashable If e occurs in self, reduces the number of times it occurs in self by 1. Otherwise does nothing.",
"name": "remove",
"signature": "def remove(self, e)"
},
{
"docstring": "assumes e is hashable Returns the number of times e occurs in self.",
"name": "coun... | 3 | null | Implement the Python class `Bag` described below.
Class description:
Implement the Bag class.
Method signatures and docstrings:
- def remove(self, e): assumes e is hashable If e occurs in self, reduces the number of times it occurs in self by 1. Otherwise does nothing.
- def count(self, e): assumes e is hashable Retu... | Implement the Python class `Bag` described below.
Class description:
Implement the Bag class.
Method signatures and docstrings:
- def remove(self, e): assumes e is hashable If e occurs in self, reduces the number of times it occurs in self by 1. Otherwise does nothing.
- def count(self, e): assumes e is hashable Retu... | 4e8727154a24c7a1d05361a559a997c8d076480d | <|skeleton|>
class Bag:
def remove(self, e):
"""assumes e is hashable If e occurs in self, reduces the number of times it occurs in self by 1. Otherwise does nothing."""
<|body_0|>
def count(self, e):
"""assumes e is hashable Returns the number of times e occurs in self."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bag:
def remove(self, e):
"""assumes e is hashable If e occurs in self, reduces the number of times it occurs in self by 1. Otherwise does nothing."""
if e in self.vals:
self.vals[e] -= 1
else:
pass
def count(self, e):
"""assumes e is hashable Retur... | the_stack_v2_python_sparse | 01_MIT_Learning/00_final_exam/final_problem_6_pt3.py | daftstar/learn_python | train | 0 | |
f268a944b2c05524456aed2f27bb804341611966 | [
"self.cb = cb\nself.configeditor = configeditor\nself.store = gtk.ListStore(str, int)\ngtk.TreeView.__init__(self, self.store)\nrenderer = gtk.CellRendererText()\ncolumn = gtk.TreeViewColumn('Name', renderer, markup=0)\nself.append_column(column)\nself.set_headers_visible(False)\nself.connect('cursor-changed', self... | <|body_start_0|>
self.cb = cb
self.configeditor = configeditor
self.store = gtk.ListStore(str, int)
gtk.TreeView.__init__(self, self.store)
renderer = gtk.CellRendererText()
column = gtk.TreeViewColumn('Name', renderer, markup=0)
self.append_column(column)
... | A treeview control for switching a notebook's tabs. | ListTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListTree:
"""A treeview control for switching a notebook's tabs."""
def __init__(self, cb, configeditor):
"""Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The configuration editor that the list is used for. @type co... | stack_v2_sparse_classes_36k_train_018781 | 15,563 | no_license | [
{
"docstring": "Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The configuration editor that the list is used for. @type configeditor: pida.config.ConfigEditor",
"name": "__init__",
"signature": "def __init__(self, cb, configeditor)"
... | 3 | stack_v2_sparse_classes_30k_train_015398 | Implement the Python class `ListTree` described below.
Class description:
A treeview control for switching a notebook's tabs.
Method signatures and docstrings:
- def __init__(self, cb, configeditor): Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The... | Implement the Python class `ListTree` described below.
Class description:
A treeview control for switching a notebook's tabs.
Method signatures and docstrings:
- def __init__(self, cb, configeditor): Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The... | 739147ed21a23cab23c2bba98f1c54108f8c2516 | <|skeleton|>
class ListTree:
"""A treeview control for switching a notebook's tabs."""
def __init__(self, cb, configeditor):
"""Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The configuration editor that the list is used for. @type co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListTree:
"""A treeview control for switching a notebook's tabs."""
def __init__(self, cb, configeditor):
"""Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The configuration editor that the list is used for. @type configeditor: p... | the_stack_v2_python_sparse | tags/release-0.2.1/src/configuration/config.py | BackupTheBerlios/pida-svn | train | 1 |
ed94486254899116b94770c0259e0fb6dc50c06d | [
"data_list = []\nresults = self.query.all()\nformatter = date.getLocaleFormatter(self.request, 'date', 'long')\nfor result in results:\n data = {}\n data['qid'] = 'm_' + str(result.motion_id)\n data['subject'] = u'M ' + str(result.motion_number) + u' ' + result.short_name\n data['title'] = result.short_... | <|body_start_0|>
data_list = []
results = self.query.all()
formatter = date.getLocaleFormatter(self.request, 'date', 'long')
for result in results:
data = {}
data['qid'] = 'm_' + str(result.motion_id)
data['subject'] = u'M ' + str(result.motion_number)... | MotionInStateViewlet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MotionInStateViewlet:
def _setData(self):
"""return the data of the query"""
<|body_0|>
def update(self):
"""refresh the query"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data_list = []
results = self.query.all()
formatter = date... | stack_v2_sparse_classes_36k_train_018782 | 27,657 | no_license | [
{
"docstring": "return the data of the query",
"name": "_setData",
"signature": "def _setData(self)"
},
{
"docstring": "refresh the query",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010097 | Implement the Python class `MotionInStateViewlet` described below.
Class description:
Implement the MotionInStateViewlet class.
Method signatures and docstrings:
- def _setData(self): return the data of the query
- def update(self): refresh the query | Implement the Python class `MotionInStateViewlet` described below.
Class description:
Implement the MotionInStateViewlet class.
Method signatures and docstrings:
- def _setData(self): return the data of the query
- def update(self): refresh the query
<|skeleton|>
class MotionInStateViewlet:
def _setData(self):
... | 5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d | <|skeleton|>
class MotionInStateViewlet:
def _setData(self):
"""return the data of the query"""
<|body_0|>
def update(self):
"""refresh the query"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MotionInStateViewlet:
def _setData(self):
"""return the data of the query"""
data_list = []
results = self.query.all()
formatter = date.getLocaleFormatter(self.request, 'date', 'long')
for result in results:
data = {}
data['qid'] = 'm_' + str(res... | the_stack_v2_python_sparse | bungeni.main/branches/mr/bungeni/ui/viewlets/workspace.py | malangalanga/bungeni-portal | train | 0 | |
03cc23d3f602c96853711e63e49e476ef3adf910 | [
"if rec1[0] <= rec2[0] < rec2[2] <= rec1[2] and rec1[1] <= rec2[1] < rec2[3] <= rec1[3] or (rec2[0] <= rec1[0] < rec1[2] <= rec2[2] and rec2[1] <= rec1[1] < rec1[3] <= rec2[3]) or (rec2[0] <= rec1[0] <= rec2[2] and rec2[1] <= rec1[3] <= rec2[3]) or (rec1[0] <= rec2[0] <= rec1[2] and rec1[1] <= rec2[3] <= rec1[3]) o... | <|body_start_0|>
if rec1[0] <= rec2[0] < rec2[2] <= rec1[2] and rec1[1] <= rec2[1] < rec2[3] <= rec1[3] or (rec2[0] <= rec1[0] < rec1[2] <= rec2[2] and rec2[1] <= rec1[1] < rec1[3] <= rec2[3]) or (rec2[0] <= rec1[0] <= rec2[2] and rec2[1] <= rec1[3] <= rec2[3]) or (rec1[0] <= rec2[0] <= rec1[2] and rec1[1] <= r... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _isRectangleOverlap(self, rec1, rec2):
""":type rec1: List[int] :type rec2: List[int] :rtype: bool"""
<|body_0|>
def __isRectangleOverlap(self, rec1, rec2):
""":type rec1: List[int] :type rec2: List[int] :rtype: bool"""
<|body_1|>
def isRec... | stack_v2_sparse_classes_36k_train_018783 | 3,178 | permissive | [
{
"docstring": ":type rec1: List[int] :type rec2: List[int] :rtype: bool",
"name": "_isRectangleOverlap",
"signature": "def _isRectangleOverlap(self, rec1, rec2)"
},
{
"docstring": ":type rec1: List[int] :type rec2: List[int] :rtype: bool",
"name": "__isRectangleOverlap",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_val_000093 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _isRectangleOverlap(self, rec1, rec2): :type rec1: List[int] :type rec2: List[int] :rtype: bool
- def __isRectangleOverlap(self, rec1, rec2): :type rec1: List[int] :type rec2... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _isRectangleOverlap(self, rec1, rec2): :type rec1: List[int] :type rec2: List[int] :rtype: bool
- def __isRectangleOverlap(self, rec1, rec2): :type rec1: List[int] :type rec2... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _isRectangleOverlap(self, rec1, rec2):
""":type rec1: List[int] :type rec2: List[int] :rtype: bool"""
<|body_0|>
def __isRectangleOverlap(self, rec1, rec2):
""":type rec1: List[int] :type rec2: List[int] :rtype: bool"""
<|body_1|>
def isRec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _isRectangleOverlap(self, rec1, rec2):
""":type rec1: List[int] :type rec2: List[int] :rtype: bool"""
if rec1[0] <= rec2[0] < rec2[2] <= rec1[2] and rec1[1] <= rec2[1] < rec2[3] <= rec1[3] or (rec2[0] <= rec1[0] < rec1[2] <= rec2[2] and rec2[1] <= rec1[1] < rec1[3] <= rec2[3]) or... | the_stack_v2_python_sparse | 836.rectangle-overlap.py | windard/leeeeee | train | 0 | |
7d6b51cf731a9ccdba9e30b486effc36c2e19284 | [
"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... | The API interface for managing autoscaling policies in the Google Cloud Dataproc API. | AutoscalingPolicyServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoscalingPolicyServiceServicer:
"""The API interface for managing autoscaling policies in the Google Cloud Dataproc API."""
def CreateAutoscalingPolicy(self, request, context):
"""Creates new autoscaling policy."""
<|body_0|>
def UpdateAutoscalingPolicy(self, request, ... | stack_v2_sparse_classes_36k_train_018784 | 6,926 | permissive | [
{
"docstring": "Creates new autoscaling policy.",
"name": "CreateAutoscalingPolicy",
"signature": "def CreateAutoscalingPolicy(self, request, context)"
},
{
"docstring": "Updates (replaces) autoscaling policy. Disabled check for update_mask, because all updates will be full replacements.",
"... | 5 | null | Implement the Python class `AutoscalingPolicyServiceServicer` described below.
Class description:
The API interface for managing autoscaling policies in the Google Cloud Dataproc API.
Method signatures and docstrings:
- def CreateAutoscalingPolicy(self, request, context): Creates new autoscaling policy.
- def UpdateA... | Implement the Python class `AutoscalingPolicyServiceServicer` described below.
Class description:
The API interface for managing autoscaling policies in the Google Cloud Dataproc API.
Method signatures and docstrings:
- def CreateAutoscalingPolicy(self, request, context): Creates new autoscaling policy.
- def UpdateA... | d897d56bce03d1fda98b79afb08264e51d46c421 | <|skeleton|>
class AutoscalingPolicyServiceServicer:
"""The API interface for managing autoscaling policies in the Google Cloud Dataproc API."""
def CreateAutoscalingPolicy(self, request, context):
"""Creates new autoscaling policy."""
<|body_0|>
def UpdateAutoscalingPolicy(self, request, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoscalingPolicyServiceServicer:
"""The API interface for managing autoscaling policies in the Google Cloud Dataproc API."""
def CreateAutoscalingPolicy(self, request, context):
"""Creates new autoscaling policy."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_deta... | the_stack_v2_python_sparse | dataproc/google/cloud/dataproc_v1/proto/autoscaling_policies_pb2_grpc.py | tswast/google-cloud-python | train | 1 |
a891b75f222f7da8a955c11e9b500a1288a6d861 | [
"wx.Frame.__init__(self, None, title='LScan', size=UIStyle.main_frame_size, style=UIStyle.main_frame_border | wx.FULL_REPAINT_ON_RESIZE | wx.MINIMIZE_BOX)\nUIStyle.setup_dark_theme()\nself._build_gui()",
"self.SetMinSize(UIStyle.main_frame_size)\nself.SetMaxSize(UIStyle.main_frame_size)\nself.Bind(wx.EVT_CLOSE, s... | <|body_start_0|>
wx.Frame.__init__(self, None, title='LScan', size=UIStyle.main_frame_size, style=UIStyle.main_frame_border | wx.FULL_REPAINT_ON_RESIZE | wx.MINIMIZE_BOX)
UIStyle.setup_dark_theme()
self._build_gui()
<|end_body_0|>
<|body_start_1|>
self.SetMinSize(UIStyle.main_frame_size... | The root Wx Frame that will be the parent of all Wx controls. | MainFrame | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainFrame:
"""The root Wx Frame that will be the parent of all Wx controls."""
def __init__(self):
"""Default constructor for MainFrame class."""
<|body_0|>
def _build_gui(self):
"""Create all the sub-panels and their layout on this main panel. :return: None"""
... | stack_v2_sparse_classes_36k_train_018785 | 1,827 | permissive | [
{
"docstring": "Default constructor for MainFrame class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create all the sub-panels and their layout on this main panel. :return: None",
"name": "_build_gui",
"signature": "def _build_gui(self)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_009944 | Implement the Python class `MainFrame` described below.
Class description:
The root Wx Frame that will be the parent of all Wx controls.
Method signatures and docstrings:
- def __init__(self): Default constructor for MainFrame class.
- def _build_gui(self): Create all the sub-panels and their layout on this main pane... | Implement the Python class `MainFrame` described below.
Class description:
The root Wx Frame that will be the parent of all Wx controls.
Method signatures and docstrings:
- def __init__(self): Default constructor for MainFrame class.
- def _build_gui(self): Create all the sub-panels and their layout on this main pane... | 61a3fde105d0c0841a571037537ec3347bae8808 | <|skeleton|>
class MainFrame:
"""The root Wx Frame that will be the parent of all Wx controls."""
def __init__(self):
"""Default constructor for MainFrame class."""
<|body_0|>
def _build_gui(self):
"""Create all the sub-panels and their layout on this main panel. :return: None"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MainFrame:
"""The root Wx Frame that will be the parent of all Wx controls."""
def __init__(self):
"""Default constructor for MainFrame class."""
wx.Frame.__init__(self, None, title='LScan', size=UIStyle.main_frame_size, style=UIStyle.main_frame_border | wx.FULL_REPAINT_ON_RESIZE | wx.MIN... | the_stack_v2_python_sparse | src/ui/main_frame.py | sohantamang/lscan | train | 0 |
11308f47d1166fd60753b4ff1f512052d4e3a6b1 | [
"restaurant_keywords = RestaurantKeyword.objects.all()\nrestaurant = self.request.query_params.get('restaurant', None)\nif restaurant is not None:\n restaurant_keywords = restaurant_keywords.filter(restaurant__id=restaurant)\nserializer = RestaurantKeywordSerializer(restaurant_keywords, many=True, context={'requ... | <|body_start_0|>
restaurant_keywords = RestaurantKeyword.objects.all()
restaurant = self.request.query_params.get('restaurant', None)
if restaurant is not None:
restaurant_keywords = restaurant_keywords.filter(restaurant__id=restaurant)
serializer = RestaurantKeywordSerialize... | Restaurant Keywords | RestaurantKeywordView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestaurantKeywordView:
"""Restaurant Keywords"""
def list(self, request):
"""Handle GET requests to restaurant_keywords resource Returns: Response -- JSON serialized list of restaurant_keywords"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET req... | stack_v2_sparse_classes_36k_train_018786 | 3,197 | no_license | [
{
"docstring": "Handle GET requests to restaurant_keywords resource Returns: Response -- JSON serialized list of restaurant_keywords",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Handle GET requests for single keyword Returns: Response -- JSON serialized keyword ins... | 3 | stack_v2_sparse_classes_30k_train_011189 | Implement the Python class `RestaurantKeywordView` described below.
Class description:
Restaurant Keywords
Method signatures and docstrings:
- def list(self, request): Handle GET requests to restaurant_keywords resource Returns: Response -- JSON serialized list of restaurant_keywords
- def retrieve(self, request, pk=... | Implement the Python class `RestaurantKeywordView` described below.
Class description:
Restaurant Keywords
Method signatures and docstrings:
- def list(self, request): Handle GET requests to restaurant_keywords resource Returns: Response -- JSON serialized list of restaurant_keywords
- def retrieve(self, request, pk=... | c32f40f862cb06354d9f987d79e199faa239d3c5 | <|skeleton|>
class RestaurantKeywordView:
"""Restaurant Keywords"""
def list(self, request):
"""Handle GET requests to restaurant_keywords resource Returns: Response -- JSON serialized list of restaurant_keywords"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET req... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestaurantKeywordView:
"""Restaurant Keywords"""
def list(self, request):
"""Handle GET requests to restaurant_keywords resource Returns: Response -- JSON serialized list of restaurant_keywords"""
restaurant_keywords = RestaurantKeyword.objects.all()
restaurant = self.request.quer... | the_stack_v2_python_sparse | blessipeapi/views/restaurant_keyword.py | gqgonzales/blessipe-api | train | 0 |
bff7b017dfa54596a7b68196d6fdf2e44896c215 | [
"context = super(SponsorshipLevelListView, self).get_context_data(**kwargs)\ncontext['num_sponsorshiplevels'] = context['sponsorshiplevels'].count()\ncontext['unapproved'] = False\nproject_slug = self.kwargs.get('project_slug', None)\ncontext['project_slug'] = project_slug\nif project_slug:\n context['the_projec... | <|body_start_0|>
context = super(SponsorshipLevelListView, self).get_context_data(**kwargs)
context['num_sponsorshiplevels'] = context['sponsorshiplevels'].count()
context['unapproved'] = False
project_slug = self.kwargs.get('project_slug', None)
context['project_slug'] = project... | List view for Sponsorship Level. | SponsorshipLevelListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SponsorshipLevelListView:
"""List view for Sponsorship Level."""
def get_context_data(self, **kwargs):
"""Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :returns: Context data which will be passed to the ... | stack_v2_sparse_classes_36k_train_018787 | 17,162 | no_license | [
{
"docstring": "Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :returns: Context data which will be passed to the template. :rtype: dict",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
... | 2 | stack_v2_sparse_classes_30k_train_015220 | Implement the Python class `SponsorshipLevelListView` described below.
Class description:
List view for Sponsorship Level.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs:... | Implement the Python class `SponsorshipLevelListView` described below.
Class description:
List view for Sponsorship Level.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs:... | ca489c38fdfde29f75c9c1e7f4b4c55d78d91c79 | <|skeleton|>
class SponsorshipLevelListView:
"""List view for Sponsorship Level."""
def get_context_data(self, **kwargs):
"""Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :returns: Context data which will be passed to the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SponsorshipLevelListView:
"""List view for Sponsorship Level."""
def get_context_data(self, **kwargs):
"""Get the context data which is passed to a template. :param kwargs: Any arguments to pass to the superclass. :type kwargs: dict :returns: Context data which will be passed to the template. :rt... | the_stack_v2_python_sparse | django_project/changes/views/sponsorship_level.py | gitter-badger/projecta | train | 0 |
618750fbcf9680dee4845fa04c60c3f0345da469 | [
"super(Criterion, self).__init__()\nself.margin = opt.loss_lifted_neg_margin\nself.l2_weight = opt.loss_lifted_l2\nself.batchminer = batchminer\nself.name = 'lifted'",
"anchors, positives, negatives = self.batchminer(batch, labels)\nloss = []\nfor anchor, positive_set, negative_set in zip(anchors, positives, nega... | <|body_start_0|>
super(Criterion, self).__init__()
self.margin = opt.loss_lifted_neg_margin
self.l2_weight = opt.loss_lifted_l2
self.batchminer = batchminer
self.name = 'lifted'
<|end_body_0|>
<|body_start_1|>
anchors, positives, negatives = self.batchminer(batch, labels... | Criterion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Criterion:
def __init__(self, opt, batchminer):
"""Args: margin: Triplet Margin."""
<|body_0|>
def forward(self, batch, labels, **kwargs):
"""Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels: nparray/list: For each element of the batch assig... | stack_v2_sparse_classes_36k_train_018788 | 1,749 | permissive | [
{
"docstring": "Args: margin: Triplet Margin.",
"name": "__init__",
"signature": "def __init__(self, opt, batchminer)"
},
{
"docstring": "Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels: nparray/list: For each element of the batch assigns a class [0,...,C-1], shape: (B... | 2 | stack_v2_sparse_classes_30k_train_019143 | Implement the Python class `Criterion` described below.
Class description:
Implement the Criterion class.
Method signatures and docstrings:
- def __init__(self, opt, batchminer): Args: margin: Triplet Margin.
- def forward(self, batch, labels, **kwargs): Args: batch: torch.Tensor: Input of embeddings with size (BS x ... | Implement the Python class `Criterion` described below.
Class description:
Implement the Criterion class.
Method signatures and docstrings:
- def __init__(self, opt, batchminer): Args: margin: Triplet Margin.
- def forward(self, batch, labels, **kwargs): Args: batch: torch.Tensor: Input of embeddings with size (BS x ... | 01a7220bac7ebb1e70416ef663f3ba7cee9e8bf5 | <|skeleton|>
class Criterion:
def __init__(self, opt, batchminer):
"""Args: margin: Triplet Margin."""
<|body_0|>
def forward(self, batch, labels, **kwargs):
"""Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels: nparray/list: For each element of the batch assig... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Criterion:
def __init__(self, opt, batchminer):
"""Args: margin: Triplet Margin."""
super(Criterion, self).__init__()
self.margin = opt.loss_lifted_neg_margin
self.l2_weight = opt.loss_lifted_l2
self.batchminer = batchminer
self.name = 'lifted'
def forward(... | the_stack_v2_python_sparse | criteria/lifted.py | chenyanlinzhugoushou/DCML | train | 0 | |
d333a4c20a3b0c2d7fefe507ba60b5532f408927 | [
"inds = [i for i, (a, b) in enumerate(zip(gas, cost)) if a - b >= 0]\nfor i in inds:\n com = zip(gas[i:] + gas[:i], cost[i:] + cost[:i])\n s = 0\n for a, b in com:\n s += a - b\n if s < 0:\n break\n else:\n return i\nelse:\n return -1",
"start, crt_sum, total_sum = (... | <|body_start_0|>
inds = [i for i, (a, b) in enumerate(zip(gas, cost)) if a - b >= 0]
for i in inds:
com = zip(gas[i:] + gas[:i], cost[i:] + cost[:i])
s = 0
for a, b in com:
s += a - b
if s < 0:
break
else... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_018789 | 3,351 | no_license | [
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit",
"signature": "def canCompleteCircuit(self, gas, cost)"
},
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit",
"signature": "def canCom... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[i... | 416fed6e441612e1ad82467d07ee1b5570386a94 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
inds = [i for i, (a, b) in enumerate(zip(gas, cost)) if a - b >= 0]
for i in inds:
com = zip(gas[i:] + gas[:i], cost[i:] + cost[:i])
s = 0
... | the_stack_v2_python_sparse | src/python/greedy_algorithm/gas_station.py | liadbiz/Leetcode-Solutions | train | 1 | |
a56551e462bf434139ffd8498015c81df1bcc9e0 | [
"units = ListOfTracks.read(dir_name)\nif os.path.exists(dir_name) is False:\n raise NoDirectoryError(dirname=dir_name)\ntier_phn = sppasTier('PhonAlign')\ntier_tok = sppasTier('TokensAlign')\ntier_pron = sppasTier('PronTokAlign')\ntrack_number = 1\nfor unit_start, unit_end in units:\n basename = TrackNamesGen... | <|body_start_0|>
units = ListOfTracks.read(dir_name)
if os.path.exists(dir_name) is False:
raise NoDirectoryError(dirname=dir_name)
tier_phn = sppasTier('PhonAlign')
tier_tok = sppasTier('TokensAlign')
tier_pron = sppasTier('PronTokAlign')
track_number = 1
... | Read time-aligned tracks. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Manage tracks for the time-aligned phonemes and tokens. | TracksReader | [
"MIT",
"GFDL-1.1-or-later",
"GPL-3.0-only",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TracksReader:
"""Read time-aligned tracks. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Manage tracks for the time-aligned phonemes and tokens."""
d... | stack_v2_sparse_classes_36k_train_018790 | 20,964 | permissive | [
{
"docstring": "Read a set of alignment files and set as tiers. :param dir_name: (str) input directory containing a set of units :returns: PhonAlign, TokensAlign",
"name": "read_aligned_tracks",
"signature": "def read_aligned_tracks(dir_name)"
},
{
"docstring": "Append a list of (start, end, tex... | 2 | null | Implement the Python class `TracksReader` described below.
Class description:
Read time-aligned tracks. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Manage tracks for the time... | Implement the Python class `TracksReader` described below.
Class description:
Read time-aligned tracks. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Manage tracks for the time... | 3167b65f576abcc27a8767d24c274a04712bd948 | <|skeleton|>
class TracksReader:
"""Read time-aligned tracks. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Manage tracks for the time-aligned phonemes and tokens."""
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TracksReader:
"""Read time-aligned tracks. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Manage tracks for the time-aligned phonemes and tokens."""
def read_align... | the_stack_v2_python_sparse | sppas/sppas/src/annotations/Align/tracksio.py | mirfan899/MTTS | train | 0 |
4a66e9484749703c166d045dc5e99368a6271f40 | [
"self._nucleus = pipeline_nucleus.PipelineNucleus(pipeline_configuration)\nself._pipeline = pipeline_stages_base.PipelineRootStage(self._nucleus).append_stage(pipeline_stages_iothub_http.IoTHubHTTPTranslationStage()).append_stage(pipeline_stages_http.HTTPTransportStage())\ncallback = EventedCallback()\nop = pipelin... | <|body_start_0|>
self._nucleus = pipeline_nucleus.PipelineNucleus(pipeline_configuration)
self._pipeline = pipeline_stages_base.PipelineRootStage(self._nucleus).append_stage(pipeline_stages_iothub_http.IoTHubHTTPTranslationStage()).append_stage(pipeline_stages_http.HTTPTransportStage())
callback... | Pipeline to communicate with Edge. Uses HTTP. | HTTPPipeline | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTTPPipeline:
"""Pipeline to communicate with Edge. Uses HTTP."""
def __init__(self, pipeline_configuration):
"""Constructor for instantiating a pipeline adapter object. :param auth_provider: The authentication provider :param pipeline_configuration: The configuration generated based... | stack_v2_sparse_classes_36k_train_018791 | 8,115 | permissive | [
{
"docstring": "Constructor for instantiating a pipeline adapter object. :param auth_provider: The authentication provider :param pipeline_configuration: The configuration generated based on user inputs",
"name": "__init__",
"signature": "def __init__(self, pipeline_configuration)"
},
{
"docstri... | 4 | stack_v2_sparse_classes_30k_val_000351 | Implement the Python class `HTTPPipeline` described below.
Class description:
Pipeline to communicate with Edge. Uses HTTP.
Method signatures and docstrings:
- def __init__(self, pipeline_configuration): Constructor for instantiating a pipeline adapter object. :param auth_provider: The authentication provider :param ... | Implement the Python class `HTTPPipeline` described below.
Class description:
Pipeline to communicate with Edge. Uses HTTP.
Method signatures and docstrings:
- def __init__(self, pipeline_configuration): Constructor for instantiating a pipeline adapter object. :param auth_provider: The authentication provider :param ... | 5d343d5904aaa98c6a88101e0dc40263acff4db2 | <|skeleton|>
class HTTPPipeline:
"""Pipeline to communicate with Edge. Uses HTTP."""
def __init__(self, pipeline_configuration):
"""Constructor for instantiating a pipeline adapter object. :param auth_provider: The authentication provider :param pipeline_configuration: The configuration generated based... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HTTPPipeline:
"""Pipeline to communicate with Edge. Uses HTTP."""
def __init__(self, pipeline_configuration):
"""Constructor for instantiating a pipeline adapter object. :param auth_provider: The authentication provider :param pipeline_configuration: The configuration generated based on user inpu... | the_stack_v2_python_sparse | azure-iot-device/azure/iot/device/iothub/pipeline/http_pipeline.py | Azure/azure-iot-sdk-python | train | 441 |
3586efe294928f4658599dc5081e86498d8d561b | [
"self.fat_type = get_filesystem_type(stream)\nself.fatfs = create_fat(stream)\nself.stream = stream",
"metadata = BadClusterMetadata()\ncluster_count = 0\nwritten_length = 0\nLOGGER.info('%d Bytes in buffer to write', len(instream.peek()))\nwhile instream.peek():\n try:\n next_cluster = self.fatfs.get_f... | <|body_start_0|>
self.fat_type = get_filesystem_type(stream)
self.fatfs = create_fat(stream)
self.stream = stream
<|end_body_0|>
<|body_start_1|>
metadata = BadClusterMetadata()
cluster_count = 0
written_length = 0
LOGGER.info('%d Bytes in buffer to write', len(i... | Provides methods to hide and restore data from bad clusters | BadCluster | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BadCluster:
"""Provides methods to hide and restore data from bad clusters"""
def __init__(self, stream: typ.BinaryIO):
""":param stream: filedescriptor of a FAT filesystem"""
<|body_0|>
def write(self, instream: typ.BinaryIO) -> BadClusterMetadata:
"""writes fro... | stack_v2_sparse_classes_36k_train_018792 | 7,262 | permissive | [
{
"docstring": ":param stream: filedescriptor of a FAT filesystem",
"name": "__init__",
"signature": "def __init__(self, stream: typ.BinaryIO)"
},
{
"docstring": "writes from instream bad clusters :param instream: stream to read from :return: BadCluster",
"name": "write",
"signature": "d... | 5 | stack_v2_sparse_classes_30k_train_001309 | Implement the Python class `BadCluster` described below.
Class description:
Provides methods to hide and restore data from bad clusters
Method signatures and docstrings:
- def __init__(self, stream: typ.BinaryIO): :param stream: filedescriptor of a FAT filesystem
- def write(self, instream: typ.BinaryIO) -> BadCluste... | Implement the Python class `BadCluster` described below.
Class description:
Provides methods to hide and restore data from bad clusters
Method signatures and docstrings:
- def __init__(self, stream: typ.BinaryIO): :param stream: filedescriptor of a FAT filesystem
- def write(self, instream: typ.BinaryIO) -> BadCluste... | b602e90ddecb8e469a28e092da3ca7fec514e3dc | <|skeleton|>
class BadCluster:
"""Provides methods to hide and restore data from bad clusters"""
def __init__(self, stream: typ.BinaryIO):
""":param stream: filedescriptor of a FAT filesystem"""
<|body_0|>
def write(self, instream: typ.BinaryIO) -> BadClusterMetadata:
"""writes fro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BadCluster:
"""Provides methods to hide and restore data from bad clusters"""
def __init__(self, stream: typ.BinaryIO):
""":param stream: filedescriptor of a FAT filesystem"""
self.fat_type = get_filesystem_type(stream)
self.fatfs = create_fat(stream)
self.stream = stream
... | the_stack_v2_python_sparse | src/fat/bad_cluster.py | VanirLab/weever | train | 3 |
ab445f1c4bb51c0597c570d600537670622051cd | [
"for facility in facilities:\n print('* `%s`: %s' % (facility['name'], facility['doc']))\n value = facility['descriptor'].value\n locator = facility['descriptor'].locator\n print(' - **current value**: %r, from %s' % (value.name, locator))\n print(' - **configurable as**: %s' % ', '.join(value.alia... | <|body_start_0|>
for facility in facilities:
print('* `%s`: %s' % (facility['name'], facility['doc']))
value = facility['descriptor'].value
locator = facility['descriptor'].locator
print(' - **current value**: %r, from %s' % (value.name, locator))
pri... | Markedly structured text flavored Markdown. | MarkdownMyST | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MarkdownMyST:
"""Markedly structured text flavored Markdown."""
def formatComponents(name, facilities):
"""Format components information. name: Facility name. facilities: Dictionary with facilities information. - name: Name of facility - doc: Facility help string. - descriptor: Descr... | stack_v2_sparse_classes_36k_train_018793 | 3,406 | permissive | [
{
"docstring": "Format components information. name: Facility name. facilities: Dictionary with facilities information. - name: Name of facility - doc: Facility help string. - descriptor: Descriptor for facility.",
"name": "formatComponents",
"signature": "def formatComponents(name, facilities)"
},
... | 2 | null | Implement the Python class `MarkdownMyST` described below.
Class description:
Markedly structured text flavored Markdown.
Method signatures and docstrings:
- def formatComponents(name, facilities): Format components information. name: Facility name. facilities: Dictionary with facilities information. - name: Name of ... | Implement the Python class `MarkdownMyST` described below.
Class description:
Markedly structured text flavored Markdown.
Method signatures and docstrings:
- def formatComponents(name, facilities): Format components information. name: Facility name. facilities: Dictionary with facilities information. - name: Name of ... | e914bc62ae974b999ce556cb6b34cdbcc17338fc | <|skeleton|>
class MarkdownMyST:
"""Markedly structured text flavored Markdown."""
def formatComponents(name, facilities):
"""Format components information. name: Facility name. facilities: Dictionary with facilities information. - name: Name of facility - doc: Facility help string. - descriptor: Descr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MarkdownMyST:
"""Markedly structured text flavored Markdown."""
def formatComponents(name, facilities):
"""Format components information. name: Facility name. facilities: Dictionary with facilities information. - name: Name of facility - doc: Facility help string. - descriptor: Descriptor for fac... | the_stack_v2_python_sparse | pythia/pyre/util/help.py | geodynamics/pythia | train | 1 |
e1c5109b542a581899d1684cb2889faeeb61edd7 | [
"super(Repoquery, self).__init__(None)\nself.name = name\nself.query_type = query_type\nself.show_duplicates = show_duplicates\nself.match_version = match_version\nself.ignore_excluders = ignore_excluders\nself.verbose = verbose\nif self.match_version:\n self.show_duplicates = True\nself.query_format = '%{versio... | <|body_start_0|>
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show_duplicates = show_duplicates
self.match_version = match_version
self.ignore_excluders = ignore_excluders
self.verbose = verbose
if self.match_ver... | Class to wrap the repoquery | Repoquery | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose):
"""Constructor for YumList"""
<|body_0|>
def build_cmd(self):
"""build the repoquery cmd options"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_018794 | 6,322 | permissive | [
{
"docstring": "Constructor for YumList",
"name": "__init__",
"signature": "def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose)"
},
{
"docstring": "build the repoquery cmd options",
"name": "build_cmd",
"signature": "def build_cmd(self)"
},
... | 6 | null | Implement the Python class `Repoquery` described below.
Class description:
Class to wrap the repoquery
Method signatures and docstrings:
- def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose): Constructor for YumList
- def build_cmd(self): build the repoquery cmd options
- d... | Implement the Python class `Repoquery` described below.
Class description:
Class to wrap the repoquery
Method signatures and docstrings:
- def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose): Constructor for YumList
- def build_cmd(self): build the repoquery cmd options
- d... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose):
"""Constructor for YumList"""
<|body_0|>
def build_cmd(self):
"""build the repoquery cmd options"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose):
"""Constructor for YumList"""
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show... | the_stack_v2_python_sparse | openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_utils/src/class/repoquery.py | openshift/openshift-tools | train | 170 |
cb607622a0d22022b885da9649528336c6c63378 | [
"password = validated_data.pop('password', None)\nvalidated_data.pop('password2', None)\nnew_user = self.Meta.model(**validated_data)\nif password is not None:\n new_user.set_password(password)\nnew_user.save()\nuser = User.objects.get(username=new_user.username)\nToken.objects.create(user=user)\nreturn user",
... | <|body_start_0|>
password = validated_data.pop('password', None)
validated_data.pop('password2', None)
new_user = self.Meta.model(**validated_data)
if password is not None:
new_user.set_password(password)
new_user.save()
user = User.objects.get(username=new_us... | This class serializes the creation of a new account, with all the validations are ok. | SignUpSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignUpSerializer:
"""This class serializes the creation of a new account, with all the validations are ok."""
def create(self, validated_data: dict) -> User:
"""User creation."""
<|body_0|>
def validate(self, attrs: dict) -> dict:
"""SignUp data validation."""
... | stack_v2_sparse_classes_36k_train_018795 | 8,565 | permissive | [
{
"docstring": "User creation.",
"name": "create",
"signature": "def create(self, validated_data: dict) -> User"
},
{
"docstring": "SignUp data validation.",
"name": "validate",
"signature": "def validate(self, attrs: dict) -> dict"
}
] | 2 | stack_v2_sparse_classes_30k_train_018405 | Implement the Python class `SignUpSerializer` described below.
Class description:
This class serializes the creation of a new account, with all the validations are ok.
Method signatures and docstrings:
- def create(self, validated_data: dict) -> User: User creation.
- def validate(self, attrs: dict) -> dict: SignUp d... | Implement the Python class `SignUpSerializer` described below.
Class description:
This class serializes the creation of a new account, with all the validations are ok.
Method signatures and docstrings:
- def create(self, validated_data: dict) -> User: User creation.
- def validate(self, attrs: dict) -> dict: SignUp d... | 1d08fdc8a2ec58886d7d2b8d40e7b3598613caca | <|skeleton|>
class SignUpSerializer:
"""This class serializes the creation of a new account, with all the validations are ok."""
def create(self, validated_data: dict) -> User:
"""User creation."""
<|body_0|>
def validate(self, attrs: dict) -> dict:
"""SignUp data validation."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignUpSerializer:
"""This class serializes the creation of a new account, with all the validations are ok."""
def create(self, validated_data: dict) -> User:
"""User creation."""
password = validated_data.pop('password', None)
validated_data.pop('password2', None)
new_user... | the_stack_v2_python_sparse | src/main/apps/authentication/serializers.py | Nouvellie/django-mlops-docker | train | 3 |
2a6b58759dd45acb94396a2aaee090e46a38aab6 | [
"cr, uid, context = self.env.args\ncontext = dict(context)\nfor rec in self:\n rec.write({'date_from': time.strftime(DEFAULT_SERVER_DATE_FORMAT)})\n emp_rec = self.env['hr.employee'].search([('id', '=', rec.emp_id.id)])\n if emp_rec:\n emp_rec.write({'away': True})\nreturn True",
"cr, uid, context... | <|body_start_0|>
cr, uid, context = self.env.args
context = dict(context)
for rec in self:
rec.write({'date_from': time.strftime(DEFAULT_SERVER_DATE_FORMAT)})
emp_rec = self.env['hr.employee'].search([('id', '=', rec.emp_id.id)])
if emp_rec:
em... | employee_away_history | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class employee_away_history:
def set_date_from(self):
"""This method is used to set the Date From field based on Leave Button ------------------------------------------------"""
<|body_0|>
def set_date_to(self):
"""This method is used to set the Date To field based on Retu... | stack_v2_sparse_classes_36k_train_018796 | 2,760 | no_license | [
{
"docstring": "This method is used to set the Date From field based on Leave Button ------------------------------------------------",
"name": "set_date_from",
"signature": "def set_date_from(self)"
},
{
"docstring": "This method is used to set the Date To field based on Return Button ---------... | 2 | stack_v2_sparse_classes_30k_train_020762 | Implement the Python class `employee_away_history` described below.
Class description:
Implement the employee_away_history class.
Method signatures and docstrings:
- def set_date_from(self): This method is used to set the Date From field based on Leave Button ------------------------------------------------
- def set... | Implement the Python class `employee_away_history` described below.
Class description:
Implement the employee_away_history class.
Method signatures and docstrings:
- def set_date_from(self): This method is used to set the Date From field based on Leave Button ------------------------------------------------
- def set... | 46e15330b5d642053da61754247f3fbf9d02717e | <|skeleton|>
class employee_away_history:
def set_date_from(self):
"""This method is used to set the Date From field based on Leave Button ------------------------------------------------"""
<|body_0|>
def set_date_to(self):
"""This method is used to set the Date To field based on Retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class employee_away_history:
def set_date_from(self):
"""This method is used to set the Date From field based on Leave Button ------------------------------------------------"""
cr, uid, context = self.env.args
context = dict(context)
for rec in self:
rec.write({'date_fro... | the_stack_v2_python_sparse | core/sg_accommodation/models/employee_away_history.py | Muhammad-SF/Test | train | 0 | |
acee674836cc742894e6b784228dbd3a882e23dd | [
"db_model = circle_models.Circle.select().dj_where(id=circle_id, is_banned=False).first()\nif db_model:\n return Circle(db_model)",
"db_models = circle_models.Circle.select().dj_where(is_banned=False)\nif filters:\n db_models = db_models.dj_where(**filters)\nif target_page:\n db_models = target_page.pagi... | <|body_start_0|>
db_model = circle_models.Circle.select().dj_where(id=circle_id, is_banned=False).first()
if db_model:
return Circle(db_model)
<|end_body_0|>
<|body_start_1|>
db_models = circle_models.Circle.select().dj_where(is_banned=False)
if filters:
db_model... | 获取Circle对象的repository | CircleRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CircleRepository:
"""获取Circle对象的repository"""
def get_circle_by_id(self, circle_id):
"""根据id获取圈子"""
<|body_0|>
def get_circles(self, filters=None, target_page=None):
"""获取圈子列表"""
<|body_1|>
def get_banned_circles(self, filters=None, target_page=None)... | stack_v2_sparse_classes_36k_train_018797 | 1,838 | no_license | [
{
"docstring": "根据id获取圈子",
"name": "get_circle_by_id",
"signature": "def get_circle_by_id(self, circle_id)"
},
{
"docstring": "获取圈子列表",
"name": "get_circles",
"signature": "def get_circles(self, filters=None, target_page=None)"
},
{
"docstring": "获取被禁用的圈子列表",
"name": "get_ban... | 4 | stack_v2_sparse_classes_30k_train_013674 | Implement the Python class `CircleRepository` described below.
Class description:
获取Circle对象的repository
Method signatures and docstrings:
- def get_circle_by_id(self, circle_id): 根据id获取圈子
- def get_circles(self, filters=None, target_page=None): 获取圈子列表
- def get_banned_circles(self, filters=None, target_page=None): 获取... | Implement the Python class `CircleRepository` described below.
Class description:
获取Circle对象的repository
Method signatures and docstrings:
- def get_circle_by_id(self, circle_id): 根据id获取圈子
- def get_circles(self, filters=None, target_page=None): 获取圈子列表
- def get_banned_circles(self, filters=None, target_page=None): 获取... | d7a6d9d701031c28d1c7572f5c204600fbecb53a | <|skeleton|>
class CircleRepository:
"""获取Circle对象的repository"""
def get_circle_by_id(self, circle_id):
"""根据id获取圈子"""
<|body_0|>
def get_circles(self, filters=None, target_page=None):
"""获取圈子列表"""
<|body_1|>
def get_banned_circles(self, filters=None, target_page=None)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CircleRepository:
"""获取Circle对象的repository"""
def get_circle_by_id(self, circle_id):
"""根据id获取圈子"""
db_model = circle_models.Circle.select().dj_where(id=circle_id, is_banned=False).first()
if db_model:
return Circle(db_model)
def get_circles(self, filters=None, ta... | the_stack_v2_python_sparse | business/circle/circle_repository.py | Peri-albert/membership | train | 0 |
9b64770cf6d0131bcc16329824d9f3f0877db613 | [
"num = len(nums)\nif k == num / 2:\n for i in range(int(num / 2)):\n target = (i + k) % num\n temp = nums[i]\n nums[i] = nums[target]\n nums[target] = temp\nelse:\n flags = []\n j = 0\n temp1 = nums[j]\n for i in range(num):\n flags.append('0')\n while str(flags)... | <|body_start_0|>
num = len(nums)
if k == num / 2:
for i in range(int(num / 2)):
target = (i + k) % num
temp = nums[i]
nums[i] = nums[target]
nums[target] = temp
else:
flags = []
j = 0
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate1(self, nums, k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate(self, nums, k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_018798 | 1,631 | permissive | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "rotate1",
"signature": "def rotate1(self, nums, k: int) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums, k: int) -> N... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate1(self, nums, k: int) -> None: Do not return anything, modify nums in-place instead.
- def rotate(self, nums, k: int) -> None: Do not return anything, modify nums in-pl... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate1(self, nums, k: int) -> None: Do not return anything, modify nums in-place instead.
- def rotate(self, nums, k: int) -> None: Do not return anything, modify nums in-pl... | 55c6c3e7890b596b709b50cafa415b9594c03edd | <|skeleton|>
class Solution:
def rotate1(self, nums, k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate(self, nums, k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate1(self, nums, k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
num = len(nums)
if k == num / 2:
for i in range(int(num / 2)):
target = (i + k) % num
temp = nums[i]
nums[i] = nums... | the_stack_v2_python_sparse | top1_interview/rotate.py | summer-vacation/AlgoExec | train | 1 | |
4c21b074ff92326dcffb2757f55ed6f09a16f3cc | [
"try:\n s = str.strip()\n s = list(s)\n num, sign = (0, 1)\n if s[0] == '-' or s[0] == '+':\n if s[0] == '-':\n sign = -1\n del s[0]\n for c in s:\n if c.isdigit():\n num = 10 * num + int(c)\n else:\n break\n return min(2147483647, max(-... | <|body_start_0|>
try:
s = str.strip()
s = list(s)
num, sign = (0, 1)
if s[0] == '-' or s[0] == '+':
if s[0] == '-':
sign = -1
del s[0]
for c in s:
if c.isdigit():
n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myAtoi(self, str):
""":type str: str :rtype: int"""
<|body_0|>
def myAtoi_RegEx(self, str):
""":type str: str :rtype: int ^: start [+-]?: 1 or 0 [+-] \\d+: any numbers"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
s ... | stack_v2_sparse_classes_36k_train_018799 | 1,045 | no_license | [
{
"docstring": ":type str: str :rtype: int",
"name": "myAtoi",
"signature": "def myAtoi(self, str)"
},
{
"docstring": ":type str: str :rtype: int ^: start [+-]?: 1 or 0 [+-] \\\\d+: any numbers",
"name": "myAtoi_RegEx",
"signature": "def myAtoi_RegEx(self, str)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, str): :type str: str :rtype: int
- def myAtoi_RegEx(self, str): :type str: str :rtype: int ^: start [+-]?: 1 or 0 [+-] \\d+: any numbers | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, str): :type str: str :rtype: int
- def myAtoi_RegEx(self, str): :type str: str :rtype: int ^: start [+-]?: 1 or 0 [+-] \\d+: any numbers
<|skeleton|>
class Solu... | 863b89be674a82eef60c0f33d726ac08d43f2e01 | <|skeleton|>
class Solution:
def myAtoi(self, str):
""":type str: str :rtype: int"""
<|body_0|>
def myAtoi_RegEx(self, str):
""":type str: str :rtype: int ^: start [+-]?: 1 or 0 [+-] \\d+: any numbers"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def myAtoi(self, str):
""":type str: str :rtype: int"""
try:
s = str.strip()
s = list(s)
num, sign = (0, 1)
if s[0] == '-' or s[0] == '+':
if s[0] == '-':
sign = -1
del s[0]
... | the_stack_v2_python_sparse | q8_String_to_Integer.py | Ryuya1995/leetcode | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.