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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8a811a0ece610f3c3f50cf6a572fa198a6b2a4be | [
"if sk:\n self.n = sk.n\n self.h = sk.h\nelif n and h:\n self.n = n\n self.h = h\nelse:\n raise Exception('Public Key construction failed: insufficient/wrong arguments')\nself.signature_bound = Params[self.n]['sig_bound']\nself.sig_bytelen = Params[self.n]['sig_bytelen']",
"rep = 'Public for n = {n... | <|body_start_0|>
if sk:
self.n = sk.n
self.h = sk.h
elif n and h:
self.n = n
self.h = h
else:
raise Exception('Public Key construction failed: insufficient/wrong arguments')
self.signature_bound = Params[self.n]['sig_bound']
... | This class contains methods for performing public key operations in Falcon. | PublicKey | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PublicKey:
"""This class contains methods for performing public key operations in Falcon."""
def __init__(self, sk=None, n=None, h=None):
"""Initialize a public key."""
<|body_0|>
def __repr__(self):
"""Print the object in readable form."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_033000 | 15,043 | permissive | [
{
"docstring": "Initialize a public key.",
"name": "__init__",
"signature": "def __init__(self, sk=None, n=None, h=None)"
},
{
"docstring": "Print the object in readable form.",
"name": "__repr__",
"signature": "def __repr__(self)"
},
{
"docstring": "Hash a message to a point in ... | 4 | stack_v2_sparse_classes_30k_train_015182 | Implement the Python class `PublicKey` described below.
Class description:
This class contains methods for performing public key operations in Falcon.
Method signatures and docstrings:
- def __init__(self, sk=None, n=None, h=None): Initialize a public key.
- def __repr__(self): Print the object in readable form.
- de... | Implement the Python class `PublicKey` described below.
Class description:
This class contains methods for performing public key operations in Falcon.
Method signatures and docstrings:
- def __init__(self, sk=None, n=None, h=None): Initialize a public key.
- def __repr__(self): Print the object in readable form.
- de... | 1480c1e71b624a147dc0a18aa043f1101435ba85 | <|skeleton|>
class PublicKey:
"""This class contains methods for performing public key operations in Falcon."""
def __init__(self, sk=None, n=None, h=None):
"""Initialize a public key."""
<|body_0|>
def __repr__(self):
"""Print the object in readable form."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PublicKey:
"""This class contains methods for performing public key operations in Falcon."""
def __init__(self, sk=None, n=None, h=None):
"""Initialize a public key."""
if sk:
self.n = sk.n
self.h = sk.h
elif n and h:
self.n = n
self... | the_stack_v2_python_sparse | falcon/falcon.py | samuelgoh1525/falcon-blockchain | train | 4 |
fa857fc0ac0d6b08c87820362e8d6005ba181cfa | [
"DefaultDelegate.__init__(self)\nself._logger = logging.getLogger('BlueSTSDK')\nself._show_warnings = show_warnings",
"manager = Manager.instance()\ntry:\n nodes = manager.get_nodes()[:]\n for node in nodes:\n if node.get_tag() == scan_entry.addr:\n node.is_alive(scan_entry.rssi)\n ... | <|body_start_0|>
DefaultDelegate.__init__(self)
self._logger = logging.getLogger('BlueSTSDK')
self._show_warnings = show_warnings
<|end_body_0|>
<|body_start_1|>
manager = Manager.instance()
try:
nodes = manager.get_nodes()[:]
for node in nodes:
... | Delegate class to scan Bluetooth Low Energy devices. | _ScannerDelegate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ScannerDelegate:
"""Delegate class to scan Bluetooth Low Energy devices."""
def __init__(self, show_warnings=False):
"""Constructor. Args: show_warnings (bool, optional): If True shows warnings, if any, when discovering devices that do not respect the BlueSTSDK's advertising data fo... | stack_v2_sparse_classes_36k_train_033001 | 25,914 | permissive | [
{
"docstring": "Constructor. Args: show_warnings (bool, optional): If True shows warnings, if any, when discovering devices that do not respect the BlueSTSDK's advertising data format, nothing otherwise.",
"name": "__init__",
"signature": "def __init__(self, show_warnings=False)"
},
{
"docstring... | 2 | stack_v2_sparse_classes_30k_train_002202 | Implement the Python class `_ScannerDelegate` described below.
Class description:
Delegate class to scan Bluetooth Low Energy devices.
Method signatures and docstrings:
- def __init__(self, show_warnings=False): Constructor. Args: show_warnings (bool, optional): If True shows warnings, if any, when discovering device... | Implement the Python class `_ScannerDelegate` described below.
Class description:
Delegate class to scan Bluetooth Low Energy devices.
Method signatures and docstrings:
- def __init__(self, show_warnings=False): Constructor. Args: show_warnings (bool, optional): If True shows warnings, if any, when discovering device... | 0a492c94ff056f9d942e35325c6b9a02e6938eb4 | <|skeleton|>
class _ScannerDelegate:
"""Delegate class to scan Bluetooth Low Energy devices."""
def __init__(self, show_warnings=False):
"""Constructor. Args: show_warnings (bool, optional): If True shows warnings, if any, when discovering devices that do not respect the BlueSTSDK's advertising data fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _ScannerDelegate:
"""Delegate class to scan Bluetooth Low Energy devices."""
def __init__(self, show_warnings=False):
"""Constructor. Args: show_warnings (bool, optional): If True shows warnings, if any, when discovering devices that do not respect the BlueSTSDK's advertising data format, nothing... | the_stack_v2_python_sparse | blue_st_sdk/manager.py | STMicroelectronics/BlueSTSDK_Python | train | 47 |
58e5588004556cf3f4b225684954358ecbe010fd | [
"json_data = request.get_json()\nb = event_builders.FbEventBuilder()\nb.build_with_fb_dict(json_data)\ne: event_models.SocialEvent = b.export_as_class(event_models.SocialEvent)\nref: DocumentReference = EventDao().create_fb_event(e)\ne.set_firestore_ref(ref)\ndict_view = e.to_dict_view()\ndict_view['eventId'] = ref... | <|body_start_0|>
json_data = request.get_json()
b = event_builders.FbEventBuilder()
b.build_with_fb_dict(json_data)
e: event_models.SocialEvent = b.export_as_class(event_models.SocialEvent)
ref: DocumentReference = EventDao().create_fb_event(e)
e.set_firestore_ref(ref)
... | Handles user facebook event upload | UserEventService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserEventService:
"""Handles user facebook event upload"""
def post(self, uid):
"""Creates a new event with Facebook event JSON (that is obtained from Facebook Graph API). --- tags: - events parameters: - in: body name: body schema: id: UserEventJSON type: object required: - descript... | stack_v2_sparse_classes_36k_train_033002 | 8,250 | no_license | [
{
"docstring": "Creates a new event with Facebook event JSON (that is obtained from Facebook Graph API). --- tags: - events parameters: - in: body name: body schema: id: UserEventJSON type: object required: - description - end_time - start_time - place - id properties: description: type: string example: \"Advan... | 2 | stack_v2_sparse_classes_30k_train_012762 | Implement the Python class `UserEventService` described below.
Class description:
Handles user facebook event upload
Method signatures and docstrings:
- def post(self, uid): Creates a new event with Facebook event JSON (that is obtained from Facebook Graph API). --- tags: - events parameters: - in: body name: body sc... | Implement the Python class `UserEventService` described below.
Class description:
Handles user facebook event upload
Method signatures and docstrings:
- def post(self, uid): Creates a new event with Facebook event JSON (that is obtained from Facebook Graph API). --- tags: - events parameters: - in: body name: body sc... | f1e98f0002046cb4c932f9f1badbdf2eb8af92d1 | <|skeleton|>
class UserEventService:
"""Handles user facebook event upload"""
def post(self, uid):
"""Creates a new event with Facebook event JSON (that is obtained from Facebook Graph API). --- tags: - events parameters: - in: body name: body schema: id: UserEventJSON type: object required: - descript... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserEventService:
"""Handles user facebook event upload"""
def post(self, uid):
"""Creates a new event with Facebook event JSON (that is obtained from Facebook Graph API). --- tags: - events parameters: - in: body name: body schema: id: UserEventJSON type: object required: - description - end_tim... | the_stack_v2_python_sparse | gravitate/api_server/event/services.py | billyrrr/gravitate-backend | train | 0 |
c5043a4054952153f7f05659bb54bf4cf7821e0e | [
"self._keep_original = True\nif mode == ModeKeys.INFER and ignore_fields is not None and (len(ignore_fields) > 0):\n self._keep_original = False\n self._reserved_fields = [x for x in all_fields if x not in ignore_fields]\n self._new_type = namedtuple('new_type', self._reserved_fields)",
"if self._keep_or... | <|body_start_0|>
self._keep_original = True
if mode == ModeKeys.INFER and ignore_fields is not None and (len(ignore_fields) > 0):
self._keep_original = False
self._reserved_fields = [x for x in all_fields if x not in ignore_fields]
self._new_type = namedtuple('new_typ... | A helper to remove fields from a namedtuple. | DecoderOutputRemover | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderOutputRemover:
"""A helper to remove fields from a namedtuple."""
def __init__(self, mode, all_fields, ignore_fields):
"""Initializes the fields. Only when mode==INFER, apply removes. Args: mode: A mode. all_fields: A list of string, all fields of a namedtuple. ignore_fields: ... | stack_v2_sparse_classes_36k_train_033003 | 8,227 | permissive | [
{
"docstring": "Initializes the fields. Only when mode==INFER, apply removes. Args: mode: A mode. all_fields: A list of string, all fields of a namedtuple. ignore_fields: A list of string or None, the fields to be removed.",
"name": "__init__",
"signature": "def __init__(self, mode, all_fields, ignore_f... | 2 | stack_v2_sparse_classes_30k_train_018743 | Implement the Python class `DecoderOutputRemover` described below.
Class description:
A helper to remove fields from a namedtuple.
Method signatures and docstrings:
- def __init__(self, mode, all_fields, ignore_fields): Initializes the fields. Only when mode==INFER, apply removes. Args: mode: A mode. all_fields: A li... | Implement the Python class `DecoderOutputRemover` described below.
Class description:
A helper to remove fields from a namedtuple.
Method signatures and docstrings:
- def __init__(self, mode, all_fields, ignore_fields): Initializes the fields. Only when mode==INFER, apply removes. Args: mode: A mode. all_fields: A li... | 01155c740705f1641ebf3134829cea0e212f2d28 | <|skeleton|>
class DecoderOutputRemover:
"""A helper to remove fields from a namedtuple."""
def __init__(self, mode, all_fields, ignore_fields):
"""Initializes the fields. Only when mode==INFER, apply removes. Args: mode: A mode. all_fields: A list of string, all fields of a namedtuple. ignore_fields: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderOutputRemover:
"""A helper to remove fields from a namedtuple."""
def __init__(self, mode, all_fields, ignore_fields):
"""Initializes the fields. Only when mode==INFER, apply removes. Args: mode: A mode. all_fields: A list of string, all fields of a namedtuple. ignore_fields: A list of str... | the_stack_v2_python_sparse | njunmt/utils/expert_utils.py | zhaocq-nlp/NJUNMT-tf | train | 114 |
a89486f1b62b3ba2fd79ce5f7319a23a9b843bf3 | [
"self.offer_id = offer_id\nself.order_id = order_id\nself.products = products\nself.cc_expiration_date = cc_expiration_date\nself.delay = delay\nself.grand_total = grand_total\nself.has_shipping = has_shipping\nself.has_taxes = has_taxes\nself.shipping = shipping\nself.shipping_charge_reoccurring_orders = shipping_... | <|body_start_0|>
self.offer_id = offer_id
self.order_id = order_id
self.products = products
self.cc_expiration_date = cc_expiration_date
self.delay = delay
self.grand_total = grand_total
self.has_shipping = has_shipping
self.has_taxes = has_taxes
s... | Implementation of the 'Offer' model. TODO: type model description here. Attributes: offer_id (int): This must be a valid Offer ID. order_id (int): This must be a valid Order ID. products (list of Product): TODO: type description here. cc_expiration_date (string): Credit card expiration date. delay (int): Days to delay ... | Offer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Offer:
"""Implementation of the 'Offer' model. TODO: type model description here. Attributes: offer_id (int): This must be a valid Offer ID. order_id (int): This must be a valid Order ID. products (list of Product): TODO: type description here. cc_expiration_date (string): Credit card expiration ... | stack_v2_sparse_classes_36k_train_033004 | 5,301 | permissive | [
{
"docstring": "Constructor for the Offer class",
"name": "__init__",
"signature": "def __init__(self, offer_id=None, order_id=None, products=None, cc_expiration_date=None, delay=None, grand_total=None, has_shipping=False, has_taxes=False, shipping=None, shipping_charge_reoccurring_orders=False, sub_tot... | 2 | stack_v2_sparse_classes_30k_train_013219 | Implement the Python class `Offer` described below.
Class description:
Implementation of the 'Offer' model. TODO: type model description here. Attributes: offer_id (int): This must be a valid Offer ID. order_id (int): This must be a valid Order ID. products (list of Product): TODO: type description here. cc_expiration... | Implement the Python class `Offer` described below.
Class description:
Implementation of the 'Offer' model. TODO: type model description here. Attributes: offer_id (int): This must be a valid Offer ID. order_id (int): This must be a valid Order ID. products (list of Product): TODO: type description here. cc_expiration... | fb4834e89b897dce3475c89c7e6c34bf8756880e | <|skeleton|>
class Offer:
"""Implementation of the 'Offer' model. TODO: type model description here. Attributes: offer_id (int): This must be a valid Offer ID. order_id (int): This must be a valid Order ID. products (list of Product): TODO: type description here. cc_expiration_date (string): Credit card expiration ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Offer:
"""Implementation of the 'Offer' model. TODO: type model description here. Attributes: offer_id (int): This must be a valid Offer ID. order_id (int): This must be a valid Order ID. products (list of Product): TODO: type description here. cc_expiration_date (string): Credit card expiration date. delay (... | the_stack_v2_python_sparse | ontraportlib/models/offer.py | LifePosts/ontraportlib | train | 0 |
f6d2ede946d5c17a6ef11ce5be69c7d9e6bfb127 | [
"if not cls._api_key:\n try:\n cls._api_key = API_KEY_FILE.read_text('r').strip()\n except Exception:\n cls._log.debug('api key not present in file')\n if IniSettings.read('api_key_dont_bother', False):\n cls._log.debug('will try to obtain api key from internet')\n c... | <|body_start_0|>
if not cls._api_key:
try:
cls._api_key = API_KEY_FILE.read_text('r').strip()
except Exception:
cls._log.debug('api key not present in file')
if IniSettings.read('api_key_dont_bother', False):
cls._log.de... | Class that reads and stores google API key. If the key is not found, show prompt to download. | GoogleApiKey | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleApiKey:
"""Class that reads and stores google API key. If the key is not found, show prompt to download."""
def value(cls, GUI: bool) -> Optional[str]:
"""Reads google api key needed by lyricsfinder from file. Returns ------- Optional[str] google API key"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_033005 | 11,111 | permissive | [
{
"docstring": "Reads google api key needed by lyricsfinder from file. Returns ------- Optional[str] google API key",
"name": "value",
"signature": "def value(cls, GUI: bool) -> Optional[str]"
},
{
"docstring": "Prompt user to input google API key. Asks user through GUI or CLI if he wants to get... | 2 | stack_v2_sparse_classes_30k_train_000701 | Implement the Python class `GoogleApiKey` described below.
Class description:
Class that reads and stores google API key. If the key is not found, show prompt to download.
Method signatures and docstrings:
- def value(cls, GUI: bool) -> Optional[str]: Reads google api key needed by lyricsfinder from file. Returns ---... | Implement the Python class `GoogleApiKey` described below.
Class description:
Class that reads and stores google API key. If the key is not found, show prompt to download.
Method signatures and docstrings:
- def value(cls, GUI: bool) -> Optional[str]: Reads google api key needed by lyricsfinder from file. Returns ---... | e8836c23b7b7e43661b59afd1bfc18d381b95d4a | <|skeleton|>
class GoogleApiKey:
"""Class that reads and stores google API key. If the key is not found, show prompt to download."""
def value(cls, GUI: bool) -> Optional[str]:
"""Reads google api key needed by lyricsfinder from file. Returns ------- Optional[str] google API key"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoogleApiKey:
"""Class that reads and stores google API key. If the key is not found, show prompt to download."""
def value(cls, GUI: bool) -> Optional[str]:
"""Reads google api key needed by lyricsfinder from file. Returns ------- Optional[str] google API key"""
if not cls._api_key:
... | the_stack_v2_python_sparse | wiki_music/utilities/getters.py | marian-code/wikipedia-music-tags | train | 13 |
e39f560cd7b2eeb958a2678376aefe5ea8f14256 | [
"if not matrix:\n return\nself.row = len(matrix)\nself.col = len(matrix[0])\nself.matrix = [[0] * self.col for _ in range(self.row)]\nfor i in xrange(self.row):\n for j in xrange(self.col):\n self.matrix[i][j] = self.matrix[max(0, i - 1)][j] + matrix[i][j]",
"origin = self.matrix[0][col] if not row e... | <|body_start_0|>
if not matrix:
return
self.row = len(matrix)
self.col = len(matrix[0])
self.matrix = [[0] * self.col for _ in range(self.row)]
for i in xrange(self.row):
for j in xrange(self.col):
self.matrix[i][j] = self.matrix[max(0, i -... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_36k_train_033006 | 1,350 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row: int :type col: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, row, col, val)"
},
{
"docstring": ":type r... | 3 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, row... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, row... | ed15eb27936b39980d4cb5fb61cd937ec7ddcb6a | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
if not matrix:
return
self.row = len(matrix)
self.col = len(matrix[0])
self.matrix = [[0] * self.col for _ in range(self.row)]
for i in xrange(self.row):
for j in ... | the_stack_v2_python_sparse | alice/LC308.py | AliceTTXu/LeetCode | train | 0 | |
23bcec14b4c48f7cdf165be4baaf6f41c0d2d2b8 | [
"head = ListNode(Arr[0])\np = head\nfor i in range(1, len(Arr)):\n p.next = ListNode(Arr[i])\n p = p.next\np.next = None\nreturn head",
"p = head\nresult = []\nwhile p:\n result.append(p.val)\n p = p.next\nreturn result"
] | <|body_start_0|>
head = ListNode(Arr[0])
p = head
for i in range(1, len(Arr)):
p.next = ListNode(Arr[i])
p = p.next
p.next = None
return head
<|end_body_0|>
<|body_start_1|>
p = head
result = []
while p:
result.append(p... | LinkList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkList:
def buildList(self, Arr):
"""建立链表"""
<|body_0|>
def printLinkList(self, head):
"""从头到尾打印链表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
head = ListNode(Arr[0])
p = head
for i in range(1, len(Arr)):
p.next = L... | stack_v2_sparse_classes_36k_train_033007 | 1,643 | no_license | [
{
"docstring": "建立链表",
"name": "buildList",
"signature": "def buildList(self, Arr)"
},
{
"docstring": "从头到尾打印链表",
"name": "printLinkList",
"signature": "def printLinkList(self, head)"
}
] | 2 | null | Implement the Python class `LinkList` described below.
Class description:
Implement the LinkList class.
Method signatures and docstrings:
- def buildList(self, Arr): 建立链表
- def printLinkList(self, head): 从头到尾打印链表 | Implement the Python class `LinkList` described below.
Class description:
Implement the LinkList class.
Method signatures and docstrings:
- def buildList(self, Arr): 建立链表
- def printLinkList(self, head): 从头到尾打印链表
<|skeleton|>
class LinkList:
def buildList(self, Arr):
"""建立链表"""
<|body_0|>
d... | 4e4f739402b95691f6c91411da26d7d3bfe042b6 | <|skeleton|>
class LinkList:
def buildList(self, Arr):
"""建立链表"""
<|body_0|>
def printLinkList(self, head):
"""从头到尾打印链表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkList:
def buildList(self, Arr):
"""建立链表"""
head = ListNode(Arr[0])
p = head
for i in range(1, len(Arr)):
p.next = ListNode(Arr[i])
p = p.next
p.next = None
return head
def printLinkList(self, head):
"""从头到尾打印链表"""
... | the_stack_v2_python_sparse | 剑指offer/14.链表中倒数第k个结点.py | hugechuanqi/Algorithms-and-Data-Structures | train | 3 | |
d7ad585d4bbb4111391ef8202181282d0c9d19eb | [
"super(BundleAction, self)._fixup()\nself.type = 'coord-action'\nself.name = self.coordJobName\nif self.conf:\n conf_data = i18n.smart_str(self.conf)\n if not isinstance(conf_data, bytes):\n conf_data = conf_data.encode('utf-8')\n xml = string_io(conf_data)\n self.conf_dict = hadoop.confparse.Con... | <|body_start_0|>
super(BundleAction, self)._fixup()
self.type = 'coord-action'
self.name = self.coordJobName
if self.conf:
conf_data = i18n.smart_str(self.conf)
if not isinstance(conf_data, bytes):
conf_data = conf_data.encode('utf-8')
... | BundleAction | [
"CC-BY-3.0",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"ZPL-2.0",
"Unlicense",
"LGPL-3.0-only",
"CC0-1.0",
"LicenseRef-scancode-other-permissive",
"CNRI-Python",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-or-later",
"Python-2.0",
"GPL-3.0... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BundleAction:
def _fixup(self):
"""Fixup: - time fields as struct_time - config dict"""
<|body_0|>
def get_progress(self):
"""How much more time before the next action."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(BundleAction, self)._fixup... | stack_v2_sparse_classes_36k_train_033008 | 19,361 | permissive | [
{
"docstring": "Fixup: - time fields as struct_time - config dict",
"name": "_fixup",
"signature": "def _fixup(self)"
},
{
"docstring": "How much more time before the next action.",
"name": "get_progress",
"signature": "def get_progress(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011486 | Implement the Python class `BundleAction` described below.
Class description:
Implement the BundleAction class.
Method signatures and docstrings:
- def _fixup(self): Fixup: - time fields as struct_time - config dict
- def get_progress(self): How much more time before the next action. | Implement the Python class `BundleAction` described below.
Class description:
Implement the BundleAction class.
Method signatures and docstrings:
- def _fixup(self): Fixup: - time fields as struct_time - config dict
- def get_progress(self): How much more time before the next action.
<|skeleton|>
class BundleAction:... | dccb9467675c67b9c3399fc76c5de6d31bfb8255 | <|skeleton|>
class BundleAction:
def _fixup(self):
"""Fixup: - time fields as struct_time - config dict"""
<|body_0|>
def get_progress(self):
"""How much more time before the next action."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BundleAction:
def _fixup(self):
"""Fixup: - time fields as struct_time - config dict"""
super(BundleAction, self)._fixup()
self.type = 'coord-action'
self.name = self.coordJobName
if self.conf:
conf_data = i18n.smart_str(self.conf)
if not isinsta... | the_stack_v2_python_sparse | desktop/libs/liboozie/src/liboozie/types.py | cloudera/hue | train | 5,655 | |
4807a2ddafb4cd8fadca531f15aa415397156b9d | [
"super().__init__(unique_id, model)\nself.pos = np.array(pos)\nself.speed = speed\nself.velocity = velocity\nself.neighborhood = neighborhood\nself.separation = separation\nself.cohere_factor = cohere\nself.separate_factor = separate\nself.match_factor = match",
"cohere = np.zeros(2)\nif neighbors:\n for neigh... | <|body_start_0|>
super().__init__(unique_id, model)
self.pos = np.array(pos)
self.speed = speed
self.velocity = velocity
self.neighborhood = neighborhood
self.separation = separation
self.cohere_factor = cohere
self.separate_factor = separate
self.... | A Boid-style agent. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance from any other Boid. | Fish | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fish:
"""A Boid-style agent. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance from any other Boid."""
def __init__(self, unique_id, model, pos, speed, velocity, neighborhood... | stack_v2_sparse_classes_36k_train_033009 | 7,430 | no_license | [
{
"docstring": "Create a new Boid (bird, fish) agent. Args: unique_id: Unique agent identifier. pos: Starting position speed: Distance to move per step. velocity: numpy vector for the Boid's direction of movement. neighborhood: how many neighbours too look for. separation: Minimum distance to maintain from othe... | 5 | stack_v2_sparse_classes_30k_train_003765 | Implement the Python class `Fish` described below.
Class description:
A Boid-style agent. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance from any other Boid.
Method signatures and docstrings:
- def... | Implement the Python class `Fish` described below.
Class description:
A Boid-style agent. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance from any other Boid.
Method signatures and docstrings:
- def... | 18166af285d2a40f903bc178f5c37b7d758fb0bd | <|skeleton|>
class Fish:
"""A Boid-style agent. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance from any other Boid."""
def __init__(self, unique_id, model, pos, speed, velocity, neighborhood... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fish:
"""A Boid-style agent. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance from any other Boid."""
def __init__(self, unique_id, model, pos, speed, velocity, neighborhood, separation,... | the_stack_v2_python_sparse | alternative_models/shoal_model_neighbours.py | sowasser/fish-shoaling-model | train | 1 |
2dab435c90bc30d395583a87cfe2ea6e6e94cd9a | [
"def recursive(outputlist):\n new_list = [1]\n for i in range(1, len(outputlist)):\n new_list.append(outputlist[i - 1] + outputlist[i])\n new_list.append(1)\n return new_list\nout = [1]\nfor j in range(0, rowIndex):\n out = recursive(out)\nreturn out",
"row = [1]\nfor _ in range(rowIndex):\n... | <|body_start_0|>
def recursive(outputlist):
new_list = [1]
for i in range(1, len(outputlist)):
new_list.append(outputlist[i - 1] + outputlist[i])
new_list.append(1)
return new_list
out = [1]
for j in range(0, rowIndex):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_0|>
def getRow_cool(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_1|>
def getRow_1(self, rowIndex):
""":type rowIndex: int :rtype: List... | stack_v2_sparse_classes_36k_train_033010 | 1,680 | no_license | [
{
"docstring": ":type rowIndex: int :rtype: List[int]",
"name": "getRow",
"signature": "def getRow(self, rowIndex)"
},
{
"docstring": ":type rowIndex: int :rtype: List[int]",
"name": "getRow_cool",
"signature": "def getRow_cool(self, rowIndex)"
},
{
"docstring": ":type rowIndex: ... | 3 | stack_v2_sparse_classes_30k_train_018774 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getRow(self, rowIndex): :type rowIndex: int :rtype: List[int]
- def getRow_cool(self, rowIndex): :type rowIndex: int :rtype: List[int]
- def getRow_1(self, rowIndex): :type r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getRow(self, rowIndex): :type rowIndex: int :rtype: List[int]
- def getRow_cool(self, rowIndex): :type rowIndex: int :rtype: List[int]
- def getRow_1(self, rowIndex): :type r... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_0|>
def getRow_cool(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_1|>
def getRow_1(self, rowIndex):
""":type rowIndex: int :rtype: List... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
def recursive(outputlist):
new_list = [1]
for i in range(1, len(outputlist)):
new_list.append(outputlist[i - 1] + outputlist[i])
new_list.append(1)
... | the_stack_v2_python_sparse | LeetCode/Array/119_Pascal's_triangle_ii.py | XyK0907/for_work | train | 0 | |
06fd3242d8f322f6bab259c48bda1032d285c993 | [
"if _JSONAVAIL:\n self._json_encoder = json.JSONEncoder(separators=(',', ':'), sort_keys=True).encode\n self._json_decoder = json.JSONDecoder(strict=False).decode\nelse:\n\n def json_not_impl(dummy):\n _ = dummy\n raise NotImplementedError('Python should include json. Please check your Python... | <|body_start_0|>
if _JSONAVAIL:
self._json_encoder = json.JSONEncoder(separators=(',', ':'), sort_keys=True).encode
self._json_decoder = json.JSONDecoder(strict=False).decode
else:
def json_not_impl(dummy):
_ = dummy
raise NotImplement... | This class provides a common streaming approach for the purpose of reliably sending data over a socket interface. Replaces usage of 'Unpickler.load' where possible with JSON format prepended by message length header. Uses json in python stdlib (in python >= 2.6) or simplejson (in python < 2.6). If neither are available... | StreamHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamHandler:
"""This class provides a common streaming approach for the purpose of reliably sending data over a socket interface. Replaces usage of 'Unpickler.load' where possible with JSON format prepended by message length header. Uses json in python stdlib (in python >= 2.6) or simplejson (i... | stack_v2_sparse_classes_36k_train_033011 | 19,184 | permissive | [
{
"docstring": "Stream handler that encodes objects as either JSON (if available) with message length header prepended for sending over a socket, or as a pickled object if using python < 2.6 and simplejson is not installed. Since 'pickle.load' has memory leak issues with memoization (remembers absolutely everyt... | 4 | null | Implement the Python class `StreamHandler` described below.
Class description:
This class provides a common streaming approach for the purpose of reliably sending data over a socket interface. Replaces usage of 'Unpickler.load' where possible with JSON format prepended by message length header. Uses json in python std... | Implement the Python class `StreamHandler` described below.
Class description:
This class provides a common streaming approach for the purpose of reliably sending data over a socket interface. Replaces usage of 'Unpickler.load' where possible with JSON format prepended by message length header. Uses json in python std... | ed4d650dbd806672401d4341fecc30274c4972c7 | <|skeleton|>
class StreamHandler:
"""This class provides a common streaming approach for the purpose of reliably sending data over a socket interface. Replaces usage of 'Unpickler.load' where possible with JSON format prepended by message length header. Uses json in python stdlib (in python >= 2.6) or simplejson (i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StreamHandler:
"""This class provides a common streaming approach for the purpose of reliably sending data over a socket interface. Replaces usage of 'Unpickler.load' where possible with JSON format prepended by message length header. Uses json in python stdlib (in python >= 2.6) or simplejson (in python < 2.... | the_stack_v2_python_sparse | src/robotide/contrib/testrunner/TestRunnerAgent.py | robotframework/RIDE | train | 897 |
e0f530c691c854e7a3b0ddda8e503b61704bbce3 | [
"self.coins = [5, 7, 1, 1, 2, 3, 22]\nself.output = 20\nreturn (self.coins, self.output)",
"coins, output = self.setUp()\nmethod_output = nonConstructibleChange(coins)\nself.assertEqual(output, method_output)"
] | <|body_start_0|>
self.coins = [5, 7, 1, 1, 2, 3, 22]
self.output = 20
return (self.coins, self.output)
<|end_body_0|>
<|body_start_1|>
coins, output = self.setUp()
method_output = nonConstructibleChange(coins)
self.assertEqual(output, method_output)
<|end_body_1|>
| Class with unittests for Non_ConstructibleChange.py | test_Non_ConstructibleChange | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_Non_ConstructibleChange:
"""Class with unittests for Non_ConstructibleChange.py"""
def setUp(self):
"""Sets up input and output."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_033012 | 900 | no_license | [
{
"docstring": "Sets up input and output.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if returned output is as expected.",
"name": "test_ExpectedOutput",
"signature": "def test_ExpectedOutput(self)"
}
] | 2 | null | Implement the Python class `test_Non_ConstructibleChange` described below.
Class description:
Class with unittests for Non_ConstructibleChange.py
Method signatures and docstrings:
- def setUp(self): Sets up input and output.
- def test_ExpectedOutput(self): Checks if returned output is as expected. | Implement the Python class `test_Non_ConstructibleChange` described below.
Class description:
Class with unittests for Non_ConstructibleChange.py
Method signatures and docstrings:
- def setUp(self): Sets up input and output.
- def test_ExpectedOutput(self): Checks if returned output is as expected.
<|skeleton|>
clas... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_Non_ConstructibleChange:
"""Class with unittests for Non_ConstructibleChange.py"""
def setUp(self):
"""Sets up input and output."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_Non_ConstructibleChange:
"""Class with unittests for Non_ConstructibleChange.py"""
def setUp(self):
"""Sets up input and output."""
self.coins = [5, 7, 1, 1, 2, 3, 22]
self.output = 20
return (self.coins, self.output)
def test_ExpectedOutput(self):
"""Che... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Easy/Non_ConstructibleChange/test_Non_ConstructibleChange.py | JakubKazimierski/PythonPortfolio | train | 9 |
5d01544fb8bcde76c43635f24a7413ac13bc5d9f | [
"body = self.request.body\ntry:\n amount = body['amount']\nexcept KeyError:\n return make_response(success=False, message='Required field amount is not provided.', http_status=HTTPStatus.UNPROCESSABLE_ENTITY)\nvalidation_errors = validate_limit_amount(amount)\nif validation_errors:\n return make_response(s... | <|body_start_0|>
body = self.request.body
try:
amount = body['amount']
except KeyError:
return make_response(success=False, message='Required field amount is not provided.', http_status=HTTPStatus.UNPROCESSABLE_ENTITY)
validation_errors = validate_limit_amount(amo... | Views to interact with user's budget limit. | LimitView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LimitView:
"""Views to interact with user's budget limit."""
async def put(self):
"""Update user's budget limit."""
<|body_0|>
async def delete(self):
"""Delete user's budget limit."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
body = self.req... | stack_v2_sparse_classes_36k_train_033013 | 6,481 | permissive | [
{
"docstring": "Update user's budget limit.",
"name": "put",
"signature": "async def put(self)"
},
{
"docstring": "Delete user's budget limit.",
"name": "delete",
"signature": "async def delete(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002474 | Implement the Python class `LimitView` described below.
Class description:
Views to interact with user's budget limit.
Method signatures and docstrings:
- async def put(self): Update user's budget limit.
- async def delete(self): Delete user's budget limit. | Implement the Python class `LimitView` described below.
Class description:
Views to interact with user's budget limit.
Method signatures and docstrings:
- async def put(self): Update user's budget limit.
- async def delete(self): Delete user's budget limit.
<|skeleton|>
class LimitView:
"""Views to interact with... | 16b7154188f08b33f84d88caea217673cf989b2b | <|skeleton|>
class LimitView:
"""Views to interact with user's budget limit."""
async def put(self):
"""Update user's budget limit."""
<|body_0|>
async def delete(self):
"""Delete user's budget limit."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LimitView:
"""Views to interact with user's budget limit."""
async def put(self):
"""Update user's budget limit."""
body = self.request.body
try:
amount = body['amount']
except KeyError:
return make_response(success=False, message='Required field am... | the_stack_v2_python_sparse | server/app/api/limit.py | SpentlessInc/spentless-server | train | 0 |
c58d7b4c85986f805e555d0334c93b02cf3cac5d | [
"with self.LoggedInUser(admin=True) as admin:\n response = self.testapp.get(self.ROUTE % admin.email)\n output = response.json\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertIsInstance(output, dict)\n self.assertTrue(output['isAdmin'])\n self.assertEqual(output[... | <|body_start_0|>
with self.LoggedInUser(admin=True) as admin:
response = self.testapp.get(self.ROUTE % admin.email)
output = response.json
self.assertIn('application/json', response.headers['Content-type'])
self.assertIsInstance(output, dict)
self.asse... | UserHandlerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserHandlerTest:
def testAdminGetSelf(self):
"""Admin getting own information."""
<|body_0|>
def testAdminGetOtherUser(self):
"""Admin getting information on another user."""
<|body_1|>
def testAdminGetUnknownUser(self):
"""Admin attempting to ge... | stack_v2_sparse_classes_36k_train_033014 | 4,472 | permissive | [
{
"docstring": "Admin getting own information.",
"name": "testAdminGetSelf",
"signature": "def testAdminGetSelf(self)"
},
{
"docstring": "Admin getting information on another user.",
"name": "testAdminGetOtherUser",
"signature": "def testAdminGetOtherUser(self)"
},
{
"docstring":... | 4 | stack_v2_sparse_classes_30k_train_005245 | Implement the Python class `UserHandlerTest` described below.
Class description:
Implement the UserHandlerTest class.
Method signatures and docstrings:
- def testAdminGetSelf(self): Admin getting own information.
- def testAdminGetOtherUser(self): Admin getting information on another user.
- def testAdminGetUnknownUs... | Implement the Python class `UserHandlerTest` described below.
Class description:
Implement the UserHandlerTest class.
Method signatures and docstrings:
- def testAdminGetSelf(self): Admin getting own information.
- def testAdminGetOtherUser(self): Admin getting information on another user.
- def testAdminGetUnknownUs... | f5c76a4097ad6f524aa848c073a1ede94ecbfce4 | <|skeleton|>
class UserHandlerTest:
def testAdminGetSelf(self):
"""Admin getting own information."""
<|body_0|>
def testAdminGetOtherUser(self):
"""Admin getting information on another user."""
<|body_1|>
def testAdminGetUnknownUser(self):
"""Admin attempting to ge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserHandlerTest:
def testAdminGetSelf(self):
"""Admin getting own information."""
with self.LoggedInUser(admin=True) as admin:
response = self.testapp.get(self.ROUTE % admin.email)
output = response.json
self.assertIn('application/json', response.headers['Co... | the_stack_v2_python_sparse | upvote/gae/modules/upvote_app/api/web/users_test.py | farmersbusinessnetwork/upvote | train | 1 | |
3ffa1ab5111bcafd719be12e336dd19ed70b8eaf | [
"super().__init__(model_dir, *args, **kwargs)\nself.beam_size = 5\nself.config = kwargs.pop('config', Config.from_file(os.path.join(self.model_dir, ModelFile.CONFIGURATION)))\nself.config.model.model_dir = model_dir\nself.grammar = ASDLGrammar.from_filepath(os.path.join(model_dir, 'sql_asdl_v2.txt'))\nself.trans = ... | <|body_start_0|>
super().__init__(model_dir, *args, **kwargs)
self.beam_size = 5
self.config = kwargs.pop('config', Config.from_file(os.path.join(self.model_dir, ModelFile.CONFIGURATION)))
self.config.model.model_dir = model_dir
self.grammar = ASDLGrammar.from_filepath(os.path.jo... | StarForTextToSql | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StarForTextToSql:
def __init__(self, model_dir: str, *args, **kwargs):
"""initialize the star model from the `model_dir` path. Args: model_dir (str): the model path."""
<|body_0|>
def forward(self, input: Dict[str, Tensor]) -> Dict[str, Tensor]:
"""return the result ... | stack_v2_sparse_classes_36k_train_033015 | 3,715 | permissive | [
{
"docstring": "initialize the star model from the `model_dir` path. Args: model_dir (str): the model path.",
"name": "__init__",
"signature": "def __init__(self, model_dir: str, *args, **kwargs)"
},
{
"docstring": "return the result by the model Args: input (Dict[str, Tensor]): the preprocessed... | 2 | null | Implement the Python class `StarForTextToSql` described below.
Class description:
Implement the StarForTextToSql class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): initialize the star model from the `model_dir` path. Args: model_dir (str): the model path.
- def forward(sel... | Implement the Python class `StarForTextToSql` described below.
Class description:
Implement the StarForTextToSql class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): initialize the star model from the `model_dir` path. Args: model_dir (str): the model path.
- def forward(sel... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class StarForTextToSql:
def __init__(self, model_dir: str, *args, **kwargs):
"""initialize the star model from the `model_dir` path. Args: model_dir (str): the model path."""
<|body_0|>
def forward(self, input: Dict[str, Tensor]) -> Dict[str, Tensor]:
"""return the result ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StarForTextToSql:
def __init__(self, model_dir: str, *args, **kwargs):
"""initialize the star model from the `model_dir` path. Args: model_dir (str): the model path."""
super().__init__(model_dir, *args, **kwargs)
self.beam_size = 5
self.config = kwargs.pop('config', Config.fro... | the_stack_v2_python_sparse | ai/modelscope/modelscope/models/nlp/space_T_en/text_to_sql.py | alldatacenter/alldata | train | 774 | |
36738bced1a1d1114b719a334c33dd3e8ff5a1d0 | [
"with patch('customer_db_schema.Customers.get_or_create') as handle_get:\n handle_get.return_value = [MockCustomer]\n customer = Customers().get_or_create('test')[0]\n self.assertEqual(customer.customer_id, '123')\n self.assertEqual(customer.first_name, 'Amelia')\n self.assertEqual(customer.last_name... | <|body_start_0|>
with patch('customer_db_schema.Customers.get_or_create') as handle_get:
handle_get.return_value = [MockCustomer]
customer = Customers().get_or_create('test')[0]
self.assertEqual(customer.customer_id, '123')
self.assertEqual(customer.first_name, 'A... | Tests the Customer DB Schema | TestCustomerDBSchema | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCustomerDBSchema:
"""Tests the Customer DB Schema"""
def test_customer_schema_fields(self):
"""Validates the fileds in the customer schema"""
<|body_0|>
def test_customer_schema_save(self):
"""Validates saving the customer schema"""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_033016 | 19,162 | no_license | [
{
"docstring": "Validates the fileds in the customer schema",
"name": "test_customer_schema_fields",
"signature": "def test_customer_schema_fields(self)"
},
{
"docstring": "Validates saving the customer schema",
"name": "test_customer_schema_save",
"signature": "def test_customer_schema_... | 4 | stack_v2_sparse_classes_30k_train_014533 | Implement the Python class `TestCustomerDBSchema` described below.
Class description:
Tests the Customer DB Schema
Method signatures and docstrings:
- def test_customer_schema_fields(self): Validates the fileds in the customer schema
- def test_customer_schema_save(self): Validates saving the customer schema
- def te... | Implement the Python class `TestCustomerDBSchema` described below.
Class description:
Tests the Customer DB Schema
Method signatures and docstrings:
- def test_customer_schema_fields(self): Validates the fileds in the customer schema
- def test_customer_schema_save(self): Validates saving the customer schema
- def te... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestCustomerDBSchema:
"""Tests the Customer DB Schema"""
def test_customer_schema_fields(self):
"""Validates the fileds in the customer schema"""
<|body_0|>
def test_customer_schema_save(self):
"""Validates saving the customer schema"""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCustomerDBSchema:
"""Tests the Customer DB Schema"""
def test_customer_schema_fields(self):
"""Validates the fileds in the customer schema"""
with patch('customer_db_schema.Customers.get_or_create') as handle_get:
handle_get.return_value = [MockCustomer]
custom... | the_stack_v2_python_sparse | students/anthony_mckeever/lesson_3/assignment_1/test_unit.py | JavaRod/SP_Python220B_2019 | train | 1 |
b648466a80518bce3433b2274d6c9a078e52d50d | [
"self._prices = {const.BDAQID: {}, const.BFID: {}}\nself.newprices = {const.BDAQID: {}, const.BFID: {}}\nself._dbman = database.DBMaster()",
"self.newprices = prices\nself._prices.update(prices)\nif prices[const.BDAQID] or prices[const.BFID]:\n bdaqsels = util.flattendict(prices[const.BDAQID])\n bfsels = ut... | <|body_start_0|>
self._prices = {const.BDAQID: {}, const.BFID: {}}
self.newprices = {const.BDAQID: {}, const.BFID: {}}
self._dbman = database.DBMaster()
<|end_body_0|>
<|body_start_1|>
self.newprices = prices
self._prices.update(prices)
if prices[const.BDAQID] or prices[... | PriceStore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PriceStore:
def __init__(self):
"""Class for storing latest prices."""
<|body_0|>
def add_prices(self, prices):
"""Add prices to the store. Note this currently gets called by the PricingManager even when prices is {const.BDAQID: {}, const.BFID: {}} (i.e. no prices)""... | stack_v2_sparse_classes_36k_train_033017 | 1,476 | no_license | [
{
"docstring": "Class for storing latest prices.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add prices to the store. Note this currently gets called by the PricingManager even when prices is {const.BDAQID: {}, const.BFID: {}} (i.e. no prices)",
"name": "add_pr... | 2 | stack_v2_sparse_classes_30k_train_017241 | Implement the Python class `PriceStore` described below.
Class description:
Implement the PriceStore class.
Method signatures and docstrings:
- def __init__(self): Class for storing latest prices.
- def add_prices(self, prices): Add prices to the store. Note this currently gets called by the PricingManager even when ... | Implement the Python class `PriceStore` described below.
Class description:
Implement the PriceStore class.
Method signatures and docstrings:
- def __init__(self): Class for storing latest prices.
- def add_prices(self, prices): Add prices to the store. Note this currently gets called by the PricingManager even when ... | 058d69d7365b771eaaa8f77dead173a1262cccf0 | <|skeleton|>
class PriceStore:
def __init__(self):
"""Class for storing latest prices."""
<|body_0|>
def add_prices(self, prices):
"""Add prices to the store. Note this currently gets called by the PricingManager even when prices is {const.BDAQID: {}, const.BFID: {}} (i.e. no prices)""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PriceStore:
def __init__(self):
"""Class for storing latest prices."""
self._prices = {const.BDAQID: {}, const.BFID: {}}
self.newprices = {const.BDAQID: {}, const.BFID: {}}
self._dbman = database.DBMaster()
def add_prices(self, prices):
"""Add prices to the store. ... | the_stack_v2_python_sparse | core/stores/pricestore.py | jpmit/betman | train | 0 | |
34c66274cdb233c734e8edf1826fa119e8bd66b8 | [
"mat = spio.loadmat(geo_cfg['room'], struct_as_record=True)\nvertcoord = np.array(mat['geometry']['vertcoord'][0][0])\nself.planes = []\nplanes = mat['geometry']['plane'][0][0][0]\nfor jp, p in enumerate(planes):\n name = 'nameless matlab plane'\n vertices = []\n for v in p[0][0]:\n vertices.append(... | <|body_start_0|>
mat = spio.loadmat(geo_cfg['room'], struct_as_record=True)
vertcoord = np.array(mat['geometry']['vertcoord'][0][0])
self.planes = []
planes = mat['geometry']['plane'][0][0][0]
for jp, p in enumerate(planes):
name = 'nameless matlab plane'
... | GeometryMat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeometryMat:
def __init__(self, geo_cfg, alpha, s):
"""Set up the room geometry from the .mat file Geometry consists of: Volume, Total ara and an array of plane objects. Each plane object will be processed in a c++ class and have the following att: - name (string) - bounding box (bool) -... | stack_v2_sparse_classes_36k_train_033018 | 18,836 | no_license | [
{
"docstring": "Set up the room geometry from the .mat file Geometry consists of: Volume, Total ara and an array of plane objects. Each plane object will be processed in a c++ class and have the following att: - name (string) - bounding box (bool) - list of vertices (Eigen<double> - Nvert x 3) - normal (Eigen<d... | 3 | stack_v2_sparse_classes_30k_train_004199 | Implement the Python class `GeometryMat` described below.
Class description:
Implement the GeometryMat class.
Method signatures and docstrings:
- def __init__(self, geo_cfg, alpha, s): Set up the room geometry from the .mat file Geometry consists of: Volume, Total ara and an array of plane objects. Each plane object ... | Implement the Python class `GeometryMat` described below.
Class description:
Implement the GeometryMat class.
Method signatures and docstrings:
- def __init__(self, geo_cfg, alpha, s): Set up the room geometry from the .mat file Geometry consists of: Volume, Total ara and an array of plane objects. Each plane object ... | 345be1496d2c3f59f0aaa3594977f495c80f50e3 | <|skeleton|>
class GeometryMat:
def __init__(self, geo_cfg, alpha, s):
"""Set up the room geometry from the .mat file Geometry consists of: Volume, Total ara and an array of plane objects. Each plane object will be processed in a c++ class and have the following att: - name (string) - bounding box (bool) -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeometryMat:
def __init__(self, geo_cfg, alpha, s):
"""Set up the room geometry from the .mat file Geometry consists of: Volume, Total ara and an array of plane objects. Each plane object will be processed in a c++ class and have the following att: - name (string) - bounding box (bool) - list of verti... | the_stack_v2_python_sparse | ra/room.py | pokjnb/ra | train | 0 | |
bd1732e004337edca9b21cc9aea9d159b65b5a46 | [
"try:\n existing_reaction = UserReactionOnComment.objects.get(comment=comment, user=profile)\n existing_reaction.delete()\nexcept UserReactionOnComment.DoesNotExist:\n pass\ndata = {'comment': comment.id, 'user': profile, 'reaction': reaction}\nserializer = self.serializer_class(data=data)\nserializer.is_v... | <|body_start_0|>
try:
existing_reaction = UserReactionOnComment.objects.get(comment=comment, user=profile)
existing_reaction.delete()
except UserReactionOnComment.DoesNotExist:
pass
data = {'comment': comment.id, 'user': profile, 'reaction': reaction}
... | Define the view for UserReactionOnComment | UserReactionOnCommentView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserReactionOnCommentView:
"""Define the view for UserReactionOnComment"""
def set_reaction(self, comment, profile, reaction):
"""Helper method to set the reaction"""
<|body_0|>
def post(self, request):
"""Post a new comment reaction"""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_033019 | 6,152 | permissive | [
{
"docstring": "Helper method to set the reaction",
"name": "set_reaction",
"signature": "def set_reaction(self, comment, profile, reaction)"
},
{
"docstring": "Post a new comment reaction",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "View the reacti... | 3 | stack_v2_sparse_classes_30k_train_005776 | Implement the Python class `UserReactionOnCommentView` described below.
Class description:
Define the view for UserReactionOnComment
Method signatures and docstrings:
- def set_reaction(self, comment, profile, reaction): Helper method to set the reaction
- def post(self, request): Post a new comment reaction
- def ge... | Implement the Python class `UserReactionOnCommentView` described below.
Class description:
Define the view for UserReactionOnComment
Method signatures and docstrings:
- def set_reaction(self, comment, profile, reaction): Helper method to set the reaction
- def post(self, request): Post a new comment reaction
- def ge... | a304718929936dd4a759d737fb3570d6cc25fb76 | <|skeleton|>
class UserReactionOnCommentView:
"""Define the view for UserReactionOnComment"""
def set_reaction(self, comment, profile, reaction):
"""Helper method to set the reaction"""
<|body_0|>
def post(self, request):
"""Post a new comment reaction"""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserReactionOnCommentView:
"""Define the view for UserReactionOnComment"""
def set_reaction(self, comment, profile, reaction):
"""Helper method to set the reaction"""
try:
existing_reaction = UserReactionOnComment.objects.get(comment=comment, user=profile)
existing... | the_stack_v2_python_sparse | authors/apps/user_comment_reaction/views.py | andela/ah-jumanji | train | 1 |
87f7415183b5b25a30305cc43ec755ab278519a8 | [
"if not isinstance(player_instance, Player):\n logger.error('encode_player_to_dict: Passed non-player object')\nname = player_instance.name\ntotal_correct = player_instance._total_correct\ntotal_incorrect = player_instance._total_incorrect\nanswered_tables = player_instance._answered_tables\ntimes_tables_info... | <|body_start_0|>
if not isinstance(player_instance, Player):
logger.error('encode_player_to_dict: Passed non-player object')
name = player_instance.name
total_correct = player_instance._total_correct
total_incorrect = player_instance._total_incorrect
answered_table... | Utility class to save & load the player instance from json. | PlayerEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayerEncoder:
"""Utility class to save & load the player instance from json."""
def encode_player_to_dict(player_instance: object) -> dict:
"""Encodes the player class as a dictionary."""
<|body_0|>
def decode_dict_to_player(player_dict: dict) -> object:
"""Retu... | stack_v2_sparse_classes_36k_train_033020 | 4,378 | permissive | [
{
"docstring": "Encodes the player class as a dictionary.",
"name": "encode_player_to_dict",
"signature": "def encode_player_to_dict(player_instance: object) -> dict"
},
{
"docstring": "Returns player object with player_dict values.",
"name": "decode_dict_to_player",
"signature": "def de... | 2 | null | Implement the Python class `PlayerEncoder` described below.
Class description:
Utility class to save & load the player instance from json.
Method signatures and docstrings:
- def encode_player_to_dict(player_instance: object) -> dict: Encodes the player class as a dictionary.
- def decode_dict_to_player(player_dict: ... | Implement the Python class `PlayerEncoder` described below.
Class description:
Utility class to save & load the player instance from json.
Method signatures and docstrings:
- def encode_player_to_dict(player_instance: object) -> dict: Encodes the player class as a dictionary.
- def decode_dict_to_player(player_dict: ... | 1072dea1a5be0b339211ff39db6a89a90aca64c1 | <|skeleton|>
class PlayerEncoder:
"""Utility class to save & load the player instance from json."""
def encode_player_to_dict(player_instance: object) -> dict:
"""Encodes the player class as a dictionary."""
<|body_0|>
def decode_dict_to_player(player_dict: dict) -> object:
"""Retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlayerEncoder:
"""Utility class to save & load the player instance from json."""
def encode_player_to_dict(player_instance: object) -> dict:
"""Encodes the player class as a dictionary."""
if not isinstance(player_instance, Player):
logger.error('encode_player_to_dict: Pass... | the_stack_v2_python_sparse | 1_code/players/player_encoder.py | jaimiles23/Multiplication-Medley | train | 0 |
229316925710ccb5015c4660d6e8ed805ca32e99 | [
"super().__init__()\nself._block_args = block_args\nself._ensemble_size = ensemble_size\nself._random_sign_init = random_sign_init\nself._batch_norm_momentum = batch_norm_momentum\nself._batch_norm_epsilon = batch_norm_epsilon\nself._batch_norm = batch_norm\nself._data_format = data_format\nif self._data_format == ... | <|body_start_0|>
super().__init__()
self._block_args = block_args
self._ensemble_size = ensemble_size
self._random_sign_init = random_sign_init
self._batch_norm_momentum = batch_norm_momentum
self._batch_norm_epsilon = batch_norm_epsilon
self._batch_norm = batch_n... | A class of MBConv: Mobile Inverted Residual Bottleneck. | MBConvBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MBConvBlock:
"""A class of MBConv: Mobile Inverted Residual Bottleneck."""
def __init__(self, block_args, ensemble_size, random_sign_init, batch_norm_momentum, batch_norm_epsilon, batch_norm, data_format, relu_fn, use_se, clip_projection_output):
"""Initializes a MBConv block. Args: ... | stack_v2_sparse_classes_36k_train_033021 | 17,450 | permissive | [
{
"docstring": "Initializes a MBConv block. Args: block_args: BlockArgs, arguments to create a Block. ensemble_size: Size of ensemble. random_sign_init: Probability/stddev for fast weight initialization. batch_norm_momentum: Momentum for batch normalization. batch_norm_epsilon: Epsilon for batch normalization. ... | 3 | null | Implement the Python class `MBConvBlock` described below.
Class description:
A class of MBConv: Mobile Inverted Residual Bottleneck.
Method signatures and docstrings:
- def __init__(self, block_args, ensemble_size, random_sign_init, batch_norm_momentum, batch_norm_epsilon, batch_norm, data_format, relu_fn, use_se, cl... | Implement the Python class `MBConvBlock` described below.
Class description:
A class of MBConv: Mobile Inverted Residual Bottleneck.
Method signatures and docstrings:
- def __init__(self, block_args, ensemble_size, random_sign_init, batch_norm_momentum, batch_norm_epsilon, batch_norm, data_format, relu_fn, use_se, cl... | f5f6f50f82bd441339c9d9efbef3f09e72c5fef6 | <|skeleton|>
class MBConvBlock:
"""A class of MBConv: Mobile Inverted Residual Bottleneck."""
def __init__(self, block_args, ensemble_size, random_sign_init, batch_norm_momentum, batch_norm_epsilon, batch_norm, data_format, relu_fn, use_se, clip_projection_output):
"""Initializes a MBConv block. Args: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MBConvBlock:
"""A class of MBConv: Mobile Inverted Residual Bottleneck."""
def __init__(self, block_args, ensemble_size, random_sign_init, batch_norm_momentum, batch_norm_epsilon, batch_norm, data_format, relu_fn, use_se, clip_projection_output):
"""Initializes a MBConv block. Args: block_args: B... | the_stack_v2_python_sparse | uncertainty_baselines/models/efficientnet_batch_ensemble.py | google/uncertainty-baselines | train | 1,235 |
9702d42418b855b14e020ad1874da9f9f89b65d9 | [
"self.link_lengths = link_lengths\nself.shoulder_anchor = shoulder_anchor\nsuper(CenterOutCursorGoalJointSpace2D, self).__init__(*args, **kwargs)",
"vx, vz = super(CenterOutCursorGoalJointSpace2D, self).get(cur_target, cur_pos, keys_pressed)\nvy = 0\npx, py, pz = cur_pos\npos = np.array([px, py, pz]) - self.shoul... | <|body_start_0|>
self.link_lengths = link_lengths
self.shoulder_anchor = shoulder_anchor
super(CenterOutCursorGoalJointSpace2D, self).__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
vx, vz = super(CenterOutCursorGoalJointSpace2D, self).get(cur_target, cur_pos, keys_pressed)
... | 2-link arm controller which moves the endpoint toward a target position at a constant speed | CenterOutCursorGoalJointSpace2D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CenterOutCursorGoalJointSpace2D:
"""2-link arm controller which moves the endpoint toward a target position at a constant speed"""
def __init__(self, link_lengths, shoulder_anchor, *args, **kwargs):
"""Constructor for CenterOutCursorGoalJointSpace2D Parameters ---------- link_lengths... | stack_v2_sparse_classes_36k_train_033022 | 12,992 | permissive | [
{
"docstring": "Constructor for CenterOutCursorGoalJointSpace2D Parameters ---------- link_lengths: shoulder_anchor: args, kwargs: positional and keyword arguments for parent constructor (CenterOutCursorGoal) Returns -------",
"name": "__init__",
"signature": "def __init__(self, link_lengths, shoulder_a... | 2 | null | Implement the Python class `CenterOutCursorGoalJointSpace2D` described below.
Class description:
2-link arm controller which moves the endpoint toward a target position at a constant speed
Method signatures and docstrings:
- def __init__(self, link_lengths, shoulder_anchor, *args, **kwargs): Constructor for CenterOut... | Implement the Python class `CenterOutCursorGoalJointSpace2D` described below.
Class description:
2-link arm controller which moves the endpoint toward a target position at a constant speed
Method signatures and docstrings:
- def __init__(self, link_lengths, shoulder_anchor, *args, **kwargs): Constructor for CenterOut... | a0e296aa663b49e767c9ebb274defb54b301eb12 | <|skeleton|>
class CenterOutCursorGoalJointSpace2D:
"""2-link arm controller which moves the endpoint toward a target position at a constant speed"""
def __init__(self, link_lengths, shoulder_anchor, *args, **kwargs):
"""Constructor for CenterOutCursorGoalJointSpace2D Parameters ---------- link_lengths... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CenterOutCursorGoalJointSpace2D:
"""2-link arm controller which moves the endpoint toward a target position at a constant speed"""
def __init__(self, link_lengths, shoulder_anchor, *args, **kwargs):
"""Constructor for CenterOutCursorGoalJointSpace2D Parameters ---------- link_lengths: shoulder_an... | the_stack_v2_python_sparse | riglib/bmi/feedback_controllers.py | carmenalab/brain-python-interface | train | 9 |
ccf7fab39ea86bb8585f01ce4d371da31e239ca8 | [
"sorted_nums = sorted(nums)\nmedian = math.ceil(len(nums) / 2 - 1)\nfor i in range(len(nums)):\n if i % 2 == 0:\n nums[i] = sorted_nums[i // 2]\n else:\n nums[i] = sorted_nums[median + 1 + i // 2]",
"nums.sort()\ni = 1\nwhile i < len(nums) - 1:\n nums[i], nums[i + 1] = (nums[i + 1], nums[i]... | <|body_start_0|>
sorted_nums = sorted(nums)
median = math.ceil(len(nums) / 2 - 1)
for i in range(len(nums)):
if i % 2 == 0:
nums[i] = sorted_nums[i // 2]
else:
nums[i] = sorted_nums[median + 1 + i // 2]
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wiggleSort2(self, nums) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def wiggleSort3(self, nums) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
def wiggleSort(self, nums) -... | stack_v2_sparse_classes_36k_train_033023 | 2,246 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "wiggleSort2",
"signature": "def wiggleSort2(self, nums) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "wiggleSort3",
"signature": "def wiggleSort3(self, nums) ->... | 3 | stack_v2_sparse_classes_30k_train_005969 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleSort2(self, nums) -> None: Do not return anything, modify nums in-place instead.
- def wiggleSort3(self, nums) -> None: Do not return anything, modify nums in-place ins... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleSort2(self, nums) -> None: Do not return anything, modify nums in-place instead.
- def wiggleSort3(self, nums) -> None: Do not return anything, modify nums in-place ins... | fd4d84d5155be7dac1dde38429b1588cdf392529 | <|skeleton|>
class Solution:
def wiggleSort2(self, nums) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def wiggleSort3(self, nums) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
def wiggleSort(self, nums) -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wiggleSort2(self, nums) -> None:
"""Do not return anything, modify nums in-place instead."""
sorted_nums = sorted(nums)
median = math.ceil(len(nums) / 2 - 1)
for i in range(len(nums)):
if i % 2 == 0:
nums[i] = sorted_nums[i // 2]
... | the_stack_v2_python_sparse | 280-WiggleSort.py | hsuweibo/lc-problems | train | 0 | |
620415da001681feec33561b8fdb3823e6350b8f | [
"if self.sign_key:\n self.sign_key = self.load_key(self.sign_key, self.sign_key_pass)\nif self.decrypt_key:\n self.decrypt_key = self.load_key(self.decrypt_key, self.decrypt_key_pass)",
"try:\n key, cert, _ = asymmetric.load_pkcs12(key_str, key_pass)\nexcept ValueError as e:\n if e.args[0] == 'Passwor... | <|body_start_0|>
if self.sign_key:
self.sign_key = self.load_key(self.sign_key, self.sign_key_pass)
if self.decrypt_key:
self.decrypt_key = self.load_key(self.decrypt_key, self.decrypt_key_pass)
<|end_body_0|>
<|body_start_1|>
try:
key, cert, _ = asymmetric.l... | Class represents an AS2 organization and defines the certificates and settings to be used when sending and receiving messages. :param id: The unique integer id of record in table {Odoo} :param as2_name: The unique AS2 name for this organization :param sign_key: A byte string of the pkcs12 encoded key pair used for sign... | Organization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Organization:
"""Class represents an AS2 organization and defines the certificates and settings to be used when sending and receiving messages. :param id: The unique integer id of record in table {Odoo} :param as2_name: The unique AS2 name for this organization :param sign_key: A byte string of t... | stack_v2_sparse_classes_36k_train_033024 | 38,358 | no_license | [
{
"docstring": "Run the post initialisation checks for this class.",
"name": "__post_init__",
"signature": "def __post_init__(self)"
},
{
"docstring": "Function to load password protected key file in p12 or pem format.",
"name": "load_key",
"signature": "def load_key(key_str: bytes, key_... | 2 | stack_v2_sparse_classes_30k_train_000346 | Implement the Python class `Organization` described below.
Class description:
Class represents an AS2 organization and defines the certificates and settings to be used when sending and receiving messages. :param id: The unique integer id of record in table {Odoo} :param as2_name: The unique AS2 name for this organizat... | Implement the Python class `Organization` described below.
Class description:
Class represents an AS2 organization and defines the certificates and settings to be used when sending and receiving messages. :param id: The unique integer id of record in table {Odoo} :param as2_name: The unique AS2 name for this organizat... | e563e15d81d0bf77a99b15290ee6e4b18daf1476 | <|skeleton|>
class Organization:
"""Class represents an AS2 organization and defines the certificates and settings to be used when sending and receiving messages. :param id: The unique integer id of record in table {Odoo} :param as2_name: The unique AS2 name for this organization :param sign_key: A byte string of t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Organization:
"""Class represents an AS2 organization and defines the certificates and settings to be used when sending and receiving messages. :param id: The unique integer id of record in table {Odoo} :param as2_name: The unique AS2 name for this organization :param sign_key: A byte string of the pkcs12 enc... | the_stack_v2_python_sparse | tools_edi_as2/pyas2lib/as2.py | afzal44/my_new_work | train | 0 |
dd8936693b5bf6ca6f798326144b82cd1d987753 | [
"if not s:\n return []\nfrom collections import Counter as cc\nresult = []\np_len = len(p)\npc = cc(p)\ntmp_cc = cc()\nfor i in range(len(s)):\n tmp_cc.update([s[i]])\n if i >= p_len - 1:\n if pc == tmp_cc:\n result += (i - p_len + 1,)\n tmp_cc.subtract([s[i - p_len + 1]])\nreturn ... | <|body_start_0|>
if not s:
return []
from collections import Counter as cc
result = []
p_len = len(p)
pc = cc(p)
tmp_cc = cc()
for i in range(len(s)):
tmp_cc.update([s[i]])
if i >= p_len - 1:
if pc == tmp_cc:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int] looking for signature."""
<|body_0|>
def rewrite(self, s, p):
""":type s: str :type p: str :rtype: List[int] looking for signature."""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_033025 | 2,356 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: List[int] looking for signature.",
"name": "findAnagrams",
"signature": "def findAnagrams(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: List[int] looking for signature.",
"name": "rewrite",
"signature": "def rewrite(se... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int] looking for signature.
- def rewrite(self, s, p): :type s: str :type p: str :rtype: List[int] looking fo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int] looking for signature.
- def rewrite(self, s, p): :type s: str :type p: str :rtype: List[int] looking fo... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int] looking for signature."""
<|body_0|>
def rewrite(self, s, p):
""":type s: str :type p: str :rtype: List[int] looking for signature."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int] looking for signature."""
if not s:
return []
from collections import Counter as cc
result = []
p_len = len(p)
pc = cc(p)
tmp_cc = cc()
for i in ra... | the_stack_v2_python_sparse | co_amazon/438_Find_All_Anagrams_in_a_String.py | vsdrun/lc_public | train | 6 | |
cf60cec2b85ed9865c4b452f7df346b238c88bcd | [
"n = len(nums)\nl, r = (0, n - 1)\n\ndef getMissingCnt(nums, idx):\n return nums[idx] - nums[0] + 1 - (idx - 0 + 1)\nwhile l <= r:\n mid = l + (r - l) // 2\n missingCnt = getMissingCnt(nums, mid)\n if missingCnt > k:\n r = mid - 1\n elif missingCnt < k:\n l = mid + 1\n elif missingCn... | <|body_start_0|>
n = len(nums)
l, r = (0, n - 1)
def getMissingCnt(nums, idx):
return nums[idx] - nums[0] + 1 - (idx - 0 + 1)
while l <= r:
mid = l + (r - l) // 2
missingCnt = getMissingCnt(nums, mid)
if missingCnt > k:
r =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def missingElement(self, nums: List[int], k: int) -> int:
"""一次性二分, missing counting 二分的时候算"""
<|body_0|>
def missingElement2(self, nums: List[int], k: int) -> int:
"""https://leetcode-cn.com/problems/missing-element-in-sorted-array/solution/you-xu-shu-zu-z... | stack_v2_sparse_classes_36k_train_033026 | 8,259 | no_license | [
{
"docstring": "一次性二分, missing counting 二分的时候算",
"name": "missingElement",
"signature": "def missingElement(self, nums: List[int], k: int) -> int"
},
{
"docstring": "https://leetcode-cn.com/problems/missing-element-in-sorted-array/solution/you-xu-shu-zu-zhong-de-que-shi-yuan-su-by-leetcode/ 更容易理... | 3 | stack_v2_sparse_classes_30k_train_010534 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingElement(self, nums: List[int], k: int) -> int: 一次性二分, missing counting 二分的时候算
- def missingElement2(self, nums: List[int], k: int) -> int: https://leetcode-cn.com/prob... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingElement(self, nums: List[int], k: int) -> int: 一次性二分, missing counting 二分的时候算
- def missingElement2(self, nums: List[int], k: int) -> int: https://leetcode-cn.com/prob... | 29f1bd681ae823ec6fe755c8f91bfe1ca80b6367 | <|skeleton|>
class Solution:
def missingElement(self, nums: List[int], k: int) -> int:
"""一次性二分, missing counting 二分的时候算"""
<|body_0|>
def missingElement2(self, nums: List[int], k: int) -> int:
"""https://leetcode-cn.com/problems/missing-element-in-sorted-array/solution/you-xu-shu-zu-z... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def missingElement(self, nums: List[int], k: int) -> int:
"""一次性二分, missing counting 二分的时候算"""
n = len(nums)
l, r = (0, n - 1)
def getMissingCnt(nums, idx):
return nums[idx] - nums[0] + 1 - (idx - 0 + 1)
while l <= r:
mid = l + (r - l)... | the_stack_v2_python_sparse | 1. solvedProblems/1060. Missing Element in Sorted Array/1060.py | tgaochn/leetcode | train | 1 | |
e5ebd27549b6c06a06ea864f3e9d02364f0a05b7 | [
"if type(network_distribution) is not type(known_distribution):\n raise TypeError('Input distributions must be of same type')\nif isinstance(network_distribution, dict):\n if network_distribution.keys() != known_distribution.keys():\n for key in list(network_distribution.keys()):\n if key no... | <|body_start_0|>
if type(network_distribution) is not type(known_distribution):
raise TypeError('Input distributions must be of same type')
if isinstance(network_distribution, dict):
if network_distribution.keys() != known_distribution.keys():
for key in list(netw... | Class of metrics/distances (norms) between probability distributions | Metrics | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Metrics:
"""Class of metrics/distances (norms) between probability distributions"""
def __init__(self, network_distribution, known_distribution):
"""Initializes a metric to compare distance between network and known (data) distribution. Args: network_distribution : dict or np.ndarray... | stack_v2_sparse_classes_36k_train_033027 | 11,971 | permissive | [
{
"docstring": "Initializes a metric to compare distance between network and known (data) distribution. Args: network_distribution : dict or np.ndarray Output probability distribution from network circuit. known_distribution : dict or np.ndarray Actual probability distribution from data.",
"name": "__init__... | 5 | stack_v2_sparse_classes_30k_train_003411 | Implement the Python class `Metrics` described below.
Class description:
Class of metrics/distances (norms) between probability distributions
Method signatures and docstrings:
- def __init__(self, network_distribution, known_distribution): Initializes a metric to compare distance between network and known (data) dist... | Implement the Python class `Metrics` described below.
Class description:
Class of metrics/distances (norms) between probability distributions
Method signatures and docstrings:
- def __init__(self, network_distribution, known_distribution): Initializes a metric to compare distance between network and known (data) dist... | 5fe919f100f54310a9300b32a838f965f834bbdf | <|skeleton|>
class Metrics:
"""Class of metrics/distances (norms) between probability distributions"""
def __init__(self, network_distribution, known_distribution):
"""Initializes a metric to compare distance between network and known (data) distribution. Args: network_distribution : dict or np.ndarray... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Metrics:
"""Class of metrics/distances (norms) between probability distributions"""
def __init__(self, network_distribution, known_distribution):
"""Initializes a metric to compare distance between network and known (data) distribution. Args: network_distribution : dict or np.ndarray Output proba... | the_stack_v2_python_sparse | src/nisqai/cost/_classical_costs.py | rmlarose/nisqai-dev | train | 15 |
aeb7faa37bcf6f39d899933445f5c230f972a6b1 | [
"self = object.__new__(cls)\nself.name = cls.DEFAULT_NAME\nself.metadata_type = None\nself.INSTANCES[value] = self\nreturn self",
"self.name = name\nself.value = value\nself.metadata_type = metadata_type\nself.INSTANCES[value] = self"
] | <|body_start_0|>
self = object.__new__(cls)
self.name = cls.DEFAULT_NAME
self.metadata_type = None
self.INSTANCES[value] = self
return self
<|end_body_0|>
<|body_start_1|>
self.name = name
self.value = value
self.metadata_type = metadata_type
self... | Represents a scheduled event's entity's type. Attributes ---------- name : `str` The name of the scheduled event's entity's type. value : `int` The identifier value the scheduled event's entity type. metadata_type : `None`, ``ScheduledEventEntityMetadata`` subclass The scheduled event's metadata's applicable type. Clas... | ScheduledEventEntityType | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduledEventEntityType:
"""Represents a scheduled event's entity's type. Attributes ---------- name : `str` The name of the scheduled event's entity's type. value : `int` The identifier value the scheduled event's entity type. metadata_type : `None`, ``ScheduledEventEntityMetadata`` subclass Th... | stack_v2_sparse_classes_36k_train_033028 | 7,142 | permissive | [
{
"docstring": "Creates a scheduled event entity type from the given id and stores it at class's `.INSTANCES`. Called by `.get` when no scheduled event entity type was found with the given id. Parameters ---------- value : `int` The identifier of the scheduled event entity type. Returns ------- self : `instance... | 2 | stack_v2_sparse_classes_30k_val_000490 | Implement the Python class `ScheduledEventEntityType` described below.
Class description:
Represents a scheduled event's entity's type. Attributes ---------- name : `str` The name of the scheduled event's entity's type. value : `int` The identifier value the scheduled event's entity type. metadata_type : `None`, ``Sch... | Implement the Python class `ScheduledEventEntityType` described below.
Class description:
Represents a scheduled event's entity's type. Attributes ---------- name : `str` The name of the scheduled event's entity's type. value : `int` The identifier value the scheduled event's entity type. metadata_type : `None`, ``Sch... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class ScheduledEventEntityType:
"""Represents a scheduled event's entity's type. Attributes ---------- name : `str` The name of the scheduled event's entity's type. value : `int` The identifier value the scheduled event's entity type. metadata_type : `None`, ``ScheduledEventEntityMetadata`` subclass Th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScheduledEventEntityType:
"""Represents a scheduled event's entity's type. Attributes ---------- name : `str` The name of the scheduled event's entity's type. value : `int` The identifier value the scheduled event's entity type. metadata_type : `None`, ``ScheduledEventEntityMetadata`` subclass The scheduled e... | the_stack_v2_python_sparse | hata/discord/scheduled_event/scheduled_event/preinstanced.py | HuyaneMatsu/hata | train | 3 |
b832c3653ade528abe1c3d78914c59a19712d23d | [
"if N < 2:\n return N\nreturn self.fib(N - 1) + self.fib(N - 2)",
"if N < 2:\n return N\na, b = (0, 1)\nfor _ in range(1, N):\n a, b = (b, a + b)\nreturn b",
"cache = {0: 0, 1: 1}\n\ndef fibo_rec(n):\n if n in cache:\n return cache[n]\n res = fibo_rec(n - 1) + fibo_rec(n - 2)\n cache[n]... | <|body_start_0|>
if N < 2:
return N
return self.fib(N - 1) + self.fib(N - 2)
<|end_body_0|>
<|body_start_1|>
if N < 2:
return N
a, b = (0, 1)
for _ in range(1, N):
a, b = (b, a + b)
return b
<|end_body_1|>
<|body_start_2|>
cac... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fib(self, N: 'int') -> 'int':
"""Runtime: 740 ms, faster than 28.75% of Python3. Memory Usage: 12.4 MB, less than 100.00% of Python3."""
<|body_0|>
def fib2(self, N):
"""Runtime: 32 ms, faster than 100.00% of Python3. Memory Usage: 12.5 MB, less than 10... | stack_v2_sparse_classes_36k_train_033029 | 1,846 | permissive | [
{
"docstring": "Runtime: 740 ms, faster than 28.75% of Python3. Memory Usage: 12.4 MB, less than 100.00% of Python3.",
"name": "fib",
"signature": "def fib(self, N: 'int') -> 'int'"
},
{
"docstring": "Runtime: 32 ms, faster than 100.00% of Python3. Memory Usage: 12.5 MB, less than 100.00% of Pyt... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fib(self, N: 'int') -> 'int': Runtime: 740 ms, faster than 28.75% of Python3. Memory Usage: 12.4 MB, less than 100.00% of Python3.
- def fib2(self, N): Runtime: 32 ms, faster... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fib(self, N: 'int') -> 'int': Runtime: 740 ms, faster than 28.75% of Python3. Memory Usage: 12.4 MB, less than 100.00% of Python3.
- def fib2(self, N): Runtime: 32 ms, faster... | 9f66d352c805fcdd9930aaa18c93d7546768287c | <|skeleton|>
class Solution:
def fib(self, N: 'int') -> 'int':
"""Runtime: 740 ms, faster than 28.75% of Python3. Memory Usage: 12.4 MB, less than 100.00% of Python3."""
<|body_0|>
def fib2(self, N):
"""Runtime: 32 ms, faster than 100.00% of Python3. Memory Usage: 12.5 MB, less than 10... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def fib(self, N: 'int') -> 'int':
"""Runtime: 740 ms, faster than 28.75% of Python3. Memory Usage: 12.4 MB, less than 100.00% of Python3."""
if N < 2:
return N
return self.fib(N - 1) + self.fib(N - 2)
def fib2(self, N):
"""Runtime: 32 ms, faster than ... | the_stack_v2_python_sparse | easy/509_fibonacci_number.py | niki4/leetcode_py3 | train | 0 | |
68d3c1715df5337f128cf3ba96c3cd436ca539d8 | [
"tp = 1\nfp = 1\nself.assertEqual(precision(tp, fp), Decimal('0.5'))\ntp = 1\nfp = 3\nself.assertEqual(precision(tp, fp), Decimal('0.25'))\ntp = 6\nfp = 2\nself.assertEqual(precision(tp, fp), Decimal('0.75'))\ntp = 0\nfp = 2\nself.assertEqual(precision(tp, fp), Decimal('0'))\ntp = 2\nfp = 0\nself.assertEqual(precis... | <|body_start_0|>
tp = 1
fp = 1
self.assertEqual(precision(tp, fp), Decimal('0.5'))
tp = 1
fp = 3
self.assertEqual(precision(tp, fp), Decimal('0.25'))
tp = 6
fp = 2
self.assertEqual(precision(tp, fp), Decimal('0.75'))
tp = 0
fp = 2
... | Machine-learning metric tests. | TestML | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestML:
"""Machine-learning metric tests."""
def test_precision(self):
"""Test precision."""
<|body_0|>
def test_recall(self):
"""Test recall."""
<|body_1|>
def test_f1(self):
"""Test F-Score with a beta of 1.0, 0.5, or 2.0."""
<|body... | stack_v2_sparse_classes_36k_train_033030 | 4,841 | permissive | [
{
"docstring": "Test precision.",
"name": "test_precision",
"signature": "def test_precision(self)"
},
{
"docstring": "Test recall.",
"name": "test_recall",
"signature": "def test_recall(self)"
},
{
"docstring": "Test F-Score with a beta of 1.0, 0.5, or 2.0.",
"name": "test_f... | 5 | stack_v2_sparse_classes_30k_train_014054 | Implement the Python class `TestML` described below.
Class description:
Machine-learning metric tests.
Method signatures and docstrings:
- def test_precision(self): Test precision.
- def test_recall(self): Test recall.
- def test_f1(self): Test F-Score with a beta of 1.0, 0.5, or 2.0.
- def test_confusion_matrix(self... | Implement the Python class `TestML` described below.
Class description:
Machine-learning metric tests.
Method signatures and docstrings:
- def test_precision(self): Test precision.
- def test_recall(self): Test recall.
- def test_f1(self): Test F-Score with a beta of 1.0, 0.5, or 2.0.
- def test_confusion_matrix(self... | b7eddc9067fc773f3d040dd5eef33dabac07abc0 | <|skeleton|>
class TestML:
"""Machine-learning metric tests."""
def test_precision(self):
"""Test precision."""
<|body_0|>
def test_recall(self):
"""Test recall."""
<|body_1|>
def test_f1(self):
"""Test F-Score with a beta of 1.0, 0.5, or 2.0."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestML:
"""Machine-learning metric tests."""
def test_precision(self):
"""Test precision."""
tp = 1
fp = 1
self.assertEqual(precision(tp, fp), Decimal('0.5'))
tp = 1
fp = 3
self.assertEqual(precision(tp, fp), Decimal('0.25'))
tp = 6
... | the_stack_v2_python_sparse | src/python/main/segeval/ml/Test.py | anna-ka/segmentation.evaluation | train | 1 |
3b1eb63c7c5b22c4c784c696ff03a3b0f8430efc | [
"number = ''.join((c for c in number if c.isnumeric()))\nif len(number) == number_length:\n return number\nreturn None",
"number = number.replace(' ', '')\nresult = re.match('^[0-9]+$', number)\nif not result:\n return True\nreturn False",
"ni_nuber = re.match('^\\\\s*[a-zA-Z]{2}(?:\\\\s*\\\\d\\\\s*){6}[a... | <|body_start_0|>
number = ''.join((c for c in number if c.isnumeric()))
if len(number) == number_length:
return number
return None
<|end_body_0|>
<|body_start_1|>
number = number.replace(' ', '')
result = re.match('^[0-9]+$', number)
if not result:
... | NumberLengthValidator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumberLengthValidator:
def normalise_number(number, number_length):
"""Return a normalised NHS number if valid, or None if not,"""
<|body_0|>
def number_only(number):
"""Return a normalised NHS number if valid, or None if not,"""
<|body_1|>
def ni_number... | stack_v2_sparse_classes_36k_train_033031 | 1,349 | permissive | [
{
"docstring": "Return a normalised NHS number if valid, or None if not,",
"name": "normalise_number",
"signature": "def normalise_number(number, number_length)"
},
{
"docstring": "Return a normalised NHS number if valid, or None if not,",
"name": "number_only",
"signature": "def number_... | 3 | stack_v2_sparse_classes_30k_train_006571 | Implement the Python class `NumberLengthValidator` described below.
Class description:
Implement the NumberLengthValidator class.
Method signatures and docstrings:
- def normalise_number(number, number_length): Return a normalised NHS number if valid, or None if not,
- def number_only(number): Return a normalised NHS... | Implement the Python class `NumberLengthValidator` described below.
Class description:
Implement the NumberLengthValidator class.
Method signatures and docstrings:
- def normalise_number(number, number_length): Return a normalised NHS number if valid, or None if not,
- def number_only(number): Return a normalised NHS... | ad049db27650e850742a3bd466f96d36a3420589 | <|skeleton|>
class NumberLengthValidator:
def normalise_number(number, number_length):
"""Return a normalised NHS number if valid, or None if not,"""
<|body_0|>
def number_only(number):
"""Return a normalised NHS number if valid, or None if not,"""
<|body_1|>
def ni_number... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumberLengthValidator:
def normalise_number(number, number_length):
"""Return a normalised NHS number if valid, or None if not,"""
number = ''.join((c for c in number if c.isnumeric()))
if len(number) == number_length:
return number
return None
def number_only(... | the_stack_v2_python_sparse | ndopapp/main/ndop_validator.py | uk-gov-mirror/nhsconnect.ndop-nojs | train | 0 | |
5b1ef5fd6c7696f62358d1765a07c5d4915cdd5e | [
"import re\ninput = re.split('(\\\\+|\\\\-|\\\\*|\\\\/)', input)\nn = len(input)\ndp = [[[] for _ in xrange(n)] for _ in xrange(n)]\nfor i in xrange(1, n + 1, 2):\n for j in xrange(0, n + 1 - i, 2):\n if i == 1:\n dp[j][j + i - 1].append(eval(input[j]))\n else:\n for k in xran... | <|body_start_0|>
import re
input = re.split('(\\+|\\-|\\*|\\/)', input)
n = len(input)
dp = [[[] for _ in xrange(n)] for _ in xrange(n)]
for i in xrange(1, n + 1, 2):
for j in xrange(0, n + 1 - i, 2):
if i == 1:
dp[j][j + i - 1].app... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def diffWaysToCompute(self, input):
"""define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position"""
<|body_0|>
def diffWaysToCompute_rec(self, input):
""":type input: str :rtype: List[int]"""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_033032 | 2,376 | permissive | [
{
"docstring": "define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position",
"name": "diffWaysToCompute",
"signature": "def diffWaysToCompute(self, input)"
},
{
"docstring": ":type input: str :rtype: List[int]",
"name": "diffWaysToCompute_rec",
... | 2 | stack_v2_sparse_classes_30k_train_010603 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diffWaysToCompute(self, input): define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position
- def diffWaysToCompute_rec(self, input)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diffWaysToCompute(self, input): define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position
- def diffWaysToCompute_rec(self, input)... | 86f1cb98de801f58c39d9a48ce9de12df7303d20 | <|skeleton|>
class Solution:
def diffWaysToCompute(self, input):
"""define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position"""
<|body_0|>
def diffWaysToCompute_rec(self, input):
""":type input: str :rtype: List[int]"""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def diffWaysToCompute(self, input):
"""define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position"""
import re
input = re.split('(\\+|\\-|\\*|\\/)', input)
n = len(input)
dp = [[[] for _ in xrange(n)] for _ in xrange(... | the_stack_v2_python_sparse | 241-Different-Ways-to-Add-Parentheses/solution.py | Tanych/CodeTracking | train | 0 | |
0f3df79cfd3f9e907a37378324754d340005be10 | [
"super().__init__(offset)\nif shadow_color is None:\n self._shadow_color = shadow_color\nelse:\n self._shadow_color = mcolors.to_rgba(shadow_color)\nself._alpha = alpha\nself._rho = rho\nself._gc = kwargs",
"gc0 = renderer.new_gc()\ngc0.copy_properties(gc)\nif self._shadow_color is None:\n r, g, b = (gc0... | <|body_start_0|>
super().__init__(offset)
if shadow_color is None:
self._shadow_color = shadow_color
else:
self._shadow_color = mcolors.to_rgba(shadow_color)
self._alpha = alpha
self._rho = rho
self._gc = kwargs
<|end_body_0|>
<|body_start_1|>
... | A simple shadow via a line. | SimpleLineShadow | [
"CC0-1.0",
"BSD-3-Clause",
"MIT",
"Bitstream-Charter",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-bakoma-fonts-1995",
"LicenseRef-scancode-unknown-license-reference",
"OFL-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleLineShadow:
"""A simple shadow via a line."""
def __init__(self, offset=(2, -2), shadow_color='k', alpha=0.3, rho=0.3, **kwargs):
"""Parameters ---------- offset : (float, float), default: (2, -2) The (x, y) offset to apply to the path, in points. shadow_color : color, default:... | stack_v2_sparse_classes_36k_train_033033 | 18,595 | permissive | [
{
"docstring": "Parameters ---------- offset : (float, float), default: (2, -2) The (x, y) offset to apply to the path, in points. shadow_color : color, default: 'black' The shadow color. A value of ``None`` takes the original artist's color with a scale factor of *rho*. alpha : float, default: 0.3 The alpha tr... | 2 | null | Implement the Python class `SimpleLineShadow` described below.
Class description:
A simple shadow via a line.
Method signatures and docstrings:
- def __init__(self, offset=(2, -2), shadow_color='k', alpha=0.3, rho=0.3, **kwargs): Parameters ---------- offset : (float, float), default: (2, -2) The (x, y) offset to app... | Implement the Python class `SimpleLineShadow` described below.
Class description:
A simple shadow via a line.
Method signatures and docstrings:
- def __init__(self, offset=(2, -2), shadow_color='k', alpha=0.3, rho=0.3, **kwargs): Parameters ---------- offset : (float, float), default: (2, -2) The (x, y) offset to app... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class SimpleLineShadow:
"""A simple shadow via a line."""
def __init__(self, offset=(2, -2), shadow_color='k', alpha=0.3, rho=0.3, **kwargs):
"""Parameters ---------- offset : (float, float), default: (2, -2) The (x, y) offset to apply to the path, in points. shadow_color : color, default:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleLineShadow:
"""A simple shadow via a line."""
def __init__(self, offset=(2, -2), shadow_color='k', alpha=0.3, rho=0.3, **kwargs):
"""Parameters ---------- offset : (float, float), default: (2, -2) The (x, y) offset to apply to the path, in points. shadow_color : color, default: 'black' The ... | the_stack_v2_python_sparse | contrib/python/matplotlib/py3/matplotlib/patheffects.py | catboost/catboost | train | 8,012 |
8202b65efd2e9414410d73fc04decc39c5fd5749 | [
"if not graph.is_directed():\n raise ValueError('the graph is not directed')\nself.graph = graph\nself.distance = dict()\nfor source in self.graph.iternodes():\n self.distance[source] = dict()\n for target in self.graph.iternodes():\n self.distance[source][target] = float('inf')\n self.distance[s... | <|body_start_0|>
if not graph.is_directed():
raise ValueError('the graph is not directed')
self.graph = graph
self.distance = dict()
for source in self.graph.iternodes():
self.distance[source] = dict()
for target in self.graph.iternodes():
... | The Floyd-Warshall algorithm (all-pairs shortest paths). Negative cycles are forbidden. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph >>> from graphtheory.shortes... | FloydWarshall | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloydWarshall:
"""The Floyd-Warshall algorithm (all-pairs shortest paths). Negative cycles are forbidden. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs ... | stack_v2_sparse_classes_36k_train_033034 | 7,754 | permissive | [
{
"docstring": "The algorithm initialization. Parameters ---------- graph : directed weighted graph",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Finding all shortest paths.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015058 | Implement the Python class `FloydWarshall` described below.
Class description:
The Floyd-Warshall algorithm (all-pairs shortest paths). Negative cycles are forbidden. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge ... | Implement the Python class `FloydWarshall` described below.
Class description:
The Floyd-Warshall algorithm (all-pairs shortest paths). Negative cycles are forbidden. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge ... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class FloydWarshall:
"""The Floyd-Warshall algorithm (all-pairs shortest paths). Negative cycles are forbidden. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FloydWarshall:
"""The Floyd-Warshall algorithm (all-pairs shortest paths). Negative cycles are forbidden. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph ... | the_stack_v2_python_sparse | graphtheory/shortestpaths/floydwarshall.py | kgashok/graphs-dict | train | 0 |
e0872f3505fff212efa78d8440a7709f3f9e2565 | [
"env.filters['basename'] = os.path.basename\nenv.filters['dirname'] = os.path.dirname\nenv.filters['splitext'] = os.path.splitext\nenv.filters['combine'] = combine\nenv.filters['as_dict'] = as_dict\nenv.filters['ternary'] = ternary\nenv.globals['gpu_count'] = gpu_count\nenv.globals['load_json'] = create_load_json(s... | <|body_start_0|>
env.filters['basename'] = os.path.basename
env.filters['dirname'] = os.path.dirname
env.filters['splitext'] = os.path.splitext
env.filters['combine'] = combine
env.filters['as_dict'] = as_dict
env.filters['ternary'] = ternary
env.globals['gpu_coun... | An evaluation engine which uses Jinja2 for templating. | JinjaEngine | [
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JinjaEngine:
"""An evaluation engine which uses Jinja2 for templating."""
def register_custom_filters(self, env):
"""Adds our custom filters to the Jinja2 engine. Arguments --------- env: jinja2.Environment instance. The environment to add the custom filters to."""
<|body_0|>... | stack_v2_sparse_classes_36k_train_033035 | 6,185 | permissive | [
{
"docstring": "Adds our custom filters to the Jinja2 engine. Arguments --------- env: jinja2.Environment instance. The environment to add the custom filters to.",
"name": "register_custom_filters",
"signature": "def register_custom_filters(self, env)"
},
{
"docstring": "Creates a new Jinja2 tem... | 3 | stack_v2_sparse_classes_30k_train_007804 | Implement the Python class `JinjaEngine` described below.
Class description:
An evaluation engine which uses Jinja2 for templating.
Method signatures and docstrings:
- def register_custom_filters(self, env): Adds our custom filters to the Jinja2 engine. Arguments --------- env: jinja2.Environment instance. The enviro... | Implement the Python class `JinjaEngine` described below.
Class description:
An evaluation engine which uses Jinja2 for templating.
Method signatures and docstrings:
- def register_custom_filters(self, env): Adds our custom filters to the Jinja2 engine. Arguments --------- env: jinja2.Environment instance. The enviro... | fd0c120e50815c1e5be64e5dde964dcd47234556 | <|skeleton|>
class JinjaEngine:
"""An evaluation engine which uses Jinja2 for templating."""
def register_custom_filters(self, env):
"""Adds our custom filters to the Jinja2 engine. Arguments --------- env: jinja2.Environment instance. The environment to add the custom filters to."""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JinjaEngine:
"""An evaluation engine which uses Jinja2 for templating."""
def register_custom_filters(self, env):
"""Adds our custom filters to the Jinja2 engine. Arguments --------- env: jinja2.Environment instance. The environment to add the custom filters to."""
env.filters['basename']... | the_stack_v2_python_sparse | kur/engine/jinja_engine.py | deepgram/kur | train | 873 |
59c34c3273194b69860ef5209421f8e9cdf13b79 | [
"assignor = Assignor()\njson_object = assignor.assign(pythonobject)\nreturn json_object.to_string()",
"t = Tokenizer()\np = Parser()\ntokens = t.tokenize(jsonstring)\njson_object = p.parse(tokens)\nreturn json_object.to_py_object()"
] | <|body_start_0|>
assignor = Assignor()
json_object = assignor.assign(pythonobject)
return json_object.to_string()
<|end_body_0|>
<|body_start_1|>
t = Tokenizer()
p = Parser()
tokens = t.tokenize(jsonstring)
json_object = p.parse(tokens)
return json_object... | Json | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Json:
def serialize(self, pythonobject: Any):
"""Serialize python object to json"""
<|body_0|>
def deserialize(self, jsonstring: str) -> Any:
"""Deseiralize s to a python object."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
assignor = Assignor()
... | stack_v2_sparse_classes_36k_train_033036 | 15,110 | no_license | [
{
"docstring": "Serialize python object to json",
"name": "serialize",
"signature": "def serialize(self, pythonobject: Any)"
},
{
"docstring": "Deseiralize s to a python object.",
"name": "deserialize",
"signature": "def deserialize(self, jsonstring: str) -> Any"
}
] | 2 | stack_v2_sparse_classes_30k_train_009048 | Implement the Python class `Json` described below.
Class description:
Implement the Json class.
Method signatures and docstrings:
- def serialize(self, pythonobject: Any): Serialize python object to json
- def deserialize(self, jsonstring: str) -> Any: Deseiralize s to a python object. | Implement the Python class `Json` described below.
Class description:
Implement the Json class.
Method signatures and docstrings:
- def serialize(self, pythonobject: Any): Serialize python object to json
- def deserialize(self, jsonstring: str) -> Any: Deseiralize s to a python object.
<|skeleton|>
class Json:
... | 26dc09d6d48b08d74925c6f3d412aa168ba0b7dd | <|skeleton|>
class Json:
def serialize(self, pythonobject: Any):
"""Serialize python object to json"""
<|body_0|>
def deserialize(self, jsonstring: str) -> Any:
"""Deseiralize s to a python object."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Json:
def serialize(self, pythonobject: Any):
"""Serialize python object to json"""
assignor = Assignor()
json_object = assignor.assign(pythonobject)
return json_object.to_string()
def deserialize(self, jsonstring: str) -> Any:
"""Deseiralize s to a python object."... | the_stack_v2_python_sparse | py/jsonparser2/parser.py | ichihara-3/practice | train | 0 | |
5841de63c5cb7bca5da9919e14ef93e6a2a52e4f | [
"super().__init__()\nif not is_sqrt(patch_size):\n raise ValueError(f'patch_size should be square number, got {patch_size}.')\nself.patch_size = ensure_tuple_rep(patch_size, spatial_dims)\nself.img_size = ensure_tuple_rep(img_size, spatial_dims)\nself.spatial_dims = spatial_dims\nfor m, p in zip(self.img_size, s... | <|body_start_0|>
super().__init__()
if not is_sqrt(patch_size):
raise ValueError(f'patch_size should be square number, got {patch_size}.')
self.patch_size = ensure_tuple_rep(patch_size, spatial_dims)
self.img_size = ensure_tuple_rep(img_size, spatial_dims)
self.spatia... | Vision Transformer (ViT), based on: "Dosovitskiy et al., An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale <https://arxiv.org/abs/2010.11929>" Modified to also give same dimension outputs as the input size of the image | ViTAutoEnc | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViTAutoEnc:
"""Vision Transformer (ViT), based on: "Dosovitskiy et al., An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale <https://arxiv.org/abs/2010.11929>" Modified to also give same dimension outputs as the input size of the image"""
def __init__(self, in_channels... | stack_v2_sparse_classes_36k_train_033037 | 5,739 | permissive | [
{
"docstring": "Args: in_channels: dimension of input channels or the number of channels for input. img_size: dimension of input image. patch_size: dimension of patch size out_channels: number of output channels. Defaults to 1. deconv_chns: number of channels for the deconvolution layers. Defaults to 16. hidden... | 2 | null | Implement the Python class `ViTAutoEnc` described below.
Class description:
Vision Transformer (ViT), based on: "Dosovitskiy et al., An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale <https://arxiv.org/abs/2010.11929>" Modified to also give same dimension outputs as the input size of the image... | Implement the Python class `ViTAutoEnc` described below.
Class description:
Vision Transformer (ViT), based on: "Dosovitskiy et al., An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale <https://arxiv.org/abs/2010.11929>" Modified to also give same dimension outputs as the input size of the image... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class ViTAutoEnc:
"""Vision Transformer (ViT), based on: "Dosovitskiy et al., An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale <https://arxiv.org/abs/2010.11929>" Modified to also give same dimension outputs as the input size of the image"""
def __init__(self, in_channels... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViTAutoEnc:
"""Vision Transformer (ViT), based on: "Dosovitskiy et al., An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale <https://arxiv.org/abs/2010.11929>" Modified to also give same dimension outputs as the input size of the image"""
def __init__(self, in_channels: int, img_si... | the_stack_v2_python_sparse | monai/networks/nets/vitautoenc.py | Project-MONAI/MONAI | train | 4,805 |
acb9782eada37fc8f6862c48d5eb7a7e1eb102e7 | [
"self.reqpaser = reqparse.RequestParser()\nself.reqpaser.add_argument('attribute_id', type=str, required=True, help='attribute id required')\nself.reqpaser.add_argument('sub_theme_id', type=int, required=True, help='user id required')",
"args = self.reqpaser.parse_args()\nattribute = AttrAlias.get_by_attr_id(args... | <|body_start_0|>
self.reqpaser = reqparse.RequestParser()
self.reqpaser.add_argument('attribute_id', type=str, required=True, help='attribute id required')
self.reqpaser.add_argument('sub_theme_id', type=int, required=True, help='user id required')
<|end_body_0|>
<|body_start_1|>
args =... | Update Attribute Subtheme | UpdateAttributeSubTheme | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateAttributeSubTheme:
"""Update Attribute Subtheme"""
def __init__(self):
"""Set reqpase arguments"""
<|body_0|>
def post(self) -> ({str: str}, HTTPStatus):
"""Update Attributes SubTheme :param attribute_id: Attributes identification number :param sub_theme_id... | stack_v2_sparse_classes_36k_train_033038 | 2,004 | permissive | [
{
"docstring": "Set reqpase arguments",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Update Attributes SubTheme :param attribute_id: Attributes identification number :param sub_theme_id: SubTheme identification number :type attribute_id: str :type sub_theme_id: int :r... | 2 | null | Implement the Python class `UpdateAttributeSubTheme` described below.
Class description:
Update Attribute Subtheme
Method signatures and docstrings:
- def __init__(self): Set reqpase arguments
- def post(self) -> ({str: str}, HTTPStatus): Update Attributes SubTheme :param attribute_id: Attributes identification numbe... | Implement the Python class `UpdateAttributeSubTheme` described below.
Class description:
Update Attribute Subtheme
Method signatures and docstrings:
- def __init__(self): Set reqpase arguments
- def post(self) -> ({str: str}, HTTPStatus): Update Attributes SubTheme :param attribute_id: Attributes identification numbe... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class UpdateAttributeSubTheme:
"""Update Attribute Subtheme"""
def __init__(self):
"""Set reqpase arguments"""
<|body_0|>
def post(self) -> ({str: str}, HTTPStatus):
"""Update Attributes SubTheme :param attribute_id: Attributes identification number :param sub_theme_id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateAttributeSubTheme:
"""Update Attribute Subtheme"""
def __init__(self):
"""Set reqpase arguments"""
self.reqpaser = reqparse.RequestParser()
self.reqpaser.add_argument('attribute_id', type=str, required=True, help='attribute id required')
self.reqpaser.add_argument('s... | the_stack_v2_python_sparse | Analytics/resources/attributes/update_attribute_sub_theme.py | thanosbnt/SharingCitiesDashboard | train | 0 |
6fa7afb2304aa94f346e9dfcd144992cc3ca38e1 | [
"if not s:\n return True\nans = False\nfor idx in range(1, len(s) + 1):\n if s[:idx] in wordDict:\n ans = ans or self.wordBreak(s[idx:], wordDict)\nreturn ans",
"dp = [False] * (len(s) + 1)\ndp[0] = True\nfor i in range(1, len(s) + 1):\n for j in range(i + 1):\n if dp[j] and s[j:i] in wordD... | <|body_start_0|>
if not s:
return True
ans = False
for idx in range(1, len(s) + 1):
if s[:idx] in wordDict:
ans = ans or self.wordBreak(s[idx:], wordDict)
return ans
<|end_body_0|>
<|body_start_1|>
dp = [False] * (len(s) + 1)
dp[0]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
"""Recursive solution"""
<|body_0|>
def wordBreakDP(self, s, wordDict):
"""DP based solution"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s:
return True
ans = False
fo... | stack_v2_sparse_classes_36k_train_033039 | 902 | no_license | [
{
"docstring": "Recursive solution",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
},
{
"docstring": "DP based solution",
"name": "wordBreakDP",
"signature": "def wordBreakDP(self, s, wordDict)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020096 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): Recursive solution
- def wordBreakDP(self, s, wordDict): DP based solution | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): Recursive solution
- def wordBreakDP(self, s, wordDict): DP based solution
<|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
... | e271069f5e8b67ccb2770150960edba5147120dc | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
"""Recursive solution"""
<|body_0|>
def wordBreakDP(self, s, wordDict):
"""DP based solution"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak(self, s, wordDict):
"""Recursive solution"""
if not s:
return True
ans = False
for idx in range(1, len(s) + 1):
if s[:idx] in wordDict:
ans = ans or self.wordBreak(s[idx:], wordDict)
return ans
def wor... | the_stack_v2_python_sparse | leetcode/word_break_1.py | ajay2611/ds-algo | train | 3 | |
d747529797c266d0199220879c7cdd9392d532d6 | [
"super().__init__()\nif d_model % nhead != 0:\n raise ValueError(f'd_model={d_model} not divisible by nhead={nhead}')\nself.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout)\nself.linear = LinearDecoder(LinearDecoderHparams(decode_dims=dim_feedforward, n_decode_layers=2, decode_dropout=dropout), d_... | <|body_start_0|>
super().__init__()
if d_model % nhead != 0:
raise ValueError(f'd_model={d_model} not divisible by nhead={nhead}')
self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout)
self.linear = LinearDecoder(LinearDecoderHparams(decode_dims=dim_feedforward... | Internal object modifying pytorch's TransformerEncoderLayer, for use by `seqmodel.model.transformer.TransformerEncoder`. See `TransformerEncoder` for documentation. | TransformerEncoderLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoderLayer:
"""Internal object modifying pytorch's TransformerEncoderLayer, for use by `seqmodel.model.transformer.TransformerEncoder`. See `TransformerEncoder` for documentation."""
def __init__(self, d_model: int, nhead: int, dim_feedforward: int, dropout: float, ActivationFn:... | stack_v2_sparse_classes_36k_train_033040 | 20,414 | no_license | [
{
"docstring": "See documentation in `seqmodel.model.transformer.TransformerEncoder`.",
"name": "__init__",
"signature": "def __init__(self, d_model: int, nhead: int, dim_feedforward: int, dropout: float, ActivationFn: nn.Module=nn.ReLU, DropoutFn: nn.Module=nn.Dropout, LayerNormFn: nn.Module=nn.LayerNo... | 2 | stack_v2_sparse_classes_30k_train_016631 | Implement the Python class `TransformerEncoderLayer` described below.
Class description:
Internal object modifying pytorch's TransformerEncoderLayer, for use by `seqmodel.model.transformer.TransformerEncoder`. See `TransformerEncoder` for documentation.
Method signatures and docstrings:
- def __init__(self, d_model: ... | Implement the Python class `TransformerEncoderLayer` described below.
Class description:
Internal object modifying pytorch's TransformerEncoderLayer, for use by `seqmodel.model.transformer.TransformerEncoder`. See `TransformerEncoder` for documentation.
Method signatures and docstrings:
- def __init__(self, d_model: ... | 793543ebd3e526bdd8931a269fdf17808762d9bc | <|skeleton|>
class TransformerEncoderLayer:
"""Internal object modifying pytorch's TransformerEncoderLayer, for use by `seqmodel.model.transformer.TransformerEncoder`. See `TransformerEncoder` for documentation."""
def __init__(self, d_model: int, nhead: int, dim_feedforward: int, dropout: float, ActivationFn:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerEncoderLayer:
"""Internal object modifying pytorch's TransformerEncoderLayer, for use by `seqmodel.model.transformer.TransformerEncoder`. See `TransformerEncoder` for documentation."""
def __init__(self, d_model: int, nhead: int, dim_feedforward: int, dropout: float, ActivationFn: nn.Module=nn... | the_stack_v2_python_sparse | seqmodel/model/transformer.py | devinkwok/seqmodelv2 | train | 0 |
1db88fd782c0739ee44b2d79db0e5c6b601bc935 | [
"super(IdentityV3Fixture, cls).setUpClass()\ncls.v3_composite = IdentityV3Composite(cls.user_config)\ncls.v3_composite.load_clients_and_behaviors()",
"if catalog_is_empty is True:\n self.assertEqual(len(catalog_response.entity.catalog), 0)\nelse:\n self.assertGreater(len(catalog_response.entity.catalog), 0)... | <|body_start_0|>
super(IdentityV3Fixture, cls).setUpClass()
cls.v3_composite = IdentityV3Composite(cls.user_config)
cls.v3_composite.load_clients_and_behaviors()
<|end_body_0|>
<|body_start_1|>
if catalog_is_empty is True:
self.assertEqual(len(catalog_response.entity.catalog... | IdentityV3Fixture | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityV3Fixture:
def setUpClass(cls):
"""Function to create test bed fixture for all the v3 tests. Execute once at the beginning of class @param cls: instance of class"""
<|body_0|>
def _verify_catalog_response(self, catalog_response, catalog_is_empty=False):
"""Ve... | stack_v2_sparse_classes_36k_train_033041 | 1,942 | permissive | [
{
"docstring": "Function to create test bed fixture for all the v3 tests. Execute once at the beginning of class @param cls: instance of class",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Verify the response received for the catalog. Verifying the assertions are ... | 2 | null | Implement the Python class `IdentityV3Fixture` described below.
Class description:
Implement the IdentityV3Fixture class.
Method signatures and docstrings:
- def setUpClass(cls): Function to create test bed fixture for all the v3 tests. Execute once at the beginning of class @param cls: instance of class
- def _verif... | Implement the Python class `IdentityV3Fixture` described below.
Class description:
Implement the IdentityV3Fixture class.
Method signatures and docstrings:
- def setUpClass(cls): Function to create test bed fixture for all the v3 tests. Execute once at the beginning of class @param cls: instance of class
- def _verif... | 30f0e64672676c3f90b4a582fe90fac6621475b3 | <|skeleton|>
class IdentityV3Fixture:
def setUpClass(cls):
"""Function to create test bed fixture for all the v3 tests. Execute once at the beginning of class @param cls: instance of class"""
<|body_0|>
def _verify_catalog_response(self, catalog_response, catalog_is_empty=False):
"""Ve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdentityV3Fixture:
def setUpClass(cls):
"""Function to create test bed fixture for all the v3 tests. Execute once at the beginning of class @param cls: instance of class"""
super(IdentityV3Fixture, cls).setUpClass()
cls.v3_composite = IdentityV3Composite(cls.user_config)
cls.v3... | the_stack_v2_python_sparse | cloudroast/identity/v3/fixture.py | RULCSoft/cloudroast | train | 1 | |
c6683ac9c4d1cc344c1d55a3550438bef33092b1 | [
"super().__init__()\nself.data = data\nself.args = args\nself.batch_size = args.batch_size\nself.num_workers = args.num_workers",
"num_samples = self.data.shape[0]\nnum_train = round(num_samples * self.args.splits[0])\nnum_test = round(num_samples * self.args.splits[1])\nnum_val = num_samples - num_train - num_te... | <|body_start_0|>
super().__init__()
self.data = data
self.args = args
self.batch_size = args.batch_size
self.num_workers = args.num_workers
<|end_body_0|>
<|body_start_1|>
num_samples = self.data.shape[0]
num_train = round(num_samples * self.args.splits[0])
... | PyTorch Lightning data module class for time series data. | DataModule | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataModule:
"""PyTorch Lightning data module class for time series data."""
def __init__(self, data, args):
"""Instantiates the data module. Args: data: the numpy array of time series data, with the shape (seq_len x num_nodes x num_features). args: python argparse.ArgumentParser clas... | stack_v2_sparse_classes_36k_train_033042 | 6,627 | permissive | [
{
"docstring": "Instantiates the data module. Args: data: the numpy array of time series data, with the shape (seq_len x num_nodes x num_features). args: python argparse.ArgumentParser class.",
"name": "__init__",
"signature": "def __init__(self, data, args)"
},
{
"docstring": "Splits the data a... | 5 | null | Implement the Python class `DataModule` described below.
Class description:
PyTorch Lightning data module class for time series data.
Method signatures and docstrings:
- def __init__(self, data, args): Instantiates the data module. Args: data: the numpy array of time series data, with the shape (seq_len x num_nodes x... | Implement the Python class `DataModule` described below.
Class description:
PyTorch Lightning data module class for time series data.
Method signatures and docstrings:
- def __init__(self, data, args): Instantiates the data module. Args: data: the numpy array of time series data, with the shape (seq_len x num_nodes x... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class DataModule:
"""PyTorch Lightning data module class for time series data."""
def __init__(self, data, args):
"""Instantiates the data module. Args: data: the numpy array of time series data, with the shape (seq_len x num_nodes x num_features). args: python argparse.ArgumentParser clas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataModule:
"""PyTorch Lightning data module class for time series data."""
def __init__(self, data, args):
"""Instantiates the data module. Args: data: the numpy array of time series data, with the shape (seq_len x num_nodes x num_features). args: python argparse.ArgumentParser class."""
... | the_stack_v2_python_sparse | editable_graph_temporal/data.py | Jimmy-INL/google-research | train | 1 |
7f53b5309391823c2ea553d2afb845e1bb4b13ff | [
"user_list_page = UserListPageObject(self.driver)\nsearch_page = FindUserPageObject(self.driver)\nresults_page = ResultsListPageObject(self.driver)\ntest_user = self.test_settings['test_users']['1']\nself.api.remove_user(self.test_settings['test_course']['cid'], test_user['user_id'], test_user['role_id'])\nuser_lis... | <|body_start_0|>
user_list_page = UserListPageObject(self.driver)
search_page = FindUserPageObject(self.driver)
results_page = ResultsListPageObject(self.driver)
test_user = self.test_settings['test_users']['1']
self.api.remove_user(self.test_settings['test_course']['cid'], test_... | Testing Searching functionality of Manage People | SearchTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchTests:
"""Testing Searching functionality of Manage People"""
def test_search_by_huid_successful(self):
"""This searches for an existing ID and asserts the search results page is loaded after search"""
<|body_0|>
def test_search_by_huid_unsuccessful(self):
... | stack_v2_sparse_classes_36k_train_033043 | 1,798 | no_license | [
{
"docstring": "This searches for an existing ID and asserts the search results page is loaded after search",
"name": "test_search_by_huid_successful",
"signature": "def test_search_by_huid_successful(self)"
},
{
"docstring": "This searches for an invalid id and asserts that search page is not l... | 2 | stack_v2_sparse_classes_30k_train_011712 | Implement the Python class `SearchTests` described below.
Class description:
Testing Searching functionality of Manage People
Method signatures and docstrings:
- def test_search_by_huid_successful(self): This searches for an existing ID and asserts the search results page is loaded after search
- def test_search_by_h... | Implement the Python class `SearchTests` described below.
Class description:
Testing Searching functionality of Manage People
Method signatures and docstrings:
- def test_search_by_huid_successful(self): This searches for an existing ID and asserts the search results page is loaded after search
- def test_search_by_h... | 6d20ee2c193ed69b29aaf3f1dd23be419153ca72 | <|skeleton|>
class SearchTests:
"""Testing Searching functionality of Manage People"""
def test_search_by_huid_successful(self):
"""This searches for an existing ID and asserts the search results page is loaded after search"""
<|body_0|>
def test_search_by_huid_unsuccessful(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchTests:
"""Testing Searching functionality of Manage People"""
def test_search_by_huid_successful(self):
"""This searches for an existing ID and asserts the search results page is loaded after search"""
user_list_page = UserListPageObject(self.driver)
search_page = FindUserPa... | the_stack_v2_python_sparse | selenium_tests/manage_people/search_tests.py | Harvard-University-iCommons/canvas_manage_course | train | 4 |
1b3abc5be857c96ee9c182982bbd26baaa399f86 | [
"super().__init__()\nself.h = h\nself.dm = dm\nself.depth = int(dm / h)\nself.Wq = tf.keras.layers.Dense(units=dm)\nself.Wk = tf.keras.layers.Dense(units=dm)\nself.Wv = tf.keras.layers.Dense(units=dm)\nself.linear = tf.keras.layers.Dense(units=dm)",
"batch = tf.shape(Q)[0]\nq = self.Wq(Q)\nq = tf.reshape(q, (batc... | <|body_start_0|>
super().__init__()
self.h = h
self.dm = dm
self.depth = int(dm / h)
self.Wq = tf.keras.layers.Dense(units=dm)
self.Wk = tf.keras.layers.Dense(units=dm)
self.Wv = tf.keras.layers.Dense(units=dm)
self.linear = tf.keras.layers.Dense(units=dm)... | class MultiHeadAttention | MultiHeadAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
"""class MultiHeadAttention"""
def __init__(self, dm, h):
"""Initializer. Args: dm: (int) representing the dimensionality of the model. h: (int) representing the number of heads."""
<|body_0|>
def call(self, Q, K, V, mask):
"""call method. Arg... | stack_v2_sparse_classes_36k_train_033044 | 2,042 | no_license | [
{
"docstring": "Initializer. Args: dm: (int) representing the dimensionality of the model. h: (int) representing the number of heads.",
"name": "__init__",
"signature": "def __init__(self, dm, h)"
},
{
"docstring": "call method. Args: Q: (tf.Tensor) containing the input to generate the query mat... | 2 | null | Implement the Python class `MultiHeadAttention` described below.
Class description:
class MultiHeadAttention
Method signatures and docstrings:
- def __init__(self, dm, h): Initializer. Args: dm: (int) representing the dimensionality of the model. h: (int) representing the number of heads.
- def call(self, Q, K, V, ma... | Implement the Python class `MultiHeadAttention` described below.
Class description:
class MultiHeadAttention
Method signatures and docstrings:
- def __init__(self, dm, h): Initializer. Args: dm: (int) representing the dimensionality of the model. h: (int) representing the number of heads.
- def call(self, Q, K, V, ma... | 75274394adb52d740f6cd4000cc00bbde44b9b72 | <|skeleton|>
class MultiHeadAttention:
"""class MultiHeadAttention"""
def __init__(self, dm, h):
"""Initializer. Args: dm: (int) representing the dimensionality of the model. h: (int) representing the number of heads."""
<|body_0|>
def call(self, Q, K, V, mask):
"""call method. Arg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadAttention:
"""class MultiHeadAttention"""
def __init__(self, dm, h):
"""Initializer. Args: dm: (int) representing the dimensionality of the model. h: (int) representing the number of heads."""
super().__init__()
self.h = h
self.dm = dm
self.depth = int(dm ... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/6-multihead_attention.py | jdarangop/holbertonschool-machine_learning | train | 2 |
ea65c601728bb1648b9e47ddd64905bdd914ddbf | [
"dwi, phasediff = (kwargs.pop('dwi_file'), kwargs.pop('phasediff_file'))\nkwargs['encoding_direction'] = [self.fix_phase_encoding(dwi.get_phase_encoding_direction()), self.fix_phase_encoding(phasediff.get_phase_encoding_direction())]\nkwargs['readout_times'] = [dwi.get_total_readout_time(), phasediff.get_total_read... | <|body_start_0|>
dwi, phasediff = (kwargs.pop('dwi_file'), kwargs.pop('phasediff_file'))
kwargs['encoding_direction'] = [self.fix_phase_encoding(dwi.get_phase_encoding_direction()), self.fix_phase_encoding(phasediff.get_phase_encoding_direction())]
kwargs['readout_times'] = [dwi.get_total_readou... | A simple subclass of nipype's :class:`~nipype.interfaces.fsl.TOPUP` interface, tweaking the interface's :meth:`__init__` method to make input specification easier. | TopupWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopupWrapper:
"""A simple subclass of nipype's :class:`~nipype.interfaces.fsl.TOPUP` interface, tweaking the interface's :meth:`__init__` method to make input specification easier."""
def __init__(self, *args, **kwargs):
"""Sets the *encoding_direction* and *readout_times* parameter ... | stack_v2_sparse_classes_36k_train_033045 | 1,582 | permissive | [
{
"docstring": "Sets the *encoding_direction* and *readout_times* parameter values using the provided :class:`~django_mri.models.nifti.NIfTI` instances.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Converts phase encoding values from *i, j, k* to *x... | 2 | null | Implement the Python class `TopupWrapper` described below.
Class description:
A simple subclass of nipype's :class:`~nipype.interfaces.fsl.TOPUP` interface, tweaking the interface's :meth:`__init__` method to make input specification easier.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set... | Implement the Python class `TopupWrapper` described below.
Class description:
A simple subclass of nipype's :class:`~nipype.interfaces.fsl.TOPUP` interface, tweaking the interface's :meth:`__init__` method to make input specification easier.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set... | 5b5ca1b119144d01e526825d2b2a2b87541b4d4a | <|skeleton|>
class TopupWrapper:
"""A simple subclass of nipype's :class:`~nipype.interfaces.fsl.TOPUP` interface, tweaking the interface's :meth:`__init__` method to make input specification easier."""
def __init__(self, *args, **kwargs):
"""Sets the *encoding_direction* and *readout_times* parameter ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopupWrapper:
"""A simple subclass of nipype's :class:`~nipype.interfaces.fsl.TOPUP` interface, tweaking the interface's :meth:`__init__` method to make input specification easier."""
def __init__(self, *args, **kwargs):
"""Sets the *encoding_direction* and *readout_times* parameter values using ... | the_stack_v2_python_sparse | django_mri/analysis/interfaces/fsl/topup.py | TheLabbingProject/django_mri | train | 7 |
f92ebd892ceaf62a969ac132bb47e0863aefc2df | [
"super().__init__(constants.CROSS_HAIR, 0.25)\nself.offset = 0\nself.cast = cast\nself.timer = time.time()\nself.slash_sound = arcade.load_sound(constants.HERO_SLASH_SOUND)\nself.hit_resource_sound = arcade.load_sound(constants.HERO_RESOURCE_SOUND)",
"if time.time() - self.timer >= 0.5:\n self.timer = time.tim... | <|body_start_0|>
super().__init__(constants.CROSS_HAIR, 0.25)
self.offset = 0
self.cast = cast
self.timer = time.time()
self.slash_sound = arcade.load_sound(constants.HERO_SLASH_SOUND)
self.hit_resource_sound = arcade.load_sound(constants.HERO_RESOURCE_SOUND)
<|end_body_0... | Melee | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Melee:
def __init__(self, cast):
"""Class constructor. Calls the constructor of the parent class. Args: self (Melee): an instance of Melee cast (dict): dictionary that holds all the actors"""
<|body_0|>
def attack(self):
"""Attack method. Attacks zombies. Args: self ... | stack_v2_sparse_classes_36k_train_033046 | 2,168 | no_license | [
{
"docstring": "Class constructor. Calls the constructor of the parent class. Args: self (Melee): an instance of Melee cast (dict): dictionary that holds all the actors",
"name": "__init__",
"signature": "def __init__(self, cast)"
},
{
"docstring": "Attack method. Attacks zombies. Args: self (Me... | 3 | stack_v2_sparse_classes_30k_train_013349 | Implement the Python class `Melee` described below.
Class description:
Implement the Melee class.
Method signatures and docstrings:
- def __init__(self, cast): Class constructor. Calls the constructor of the parent class. Args: self (Melee): an instance of Melee cast (dict): dictionary that holds all the actors
- def... | Implement the Python class `Melee` described below.
Class description:
Implement the Melee class.
Method signatures and docstrings:
- def __init__(self, cast): Class constructor. Calls the constructor of the parent class. Args: self (Melee): an instance of Melee cast (dict): dictionary that holds all the actors
- def... | 6826ac570c71499782a107e27624e71daba9ed84 | <|skeleton|>
class Melee:
def __init__(self, cast):
"""Class constructor. Calls the constructor of the parent class. Args: self (Melee): an instance of Melee cast (dict): dictionary that holds all the actors"""
<|body_0|>
def attack(self):
"""Attack method. Attacks zombies. Args: self ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Melee:
def __init__(self, cast):
"""Class constructor. Calls the constructor of the parent class. Args: self (Melee): an instance of Melee cast (dict): dictionary that holds all the actors"""
super().__init__(constants.CROSS_HAIR, 0.25)
self.offset = 0
self.cast = cast
... | the_stack_v2_python_sparse | towerz/game/melee.py | NolanMeacham/cse210-project | train | 0 | |
4f6ef00381dfaee813de6bb6d01b7c341fdafc6a | [
"complete = status == 'complete'\nsort = request.GET.get('sort', 'created_date')\nsort_fields = ['created_date', 'user']\nimports = models.ImportJob.objects.filter(complete=complete).order_by('created_date')\nif sort in sort_fields + ['-{:s}'.format(f) for f in sort_fields]:\n imports = imports.order_by(sort)\np... | <|body_start_0|>
complete = status == 'complete'
sort = request.GET.get('sort', 'created_date')
sort_fields = ['created_date', 'user']
imports = models.ImportJob.objects.filter(complete=complete).order_by('created_date')
if sort in sort_fields + ['-{:s}'.format(f) for f in sort_f... | admin view of imports on this server | ImportList | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportList:
"""admin view of imports on this server"""
def get(self, request, status='active'):
"""list of imports"""
<|body_0|>
def post(self, request, import_id):
"""Mark an import as complete"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
co... | stack_v2_sparse_classes_36k_train_033047 | 3,614 | no_license | [
{
"docstring": "list of imports",
"name": "get",
"signature": "def get(self, request, status='active')"
},
{
"docstring": "Mark an import as complete",
"name": "post",
"signature": "def post(self, request, import_id)"
}
] | 2 | null | Implement the Python class `ImportList` described below.
Class description:
admin view of imports on this server
Method signatures and docstrings:
- def get(self, request, status='active'): list of imports
- def post(self, request, import_id): Mark an import as complete | Implement the Python class `ImportList` described below.
Class description:
admin view of imports on this server
Method signatures and docstrings:
- def get(self, request, status='active'): list of imports
- def post(self, request, import_id): Mark an import as complete
<|skeleton|>
class ImportList:
"""admin vi... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class ImportList:
"""admin view of imports on this server"""
def get(self, request, status='active'):
"""list of imports"""
<|body_0|>
def post(self, request, import_id):
"""Mark an import as complete"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImportList:
"""admin view of imports on this server"""
def get(self, request, status='active'):
"""list of imports"""
complete = status == 'complete'
sort = request.GET.get('sort', 'created_date')
sort_fields = ['created_date', 'user']
imports = models.ImportJob.ob... | the_stack_v2_python_sparse | bookwyrm/views/admin/imports.py | bookwyrm-social/bookwyrm | train | 1,398 |
681773075555ff2154620de3be27fcba88eb59bc | [
"import boto\nfrom botoweb.environment import Environment\ne = Environment(self.application)\nself.env = e\nboto.config = self.env.config\nfrom botoweb.appserver.url_mapper import URLMapper\nfrom botoweb.appserver.filter_mapper import FilterMapper\nfrom botoweb.appserver.auth_layer import AuthLayer\nself.mapper = A... | <|body_start_0|>
import boto
from botoweb.environment import Environment
e = Environment(self.application)
self.env = e
boto.config = self.env.config
from botoweb.appserver.url_mapper import URLMapper
from botoweb.appserver.filter_mapper import FilterMapper
... | Testing base class, this provides some simple shared functionality for all classes to use. This emulates what would actually happen if you connected via the HTTP server without actually running the HTTP server. | TestBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBase:
"""Testing base class, this provides some simple shared functionality for all classes to use. This emulates what would actually happen if you connected via the HTTP server without actually running the HTTP server."""
def __init__(self):
"""Setup this class to handle testing... | stack_v2_sparse_classes_36k_train_033048 | 2,617 | no_license | [
{
"docstring": "Setup this class to handle testing",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Make a request to a given resource @param resource: The resource URI to fetch from (ex. /users) @type resource: str @param method: The HTTP/1.1 Method to use, (GET/PUT/DE... | 3 | stack_v2_sparse_classes_30k_train_018059 | Implement the Python class `TestBase` described below.
Class description:
Testing base class, this provides some simple shared functionality for all classes to use. This emulates what would actually happen if you connected via the HTTP server without actually running the HTTP server.
Method signatures and docstrings:... | Implement the Python class `TestBase` described below.
Class description:
Testing base class, this provides some simple shared functionality for all classes to use. This emulates what would actually happen if you connected via the HTTP server without actually running the HTTP server.
Method signatures and docstrings:... | 42f65f71d7a48cc09f92c5bb368a8105de78f42a | <|skeleton|>
class TestBase:
"""Testing base class, this provides some simple shared functionality for all classes to use. This emulates what would actually happen if you connected via the HTTP server without actually running the HTTP server."""
def __init__(self):
"""Setup this class to handle testing... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestBase:
"""Testing base class, this provides some simple shared functionality for all classes to use. This emulates what would actually happen if you connected via the HTTP server without actually running the HTTP server."""
def __init__(self):
"""Setup this class to handle testing"""
i... | the_stack_v2_python_sparse | botoweb/testbase.py | p3pijn/botoweb | train | 0 |
f89ada51cac44a510353917b7303911918fb30c9 | [
"self.surface = pygame.Surface(dim)\nself.rect = rect\nself.width = dim[0] // scale\nself.height = dim[1] // scale\nself.scale = scale\nself.drawsurface = pygame.Surface((self.width, self.height))\nself.drawsurface.fill((0, 0, 0))\nself.array2d = None\nself.fire = None\nself.palette = None\nself.initialize()",
"s... | <|body_start_0|>
self.surface = pygame.Surface(dim)
self.rect = rect
self.width = dim[0] // scale
self.height = dim[1] // scale
self.scale = scale
self.drawsurface = pygame.Surface((self.width, self.height))
self.drawsurface.fill((0, 0, 0))
self.array2d = ... | Simulated Fire, 2d effect idea and basic algorithm from http://lodev.org/cgtutor/fire.html | Fire | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fire:
"""Simulated Fire, 2d effect idea and basic algorithm from http://lodev.org/cgtutor/fire.html"""
def __init__(self, dim, rect, scale=4):
"""(pygame.surface) surface - to draw on (pygame.Rect) dest - rect to blit fire on (int) width - width of fire (int) height - height of fire ... | stack_v2_sparse_classes_36k_train_033049 | 4,189 | no_license | [
{
"docstring": "(pygame.surface) surface - to draw on (pygame.Rect) dest - rect to blit fire on (int) width - width of fire (int) height - height of fire (int) scale - scale fire",
"name": "__init__",
"signature": "def __init__(self, dim, rect, scale=4)"
},
{
"docstring": "generate palette and s... | 3 | stack_v2_sparse_classes_30k_test_001068 | Implement the Python class `Fire` described below.
Class description:
Simulated Fire, 2d effect idea and basic algorithm from http://lodev.org/cgtutor/fire.html
Method signatures and docstrings:
- def __init__(self, dim, rect, scale=4): (pygame.surface) surface - to draw on (pygame.Rect) dest - rect to blit fire on (... | Implement the Python class `Fire` described below.
Class description:
Simulated Fire, 2d effect idea and basic algorithm from http://lodev.org/cgtutor/fire.html
Method signatures and docstrings:
- def __init__(self, dim, rect, scale=4): (pygame.surface) surface - to draw on (pygame.Rect) dest - rect to blit fire on (... | 1fd421195a2888c0588a49f5a043a1110eedcdbf | <|skeleton|>
class Fire:
"""Simulated Fire, 2d effect idea and basic algorithm from http://lodev.org/cgtutor/fire.html"""
def __init__(self, dim, rect, scale=4):
"""(pygame.surface) surface - to draw on (pygame.Rect) dest - rect to blit fire on (int) width - width of fire (int) height - height of fire ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fire:
"""Simulated Fire, 2d effect idea and basic algorithm from http://lodev.org/cgtutor/fire.html"""
def __init__(self, dim, rect, scale=4):
"""(pygame.surface) surface - to draw on (pygame.Rect) dest - rect to blit fire on (int) width - width of fire (int) height - height of fire (int) scale -... | the_stack_v2_python_sparse | effects/Fire.py | gunny26/pygame | train | 5 |
1c0f8b2304f9f4080429d3311b63de439c5d28e4 | [
"slot = Slot.objects.create(business_id=business.id, site_id=business.advertiser.site.id, start_date=datetime.date(2011, 1, 1), end_date=datetime.date(2099, 1, 1))\nif parent_slot:\n slot.parent_slot_id = parent_slot.id\nelse:\n slot.parent_slot_id = slot.id\nslot.save()\nreturn slot",
"if not coupon:\n ... | <|body_start_0|>
slot = Slot.objects.create(business_id=business.id, site_id=business.advertiser.site.id, start_date=datetime.date(2011, 1, 1), end_date=datetime.date(2099, 1, 1))
if parent_slot:
slot.parent_slot_id = parent_slot.id
else:
slot.parent_slot_id = slot.id
... | Slot Factory Class | SlotFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlotFactory:
"""Slot Factory Class"""
def _create(business, parent_slot=None):
"""Create a single slot instance. If no parent_slot is passed in, this slot will be created as a parent. If a parent_slot is passed in, the slot will become a child of the parent."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_033050 | 6,089 | no_license | [
{
"docstring": "Create a single slot instance. If no parent_slot is passed in, this slot will be created as a parent. If a parent_slot is passed in, the slot will become a child of the parent.",
"name": "_create",
"signature": "def _create(business, parent_slot=None)"
},
{
"docstring": "Create a... | 6 | null | Implement the Python class `SlotFactory` described below.
Class description:
Slot Factory Class
Method signatures and docstrings:
- def _create(business, parent_slot=None): Create a single slot instance. If no parent_slot is passed in, this slot will be created as a parent. If a parent_slot is passed in, the slot wil... | Implement the Python class `SlotFactory` described below.
Class description:
Slot Factory Class
Method signatures and docstrings:
- def _create(business, parent_slot=None): Create a single slot instance. If no parent_slot is passed in, this slot will be created as a parent. If a parent_slot is passed in, the slot wil... | a780ccdc3350d4b5c7990c65d1af8d71060c62cc | <|skeleton|>
class SlotFactory:
"""Slot Factory Class"""
def _create(business, parent_slot=None):
"""Create a single slot instance. If no parent_slot is passed in, this slot will be created as a parent. If a parent_slot is passed in, the slot will become a child of the parent."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SlotFactory:
"""Slot Factory Class"""
def _create(business, parent_slot=None):
"""Create a single slot instance. If no parent_slot is passed in, this slot will be created as a parent. If a parent_slot is passed in, the slot will become a child of the parent."""
slot = Slot.objects.create(... | the_stack_v2_python_sparse | coupon/factories/slot_factory.py | wcirillo/ten | train | 0 |
06fa5eb377475ec063b4c10df95fe89990487693 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MobileThreatDefenseConnector()",
"from .entity import Entity\nfrom .mobile_threat_partner_tenant_state import MobileThreatPartnerTenantState\nfrom .entity import Entity\nfrom .mobile_threat_partner_tenant_state import MobileThreatPartn... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return MobileThreatDefenseConnector()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .mobile_threat_partner_tenant_state import MobileThreatPartnerTenantState
from .ent... | Entity which represents a connection to Mobile Threat Defense partner. | MobileThreatDefenseConnector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MobileThreatDefenseConnector:
"""Entity which represents a connection to Mobile Threat Defense partner."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MobileThreatDefenseConnector:
"""Creates a new instance of the appropriate class based on discrimina... | stack_v2_sparse_classes_36k_train_033051 | 10,079 | 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: MobileThreatDefenseConnector",
"name": "create_from_discriminator_value",
"signature": "def create_from_disc... | 3 | stack_v2_sparse_classes_30k_train_017124 | Implement the Python class `MobileThreatDefenseConnector` described below.
Class description:
Entity which represents a connection to Mobile Threat Defense partner.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MobileThreatDefenseConnector: Creates a ... | Implement the Python class `MobileThreatDefenseConnector` described below.
Class description:
Entity which represents a connection to Mobile Threat Defense partner.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MobileThreatDefenseConnector: Creates a ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class MobileThreatDefenseConnector:
"""Entity which represents a connection to Mobile Threat Defense partner."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MobileThreatDefenseConnector:
"""Creates a new instance of the appropriate class based on discrimina... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MobileThreatDefenseConnector:
"""Entity which represents a connection to Mobile Threat Defense partner."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MobileThreatDefenseConnector:
"""Creates a new instance of the appropriate class based on discriminator value Arg... | the_stack_v2_python_sparse | msgraph/generated/models/mobile_threat_defense_connector.py | microsoftgraph/msgraph-sdk-python | train | 135 |
c4de9cfe75f7fe7582a91c2661746e12d8d3a967 | [
"c = Counter()\nfor ch in s:\n c[ch] = c[ch] + 1\na = sorted(c.items(), key=lambda item: item[1], reverse=True)\nindex_dict = {k[0]: i for i, k in enumerate(a)}\nB_ordered = sorted(s, key=lambda x: index_dict[x])\nreturn ''.join(B_ordered)",
"count = dict()\nresult = ''\nsort = dict()\nfor c in s:\n if c no... | <|body_start_0|>
c = Counter()
for ch in s:
c[ch] = c[ch] + 1
a = sorted(c.items(), key=lambda item: item[1], reverse=True)
index_dict = {k[0]: i for i, k in enumerate(a)}
B_ordered = sorted(s, key=lambda x: index_dict[x])
return ''.join(B_ordered)
<|end_body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def frequencySort(self, s):
""":type s: str :rtype: str 175ms"""
<|body_0|>
def frequencySort_1(self, s):
""":type s: str :rtype: str 62ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
c = Counter()
for ch in s:
c[ch]... | stack_v2_sparse_classes_36k_train_033052 | 2,079 | no_license | [
{
"docstring": ":type s: str :rtype: str 175ms",
"name": "frequencySort",
"signature": "def frequencySort(self, s)"
},
{
"docstring": ":type s: str :rtype: str 62ms",
"name": "frequencySort_1",
"signature": "def frequencySort_1(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016622 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def frequencySort(self, s): :type s: str :rtype: str 175ms
- def frequencySort_1(self, s): :type s: str :rtype: str 62ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def frequencySort(self, s): :type s: str :rtype: str 175ms
- def frequencySort_1(self, s): :type s: str :rtype: str 62ms
<|skeleton|>
class Solution:
def frequencySort(self... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def frequencySort(self, s):
""":type s: str :rtype: str 175ms"""
<|body_0|>
def frequencySort_1(self, s):
""":type s: str :rtype: str 62ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def frequencySort(self, s):
""":type s: str :rtype: str 175ms"""
c = Counter()
for ch in s:
c[ch] = c[ch] + 1
a = sorted(c.items(), key=lambda item: item[1], reverse=True)
index_dict = {k[0]: i for i, k in enumerate(a)}
B_ordered = sorted(s... | the_stack_v2_python_sparse | SortCharactersByFrequency_MID_451.py | 953250587/leetcode-python | train | 2 | |
57cc5c465113c188088b9112ac1f07d1ac78c321 | [
"if root == None:\n return ''\nres = []\nqueue = [root]\nwhile queue:\n node = queue.pop(0)\n if node:\n queue.append(node.left)\n queue.append(node.right)\n res.append(str(node.val))\n else:\n res.append('#')\nreturn ','.join(res)",
"if not data:\n return None\nnode_col... | <|body_start_0|>
if root == None:
return ''
res = []
queue = [root]
while queue:
node = queue.pop(0)
if node:
queue.append(node.left)
queue.append(node.right)
res.append(str(node.val))
else:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_033053 | 2,418 | 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 deserialize... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: ... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: ... | 0a2e0e4a5176c02910d7718c42903d10a6c47a5f | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string :type root: TreeNode :rtype: str"""
if root == None:
return ''
res = []
queue = [root]
while queue:
node = queue.pop(0)
if node:
queue.append(node.... | the_stack_v2_python_sparse | serialize_deserialize_binary_tree.py | baichuan/Leetcode | train | 0 | |
24081bea73b4c503c2ea7969c412baef7baf5858 | [
"self.mask = mask\nself.n_inputs = n_inputs\nself.n_outputs = n_outputs\nself.s_hiddens = s_hiddens\nself.s_act = s_act\nself.t_hiddens = t_hiddens\nself.t_act = t_act\nmy = mask * y\nself.s_net = nn.FeedforwardNet(n_inputs + n_outputs, tt.concatenate([x, my], axis=1))\nfor h in s_hiddens:\n self.s_net.addLayer(... | <|body_start_0|>
self.mask = mask
self.n_inputs = n_inputs
self.n_outputs = n_outputs
self.s_hiddens = s_hiddens
self.s_act = s_act
self.t_hiddens = t_hiddens
self.t_act = t_act
my = mask * y
self.s_net = nn.FeedforwardNet(n_inputs + n_outputs, tt.... | Coupling layer for the conditional version of Real NVP. | ConditionalCouplingLayer | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionalCouplingLayer:
"""Coupling layer for the conditional version of Real NVP."""
def __init__(self, x, y, mask, n_inputs, n_outputs, s_hiddens, s_act, t_hiddens, t_act):
"""Constructor of the backward computation graph. :param x: theano array, the conditional input :param y: t... | stack_v2_sparse_classes_36k_train_033054 | 15,147 | permissive | [
{
"docstring": "Constructor of the backward computation graph. :param x: theano array, the conditional input :param y: theano array, the output :param mask: theano array, a mask indicating which outputs are unchanged :param n_inputs: int, number of conditional inputs :param n_outputs: int, number of outputs :pa... | 2 | stack_v2_sparse_classes_30k_train_010143 | Implement the Python class `ConditionalCouplingLayer` described below.
Class description:
Coupling layer for the conditional version of Real NVP.
Method signatures and docstrings:
- def __init__(self, x, y, mask, n_inputs, n_outputs, s_hiddens, s_act, t_hiddens, t_act): Constructor of the backward computation graph. ... | Implement the Python class `ConditionalCouplingLayer` described below.
Class description:
Coupling layer for the conditional version of Real NVP.
Method signatures and docstrings:
- def __init__(self, x, y, mask, n_inputs, n_outputs, s_hiddens, s_act, t_hiddens, t_act): Constructor of the backward computation graph. ... | d5fa619db637d19f0c3018aeb1431f657dd533bf | <|skeleton|>
class ConditionalCouplingLayer:
"""Coupling layer for the conditional version of Real NVP."""
def __init__(self, x, y, mask, n_inputs, n_outputs, s_hiddens, s_act, t_hiddens, t_act):
"""Constructor of the backward computation graph. :param x: theano array, the conditional input :param y: t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionalCouplingLayer:
"""Coupling layer for the conditional version of Real NVP."""
def __init__(self, x, y, mask, n_inputs, n_outputs, s_hiddens, s_act, t_hiddens, t_act):
"""Constructor of the backward computation graph. :param x: theano array, the conditional input :param y: theano array, ... | the_stack_v2_python_sparse | ml/models/nvps.py | gpapamak/maf | train | 199 |
c24a333d4228d3898e8d0ab20b12c8120265dd08 | [
"assert width > 0\nassert infiniteSide in {'L', 'R', None}\nself.left = lambda x: (x - xcenter) / width + 1\nself.leftBorder = (xcenter - width, xcenter)\nself.right = lambda x: -(x - xcenter) / width + 1\nself.rightBorder = (xcenter, xcenter + width)\nself.orientation = infiniteSide",
"if x >= self.rightBorder[1... | <|body_start_0|>
assert width > 0
assert infiniteSide in {'L', 'R', None}
self.left = lambda x: (x - xcenter) / width + 1
self.leftBorder = (xcenter - width, xcenter)
self.right = lambda x: -(x - xcenter) / width + 1
self.rightBorder = (xcenter, xcenter + width)
s... | Triangular fuzzy set. Attributes: left leftBorder right rightBorder orientation | TriangularSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriangularSet:
"""Triangular fuzzy set. Attributes: left leftBorder right rightBorder orientation"""
def __init__(self, width=1, xcenter=0, infiniteSide=None):
"""Constructor of TriangularSet. Arguments: width xcenter infiniteSide"""
<|body_0|>
def getLeftInfinite(self, ... | stack_v2_sparse_classes_36k_train_033055 | 7,372 | no_license | [
{
"docstring": "Constructor of TriangularSet. Arguments: width xcenter infiniteSide",
"name": "__init__",
"signature": "def __init__(self, width=1, xcenter=0, infiniteSide=None)"
},
{
"docstring": "Returns value from left side, if infinite. Arguments: x",
"name": "getLeftInfinite",
"sign... | 5 | null | Implement the Python class `TriangularSet` described below.
Class description:
Triangular fuzzy set. Attributes: left leftBorder right rightBorder orientation
Method signatures and docstrings:
- def __init__(self, width=1, xcenter=0, infiniteSide=None): Constructor of TriangularSet. Arguments: width xcenter infiniteS... | Implement the Python class `TriangularSet` described below.
Class description:
Triangular fuzzy set. Attributes: left leftBorder right rightBorder orientation
Method signatures and docstrings:
- def __init__(self, width=1, xcenter=0, infiniteSide=None): Constructor of TriangularSet. Arguments: width xcenter infiniteS... | 1c2c3abe50bd9125b105ffd13eef513839f3f9d8 | <|skeleton|>
class TriangularSet:
"""Triangular fuzzy set. Attributes: left leftBorder right rightBorder orientation"""
def __init__(self, width=1, xcenter=0, infiniteSide=None):
"""Constructor of TriangularSet. Arguments: width xcenter infiniteSide"""
<|body_0|>
def getLeftInfinite(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TriangularSet:
"""Triangular fuzzy set. Attributes: left leftBorder right rightBorder orientation"""
def __init__(self, width=1, xcenter=0, infiniteSide=None):
"""Constructor of TriangularSet. Arguments: width xcenter infiniteSide"""
assert width > 0
assert infiniteSide in {'L', '... | the_stack_v2_python_sparse | monitor/fuzzy.py | martinbenes1996/bc | train | 0 |
f3ee67d773833e82f7e5d3e446f7f2e311d5e119 | [
"email = self.cleaned_data.get('email')\nif not User.objects.filter(email=email):\n raise forms.ValidationError('该邮箱没有被注册, 请重新输入')\nreturn email",
"password = self.cleaned_data.get('password')\npassword_2 = self.cleaned_data.get('password_2')\nif password != password_2:\n raise forms.ValidationError('两次密码输入... | <|body_start_0|>
email = self.cleaned_data.get('email')
if not User.objects.filter(email=email):
raise forms.ValidationError('该邮箱没有被注册, 请重新输入')
return email
<|end_body_0|>
<|body_start_1|>
password = self.cleaned_data.get('password')
password_2 = self.cleaned_data.ge... | ForgetPwdForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForgetPwdForm:
def clean_email(self):
"""验证邮箱字段"""
<|body_0|>
def clean_password_2(self):
"""验证码密码一致"""
<|body_1|>
def clean_check_code(self):
"""验证验证码是否正确"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
email = self.cleaned_dat... | stack_v2_sparse_classes_36k_train_033056 | 7,045 | permissive | [
{
"docstring": "验证邮箱字段",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "验证码密码一致",
"name": "clean_password_2",
"signature": "def clean_password_2(self)"
},
{
"docstring": "验证验证码是否正确",
"name": "clean_check_code",
"signature": "def clean_check... | 3 | stack_v2_sparse_classes_30k_test_000847 | Implement the Python class `ForgetPwdForm` described below.
Class description:
Implement the ForgetPwdForm class.
Method signatures and docstrings:
- def clean_email(self): 验证邮箱字段
- def clean_password_2(self): 验证码密码一致
- def clean_check_code(self): 验证验证码是否正确 | Implement the Python class `ForgetPwdForm` described below.
Class description:
Implement the ForgetPwdForm class.
Method signatures and docstrings:
- def clean_email(self): 验证邮箱字段
- def clean_password_2(self): 验证码密码一致
- def clean_check_code(self): 验证验证码是否正确
<|skeleton|>
class ForgetPwdForm:
def clean_email(self... | 043889688c2ed55884b8ddde9cdf6949ee52f905 | <|skeleton|>
class ForgetPwdForm:
def clean_email(self):
"""验证邮箱字段"""
<|body_0|>
def clean_password_2(self):
"""验证码密码一致"""
<|body_1|>
def clean_check_code(self):
"""验证验证码是否正确"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ForgetPwdForm:
def clean_email(self):
"""验证邮箱字段"""
email = self.cleaned_data.get('email')
if not User.objects.filter(email=email):
raise forms.ValidationError('该邮箱没有被注册, 请重新输入')
return email
def clean_password_2(self):
"""验证码密码一致"""
password = s... | the_stack_v2_python_sparse | user/forms.py | guojy1314/stw1209 | train | 0 | |
6a98f55297744e78bb9f9b18aace527e3f882fbe | [
"gobject.GObject.__init__(self)\nself.__root = gio.File(root_dir)\nself.__monitored = False\nself.__monitors = {}\nself.__queue = []\nself.__lock = threading.RLock()",
"if property.name == 'monitored':\n return self.__monitored\nelse:\n raise AttributeError('unkown property %s' % property.name)",
"if prop... | <|body_start_0|>
gobject.GObject.__init__(self)
self.__root = gio.File(root_dir)
self.__monitored = False
self.__monitors = {}
self.__queue = []
self.__lock = threading.RLock()
<|end_body_0|>
<|body_start_1|>
if property.name == 'monitored':
return se... | Monitors library locations for changes | LibraryMonitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryMonitor:
"""Monitors library locations for changes"""
def __init__(self, root_dir):
""":param library: the library to monitor :type library: :class:`Library`"""
<|body_0|>
def do_get_property(self, property):
"""Gets GObject properties"""
<|body_1|... | stack_v2_sparse_classes_36k_train_033057 | 4,974 | no_license | [
{
"docstring": ":param library: the library to monitor :type library: :class:`Library`",
"name": "__init__",
"signature": "def __init__(self, root_dir)"
},
{
"docstring": "Gets GObject properties",
"name": "do_get_property",
"signature": "def do_get_property(self, property)"
},
{
... | 5 | null | Implement the Python class `LibraryMonitor` described below.
Class description:
Monitors library locations for changes
Method signatures and docstrings:
- def __init__(self, root_dir): :param library: the library to monitor :type library: :class:`Library`
- def do_get_property(self, property): Gets GObject properties... | Implement the Python class `LibraryMonitor` described below.
Class description:
Monitors library locations for changes
Method signatures and docstrings:
- def __init__(self, root_dir): :param library: the library to monitor :type library: :class:`Library`
- def do_get_property(self, property): Gets GObject properties... | 1b83a035a4dfd57a2ba87c453f6b394d506c98f1 | <|skeleton|>
class LibraryMonitor:
"""Monitors library locations for changes"""
def __init__(self, root_dir):
""":param library: the library to monitor :type library: :class:`Library`"""
<|body_0|>
def do_get_property(self, property):
"""Gets GObject properties"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LibraryMonitor:
"""Monitors library locations for changes"""
def __init__(self, root_dir):
""":param library: the library to monitor :type library: :class:`Library`"""
gobject.GObject.__init__(self)
self.__root = gio.File(root_dir)
self.__monitored = False
self.__m... | the_stack_v2_python_sparse | modules/individuation/src/monitor.py | electricface/deepin-system-settings | train | 0 |
5542b90fccd52b06da458f3baf60faf126d05868 | [
"self.time = deque()\nself.lookup = defaultdict(int)\nself.now = 0",
"while self.time and timestamp - self.time[-1] + 1 > 300:\n self.lookup.pop(self.time.pop())\nif timestamp > self.now:\n self.time.appendleft(timestamp)\n self.now = timestamp\nself.lookup[timestamp] += 1",
"while self.time and timest... | <|body_start_0|>
self.time = deque()
self.lookup = defaultdict(int)
self.now = 0
<|end_body_0|>
<|body_start_1|>
while self.time and timestamp - self.time[-1] + 1 > 300:
self.lookup.pop(self.time.pop())
if timestamp > self.now:
self.time.appendleft(timest... | HitCounter1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HitCounter1:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: i... | stack_v2_sparse_classes_36k_train_033058 | 1,884 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Record a hit. @param timestamp - The current timestamp (in seconds granularity).",
"name": "hit",
"signature": "def hit(self, timestamp: int) -> None"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_020702 | Implement the Python class `HitCounter1` described below.
Class description:
Implement the HitCounter1 class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granula... | Implement the Python class `HitCounter1` described below.
Class description:
Implement the HitCounter1 class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granula... | 631df2ce6892a6fbb3e435f57e90d85f8200d125 | <|skeleton|>
class HitCounter1:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HitCounter1:
def __init__(self):
"""Initialize your data structure here."""
self.time = deque()
self.lookup = defaultdict(int)
self.now = 0
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""... | the_stack_v2_python_sparse | 362. Design Hit Counter.py | c940606/leetcode | train | 3 | |
c090d4629aa082c25e3ef7af3d6b20f82e4bf8a4 | [
"tip_label1 = widgets.Label(u'最优参数grid search暂不支持实时网络数据模式', layout=widgets.Layout(width='300px'))\ntip_label2 = widgets.Label(u\"非沙盒模式需先用'数据下载界面操作'进行下载\", layout=widgets.Layout(width='300px'))\n'沙盒数据与开放数据模式切换'\nself.date_mode = widgets.RadioButtons(options=[u'沙盒数据模式', u'开放数据模式'], value=u'沙盒数据模式' if ABuEnv._g_enable... | <|body_start_0|>
tip_label1 = widgets.Label(u'最优参数grid search暂不支持实时网络数据模式', layout=widgets.Layout(width='300px'))
tip_label2 = widgets.Label(u"非沙盒模式需先用'数据下载界面操作'进行下载", layout=widgets.Layout(width='300px'))
'沙盒数据与开放数据模式切换'
self.date_mode = widgets.RadioButtons(options=[u'沙盒数据模式', u'开放数据模式... | 策略最优参数grid search | WidgetGridSearch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WidgetGridSearch:
"""策略最优参数grid search"""
def __init__(self):
"""构建回测需要的各个组件形成tab"""
<|body_0|>
def on_data_mode_change(self, change):
"""沙盒与非沙盒数据界面操作转换"""
<|body_1|>
def run_grid_search(self, bt):
"""运行回测所对应的button按钮"""
<|body_2|>
<... | stack_v2_sparse_classes_36k_train_033059 | 4,321 | permissive | [
{
"docstring": "构建回测需要的各个组件形成tab",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "沙盒与非沙盒数据界面操作转换",
"name": "on_data_mode_change",
"signature": "def on_data_mode_change(self, change)"
},
{
"docstring": "运行回测所对应的button按钮",
"name": "run_grid_search",
... | 3 | stack_v2_sparse_classes_30k_train_013462 | Implement the Python class `WidgetGridSearch` described below.
Class description:
策略最优参数grid search
Method signatures and docstrings:
- def __init__(self): 构建回测需要的各个组件形成tab
- def on_data_mode_change(self, change): 沙盒与非沙盒数据界面操作转换
- def run_grid_search(self, bt): 运行回测所对应的button按钮 | Implement the Python class `WidgetGridSearch` described below.
Class description:
策略最优参数grid search
Method signatures and docstrings:
- def __init__(self): 构建回测需要的各个组件形成tab
- def on_data_mode_change(self, change): 沙盒与非沙盒数据界面操作转换
- def run_grid_search(self, bt): 运行回测所对应的button按钮
<|skeleton|>
class WidgetGridSearch:
... | 2e5ab17f2d20deb3c68c927f6208ea89db7c639d | <|skeleton|>
class WidgetGridSearch:
"""策略最优参数grid search"""
def __init__(self):
"""构建回测需要的各个组件形成tab"""
<|body_0|>
def on_data_mode_change(self, change):
"""沙盒与非沙盒数据界面操作转换"""
<|body_1|>
def run_grid_search(self, bt):
"""运行回测所对应的button按钮"""
<|body_2|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WidgetGridSearch:
"""策略最优参数grid search"""
def __init__(self):
"""构建回测需要的各个组件形成tab"""
tip_label1 = widgets.Label(u'最优参数grid search暂不支持实时网络数据模式', layout=widgets.Layout(width='300px'))
tip_label2 = widgets.Label(u"非沙盒模式需先用'数据下载界面操作'进行下载", layout=widgets.Layout(width='300px'))
... | the_stack_v2_python_sparse | abupy/WidgetBu/ABuWGGridSearch.py | luqin/firefly | train | 1 |
28c96e5372d64aa3050c4941c40b0dc74448f081 | [
"self.id = id\nself.mark_node_for_removal = mark_node_for_removal\nself.timestamp_secs = timestamp_secs\nself.validation_checks = validation_checks",
"if dictionary is None:\n return None\nid = dictionary.get('id')\nmark_node_for_removal = dictionary.get('markNodeForRemoval')\ntimestamp_secs = dictionary.get('... | <|body_start_0|>
self.id = id
self.mark_node_for_removal = mark_node_for_removal
self.timestamp_secs = timestamp_secs
self.validation_checks = validation_checks
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
id = dictionary.get('id')
... | Implementation of the 'NodeDeleteResult' model. NodeDeleteResult specifies response for mark node for removal Attributes: id (long|int): Id of the node to be marked for deletion. mark_node_for_removal (bool): MarkNodeForRemoval indicates if the node is marked for removal timestamp_secs (long|int): TimestampSecs specifi... | NodeDeleteResult | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeDeleteResult:
"""Implementation of the 'NodeDeleteResult' model. NodeDeleteResult specifies response for mark node for removal Attributes: id (long|int): Id of the node to be marked for deletion. mark_node_for_removal (bool): MarkNodeForRemoval indicates if the node is marked for removal time... | stack_v2_sparse_classes_36k_train_033060 | 2,719 | permissive | [
{
"docstring": "Constructor for the NodeDeleteResult class",
"name": "__init__",
"signature": "def __init__(self, id=None, mark_node_for_removal=None, timestamp_secs=None, validation_checks=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary... | 2 | null | Implement the Python class `NodeDeleteResult` described below.
Class description:
Implementation of the 'NodeDeleteResult' model. NodeDeleteResult specifies response for mark node for removal Attributes: id (long|int): Id of the node to be marked for deletion. mark_node_for_removal (bool): MarkNodeForRemoval indicates... | Implement the Python class `NodeDeleteResult` described below.
Class description:
Implementation of the 'NodeDeleteResult' model. NodeDeleteResult specifies response for mark node for removal Attributes: id (long|int): Id of the node to be marked for deletion. mark_node_for_removal (bool): MarkNodeForRemoval indicates... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NodeDeleteResult:
"""Implementation of the 'NodeDeleteResult' model. NodeDeleteResult specifies response for mark node for removal Attributes: id (long|int): Id of the node to be marked for deletion. mark_node_for_removal (bool): MarkNodeForRemoval indicates if the node is marked for removal time... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NodeDeleteResult:
"""Implementation of the 'NodeDeleteResult' model. NodeDeleteResult specifies response for mark node for removal Attributes: id (long|int): Id of the node to be marked for deletion. mark_node_for_removal (bool): MarkNodeForRemoval indicates if the node is marked for removal timestamp_secs (l... | the_stack_v2_python_sparse | cohesity_management_sdk/models/node_delete_result.py | cohesity/management-sdk-python | train | 24 |
5bda47ff86146e4e4045ff37c948c93e7515fc45 | [
"if query:\n search_vector = QueryService.build_search_vector(search_structure)\n term_query = SearchQuery(query)\n results = query_set.annotate(rank=SearchRank(search_vector, term_query)).filter(rank__gte=0.1).order_by('-rank')\nelse:\n results = query_set.all()\nreturn results",
"if search_structure... | <|body_start_0|>
if query:
search_vector = QueryService.build_search_vector(search_structure)
term_query = SearchQuery(query)
results = query_set.annotate(rank=SearchRank(search_vector, term_query)).filter(rank__gte=0.1).order_by('-rank')
else:
results = q... | Service class for query related operations | QueryService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueryService:
"""Service class for query related operations"""
def get_query_results(query_set, query, search_structure):
"""Returns the list of relevant results for the searched query :param query_set: QuerySet of the data to be searched :param query: Query with keywords to be used ... | stack_v2_sparse_classes_36k_train_033061 | 2,343 | no_license | [
{
"docstring": "Returns the list of relevant results for the searched query :param query_set: QuerySet of the data to be searched :param query: Query with keywords to be used in search :param search_structure: List of fields to search on and respective weight :return: list of models order by relevance for the s... | 3 | null | Implement the Python class `QueryService` described below.
Class description:
Service class for query related operations
Method signatures and docstrings:
- def get_query_results(query_set, query, search_structure): Returns the list of relevant results for the searched query :param query_set: QuerySet of the data to ... | Implement the Python class `QueryService` described below.
Class description:
Service class for query related operations
Method signatures and docstrings:
- def get_query_results(query_set, query, search_structure): Returns the list of relevant results for the searched query :param query_set: QuerySet of the data to ... | 941e8b2870f8724db3d5103dda5157fd597cfcc7 | <|skeleton|>
class QueryService:
"""Service class for query related operations"""
def get_query_results(query_set, query, search_structure):
"""Returns the list of relevant results for the searched query :param query_set: QuerySet of the data to be searched :param query: Query with keywords to be used ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QueryService:
"""Service class for query related operations"""
def get_query_results(query_set, query, search_structure):
"""Returns the list of relevant results for the searched query :param query_set: QuerySet of the data to be searched :param query: Query with keywords to be used in search :pa... | the_stack_v2_python_sparse | backend/martin_helder/services/query_service.py | JoaoAlvaroFerreira/FEUP-LGP | train | 1 |
92b3da3313cd58985eebbb4ccc4ae21c47b865b4 | [
"self.stevens: Repository = Repository('R:\\\\Stevens\\\\Sem-2\\\\SSW-810\\\\HW_11_Rohan_Ratwani', 'R:\\\\Stevens\\\\Sem-2\\\\SSW-810\\\\HW_11_Rohan_Ratwani\\\\810_Assignments.db')\ncalculated: List = [['10103', 'Jobs, S', ['CS 501', 'SSW 810'], ['SSW 540', 'SSW 555'], [], 3.38], ['10115', 'Bezos, J', ['SSW 810'], ... | <|body_start_0|>
self.stevens: Repository = Repository('R:\\Stevens\\Sem-2\\SSW-810\\HW_11_Rohan_Ratwani', 'R:\\Stevens\\Sem-2\\SSW-810\\HW_11_Rohan_Ratwani\\810_Assignments.db')
calculated: List = [['10103', 'Jobs, S', ['CS 501', 'SSW 810'], ['SSW 540', 'SSW 555'], [], 3.38], ['10115', 'Bezos, J', ['SS... | Helps to test all the functions | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
"""Helps to test all the functions"""
def test_data_for_Student(self):
"""This function is used to test data_for_student function's output"""
<|body_0|>
def test_data_for_Instructor(self):
"""This function is used to test data_for_instructor function's outp... | stack_v2_sparse_classes_36k_train_033062 | 3,623 | no_license | [
{
"docstring": "This function is used to test data_for_student function's output",
"name": "test_data_for_Student",
"signature": "def test_data_for_Student(self)"
},
{
"docstring": "This function is used to test data_for_instructor function's output",
"name": "test_data_for_Instructor",
... | 4 | stack_v2_sparse_classes_30k_train_007722 | Implement the Python class `Test` described below.
Class description:
Helps to test all the functions
Method signatures and docstrings:
- def test_data_for_Student(self): This function is used to test data_for_student function's output
- def test_data_for_Instructor(self): This function is used to test data_for_instr... | Implement the Python class `Test` described below.
Class description:
Helps to test all the functions
Method signatures and docstrings:
- def test_data_for_Student(self): This function is used to test data_for_student function's output
- def test_data_for_Instructor(self): This function is used to test data_for_instr... | 7fe7bb8518584cc98f00f16d6b1cd0a288254ee3 | <|skeleton|>
class Test:
"""Helps to test all the functions"""
def test_data_for_Student(self):
"""This function is used to test data_for_student function's output"""
<|body_0|>
def test_data_for_Instructor(self):
"""This function is used to test data_for_instructor function's outp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
"""Helps to test all the functions"""
def test_data_for_Student(self):
"""This function is used to test data_for_student function's output"""
self.stevens: Repository = Repository('R:\\Stevens\\Sem-2\\SSW-810\\HW_11_Rohan_Ratwani', 'R:\\Stevens\\Sem-2\\SSW-810\\HW_11_Rohan_Ratwani\\... | the_stack_v2_python_sparse | HW_11_Rohan_Ratwani/Student_Repository_Test_Rohan_Ratwani.py | RohanRatwani/SSW-810 | train | 0 |
4377d79f27e850611420a7cf846a384261787060 | [
"PPI.__init__(self, filename, sql_connection, 'bossi', 'Gene1', 'Gene2', 'ensembl')\nself.has_header = True\nself.file_field_seperator = '\\t'",
"src_table = self.get_cur_tmp_table()\ndst_table = self.next_tmp_table()\nsqlquery = 'SELECT Gene1, Gene2 FROM ' + src_table\nsql.new_table_from_query(dst_table, sqlquer... | <|body_start_0|>
PPI.__init__(self, filename, sql_connection, 'bossi', 'Gene1', 'Gene2', 'ensembl')
self.has_header = True
self.file_field_seperator = '\t'
<|end_body_0|>
<|body_start_1|>
src_table = self.get_cur_tmp_table()
dst_table = self.next_tmp_table()
sqlquery = '... | The PPI network from the Bossi and Lehner paper: http://www.ncbi.nlm.nih.gov/pubmed/19357639 This is a combined network from multiple sources. | Bossi_Lehner | [
"CC-BY-4.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bossi_Lehner:
"""The PPI network from the Bossi and Lehner paper: http://www.ncbi.nlm.nih.gov/pubmed/19357639 This is a combined network from multiple sources."""
def __init__(self, filename, sql_connection):
"""Creates a new PPI network, with the given filename and sql connection ob... | stack_v2_sparse_classes_36k_train_033063 | 1,392 | permissive | [
{
"docstring": "Creates a new PPI network, with the given filename and sql connection object. Parameter: - filename: Filename of the ppi network file. - sql_connection: SQL connection object for the database, into which the PPI network is to be imported.",
"name": "__init__",
"signature": "def __init__(... | 2 | stack_v2_sparse_classes_30k_train_000466 | Implement the Python class `Bossi_Lehner` described below.
Class description:
The PPI network from the Bossi and Lehner paper: http://www.ncbi.nlm.nih.gov/pubmed/19357639 This is a combined network from multiple sources.
Method signatures and docstrings:
- def __init__(self, filename, sql_connection): Creates a new P... | Implement the Python class `Bossi_Lehner` described below.
Class description:
The PPI network from the Bossi and Lehner paper: http://www.ncbi.nlm.nih.gov/pubmed/19357639 This is a combined network from multiple sources.
Method signatures and docstrings:
- def __init__(self, filename, sql_connection): Creates a new P... | b0a08c412bf4986cc49ee388f5160851147cb7fe | <|skeleton|>
class Bossi_Lehner:
"""The PPI network from the Bossi and Lehner paper: http://www.ncbi.nlm.nih.gov/pubmed/19357639 This is a combined network from multiple sources."""
def __init__(self, filename, sql_connection):
"""Creates a new PPI network, with the given filename and sql connection ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bossi_Lehner:
"""The PPI network from the Bossi and Lehner paper: http://www.ncbi.nlm.nih.gov/pubmed/19357639 This is a combined network from multiple sources."""
def __init__(self, filename, sql_connection):
"""Creates a new PPI network, with the given filename and sql connection object. Paramet... | the_stack_v2_python_sparse | src/pappi/ppis/bossi_lehner.py | gattofrancesco/tsppi | train | 0 |
9f36fc4dee7fef4ff76ff39992ba012bcf394447 | [
"feature = FeatureDB.get(id)\nif not feature:\n return abort(message='Feature not found', code=HTTPStatus.NOT_FOUND)\nreturn (feature, HTTPStatus.OK)",
"feature = FeatureDB.get(id)\nif not feature:\n return abort(message='Feature not found', code=HTTPStatus.NOT_FOUND)\nfeature.update(api.payload)\nfeature.a... | <|body_start_0|>
feature = FeatureDB.get(id)
if not feature:
return abort(message='Feature not found', code=HTTPStatus.NOT_FOUND)
return (feature, HTTPStatus.OK)
<|end_body_0|>
<|body_start_1|>
feature = FeatureDB.get(id)
if not feature:
return abort(mess... | Get, Update and Delete feature. | Feature | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Feature:
"""Get, Update and Delete feature."""
def get(self, id):
"""Get feature"""
<|body_0|>
def put(self, id):
"""Update feature"""
<|body_1|>
def delete(self, id):
"""Delete feature"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_033064 | 3,855 | permissive | [
{
"docstring": "Get feature",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Update feature",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "Delete feature",
"name": "delete",
"signature": "def delete(self, id)"
}
] | 3 | stack_v2_sparse_classes_30k_train_000358 | Implement the Python class `Feature` described below.
Class description:
Get, Update and Delete feature.
Method signatures and docstrings:
- def get(self, id): Get feature
- def put(self, id): Update feature
- def delete(self, id): Delete feature | Implement the Python class `Feature` described below.
Class description:
Get, Update and Delete feature.
Method signatures and docstrings:
- def get(self, id): Get feature
- def put(self, id): Update feature
- def delete(self, id): Delete feature
<|skeleton|>
class Feature:
"""Get, Update and Delete feature."""
... | 18e9ed6d2a660a9fe188881d4af79af3638cdd73 | <|skeleton|>
class Feature:
"""Get, Update and Delete feature."""
def get(self, id):
"""Get feature"""
<|body_0|>
def put(self, id):
"""Update feature"""
<|body_1|>
def delete(self, id):
"""Delete feature"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Feature:
"""Get, Update and Delete feature."""
def get(self, id):
"""Get feature"""
feature = FeatureDB.get(id)
if not feature:
return abort(message='Feature not found', code=HTTPStatus.NOT_FOUND)
return (feature, HTTPStatus.OK)
def put(self, id):
... | the_stack_v2_python_sparse | requester/api/endpoints/features.py | mrf345/flask_restful_api_production_example | train | 1 |
9e8ed5d5cb61967ca3dc653d8df4a343ec056ae3 | [
"validSet = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}\nline = [[] for _ in range(9)]\nrow = [[] for _ in range(9)]\nbox = [[] for _ in range(9)]\nfor x in range(9):\n for y in range(9):\n data = board[x][y]\n z = x // 3 + 3 * (y // 3)\n if data == '.':\n pass\n elif dat... | <|body_start_0|>
validSet = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}
line = [[] for _ in range(9)]
row = [[] for _ in range(9)]
box = [[] for _ in range(9)]
for x in range(9):
for y in range(9):
data = board[x][y]
z = x // 3 + 3 * ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidSudoku(self, board):
""":type board: List[List[str]] :rtype: bool"""
<|body_0|>
def isValidSudoku1(self, board):
""":type board: List[List[str]] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
validSet = {'1', '2', ... | stack_v2_sparse_classes_36k_train_033065 | 2,183 | no_license | [
{
"docstring": ":type board: List[List[str]] :rtype: bool",
"name": "isValidSudoku",
"signature": "def isValidSudoku(self, board)"
},
{
"docstring": ":type board: List[List[str]] :rtype: bool",
"name": "isValidSudoku1",
"signature": "def isValidSudoku1(self, board)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012387 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidSudoku(self, board): :type board: List[List[str]] :rtype: bool
- def isValidSudoku1(self, board): :type board: List[List[str]] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidSudoku(self, board): :type board: List[List[str]] :rtype: bool
- def isValidSudoku1(self, board): :type board: List[List[str]] :rtype: bool
<|skeleton|>
class Solutio... | 863b89be674a82eef60c0f33d726ac08d43f2e01 | <|skeleton|>
class Solution:
def isValidSudoku(self, board):
""":type board: List[List[str]] :rtype: bool"""
<|body_0|>
def isValidSudoku1(self, board):
""":type board: List[List[str]] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isValidSudoku(self, board):
""":type board: List[List[str]] :rtype: bool"""
validSet = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}
line = [[] for _ in range(9)]
row = [[] for _ in range(9)]
box = [[] for _ in range(9)]
for x in range(9):
... | the_stack_v2_python_sparse | q36_Valid_Sudoku.py | Ryuya1995/leetcode | train | 0 | |
28c7565cb588438c403d9c51a49e43678b3ac228 | [
"self.bottomleft = []\nself.areas = []\ntotal = 0\nfor rect in rects:\n x1, y1, x2, y2 = rect\n self.bottomleft.append([x1, y1, x2 - x1 + 1])\n total += (y2 - y1 + 1) * (x2 - x1 + 1)\n self.areas.append(total)",
"if not self.bottomleft:\n return []\nn = random.randint(1, self.areas[-1])\ni = bisect... | <|body_start_0|>
self.bottomleft = []
self.areas = []
total = 0
for rect in rects:
x1, y1, x2, y2 = rect
self.bottomleft.append([x1, y1, x2 - x1 + 1])
total += (y2 - y1 + 1) * (x2 - x1 + 1)
self.areas.append(total)
<|end_body_0|>
<|body_st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.bottomleft = []
self.areas = []
total = 0
for rect i... | stack_v2_sparse_classes_36k_train_033066 | 2,440 | no_license | [
{
"docstring": ":type rects: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016895 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: ... | 188befbfb7080ba1053ee1f7187b177b64cf42d2 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.bottomleft = []
self.areas = []
total = 0
for rect in rects:
x1, y1, x2, y2 = rect
self.bottomleft.append([x1, y1, x2 - x1 + 1])
total += (y2 - y1 + 1) * (x2... | the_stack_v2_python_sparse | 0497. Random Point in Non-overlapping Rectangles.py | pwang867/LeetCode-Solutions-Python | train | 0 | |
5473cd67a43aeac7ba032a27f3cbf8e0654f8f17 | [
"l, r = (0, len(A) - 1)\nwhile l < r:\n mid = int((l + r) / 2)\n if len(A) - 1 > mid > 0 and A[mid + 1] < A[mid] > A[mid - 1]:\n return mid\n elif A[mid] < A[mid + 1]:\n l = mid + 1\n elif A[mid] < A[mid - 1]:\n r = mid - 1\nreturn l",
"l, r = (0, len(A))\nwhile l < r:\n mid = ... | <|body_start_0|>
l, r = (0, len(A) - 1)
while l < r:
mid = int((l + r) / 2)
if len(A) - 1 > mid > 0 and A[mid + 1] < A[mid] > A[mid - 1]:
return mid
elif A[mid] < A[mid + 1]:
l = mid + 1
elif A[mid] < A[mid - 1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def peakIndexInMountainArray(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def peakIndexInMountainArray2(self, A):
"""2020.02.23: Binary search."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l, r = (0, len(A) - 1)
whi... | stack_v2_sparse_classes_36k_train_033067 | 2,067 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int",
"name": "peakIndexInMountainArray",
"signature": "def peakIndexInMountainArray(self, A)"
},
{
"docstring": "2020.02.23: Binary search.",
"name": "peakIndexInMountainArray2",
"signature": "def peakIndexInMountainArray2(self, A)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def peakIndexInMountainArray(self, A): :type A: List[int] :rtype: int
- def peakIndexInMountainArray2(self, A): 2020.02.23: Binary search. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def peakIndexInMountainArray(self, A): :type A: List[int] :rtype: int
- def peakIndexInMountainArray2(self, A): 2020.02.23: Binary search.
<|skeleton|>
class Solution:
def ... | a5b02044ef39154b6a8d32eb57682f447e1632ba | <|skeleton|>
class Solution:
def peakIndexInMountainArray(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def peakIndexInMountainArray2(self, A):
"""2020.02.23: Binary search."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def peakIndexInMountainArray(self, A):
""":type A: List[int] :rtype: int"""
l, r = (0, len(A) - 1)
while l < r:
mid = int((l + r) / 2)
if len(A) - 1 > mid > 0 and A[mid + 1] < A[mid] > A[mid - 1]:
return mid
elif A[mid] < A[... | the_stack_v2_python_sparse | algo/binary_search/peak_index_in_a_mountain_array.py | xys234/coding-problems | train | 0 | |
0b064402621ad2117faf228067a0d9c6b7c264da | [
"vertex_x_coords_padded, vertex_y_coords_padded = shape_utils.pad_polyline(POLYLINE_X_COORDS, POLYLINE_Y_COORDS, num_padding_vertices=1)\nself.assertTrue(numpy.allclose(vertex_x_coords_padded, POLYLINE_X_COORDS_PADDED1, atol=TOLERANCE))\nself.assertTrue(numpy.allclose(vertex_y_coords_padded, POLYLINE_Y_COORDS_PADDE... | <|body_start_0|>
vertex_x_coords_padded, vertex_y_coords_padded = shape_utils.pad_polyline(POLYLINE_X_COORDS, POLYLINE_Y_COORDS, num_padding_vertices=1)
self.assertTrue(numpy.allclose(vertex_x_coords_padded, POLYLINE_X_COORDS_PADDED1, atol=TOLERANCE))
self.assertTrue(numpy.allclose(vertex_y_coor... | Each method is a unit test for shape_utils.py. | ShapeUtilsTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShapeUtilsTests:
"""Each method is a unit test for shape_utils.py."""
def test_pad_polyline_1vertex(self):
"""Ensures correct output from pad_polyline with one padding vertex."""
<|body_0|>
def test_pad_polyline_3vertices(self):
"""Ensures correct output from pad... | stack_v2_sparse_classes_36k_train_033068 | 3,833 | permissive | [
{
"docstring": "Ensures correct output from pad_polyline with one padding vertex.",
"name": "test_pad_polyline_1vertex",
"signature": "def test_pad_polyline_1vertex(self)"
},
{
"docstring": "Ensures correct output from pad_polyline with 3 padding vertices.",
"name": "test_pad_polyline_3verti... | 4 | stack_v2_sparse_classes_30k_train_018564 | Implement the Python class `ShapeUtilsTests` described below.
Class description:
Each method is a unit test for shape_utils.py.
Method signatures and docstrings:
- def test_pad_polyline_1vertex(self): Ensures correct output from pad_polyline with one padding vertex.
- def test_pad_polyline_3vertices(self): Ensures co... | Implement the Python class `ShapeUtilsTests` described below.
Class description:
Each method is a unit test for shape_utils.py.
Method signatures and docstrings:
- def test_pad_polyline_1vertex(self): Ensures correct output from pad_polyline with one padding vertex.
- def test_pad_polyline_3vertices(self): Ensures co... | 1835a71ababb7ad7e47bfa19e62948d466559d56 | <|skeleton|>
class ShapeUtilsTests:
"""Each method is a unit test for shape_utils.py."""
def test_pad_polyline_1vertex(self):
"""Ensures correct output from pad_polyline with one padding vertex."""
<|body_0|>
def test_pad_polyline_3vertices(self):
"""Ensures correct output from pad... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShapeUtilsTests:
"""Each method is a unit test for shape_utils.py."""
def test_pad_polyline_1vertex(self):
"""Ensures correct output from pad_polyline with one padding vertex."""
vertex_x_coords_padded, vertex_y_coords_padded = shape_utils.pad_polyline(POLYLINE_X_COORDS, POLYLINE_Y_COORDS... | the_stack_v2_python_sparse | gewittergefahr/gg_utils/shape_utils_test.py | thunderhoser/GewitterGefahr | train | 29 |
0fec9cb4b8d86dfaea25aec8c1361f09dd7e1b5d | [
"super(Embedding, self).__init__()\nself.N_freqs = N_freqs\nself.in_channels = in_channels\nself.funcs = [torch.sin, torch.cos]\nself.out_channels = in_channels * (len(self.funcs) * N_freqs + 1)\nif logscale:\n self.freq_bands = 2 ** torch.linspace(0, N_freqs - 1, N_freqs)\nelse:\n self.freq_bands = torch.lin... | <|body_start_0|>
super(Embedding, self).__init__()
self.N_freqs = N_freqs
self.in_channels = in_channels
self.funcs = [torch.sin, torch.cos]
self.out_channels = in_channels * (len(self.funcs) * N_freqs + 1)
if logscale:
self.freq_bands = 2 ** torch.linspace(0,... | Embedding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedding:
def __init__(self, in_channels, N_freqs, logscale=True):
"""Defines a function that embeds x to (x, sin(2^k x), cos(2^k x), ...) in_channels: number of input channels (3 for both xyz and direction)"""
<|body_0|>
def forward(self, x):
"""Embeds x to (x, sin... | stack_v2_sparse_classes_36k_train_033069 | 18,983 | no_license | [
{
"docstring": "Defines a function that embeds x to (x, sin(2^k x), cos(2^k x), ...) in_channels: number of input channels (3 for both xyz and direction)",
"name": "__init__",
"signature": "def __init__(self, in_channels, N_freqs, logscale=True)"
},
{
"docstring": "Embeds x to (x, sin(2^k x), co... | 2 | stack_v2_sparse_classes_30k_train_005493 | Implement the Python class `Embedding` described below.
Class description:
Implement the Embedding class.
Method signatures and docstrings:
- def __init__(self, in_channels, N_freqs, logscale=True): Defines a function that embeds x to (x, sin(2^k x), cos(2^k x), ...) in_channels: number of input channels (3 for both ... | Implement the Python class `Embedding` described below.
Class description:
Implement the Embedding class.
Method signatures and docstrings:
- def __init__(self, in_channels, N_freqs, logscale=True): Defines a function that embeds x to (x, sin(2^k x), cos(2^k x), ...) in_channels: number of input channels (3 for both ... | 3b6e9d85e77077d1ad3b669fe88799d6a19e6d99 | <|skeleton|>
class Embedding:
def __init__(self, in_channels, N_freqs, logscale=True):
"""Defines a function that embeds x to (x, sin(2^k x), cos(2^k x), ...) in_channels: number of input channels (3 for both xyz and direction)"""
<|body_0|>
def forward(self, x):
"""Embeds x to (x, sin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Embedding:
def __init__(self, in_channels, N_freqs, logscale=True):
"""Defines a function that embeds x to (x, sin(2^k x), cos(2^k x), ...) in_channels: number of input channels (3 for both xyz and direction)"""
super(Embedding, self).__init__()
self.N_freqs = N_freqs
self.in_c... | the_stack_v2_python_sparse | models/nert.py | jcn16/nert | train | 0 | |
b837c1414ace1a5cc77be7187b5b71198cc56783 | [
"self.images_path = images_path\nself.masks_path = masks_path\nself.sort_flag = sort_flag",
"masks_path = self.masks_path\nif self.sort_flag:\n masks_path = sorted(masks_path)\nmasks_pixes_num = list()\nfor index, mask_path in enumerate(masks_path):\n mask_pixes_num = self.cal_mask_pixes(mask_path)\n mas... | <|body_start_0|>
self.images_path = images_path
self.masks_path = masks_path
self.sort_flag = sort_flag
<|end_body_0|>
<|body_start_1|>
masks_path = self.masks_path
if self.sort_flag:
masks_path = sorted(masks_path)
masks_pixes_num = list()
for index,... | DatasetsStatic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetsStatic:
def __init__(self, images_path, masks_path, sort_flag=False):
"""Args: data_root: 数据集的根目录 image_folder: 样本文件夹名 mask_folder: 掩膜文件夹名 sort_flag: bool,是否对样本路径进行排序"""
<|body_0|>
def mask_static_level(self, level=16):
"""依照掩膜的大小,按照指定的等级数对各样本包含的掩膜进行分级"""
... | stack_v2_sparse_classes_36k_train_033070 | 20,672 | no_license | [
{
"docstring": "Args: data_root: 数据集的根目录 image_folder: 样本文件夹名 mask_folder: 掩膜文件夹名 sort_flag: bool,是否对样本路径进行排序",
"name": "__init__",
"signature": "def __init__(self, images_path, masks_path, sort_flag=False)"
},
{
"docstring": "依照掩膜的大小,按照指定的等级数对各样本包含的掩膜进行分级",
"name": "mask_static_level",
... | 6 | stack_v2_sparse_classes_30k_train_015237 | Implement the Python class `DatasetsStatic` described below.
Class description:
Implement the DatasetsStatic class.
Method signatures and docstrings:
- def __init__(self, images_path, masks_path, sort_flag=False): Args: data_root: 数据集的根目录 image_folder: 样本文件夹名 mask_folder: 掩膜文件夹名 sort_flag: bool,是否对样本路径进行排序
- def mask... | Implement the Python class `DatasetsStatic` described below.
Class description:
Implement the DatasetsStatic class.
Method signatures and docstrings:
- def __init__(self, images_path, masks_path, sort_flag=False): Args: data_root: 数据集的根目录 image_folder: 样本文件夹名 mask_folder: 掩膜文件夹名 sort_flag: bool,是否对样本路径进行排序
- def mask... | 7ff0bbcc223b16d63cf1c74ef7f20cd2025f1608 | <|skeleton|>
class DatasetsStatic:
def __init__(self, images_path, masks_path, sort_flag=False):
"""Args: data_root: 数据集的根目录 image_folder: 样本文件夹名 mask_folder: 掩膜文件夹名 sort_flag: bool,是否对样本路径进行排序"""
<|body_0|>
def mask_static_level(self, level=16):
"""依照掩膜的大小,按照指定的等级数对各样本包含的掩膜进行分级"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatasetsStatic:
def __init__(self, images_path, masks_path, sort_flag=False):
"""Args: data_root: 数据集的根目录 image_folder: 样本文件夹名 mask_folder: 掩膜文件夹名 sort_flag: bool,是否对样本路径进行排序"""
self.images_path = images_path
self.masks_path = masks_path
self.sort_flag = sort_flag
def mask... | the_stack_v2_python_sparse | dataset.py | jiudawn/hualu_segmentation_jiuda | train | 0 | |
8c02a58ef5136866c03e7b7dd308f076bc2868bb | [
"row = len(triangle)\ncol = len(triangle[-1])\ndp = [[float('Inf')] * col for i in range(row)]\ndp[0][0] = triangle[0][0]\nfor j in range(1, row):\n dp[j][0] = dp[j - 1][0] + triangle[j][0]\nfor i in range(1, row):\n for j in range(1, len(triangle[i])):\n dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j]) ... | <|body_start_0|>
row = len(triangle)
col = len(triangle[-1])
dp = [[float('Inf')] * col for i in range(row)]
dp[0][0] = triangle[0][0]
for j in range(1, row):
dp[j][0] = dp[j - 1][0] + triangle[j][0]
for i in range(1, row):
for j in range(1, len(tr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
<|body_0|>
def minimumTotal2(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
row = len(tria... | stack_v2_sparse_classes_36k_train_033071 | 2,863 | no_license | [
{
"docstring": ":type triangle: List[List[int]] :rtype: int",
"name": "minimumTotal",
"signature": "def minimumTotal(self, triangle)"
},
{
"docstring": ":type triangle: List[List[int]] :rtype: int",
"name": "minimumTotal2",
"signature": "def minimumTotal2(self, triangle)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int
- def minimumTotal2(self, triangle): :type triangle: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int
- def minimumTotal2(self, triangle): :type triangle: List[List[int]] :rtype: int
<|skeleton|>
class... | 604efd2c53c369fb262f42f7f7f31997ea4d029b | <|skeleton|>
class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
<|body_0|>
def minimumTotal2(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
row = len(triangle)
col = len(triangle[-1])
dp = [[float('Inf')] * col for i in range(row)]
dp[0][0] = triangle[0][0]
for j in range(1, row):
dp[j][0] = dp[... | the_stack_v2_python_sparse | 120_Triangle.py | fxy1018/Leetcode | train | 1 | |
7c55dba11c97d19906c76e4df0ae9385c53cdbbf | [
"if cleanup:\n logger.warning('cleanup is not supported by the buildah backend')\nsuper(BuildahBackend, self).__init__(logging_level=logging_level, logging_kwargs=logging_kwargs, cleanup=cleanup)",
"raw_version = run_cmd(['buildah', 'version'], return_output=True)\nregex = re.compile('Version:\\\\s*(\\\\d+)\\\... | <|body_start_0|>
if cleanup:
logger.warning('cleanup is not supported by the buildah backend')
super(BuildahBackend, self).__init__(logging_level=logging_level, logging_kwargs=logging_kwargs, cleanup=cleanup)
<|end_body_0|>
<|body_start_1|>
raw_version = run_cmd(['buildah', 'version... | For more info on using the Backend classes, see documentation of the parent :class:`conu.apidefs.backend.Backend` class. | BuildahBackend | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildahBackend:
"""For more info on using the Backend classes, see documentation of the parent :class:`conu.apidefs.backend.Backend` class."""
def __init__(self, logging_level=logging.INFO, logging_kwargs=None, cleanup=None):
"""This method serves as a configuration interface for con... | stack_v2_sparse_classes_36k_train_033072 | 4,737 | permissive | [
{
"docstring": "This method serves as a configuration interface for conu. :param logging_level: int, control logger verbosity: see logging.{DEBUG,INFO,ERROR} :param logging_kwargs: dict, additional keyword arguments for logger set up, for more info see docstring of set_logging function :param cleanup: unsupport... | 6 | stack_v2_sparse_classes_30k_train_016680 | Implement the Python class `BuildahBackend` described below.
Class description:
For more info on using the Backend classes, see documentation of the parent :class:`conu.apidefs.backend.Backend` class.
Method signatures and docstrings:
- def __init__(self, logging_level=logging.INFO, logging_kwargs=None, cleanup=None)... | Implement the Python class `BuildahBackend` described below.
Class description:
For more info on using the Backend classes, see documentation of the parent :class:`conu.apidefs.backend.Backend` class.
Method signatures and docstrings:
- def __init__(self, logging_level=logging.INFO, logging_kwargs=None, cleanup=None)... | f6c3b9a07483ef5a22d3c22df38994d93b56ea0c | <|skeleton|>
class BuildahBackend:
"""For more info on using the Backend classes, see documentation of the parent :class:`conu.apidefs.backend.Backend` class."""
def __init__(self, logging_level=logging.INFO, logging_kwargs=None, cleanup=None):
"""This method serves as a configuration interface for con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuildahBackend:
"""For more info on using the Backend classes, see documentation of the parent :class:`conu.apidefs.backend.Backend` class."""
def __init__(self, logging_level=logging.INFO, logging_kwargs=None, cleanup=None):
"""This method serves as a configuration interface for conu. :param log... | the_stack_v2_python_sparse | conu/backend/buildah/backend.py | user-cont/conu | train | 100 |
f77cf5544bb7f755622b225e47ef082aef7dba3e | [
"res = []\nstack = []\nwhile stack or root:\n if root:\n stack.append(root)\n root = root.left\n else:\n node = stack.pop()\n res.append(node.val)\n root = node.right\nreturn res",
"res = []\nstack = []\nwhile stack or root:\n if root:\n res.append(root.val)\n ... | <|body_start_0|>
res = []
stack = []
while stack or root:
if root:
stack.append(root)
root = root.left
else:
node = stack.pop()
res.append(node.val)
root = node.right
return res
<|end_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorder(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def preorder(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def postorder(self, root):
""":type root: TreeNode :rtype: List[int]"""
... | stack_v2_sparse_classes_36k_train_033073 | 2,252 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorder",
"signature": "def inorder(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "preorder",
"signature": "def preorder(self, root)"
},
{
"docstring": ":type root: TreeNode :rtyp... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorder(self, root): :type root: TreeNode :rtype: List[int]
- def preorder(self, root): :type root: TreeNode :rtype: List[int]
- def postorder(self, root): :type root: TreeNo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorder(self, root): :type root: TreeNode :rtype: List[int]
- def preorder(self, root): :type root: TreeNode :rtype: List[int]
- def postorder(self, root): :type root: TreeNo... | f3ec3e6a82ad092bc5d83732af582dc987da6aac | <|skeleton|>
class Solution:
def inorder(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def preorder(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def postorder(self, root):
""":type root: TreeNode :rtype: List[int]"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def inorder(self, root):
""":type root: TreeNode :rtype: List[int]"""
res = []
stack = []
while stack or root:
if root:
stack.append(root)
root = root.left
else:
node = stack.pop()
... | the_stack_v2_python_sparse | stack_tree_iterative_traversal.py | lonelyarcher/leetcode.python3 | train | 0 | |
e7da091e9fb09a3a7097c497c0c6e12e031fd769 | [
"super(CsvExpressionSum, self).__init__()\nself.threads = threads\nreturn",
"if self._thread_column is None:\n if self.threads > 1:\n thread = '-1'\n else:\n thread = bran.INTEGER\n self._thread_column = bran.NAMED(ParserKeys.thread, thread)\nreturn self._thread_column"
] | <|body_start_0|>
super(CsvExpressionSum, self).__init__()
self.threads = threads
return
<|end_body_0|>
<|body_start_1|>
if self._thread_column is None:
if self.threads > 1:
thread = '-1'
else:
thread = bran.INTEGER
self... | Changes the thread column to look for -1 if needed | CsvExpressionSum | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CsvExpressionSum:
"""Changes the thread column to look for -1 if needed"""
def __init__(self, threads=4):
""":param: - `threads`: the number of parallel threads"""
<|body_0|>
def thread_column(self):
""":return: the expression to match the thread (sum) column"""
... | stack_v2_sparse_classes_36k_train_033074 | 9,671 | permissive | [
{
"docstring": ":param: - `threads`: the number of parallel threads",
"name": "__init__",
"signature": "def __init__(self, threads=4)"
},
{
"docstring": ":return: the expression to match the thread (sum) column",
"name": "thread_column",
"signature": "def thread_column(self)"
}
] | 2 | null | Implement the Python class `CsvExpressionSum` described below.
Class description:
Changes the thread column to look for -1 if needed
Method signatures and docstrings:
- def __init__(self, threads=4): :param: - `threads`: the number of parallel threads
- def thread_column(self): :return: the expression to match the th... | Implement the Python class `CsvExpressionSum` described below.
Class description:
Changes the thread column to look for -1 if needed
Method signatures and docstrings:
- def __init__(self, threads=4): :param: - `threads`: the number of parallel threads
- def thread_column(self): :return: the expression to match the th... | 2007bf3fe66edfe704e485141c55caed54fe13aa | <|skeleton|>
class CsvExpressionSum:
"""Changes the thread column to look for -1 if needed"""
def __init__(self, threads=4):
""":param: - `threads`: the number of parallel threads"""
<|body_0|>
def thread_column(self):
""":return: the expression to match the thread (sum) column"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CsvExpressionSum:
"""Changes the thread column to look for -1 if needed"""
def __init__(self, threads=4):
""":param: - `threads`: the number of parallel threads"""
super(CsvExpressionSum, self).__init__()
self.threads = threads
return
def thread_column(self):
... | the_stack_v2_python_sparse | utils/iperflexer/sumparser.py | AndriyZabavskyy/taf | train | 0 |
ffe6c2fb8d0d870d0a344837f9cbf85cc64d8bfa | [
"super(Aggregator, self).__init__()\nprint('\\nLoading patch model from [%s]...' % args.patch_snapshot)\ntry:\n patch_model = torch.load(args.patch_snapshot).cpu()\n self.patch_model = strip_model(patch_model)\nexcept Exception as e:\n raise Exception(\"Couldn't load patch model at {}. Error: {}\".format(a... | <|body_start_0|>
super(Aggregator, self).__init__()
print('\nLoading patch model from [%s]...' % args.patch_snapshot)
try:
patch_model = torch.load(args.patch_snapshot).cpu()
self.patch_model = strip_model(patch_model)
except Exception as e:
raise Exce... | Aggregator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Aggregator:
def __init__(self, args):
"""Given some a patch model, add add some FC layers and a shortcut to make whole image prediction"""
<|body_0|>
def forward(self, x):
"""param x: a batch of image tensors returns hidden: last hidden layer of model (as if wrapper ... | stack_v2_sparse_classes_36k_train_033075 | 1,832 | permissive | [
{
"docstring": "Given some a patch model, add add some FC layers and a shortcut to make whole image prediction",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "param x: a batch of image tensors returns hidden: last hidden layer of model (as if wrapper wasn't appli... | 2 | stack_v2_sparse_classes_30k_train_006403 | Implement the Python class `Aggregator` described below.
Class description:
Implement the Aggregator class.
Method signatures and docstrings:
- def __init__(self, args): Given some a patch model, add add some FC layers and a shortcut to make whole image prediction
- def forward(self, x): param x: a batch of image ten... | Implement the Python class `Aggregator` described below.
Class description:
Implement the Aggregator class.
Method signatures and docstrings:
- def __init__(self, args): Given some a patch model, add add some FC layers and a shortcut to make whole image prediction
- def forward(self, x): param x: a batch of image ten... | 12bace8fd6ce9c5bb129fd0d30a46a00a2f7b054 | <|skeleton|>
class Aggregator:
def __init__(self, args):
"""Given some a patch model, add add some FC layers and a shortcut to make whole image prediction"""
<|body_0|>
def forward(self, x):
"""param x: a batch of image tensors returns hidden: last hidden layer of model (as if wrapper ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Aggregator:
def __init__(self, args):
"""Given some a patch model, add add some FC layers and a shortcut to make whole image prediction"""
super(Aggregator, self).__init__()
print('\nLoading patch model from [%s]...' % args.patch_snapshot)
try:
patch_model = torch.l... | the_stack_v2_python_sparse | onconet/models/aggregator.py | yala/Mirai | train | 66 | |
45f9a14b40a5267d1d89f337bfd4211fda452139 | [
"all_cpis = []\nall_modules = []\nall_submods = []\nfor sub_class in configurator.common.Configurator.__subclasses__():\n all_cpis.append((sub_class.module(sub_class), sub_class.submod(sub_class)))\n all_modules.append(sub_class.module(sub_class))\n all_submods.append(sub_class.submod(sub_class))\nself.get... | <|body_start_0|>
all_cpis = []
all_modules = []
all_submods = []
for sub_class in configurator.common.Configurator.__subclasses__():
all_cpis.append((sub_class.module(sub_class), sub_class.submod(sub_class)))
all_modules.append(sub_class.module(sub_class))
... | The configurator plugin | CPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CPI:
"""The configurator plugin"""
def __init__(self):
"""Initialize. :param: None :returns: None :raises: None"""
<|body_0|>
def get_configurators(cls, module=None, submod=None):
"""Get configurators of 'module'.'submod'. :param module(optional): %s :param submo... | stack_v2_sparse_classes_36k_train_033076 | 7,577 | no_license | [
{
"docstring": "Initialize. :param: None :returns: None :raises: None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get configurators of 'module'.'submod'. :param module(optional): %s :param submod(optional): %s :returns list: Success, all found configurators or null... | 3 | stack_v2_sparse_classes_30k_test_000077 | Implement the Python class `CPI` described below.
Class description:
The configurator plugin
Method signatures and docstrings:
- def __init__(self): Initialize. :param: None :returns: None :raises: None
- def get_configurators(cls, module=None, submod=None): Get configurators of 'module'.'submod'. :param module(optio... | Implement the Python class `CPI` described below.
Class description:
The configurator plugin
Method signatures and docstrings:
- def __init__(self): Initialize. :param: None :returns: None :raises: None
- def get_configurators(cls, module=None, submod=None): Get configurators of 'module'.'submod'. :param module(optio... | e4f257d00305849b9a52a033651da09412436785 | <|skeleton|>
class CPI:
"""The configurator plugin"""
def __init__(self):
"""Initialize. :param: None :returns: None :raises: None"""
<|body_0|>
def get_configurators(cls, module=None, submod=None):
"""Get configurators of 'module'.'submod'. :param module(optional): %s :param submo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CPI:
"""The configurator plugin"""
def __init__(self):
"""Initialize. :param: None :returns: None :raises: None"""
all_cpis = []
all_modules = []
all_submods = []
for sub_class in configurator.common.Configurator.__subclasses__():
all_cpis.append((sub_c... | the_stack_v2_python_sparse | analysis/plugin/plugin.py | hanxinke/A-Tune | train | 0 |
ad5f4c1d3892b2f80d5778aa0dc0a89af7d42e64 | [
"d = departmentmanage(self.driver)\nd.open_departmentmanage()\nself.assertEqual(d.verify(), True)\nd.deptstatus()\nd.delete()\nself.assertEqual(d.result(), '您确定要删除这条信息吗')\nd.confirm()\nself.assertEqual(d.result(), '删除成功')\nfunction.screenshot(self.driver, 'delete_department.jpg')",
"d = departmentmanage(self.driv... | <|body_start_0|>
d = departmentmanage(self.driver)
d.open_departmentmanage()
self.assertEqual(d.verify(), True)
d.deptstatus()
d.delete()
self.assertEqual(d.result(), '您确定要删除这条信息吗')
d.confirm()
self.assertEqual(d.result(), '删除成功')
function.screensh... | Test029_Department_Delete_P1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test029_Department_Delete_P1:
def test_department_delete(self):
"""删除部门"""
<|body_0|>
def test_department_cancle(self):
"""取消删除部门"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = departmentmanage(self.driver)
d.open_departmentmanage()
... | stack_v2_sparse_classes_36k_train_033077 | 1,179 | no_license | [
{
"docstring": "删除部门",
"name": "test_department_delete",
"signature": "def test_department_delete(self)"
},
{
"docstring": "取消删除部门",
"name": "test_department_cancle",
"signature": "def test_department_cancle(self)"
}
] | 2 | null | Implement the Python class `Test029_Department_Delete_P1` described below.
Class description:
Implement the Test029_Department_Delete_P1 class.
Method signatures and docstrings:
- def test_department_delete(self): 删除部门
- def test_department_cancle(self): 取消删除部门 | Implement the Python class `Test029_Department_Delete_P1` described below.
Class description:
Implement the Test029_Department_Delete_P1 class.
Method signatures and docstrings:
- def test_department_delete(self): 删除部门
- def test_department_cancle(self): 取消删除部门
<|skeleton|>
class Test029_Department_Delete_P1:
d... | 6f42c25249fc642cecc270578a180820988d45b5 | <|skeleton|>
class Test029_Department_Delete_P1:
def test_department_delete(self):
"""删除部门"""
<|body_0|>
def test_department_cancle(self):
"""取消删除部门"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test029_Department_Delete_P1:
def test_department_delete(self):
"""删除部门"""
d = departmentmanage(self.driver)
d.open_departmentmanage()
self.assertEqual(d.verify(), True)
d.deptstatus()
d.delete()
self.assertEqual(d.result(), '您确定要删除这条信息吗')
d.conf... | the_stack_v2_python_sparse | GlxssLive_web/TestCase/Manage_Department/Test029_department_delete_P1.py | rrmiracle/GlxssLive | train | 0 | |
6c4d9949932869d2ee3d09f7f84de31b1e3b235a | [
"super().__init__()\nself.cache_file = cache_file\nself.image_batcher = None\nself.batch_allocation = None\nself.batch_generator = None",
"self.image_batcher = image_batcher\nsize = int(np.dtype(self.image_batcher.dtype).itemsize * np.prod(self.image_batcher.shape))\nself.batch_allocation = common.cuda_call(cudar... | <|body_start_0|>
super().__init__()
self.cache_file = cache_file
self.image_batcher = None
self.batch_allocation = None
self.batch_generator = None
<|end_body_0|>
<|body_start_1|>
self.image_batcher = image_batcher
size = int(np.dtype(self.image_batcher.dtype).it... | Implements the INT8 Entropy Calibrator 2. | EngineCalibrator | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"ISC",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EngineCalibrator:
"""Implements the INT8 Entropy Calibrator 2."""
def __init__(self, cache_file):
""":param cache_file: The location of the cache file."""
<|body_0|>
def set_image_batcher(self, image_batcher: ImageBatcher):
"""Define the image batcher to use, if ... | stack_v2_sparse_classes_36k_train_033078 | 14,578 | permissive | [
{
"docstring": ":param cache_file: The location of the cache file.",
"name": "__init__",
"signature": "def __init__(self, cache_file)"
},
{
"docstring": "Define the image batcher to use, if any. If using only the cache file, an image batcher doesn't need to be defined. :param image_batcher: The ... | 6 | null | Implement the Python class `EngineCalibrator` described below.
Class description:
Implements the INT8 Entropy Calibrator 2.
Method signatures and docstrings:
- def __init__(self, cache_file): :param cache_file: The location of the cache file.
- def set_image_batcher(self, image_batcher: ImageBatcher): Define the imag... | Implement the Python class `EngineCalibrator` described below.
Class description:
Implements the INT8 Entropy Calibrator 2.
Method signatures and docstrings:
- def __init__(self, cache_file): :param cache_file: The location of the cache file.
- def set_image_batcher(self, image_batcher: ImageBatcher): Define the imag... | a167852705d74bcc619d8fad0af4b9e4d84472fc | <|skeleton|>
class EngineCalibrator:
"""Implements the INT8 Entropy Calibrator 2."""
def __init__(self, cache_file):
""":param cache_file: The location of the cache file."""
<|body_0|>
def set_image_batcher(self, image_batcher: ImageBatcher):
"""Define the image batcher to use, if ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EngineCalibrator:
"""Implements the INT8 Entropy Calibrator 2."""
def __init__(self, cache_file):
""":param cache_file: The location of the cache file."""
super().__init__()
self.cache_file = cache_file
self.image_batcher = None
self.batch_allocation = None
... | the_stack_v2_python_sparse | samples/python/efficientdet/build_engine.py | NVIDIA/TensorRT | train | 8,026 |
94ba6f1b4f062ce9f899a3a0130cb63235d5f015 | [
"try:\n file = File.objects.get(pk=pk)\nexcept ObjectDoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\nif request.user.is_authenticated:\n serializer = FileSerializer(file)\n return Response(serializer.data)\nreturn Response(status=status.HTTP_401_UNAUTHORIZED)",
"try:\n file = Fil... | <|body_start_0|>
try:
file = File.objects.get(pk=pk)
except ObjectDoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.user.is_authenticated:
serializer = FileSerializer(file)
return Response(serializer.data)
return Re... | Retrieve or delete a File. | FileDetail | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileDetail:
"""Retrieve or delete a File."""
def get(self, request, pk):
"""Send the File corresponding to the given key."""
<|body_0|>
def delete(self, request, pk):
"""Delete the File corresponding to the given key."""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_033079 | 3,371 | permissive | [
{
"docstring": "Send the File corresponding to the given key.",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "Delete the File corresponding to the given key.",
"name": "delete",
"signature": "def delete(self, request, pk)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015039 | Implement the Python class `FileDetail` described below.
Class description:
Retrieve or delete a File.
Method signatures and docstrings:
- def get(self, request, pk): Send the File corresponding to the given key.
- def delete(self, request, pk): Delete the File corresponding to the given key. | Implement the Python class `FileDetail` described below.
Class description:
Retrieve or delete a File.
Method signatures and docstrings:
- def get(self, request, pk): Send the File corresponding to the given key.
- def delete(self, request, pk): Delete the File corresponding to the given key.
<|skeleton|>
class File... | 56511ebac83a5dc1fb8768a98bc675e88530a447 | <|skeleton|>
class FileDetail:
"""Retrieve or delete a File."""
def get(self, request, pk):
"""Send the File corresponding to the given key."""
<|body_0|>
def delete(self, request, pk):
"""Delete the File corresponding to the given key."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileDetail:
"""Retrieve or delete a File."""
def get(self, request, pk):
"""Send the File corresponding to the given key."""
try:
file = File.objects.get(pk=pk)
except ObjectDoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.... | the_stack_v2_python_sparse | maintenancemanagement/views/views_file.py | Open-CMMS/openCMMS_backend | train | 4 |
a7fe7294e09e383e52d36047b31bc2a4ba4c01e2 | [
"node_tb = {}\nfor i in xrange(n):\n node_tb[i] = GraphNode(i)\nfor edge in edges:\n node_tb[edge[0]].neighbors.add(edge[1])\n node_tb[edge[1]].neighbors.add(edge[0])\nvisited = sets.Set([0])\nloop = self._validTreeHelper(0, node_tb, visited)\nif loop:\n return False\nelse:\n return len(visited) == n... | <|body_start_0|>
node_tb = {}
for i in xrange(n):
node_tb[i] = GraphNode(i)
for edge in edges:
node_tb[edge[0]].neighbors.add(edge[1])
node_tb[edge[1]].neighbors.add(edge[0])
visited = sets.Set([0])
loop = self._validTreeHelper(0, node_tb, visi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validTree(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: bool"""
<|body_0|>
def _validTreeHelper(self, start, node_tb, visited):
"""Used to check if there is a loop in the graph"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_033080 | 2,145 | no_license | [
{
"docstring": ":type n: int :type edges: List[List[int]] :rtype: bool",
"name": "validTree",
"signature": "def validTree(self, n, edges)"
},
{
"docstring": "Used to check if there is a loop in the graph",
"name": "_validTreeHelper",
"signature": "def _validTreeHelper(self, start, node_t... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validTree(self, n, edges): :type n: int :type edges: List[List[int]] :rtype: bool
- def _validTreeHelper(self, start, node_tb, visited): Used to check if there is a loop in t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validTree(self, n, edges): :type n: int :type edges: List[List[int]] :rtype: bool
- def _validTreeHelper(self, start, node_tb, visited): Used to check if there is a loop in t... | fe089c76a4e0b9266c563e9bc731a21065d2b502 | <|skeleton|>
class Solution:
def validTree(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: bool"""
<|body_0|>
def _validTreeHelper(self, start, node_tb, visited):
"""Used to check if there is a loop in the graph"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validTree(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: bool"""
node_tb = {}
for i in xrange(n):
node_tb[i] = GraphNode(i)
for edge in edges:
node_tb[edge[0]].neighbors.add(edge[1])
node_tb[edge[1]].neigh... | the_stack_v2_python_sparse | Candice_coding/Leetcode/Graph_Valid_Tree.py | kikijtl/coding | train | 0 | |
5c175ee625eeb113853583bc163e1592c8f39e98 | [
"if not nums:\n return 0\nn = len(nums)\nyes, no = ([0] * n, [0] * n)\nyes[0], no[0] = (nums[0], 0)\nfor i in range(1, n):\n yes[i] = nums[i] + no[i - 1]\n no[i] = max(no[i - 1], yes[i - 1])\nreturn max(yes[-1], no[-1])",
"if not nums:\n return 0\nyes, no = (0, 0)\nfor i in nums:\n yes, no = (i + n... | <|body_start_0|>
if not nums:
return 0
n = len(nums)
yes, no = ([0] * n, [0] * n)
yes[0], no[0] = (nums[0], 0)
for i in range(1, n):
yes[i] = nums[i] + no[i - 1]
no[i] = max(no[i - 1], yes[i - 1])
return max(yes[-1], no[-1])
<|end_body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums: list) -> int:
"""动态规划 O(n) time O(n) space"""
<|body_0|>
def rob_2(self, nums: list) -> int:
"""动态规划-优化 O(n) time O(1) space"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
n = ... | stack_v2_sparse_classes_36k_train_033081 | 1,292 | no_license | [
{
"docstring": "动态规划 O(n) time O(n) space",
"name": "rob",
"signature": "def rob(self, nums: list) -> int"
},
{
"docstring": "动态规划-优化 O(n) time O(1) space",
"name": "rob_2",
"signature": "def rob_2(self, nums: list) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_002846 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums: list) -> int: 动态规划 O(n) time O(n) space
- def rob_2(self, nums: list) -> int: 动态规划-优化 O(n) time O(1) space | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums: list) -> int: 动态规划 O(n) time O(n) space
- def rob_2(self, nums: list) -> int: 动态规划-优化 O(n) time O(1) space
<|skeleton|>
class Solution:
def rob(self, nu... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def rob(self, nums: list) -> int:
"""动态规划 O(n) time O(n) space"""
<|body_0|>
def rob_2(self, nums: list) -> int:
"""动态规划-优化 O(n) time O(1) space"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums: list) -> int:
"""动态规划 O(n) time O(n) space"""
if not nums:
return 0
n = len(nums)
yes, no = ([0] * n, [0] * n)
yes[0], no[0] = (nums[0], 0)
for i in range(1, n):
yes[i] = nums[i] + no[i - 1]
no[i]... | the_stack_v2_python_sparse | algorithm/leetcode/dp/01-打家劫舍.py | lxconfig/UbuntuCode_bak | train | 0 | |
ff78e93cf8b10cadbe8d0fe157321741af4d096f | [
"super(InfoMix, self).__init__()\nself.view_loss_weight = view_loss_weight\nself.regularization_loss_weight = regularization_loss_weight\nself.encoder = get_encoder(embedding_dim, embedder_type)\nself.subencoder = get_encoder(embedding_dim, models.TYPE_EMBEDDER_POINT)\nself.subencoder.blocks = [block for block in s... | <|body_start_0|>
super(InfoMix, self).__init__()
self.view_loss_weight = view_loss_weight
self.regularization_loss_weight = regularization_loss_weight
self.encoder = get_encoder(embedding_dim, embedder_type)
self.subencoder = get_encoder(embedding_dim, models.TYPE_EMBEDDER_POINT)... | Model for InfoMix. | InfoMix | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfoMix:
"""Model for InfoMix."""
def __init__(self, embedding_dim, embedder_type, view_loss_weight=1.0, regularization_loss_weight=1.0):
"""Initializer. Args: embedding_dim: An integer for the dimension of the embedding. embedder_type: A string for the type of the embedder. view_los... | stack_v2_sparse_classes_36k_train_033082 | 40,948 | permissive | [
{
"docstring": "Initializer. Args: embedding_dim: An integer for the dimension of the embedding. embedder_type: A string for the type of the embedder. view_loss_weight: A float for the weight of view loss. regularization_loss_weight: A float for the weight of regularization loss.",
"name": "__init__",
"... | 4 | null | Implement the Python class `InfoMix` described below.
Class description:
Model for InfoMix.
Method signatures and docstrings:
- def __init__(self, embedding_dim, embedder_type, view_loss_weight=1.0, regularization_loss_weight=1.0): Initializer. Args: embedding_dim: An integer for the dimension of the embedding. embed... | Implement the Python class `InfoMix` described below.
Class description:
Model for InfoMix.
Method signatures and docstrings:
- def __init__(self, embedding_dim, embedder_type, view_loss_weight=1.0, regularization_loss_weight=1.0): Initializer. Args: embedding_dim: An integer for the dimension of the embedding. embed... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class InfoMix:
"""Model for InfoMix."""
def __init__(self, embedding_dim, embedder_type, view_loss_weight=1.0, regularization_loss_weight=1.0):
"""Initializer. Args: embedding_dim: An integer for the dimension of the embedding. embedder_type: A string for the type of the embedder. view_los... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InfoMix:
"""Model for InfoMix."""
def __init__(self, embedding_dim, embedder_type, view_loss_weight=1.0, regularization_loss_weight=1.0):
"""Initializer. Args: embedding_dim: An integer for the dimension of the embedding. embedder_type: A string for the type of the embedder. view_loss_weight: A f... | the_stack_v2_python_sparse | poem/cv_mim/algorithms.py | Jimmy-INL/google-research | train | 1 |
54314de91c376b6d65932a3e8917281dedbf3d97 | [
"self._client = VarlinkClient(address=self._context.uri)\nself._iface = self._client.open(self._context.interface)\nreturn self._iface",
"if hasattr(self._client, 'close'):\n self._client.close()\nself._iface.close()\nif isinstance(e, VarlinkError):\n raise error_factory(e)"
] | <|body_start_0|>
self._client = VarlinkClient(address=self._context.uri)
self._iface = self._client.open(self._context.interface)
return self._iface
<|end_body_0|>
<|body_start_1|>
if hasattr(self._client, 'close'):
self._client.close()
self._iface.close()
if... | Context manager for API workers to access varlink. | LocalClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalClient:
"""Context manager for API workers to access varlink."""
def __enter__(self):
"""Enter context for LocalClient."""
<|body_0|>
def __exit__(self, e_type, e, e_traceback):
"""Cleanup context for LocalClient."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_033083 | 7,078 | permissive | [
{
"docstring": "Enter context for LocalClient.",
"name": "__enter__",
"signature": "def __enter__(self)"
},
{
"docstring": "Cleanup context for LocalClient.",
"name": "__exit__",
"signature": "def __exit__(self, e_type, e, e_traceback)"
}
] | 2 | null | Implement the Python class `LocalClient` described below.
Class description:
Context manager for API workers to access varlink.
Method signatures and docstrings:
- def __enter__(self): Enter context for LocalClient.
- def __exit__(self, e_type, e, e_traceback): Cleanup context for LocalClient. | Implement the Python class `LocalClient` described below.
Class description:
Context manager for API workers to access varlink.
Method signatures and docstrings:
- def __enter__(self): Enter context for LocalClient.
- def __exit__(self, e_type, e, e_traceback): Cleanup context for LocalClient.
<|skeleton|>
class Loc... | ce2a8734f8b4203ec38078207297062263c49f6f | <|skeleton|>
class LocalClient:
"""Context manager for API workers to access varlink."""
def __enter__(self):
"""Enter context for LocalClient."""
<|body_0|>
def __exit__(self, e_type, e, e_traceback):
"""Cleanup context for LocalClient."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalClient:
"""Context manager for API workers to access varlink."""
def __enter__(self):
"""Enter context for LocalClient."""
self._client = VarlinkClient(address=self._context.uri)
self._iface = self._client.open(self._context.interface)
return self._iface
def __ex... | the_stack_v2_python_sparse | tobiko/podman/_podman1/client.py | FedericoRessi/tobiko | train | 1 |
98758779ac024e6df5054b5b1ddbff07ef4d9ecd | [
"heap_ = nums[:k]\nheapq.heapify(heap_)\nfor i in range(k, len(nums)):\n heapq.heappushpop(heap_, nums[i])\nreturn heapq.heappop(heap_)",
"def select(nums, k):\n m = nums.pop(len(nums) // 2)\n larger = [n for n in nums if n > m]\n ll = len(larger)\n if k <= ll:\n return select(larger, k)\n ... | <|body_start_0|>
heap_ = nums[:k]
heapq.heapify(heap_)
for i in range(k, len(nums)):
heapq.heappushpop(heap_, nums[i])
return heapq.heappop(heap_)
<|end_body_0|>
<|body_start_1|>
def select(nums, k):
m = nums.pop(len(nums) // 2)
larger = [n fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
heap_ =... | stack_v2_sparse_classes_36k_train_033084 | 1,081 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findKthLargest",
"signature": "def findKthLargest(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findKthLargest",
"signature": "def findKthLargest(self, nums, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int
<|skeleton|... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
heap_ = nums[:k]
heapq.heapify(heap_)
for i in range(k, len(nums)):
heapq.heappushpop(heap_, nums[i])
return heapq.heappop(heap_)
def findKthLargest(self, ... | the_stack_v2_python_sparse | problems/findKthLargest.py | joddiy/leetcode | train | 1 | |
f306e44a195d1175628ba089569393ba03e39409 | [
"length = len(nums)\nif length == 0:\n return False\nlastPos = length - 1\nfor i in range(lastPos, -1, -1):\n if nums[i] + i >= lastPos:\n lastPos = i\nreturn lastPos == 0",
"maxs = 0\nfor i in range(len(nums) - 1):\n maxs = max(nums[i], maxs - 1)\n if maxs == 0:\n return False\nreturn T... | <|body_start_0|>
length = len(nums)
if length == 0:
return False
lastPos = length - 1
for i in range(lastPos, -1, -1):
if nums[i] + i >= lastPos:
lastPos = i
return lastPos == 0
<|end_body_0|>
<|body_start_1|>
maxs = 0
for ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump1(self, nums):
""":type nums: List[int] :rtype: bool 时间复杂度O(n):84ms beaten 99.33% 空间复杂度O(n): 13.2MB beaten 48.48%"""
<|body_0|>
def canJump2(self, nums):
""":type nums: List[int] :rtype: bool 时间复杂度O(n):80ms beaten 95.70% 空间复杂度O(n): 13.2MB beaten ... | stack_v2_sparse_classes_36k_train_033085 | 1,989 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: bool 时间复杂度O(n):84ms beaten 99.33% 空间复杂度O(n): 13.2MB beaten 48.48%",
"name": "canJump1",
"signature": "def canJump1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool 时间复杂度O(n):80ms beaten 95.70% 空间复杂度O(n): 13.2MB beaten 46.28%",
"... | 2 | stack_v2_sparse_classes_30k_train_000078 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump1(self, nums): :type nums: List[int] :rtype: bool 时间复杂度O(n):84ms beaten 99.33% 空间复杂度O(n): 13.2MB beaten 48.48%
- def canJump2(self, nums): :type nums: List[int] :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump1(self, nums): :type nums: List[int] :rtype: bool 时间复杂度O(n):84ms beaten 99.33% 空间复杂度O(n): 13.2MB beaten 48.48%
- def canJump2(self, nums): :type nums: List[int] :rtype... | a2e5256f27dbfb23fc34119fc857cd9b00e28c03 | <|skeleton|>
class Solution:
def canJump1(self, nums):
""":type nums: List[int] :rtype: bool 时间复杂度O(n):84ms beaten 99.33% 空间复杂度O(n): 13.2MB beaten 48.48%"""
<|body_0|>
def canJump2(self, nums):
""":type nums: List[int] :rtype: bool 时间复杂度O(n):80ms beaten 95.70% 空间复杂度O(n): 13.2MB beaten ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump1(self, nums):
""":type nums: List[int] :rtype: bool 时间复杂度O(n):84ms beaten 99.33% 空间复杂度O(n): 13.2MB beaten 48.48%"""
length = len(nums)
if length == 0:
return False
lastPos = length - 1
for i in range(lastPos, -1, -1):
if num... | the_stack_v2_python_sparse | toTheMoon/leetcode_055_JumpGame.py | jercas/offer66-leetcode-newcode | train | 0 | |
c5e0dad4cc0eed51beef649c18f3b2d6113f20b9 | [
"self.n_kernels = n_kernels\nself.n_strides = n_strides\nself.dropout = dropout\nself.norm_type = normalization\nself.activation_type = activation",
"if padding:\n activation = Conv2D(filters=n_filters, kernel_size=n_kernels if n_kernels else self.n_kernels, strides=n_strides if n_strides else self.n_strides, ... | <|body_start_0|>
self.n_kernels = n_kernels
self.n_strides = n_strides
self.dropout = dropout
self.norm_type = normalization
self.activation_type = activation
<|end_body_0|>
<|body_start_1|>
if padding:
activation = Conv2D(filters=n_filters, kernel_size=n_ker... | Class to create Patch blocks for the Discriminator. | PatchBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatchBlock:
"""Class to create Patch blocks for the Discriminator."""
def __init__(self, n_kernels, n_strides, dropout, activation, normalization):
"""Initialize the Patchblock. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. dropout (float): Includ... | stack_v2_sparse_classes_36k_train_033086 | 11,636 | no_license | [
{
"docstring": "Initialize the Patchblock. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. dropout (float): Include dropout for intermediate layers. activation (str): Type of activation layer to use. normalization (str): Type of normalization layer to use.",
"name": "__ini... | 2 | stack_v2_sparse_classes_30k_train_008541 | Implement the Python class `PatchBlock` described below.
Class description:
Class to create Patch blocks for the Discriminator.
Method signatures and docstrings:
- def __init__(self, n_kernels, n_strides, dropout, activation, normalization): Initialize the Patchblock. Args: n_kernels (int): Number of kernels for Conv... | Implement the Python class `PatchBlock` described below.
Class description:
Class to create Patch blocks for the Discriminator.
Method signatures and docstrings:
- def __init__(self, n_kernels, n_strides, dropout, activation, normalization): Initialize the Patchblock. Args: n_kernels (int): Number of kernels for Conv... | 1b953d87968dac46ebbc9b1d5c254ea9493ee328 | <|skeleton|>
class PatchBlock:
"""Class to create Patch blocks for the Discriminator."""
def __init__(self, n_kernels, n_strides, dropout, activation, normalization):
"""Initialize the Patchblock. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. dropout (float): Includ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PatchBlock:
"""Class to create Patch blocks for the Discriminator."""
def __init__(self, n_kernels, n_strides, dropout, activation, normalization):
"""Initialize the Patchblock. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. dropout (float): Include dropout for... | the_stack_v2_python_sparse | fmlwright/trainer/neural_networks/blocks.py | rgresia-umd/fml-wright | train | 0 |
b24f4b98c8df80041d8dc934fde8b274f7089787 | [
"super(PictureAdminForm, self).__init__(*args, **kwargs)\ntry:\n self.fields['weight'].required = False\n self.fields['author'].required = False\n self.fields['image'].required = False\n self.fields['image'].widget = PictureInlineWidget()\n self.fields['image'].help_text = _('You can also enter an UR... | <|body_start_0|>
super(PictureAdminForm, self).__init__(*args, **kwargs)
try:
self.fields['weight'].required = False
self.fields['author'].required = False
self.fields['image'].required = False
self.fields['image'].widget = PictureInlineWidget()
... | Formulaire admin des images | PictureAdminForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PictureAdminForm:
"""Formulaire admin des images"""
def __init__(self, *args, **kwargs):
"""Initialiser l'objet"""
<|body_0|>
def clean(self):
"""Valider les données du formulaire et formater"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_36k_train_033087 | 5,812 | no_license | [
{
"docstring": "Initialiser l'objet",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Valider les données du formulaire et formater",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | null | Implement the Python class `PictureAdminForm` described below.
Class description:
Formulaire admin des images
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialiser l'objet
- def clean(self): Valider les données du formulaire et formater | Implement the Python class `PictureAdminForm` described below.
Class description:
Formulaire admin des images
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialiser l'objet
- def clean(self): Valider les données du formulaire et formater
<|skeleton|>
class PictureAdminForm:
"""Formu... | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | <|skeleton|>
class PictureAdminForm:
"""Formulaire admin des images"""
def __init__(self, *args, **kwargs):
"""Initialiser l'objet"""
<|body_0|>
def clean(self):
"""Valider les données du formulaire et formater"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PictureAdminForm:
"""Formulaire admin des images"""
def __init__(self, *args, **kwargs):
"""Initialiser l'objet"""
super(PictureAdminForm, self).__init__(*args, **kwargs)
try:
self.fields['weight'].required = False
self.fields['author'].required = False
... | the_stack_v2_python_sparse | scoop/content/forms/picture.py | artscoop/scoop | train | 0 |
1a18452edd3191d2097e01d810e859f0d883b8ca | [
"super(DecoderWithPositionLayer, self).__init__()\nself.attention0 = Attention(queries_dropout=queries_dropout, keys_dropout=keys_dropout, values_dropout=values_dropout, causal=causal)\nself.block0 = Block(hidden_size, input_size * 3, **kwargs)\nself.pos_embedding = tf.keras.layers.Dense(input_size, **kwargs)\nself... | <|body_start_0|>
super(DecoderWithPositionLayer, self).__init__()
self.attention0 = Attention(queries_dropout=queries_dropout, keys_dropout=keys_dropout, values_dropout=values_dropout, causal=causal)
self.block0 = Block(hidden_size, input_size * 3, **kwargs)
self.pos_embedding = tf.keras... | DecoderWithPositionLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderWithPositionLayer:
def __init__(self, input_size, hidden_size, heads, queries_dropout=0.0, keys_dropout=0.0, values_dropout=0.0, causal=True, **kwargs):
"""Creates a Transformer decoder layer by applying a multi head attention layer Arguments: input_size: int the number of units i... | stack_v2_sparse_classes_36k_train_033088 | 8,096 | no_license | [
{
"docstring": "Creates a Transformer decoder layer by applying a multi head attention layer Arguments: input_size: int the number of units in the input tensor to this layer also the output size of the model hidden_size: int the number of units in the hidden variables used in each multi head attention layer hea... | 3 | stack_v2_sparse_classes_30k_train_006107 | Implement the Python class `DecoderWithPositionLayer` described below.
Class description:
Implement the DecoderWithPositionLayer class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, heads, queries_dropout=0.0, keys_dropout=0.0, values_dropout=0.0, causal=True, **kwargs): Creates a Tr... | Implement the Python class `DecoderWithPositionLayer` described below.
Class description:
Implement the DecoderWithPositionLayer class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, heads, queries_dropout=0.0, keys_dropout=0.0, values_dropout=0.0, causal=True, **kwargs): Creates a Tr... | c155b16265f13d87be0108fcf815517491b93a74 | <|skeleton|>
class DecoderWithPositionLayer:
def __init__(self, input_size, hidden_size, heads, queries_dropout=0.0, keys_dropout=0.0, values_dropout=0.0, causal=True, **kwargs):
"""Creates a Transformer decoder layer by applying a multi head attention layer Arguments: input_size: int the number of units i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderWithPositionLayer:
def __init__(self, input_size, hidden_size, heads, queries_dropout=0.0, keys_dropout=0.0, values_dropout=0.0, causal=True, **kwargs):
"""Creates a Transformer decoder layer by applying a multi head attention layer Arguments: input_size: int the number of units in the input te... | the_stack_v2_python_sparse | indigo/nn/layers/decoder_with_position_layer.py | mlberkeley/indigo | train | 4 | |
3e56e0bc6a88cfed99a3b9a024311f14daa90b10 | [
"super(Cont_RDB, self).__init__()\nself.InChan = InChannel\nself.OutChan = OutChannel\nself.G = growRate\nself.C = nConvLayers\nif self.InChan != self.G:\n self.InConv = nn.Conv2d(self.InChan, self.G, 1, padding=0, stride=1)\nif self.OutChan != self.G and self.OutChan != self.InChan:\n self.OutConv = nn.Conv2... | <|body_start_0|>
super(Cont_RDB, self).__init__()
self.InChan = InChannel
self.OutChan = OutChannel
self.G = growRate
self.C = nConvLayers
if self.InChan != self.G:
self.InConv = nn.Conv2d(self.InChan, self.G, 1, padding=0, stride=1)
if self.OutChan !=... | Contextual residual dense block. | Cont_RDB | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cont_RDB:
"""Contextual residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param gro... | stack_v2_sparse_classes_36k_train_033089 | 13,650 | permissive | [
{
"docstring": "Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growRate: growth rate of block :type growRate: int :param nConvLayers: the number of convlution layer :type nConvLayers: int :param kSize: ker... | 2 | stack_v2_sparse_classes_30k_train_007701 | Implement the Python class `Cont_RDB` described below.
Class description:
Contextual residual dense block.
Method signatures and docstrings:
- def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3): Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: ... | Implement the Python class `Cont_RDB` described below.
Class description:
Contextual residual dense block.
Method signatures and docstrings:
- def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3): Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: ... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class Cont_RDB:
"""Contextual residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param gro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cont_RDB:
"""Contextual residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growRate: growth... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/pytorch/esrbodys/erdb_esr.py | Huawei-Ascend/modelzoo | train | 1 |
c69f7d248f570cf75ae54d99dca51c684939ca8a | [
"if proctitle:\n self.proctitle = proctitle\nelif setproctitle:\n self.proctitle = setproctitle.getproctitle()\nelse:\n self.proctitle = 'ray_worker'\nself.pid = pid or os.getpid()\nself.ip = ip or ray.services.get_node_ip_address()\nself.function_name = function_name\nself.traceback_str = traceback_str\ns... | <|body_start_0|>
if proctitle:
self.proctitle = proctitle
elif setproctitle:
self.proctitle = setproctitle.getproctitle()
else:
self.proctitle = 'ray_worker'
self.pid = pid or os.getpid()
self.ip = ip or ray.services.get_node_ip_address()
... | Indicates that a task threw an exception during execution. If a task throws an exception during execution, a RayTaskError is stored in the object store for each of the task's outputs. When an object is retrieved from the object store, the Python method that retrieved it checks to see if the object is a RayTaskError and... | RayTaskError | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RayTaskError:
"""Indicates that a task threw an exception during execution. If a task throws an exception during execution, a RayTaskError is stored in the object store for each of the task's outputs. When an object is retrieved from the object store, the Python method that retrieved it checks to... | stack_v2_sparse_classes_36k_train_033090 | 5,517 | permissive | [
{
"docstring": "Initialize a RayTaskError.",
"name": "__init__",
"signature": "def __init__(self, function_name, traceback_str, cause_cls, proctitle=None, pid=None, ip=None)"
},
{
"docstring": "Returns copy that is an instance of the cause's Python class. The returned exception will inherit from... | 3 | null | Implement the Python class `RayTaskError` described below.
Class description:
Indicates that a task threw an exception during execution. If a task throws an exception during execution, a RayTaskError is stored in the object store for each of the task's outputs. When an object is retrieved from the object store, the Py... | Implement the Python class `RayTaskError` described below.
Class description:
Indicates that a task threw an exception during execution. If a task throws an exception during execution, a RayTaskError is stored in the object store for each of the task's outputs. When an object is retrieved from the object store, the Py... | 62bb26d5d04343e339d014f302a9fbacbd4482d7 | <|skeleton|>
class RayTaskError:
"""Indicates that a task threw an exception during execution. If a task throws an exception during execution, a RayTaskError is stored in the object store for each of the task's outputs. When an object is retrieved from the object store, the Python method that retrieved it checks to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RayTaskError:
"""Indicates that a task threw an exception during execution. If a task throws an exception during execution, a RayTaskError is stored in the object store for each of the task's outputs. When an object is retrieved from the object store, the Python method that retrieved it checks to see if the o... | the_stack_v2_python_sparse | python/ray/exceptions.py | stephanie-wang/ray | train | 4 |
228d14886b3dc0ccde6ac02482c5c5d907547bc3 | [
"base_dtype = [('P0', (np.float32, 3), '!local', (0, 0, 0)), ('P1', (np.float32, 3), '!local', (0, 0, 0)), ('index', (np.float32, 1), '!local', 0), ('color', (np.float32, 4), 'shared', (0, 0, 0, 1)), ('linewidth', (np.float32, 1), 'shared', 1), ('antialias', (np.float32, 1), 'shared', 1)]\ndtype = base_dtype\nif us... | <|body_start_0|>
base_dtype = [('P0', (np.float32, 3), '!local', (0, 0, 0)), ('P1', (np.float32, 3), '!local', (0, 0, 0)), ('index', (np.float32, 1), '!local', 0), ('color', (np.float32, 4), 'shared', (0, 0, 0, 1)), ('linewidth', (np.float32, 1), 'shared', 1), ('antialias', (np.float32, 1), 'shared', 1)]
... | Antigrain Geometry Segment Collection This collection provides antialiased and accurate segments with caps. It consume x2 more memory than regular lines and is a bit slower, but the quality of the output is worth the cost. | AggSegmentCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AggSegmentCollection:
"""Antigrain Geometry Segment Collection This collection provides antialiased and accurate segments with caps. It consume x2 more memory than regular lines and is a bit slower, but the quality of the output is worth the cost."""
def __init__(self, user_dtype=None, trans... | stack_v2_sparse_classes_36k_train_033091 | 5,126 | permissive | [
{
"docstring": "Initialize the collection. Parameters ---------- user_dtype: list The base dtype can be completed (appended) by the used_dtype. It only make sense if user also provide vertex and/or fragment shaders transform: glumpy.Transforms The default vertex shader apply the supplied transform to the vertic... | 2 | stack_v2_sparse_classes_30k_train_002558 | Implement the Python class `AggSegmentCollection` described below.
Class description:
Antigrain Geometry Segment Collection This collection provides antialiased and accurate segments with caps. It consume x2 more memory than regular lines and is a bit slower, but the quality of the output is worth the cost.
Method si... | Implement the Python class `AggSegmentCollection` described below.
Class description:
Antigrain Geometry Segment Collection This collection provides antialiased and accurate segments with caps. It consume x2 more memory than regular lines and is a bit slower, but the quality of the output is worth the cost.
Method si... | 75408635bd46e48ff10939e308a71eafdaff35e8 | <|skeleton|>
class AggSegmentCollection:
"""Antigrain Geometry Segment Collection This collection provides antialiased and accurate segments with caps. It consume x2 more memory than regular lines and is a bit slower, but the quality of the output is worth the cost."""
def __init__(self, user_dtype=None, trans... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AggSegmentCollection:
"""Antigrain Geometry Segment Collection This collection provides antialiased and accurate segments with caps. It consume x2 more memory than regular lines and is a bit slower, but the quality of the output is worth the cost."""
def __init__(self, user_dtype=None, transform=None, vi... | the_stack_v2_python_sparse | glumpy/graphics/collections/agg_segment_collection.py | glumpy/glumpy | train | 1,228 |
83238cad5086cb919db6ddc32f64a9c663348006 | [
"file_list = []\nfor root, _, files in os.walk(path):\n for f in files:\n if log_filenames_re.match(f):\n filename = os.path.join(root, f)\n modtime = datetime.fromtimestamp(os.path.getmtime(filename)).strftime('%m/%d/%Y %H:%M:%S')\n file_list.append([filename, modtime])\n... | <|body_start_0|>
file_list = []
for root, _, files in os.walk(path):
for f in files:
if log_filenames_re.match(f):
filename = os.path.join(root, f)
modtime = datetime.fromtimestamp(os.path.getmtime(filename)).strftime('%m/%d/%Y %H:%M:%S... | LogFilesManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogFilesManager:
def list_logfiles(self, path=settings.LOGGING_ROOT):
"""Returns list of .log files recursed into logfile dir"""
<|body_0|>
def get_file_lines_count(self, logfile):
"""Returns array of counts for pagination"""
<|body_1|>
def parse_log_fil... | stack_v2_sparse_classes_36k_train_033092 | 2,618 | no_license | [
{
"docstring": "Returns list of .log files recursed into logfile dir",
"name": "list_logfiles",
"signature": "def list_logfiles(self, path=settings.LOGGING_ROOT)"
},
{
"docstring": "Returns array of counts for pagination",
"name": "get_file_lines_count",
"signature": "def get_file_lines_... | 4 | null | Implement the Python class `LogFilesManager` described below.
Class description:
Implement the LogFilesManager class.
Method signatures and docstrings:
- def list_logfiles(self, path=settings.LOGGING_ROOT): Returns list of .log files recursed into logfile dir
- def get_file_lines_count(self, logfile): Returns array o... | Implement the Python class `LogFilesManager` described below.
Class description:
Implement the LogFilesManager class.
Method signatures and docstrings:
- def list_logfiles(self, path=settings.LOGGING_ROOT): Returns list of .log files recursed into logfile dir
- def get_file_lines_count(self, logfile): Returns array o... | d0be90d610879bde0004baceac969cb02fc67d1c | <|skeleton|>
class LogFilesManager:
def list_logfiles(self, path=settings.LOGGING_ROOT):
"""Returns list of .log files recursed into logfile dir"""
<|body_0|>
def get_file_lines_count(self, logfile):
"""Returns array of counts for pagination"""
<|body_1|>
def parse_log_fil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogFilesManager:
def list_logfiles(self, path=settings.LOGGING_ROOT):
"""Returns list of .log files recursed into logfile dir"""
file_list = []
for root, _, files in os.walk(path):
for f in files:
if log_filenames_re.match(f):
filename = ... | the_stack_v2_python_sparse | mdcom/MHLogin/Logs/utils.py | DongHuaLu/mdcom | train | 0 | |
f95c21747e1138c18742f474651a3ba08acf832f | [
"context = super(FieldCreate, self).get_context_data(self.kwargs['project_id'], self.kwargs['category_id'], **kwargs)\ncontext['fieldtypes'] = Field.get_field_types()\nreturn context",
"request = self.request\ndata = form.cleaned_data\ncategory = Category.objects.as_admin(self.request.user, self.kwargs['project_i... | <|body_start_0|>
context = super(FieldCreate, self).get_context_data(self.kwargs['project_id'], self.kwargs['category_id'], **kwargs)
context['fieldtypes'] = Field.get_field_types()
return context
<|end_body_0|>
<|body_start_1|>
request = self.request
data = form.cleaned_data
... | Creat field page. | FieldCreate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FieldCreate:
"""Creat field page."""
def get_context_data(self, data=None, **kwargs):
"""Return the context to render the view. Overwrite the method to add available field types the context. Parameters ---------- project_id : int Identifies the project in the database. category_id : ... | stack_v2_sparse_classes_36k_train_033093 | 31,602 | permissive | [
{
"docstring": "Return the context to render the view. Overwrite the method to add available field types the context. Parameters ---------- project_id : int Identifies the project in the database. category_id : int Identifies the category in the database. Returns ------- dict Context.",
"name": "get_context... | 2 | null | Implement the Python class `FieldCreate` described below.
Class description:
Creat field page.
Method signatures and docstrings:
- def get_context_data(self, data=None, **kwargs): Return the context to render the view. Overwrite the method to add available field types the context. Parameters ---------- project_id : i... | Implement the Python class `FieldCreate` described below.
Class description:
Creat field page.
Method signatures and docstrings:
- def get_context_data(self, data=None, **kwargs): Return the context to render the view. Overwrite the method to add available field types the context. Parameters ---------- project_id : i... | 16d31b5207de9f699fc01054baad1fe65ad1c3ca | <|skeleton|>
class FieldCreate:
"""Creat field page."""
def get_context_data(self, data=None, **kwargs):
"""Return the context to render the view. Overwrite the method to add available field types the context. Parameters ---------- project_id : int Identifies the project in the database. category_id : ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FieldCreate:
"""Creat field page."""
def get_context_data(self, data=None, **kwargs):
"""Return the context to render the view. Overwrite the method to add available field types the context. Parameters ---------- project_id : int Identifies the project in the database. category_id : int Identifie... | the_stack_v2_python_sparse | geokey/categories/views.py | NeolithEra/geokey | train | 0 |
e5884c4eecd2966be58b30a4de13af8ac3c10eec | [
"pr = [[[0] * K for j in range(N)] for i in range(N)]\n\ndef probab(N, K, r, c):\n if K == 0:\n return 1\n elif pr[r][c][K - 1] > 0:\n return pr[r][c][K - 1]\n p = 0\n for move in [[1, 2], [2, 1], [-1, 2], [-2, 1], [-1, -2], [-2, -1], [1, -2], [2, -1]]:\n rr, cc = (r + move[0], c + ... | <|body_start_0|>
pr = [[[0] * K for j in range(N)] for i in range(N)]
def probab(N, K, r, c):
if K == 0:
return 1
elif pr[r][c][K - 1] > 0:
return pr[r][c][K - 1]
p = 0
for move in [[1, 2], [2, 1], [-1, 2], [-2, 1], [-1, -2... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def knightProbability(self, N, K, r, c):
""":type N: int :type K: int :type r: int :type c: int :rtype: float"""
<|body_0|>
def knightProbability2(self, N, K, r, c):
""":type N: int :type K: int :type r: int :type c: int :rtype: float"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_033094 | 3,065 | no_license | [
{
"docstring": ":type N: int :type K: int :type r: int :type c: int :rtype: float",
"name": "knightProbability",
"signature": "def knightProbability(self, N, K, r, c)"
},
{
"docstring": ":type N: int :type K: int :type r: int :type c: int :rtype: float",
"name": "knightProbability2",
"si... | 2 | stack_v2_sparse_classes_30k_train_006311 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def knightProbability(self, N, K, r, c): :type N: int :type K: int :type r: int :type c: int :rtype: float
- def knightProbability2(self, N, K, r, c): :type N: int :type K: int :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def knightProbability(self, N, K, r, c): :type N: int :type K: int :type r: int :type c: int :rtype: float
- def knightProbability2(self, N, K, r, c): :type N: int :type K: int :... | 30b7d5acec716b7d754141835fc8bafe4411437e | <|skeleton|>
class Solution:
def knightProbability(self, N, K, r, c):
""":type N: int :type K: int :type r: int :type c: int :rtype: float"""
<|body_0|>
def knightProbability2(self, N, K, r, c):
""":type N: int :type K: int :type r: int :type c: int :rtype: float"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def knightProbability(self, N, K, r, c):
""":type N: int :type K: int :type r: int :type c: int :rtype: float"""
pr = [[[0] * K for j in range(N)] for i in range(N)]
def probab(N, K, r, c):
if K == 0:
return 1
elif pr[r][c][K - 1] > 0:... | the_stack_v2_python_sparse | 688.py | MajestyLee/leetcode_TopInterview | train | 0 | |
63f19762c3cd44d05cd3dc51f3cb193ce3e5d93b | [
"routing_table_file = open(routing_table_file_name, 'rb')\nrouting_table = pickle.load(routing_table_file)\nrouting_table_file.close()\nreturn routing_table",
"pickle_file_name = 'picked_routing_table_for_{}_{}'.format(routing_table.x, routing_table.y)\npickle_file_path = os.path.join(binary_directory, pickle_fil... | <|body_start_0|>
routing_table_file = open(routing_table_file_name, 'rb')
routing_table = pickle.load(routing_table_file)
routing_table_file.close()
return routing_table
<|end_body_0|>
<|body_start_1|>
pickle_file_name = 'picked_routing_table_for_{}_{}'.format(routing_table.x, r... | A routing table to be reloaded | ReloadRoutingTable | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReloadRoutingTable:
"""A routing table to be reloaded"""
def reload(routing_table_file_name):
"""Reload a routing table via a pickled filename :param routing_table_file_name: the file name for the pickled routeing table :return: None"""
<|body_0|>
def store(binary_direct... | stack_v2_sparse_classes_36k_train_033095 | 1,109 | permissive | [
{
"docstring": "Reload a routing table via a pickled filename :param routing_table_file_name: the file name for the pickled routeing table :return: None",
"name": "reload",
"signature": "def reload(routing_table_file_name)"
},
{
"docstring": "Store a routing table in pickled form :param binary_d... | 2 | stack_v2_sparse_classes_30k_train_009801 | Implement the Python class `ReloadRoutingTable` described below.
Class description:
A routing table to be reloaded
Method signatures and docstrings:
- def reload(routing_table_file_name): Reload a routing table via a pickled filename :param routing_table_file_name: the file name for the pickled routeing table :return... | Implement the Python class `ReloadRoutingTable` described below.
Class description:
A routing table to be reloaded
Method signatures and docstrings:
- def reload(routing_table_file_name): Reload a routing table via a pickled filename :param routing_table_file_name: the file name for the pickled routeing table :return... | 04fa1eaf78778edea3ba3afa4c527d20c491718e | <|skeleton|>
class ReloadRoutingTable:
"""A routing table to be reloaded"""
def reload(routing_table_file_name):
"""Reload a routing table via a pickled filename :param routing_table_file_name: the file name for the pickled routeing table :return: None"""
<|body_0|>
def store(binary_direct... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReloadRoutingTable:
"""A routing table to be reloaded"""
def reload(routing_table_file_name):
"""Reload a routing table via a pickled filename :param routing_table_file_name: the file name for the pickled routeing table :return: None"""
routing_table_file = open(routing_table_file_name, '... | the_stack_v2_python_sparse | src/spinnaker_ros_lsm/venv/lib/python2.7/site-packages/spinn_front_end_common/utilities/reload/reload_routing_table.py | Roboy/LSM_SpiNNaker_MyoArm | train | 2 |
1c76ef21101d052f057298c5b3f23375a3e8acbe | [
"self.current_sentence = ''\nself.data_dict = defaultdict(int)\nfor i in range(len(sentences)):\n self.data_dict[sentences[i]] = times[i]",
"if c == '#':\n self.data_dict[self.current_sentence] += 1\n self.current_sentence = ''\nelse:\n self.current_sentence += c\n curr_search_list = []\n len_cu... | <|body_start_0|>
self.current_sentence = ''
self.data_dict = defaultdict(int)
for i in range(len(sentences)):
self.data_dict[sentences[i]] = times[i]
<|end_body_0|>
<|body_start_1|>
if c == '#':
self.data_dict[self.current_sentence] += 1
self.current_... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.current_sentence ... | stack_v2_sparse_classes_36k_train_033096 | 2,553 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | null | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | a9b2de06306f3929a82ef4e6613c972e9a2c2200 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
self.current_sentence = ''
self.data_dict = defaultdict(int)
for i in range(len(sentences)):
self.data_dict[sentences[i]] = times[i]
def input(self... | the_stack_v2_python_sparse | Array_Manipulations/Design_Search_Autocomplete_System.py | anantvir/Leetcode-Problems | train | 1 | |
a58e4160d68b175df5879c1827ff418d3db60558 | [
"taskPath = self.basePath / taskName\nkeys: Set[str] = set()\nif taskPath.is_dir():\n keys.update((path.name for path in taskPath.iterdir()))\nreturn keys",
"valuePath = self.basePath / taskName / key\nfor run in runIds:\n try:\n with open(valuePath / run) as inp:\n value = inp.readline()\... | <|body_start_0|>
taskPath = self.basePath / taskName
keys: Set[str] = set()
if taskPath.is_dir():
keys.update((path.name for path in taskPath.iterdir()))
return keys
<|end_body_0|>
<|body_start_1|>
valuePath = self.basePath / taskName / key
for run in runIds:... | ResultStorage | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResultStorage:
def getCustomKeys(self, taskName: str) -> Set[str]:
"""Get the set of used-defined keys that exist for the given task name. The existance of a key means that at least one record contains that key; it is not guaranteed all records will contain that key."""
<|body_0|... | stack_v2_sparse_classes_36k_train_033097 | 2,681 | permissive | [
{
"docstring": "Get the set of used-defined keys that exist for the given task name. The existance of a key means that at least one record contains that key; it is not guaranteed all records will contain that key.",
"name": "getCustomKeys",
"signature": "def getCustomKeys(self, taskName: str) -> Set[str... | 3 | null | Implement the Python class `ResultStorage` described below.
Class description:
Implement the ResultStorage class.
Method signatures and docstrings:
- def getCustomKeys(self, taskName: str) -> Set[str]: Get the set of used-defined keys that exist for the given task name. The existance of a key means that at least one ... | Implement the Python class `ResultStorage` described below.
Class description:
Implement the ResultStorage class.
Method signatures and docstrings:
- def getCustomKeys(self, taskName: str) -> Set[str]: Get the set of used-defined keys that exist for the given task name. The existance of a key means that at least one ... | 0ecf899f66a1fb046ee869cbfa3b5374b3f8aa14 | <|skeleton|>
class ResultStorage:
def getCustomKeys(self, taskName: str) -> Set[str]:
"""Get the set of used-defined keys that exist for the given task name. The existance of a key means that at least one record contains that key; it is not guaranteed all records will contain that key."""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResultStorage:
def getCustomKeys(self, taskName: str) -> Set[str]:
"""Get the set of used-defined keys that exist for the given task name. The existance of a key means that at least one record contains that key; it is not guaranteed all records will contain that key."""
taskPath = self.basePat... | the_stack_v2_python_sparse | src/softfab/resultlib.py | boxingbeetle/softfab | train | 20 | |
0364f1974d37932f097d0ef8424bca2f563cba0f | [
"Package.__init__(self, model)\nnrow, ncol, nlay, nper = self.parent.nrow_ncol_nlay_nper\nself.unit_number = [29, 53]\nself.extension = extension\nself.file_name = [self.parent.name + '.' + self.extension, fname_output]\nself.name = ['SWI', 'DATA(BINARY)']\nself.heading = '# Salt Water Intrusion package file for MO... | <|body_start_0|>
Package.__init__(self, model)
nrow, ncol, nlay, nper = self.parent.nrow_ncol_nlay_nper
self.unit_number = [29, 53]
self.extension = extension
self.file_name = [self.parent.name + '.' + self.extension, fname_output]
self.name = ['SWI', 'DATA(BINARY)']
... | Salt Water Intrusion (SWI) package class Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. npln : int number of active surfaces (interfaces). This equals the number of zones minus one. (default is 1). istrat : int flag indicating... | ModflowSwi | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModflowSwi:
"""Salt Water Intrusion (SWI) package class Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. npln : int number of active surfaces (interfaces). This equals the number of zones minus one. (defau... | stack_v2_sparse_classes_36k_train_033098 | 7,669 | permissive | [
{
"docstring": "Package constructor.",
"name": "__init__",
"signature": "def __init__(self, model, npln=1, istrat=1, iswizt=53, nprn=1, toeslope=0.05, tipslope=0.05, zetamin=0.005, delzeta=0.05, nu=0.025, zeta=[], ssz=[], isource=0, extension='swi', fname_output='swi.zta')"
},
{
"docstring": "Wr... | 3 | stack_v2_sparse_classes_30k_train_013261 | Implement the Python class `ModflowSwi` described below.
Class description:
Salt Water Intrusion (SWI) package class Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. npln : int number of active surfaces (interfaces). This equal... | Implement the Python class `ModflowSwi` described below.
Class description:
Salt Water Intrusion (SWI) package class Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. npln : int number of active surfaces (interfaces). This equal... | 7f73a30300645be66e8952f653e03d91ceddbac3 | <|skeleton|>
class ModflowSwi:
"""Salt Water Intrusion (SWI) package class Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. npln : int number of active surfaces (interfaces). This equals the number of zones minus one. (defau... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModflowSwi:
"""Salt Water Intrusion (SWI) package class Parameters ---------- model : model object The model object (of type :class:`flopy.modflow.mf.Modflow`) to which this package will be added. npln : int number of active surfaces (interfaces). This equals the number of zones minus one. (default is 1). ist... | the_stack_v2_python_sparse | flopy/modflow/mfswi.py | visr/flopy | train | 0 |
f44e97691dab25cc4a87f43c0438723163d80bd0 | [
"for location, pascal_value in self.knownValues:\n result = explore_pascals_triangle.C(location[0], location[1])\n self.assertEqual(pascal_value, result)",
"for location, pascal_value in self.knownValues:\n result = explore_pascals_triangle.calc_pascal_value(location[0], location[1])\n self.assertEqua... | <|body_start_0|>
for location, pascal_value in self.knownValues:
result = explore_pascals_triangle.C(location[0], location[1])
self.assertEqual(pascal_value, result)
<|end_body_0|>
<|body_start_1|>
for location, pascal_value in self.knownValues:
result = explore_pasc... | TestProblem1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProblem1:
def test_method_C_to_known_values(self):
"""C function should give known result with known input"""
<|body_0|>
def test_method_calc_pascal_value_to_known_values(self):
"""calc_pascal_value function should give known result with known input"""
<|... | stack_v2_sparse_classes_36k_train_033099 | 1,035 | no_license | [
{
"docstring": "C function should give known result with known input",
"name": "test_method_C_to_known_values",
"signature": "def test_method_C_to_known_values(self)"
},
{
"docstring": "calc_pascal_value function should give known result with known input",
"name": "test_method_calc_pascal_va... | 2 | stack_v2_sparse_classes_30k_train_001085 | Implement the Python class `TestProblem1` described below.
Class description:
Implement the TestProblem1 class.
Method signatures and docstrings:
- def test_method_C_to_known_values(self): C function should give known result with known input
- def test_method_calc_pascal_value_to_known_values(self): calc_pascal_value... | Implement the Python class `TestProblem1` described below.
Class description:
Implement the TestProblem1 class.
Method signatures and docstrings:
- def test_method_C_to_known_values(self): C function should give known result with known input
- def test_method_calc_pascal_value_to_known_values(self): calc_pascal_value... | 9a21945735add7739b062be4cd016525c592f23d | <|skeleton|>
class TestProblem1:
def test_method_C_to_known_values(self):
"""C function should give known result with known input"""
<|body_0|>
def test_method_calc_pascal_value_to_known_values(self):
"""calc_pascal_value function should give known result with known input"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestProblem1:
def test_method_C_to_known_values(self):
"""C function should give known result with known input"""
for location, pascal_value in self.knownValues:
result = explore_pascals_triangle.C(location[0], location[1])
self.assertEqual(pascal_value, result)
de... | the_stack_v2_python_sparse | test_pascal_triangle_values.py | afcarl/python-algorithms-1 | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.