blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
94fbe5b545975b1823633bb6341883b7bb556496 | [
"self.configuration = PaccMannRLProteinBasedGenerator(algorithm_version=algorithm_version, temperature=temperature, generated_length=generated_length, batch_size=batch_size)\nself.batch_size = batch_size\nself.algorithm = PaccMannRL(configuration=self.configuration, target='')\nself.model = self.configuration.get_c... | <|body_start_0|>
self.configuration = PaccMannRLProteinBasedGenerator(algorithm_version=algorithm_version, temperature=temperature, generated_length=generated_length, batch_size=batch_size)
self.batch_size = batch_size
self.algorithm = PaccMannRL(configuration=self.configuration, target='')
... | Molecular generator as implemented in https://doi.org/10.1016/j.isci.2021.102269 | PaccMannVaeDefaultGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaccMannVaeDefaultGenerator:
"""Molecular generator as implemented in https://doi.org/10.1016/j.isci.2021.102269"""
def __init__(self, temperature: float=1.4, batch_size: int=32, algorithm_version: str='v0', generated_length: int=100) -> None:
"""Initialize the generator. Args: batch... | stack_v2_sparse_classes_10k_train_006300 | 3,894 | permissive | [
{
"docstring": "Initialize the generator. Args: batch_size: batch size used for generation. algorithm_version: algorithm version for the PaccMannRLProteinBasedGenerator. NOTE: Only the decoder of that model is used here. temperature: temperature for the sampling. Defaults to 1.4. generated_length: maximum lengt... | 2 | stack_v2_sparse_classes_30k_train_007296 | Implement the Python class `PaccMannVaeDefaultGenerator` described below.
Class description:
Molecular generator as implemented in https://doi.org/10.1016/j.isci.2021.102269
Method signatures and docstrings:
- def __init__(self, temperature: float=1.4, batch_size: int=32, algorithm_version: str='v0', generated_length... | Implement the Python class `PaccMannVaeDefaultGenerator` described below.
Class description:
Molecular generator as implemented in https://doi.org/10.1016/j.isci.2021.102269
Method signatures and docstrings:
- def __init__(self, temperature: float=1.4, batch_size: int=32, algorithm_version: str='v0', generated_length... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class PaccMannVaeDefaultGenerator:
"""Molecular generator as implemented in https://doi.org/10.1016/j.isci.2021.102269"""
def __init__(self, temperature: float=1.4, batch_size: int=32, algorithm_version: str='v0', generated_length: int=100) -> None:
"""Initialize the generator. Args: batch... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PaccMannVaeDefaultGenerator:
"""Molecular generator as implemented in https://doi.org/10.1016/j.isci.2021.102269"""
def __init__(self, temperature: float=1.4, batch_size: int=32, algorithm_version: str='v0', generated_length: int=100) -> None:
"""Initialize the generator. Args: batch_size: batch ... | the_stack_v2_python_sparse | src/gt4sd/algorithms/generation/paccmann_vae/implementation.py | GT4SD/gt4sd-core | train | 239 |
13fd766f365af07d6b4f89e1bff3fcce008cea0c | [
"super(Linear, self).__init__()\nself.fc0 = paddle.nn.Linear(in_features=in_features, out_features=out_features)\nself.sigmoid = paddle.nn.Sigmoid()",
"out = self.fc0(x)\nout = self.sigmoid(out)\nreturn out"
] | <|body_start_0|>
super(Linear, self).__init__()
self.fc0 = paddle.nn.Linear(in_features=in_features, out_features=out_features)
self.sigmoid = paddle.nn.Sigmoid()
<|end_body_0|>
<|body_start_1|>
out = self.fc0(x)
out = self.sigmoid(out)
return out
<|end_body_1|>
| Linear | Linear | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linear:
"""Linear"""
def __init__(self, in_features=3, out_features=10):
"""init"""
<|body_0|>
def forward(self, x):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Linear, self).__init__()
self.fc0 = paddle.nn.Linear(in... | stack_v2_sparse_classes_10k_train_006301 | 543 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, in_features=3, out_features=10)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | null | Implement the Python class `Linear` described below.
Class description:
Linear
Method signatures and docstrings:
- def __init__(self, in_features=3, out_features=10): init
- def forward(self, x): forward | Implement the Python class `Linear` described below.
Class description:
Linear
Method signatures and docstrings:
- def __init__(self, in_features=3, out_features=10): init
- def forward(self, x): forward
<|skeleton|>
class Linear:
"""Linear"""
def __init__(self, in_features=3, out_features=10):
"""i... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class Linear:
"""Linear"""
def __init__(self, in_features=3, out_features=10):
"""init"""
<|body_0|>
def forward(self, x):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Linear:
"""Linear"""
def __init__(self, in_features=3, out_features=10):
"""init"""
super(Linear, self).__init__()
self.fc0 = paddle.nn.Linear(in_features=in_features, out_features=out_features)
self.sigmoid = paddle.nn.Sigmoid()
def forward(self, x):
"""forwa... | the_stack_v2_python_sparse | framework/e2e/moduletrans/diy/layer/linear.py | PaddlePaddle/PaddleTest | train | 42 |
368f3d65b3dcbbfb9b9ff08b82a8748cb8826381 | [
"super().setUp()\nself.signup(self.CURRICULUM_ADMIN_EMAIL, self.CURRICULUM_ADMIN_USERNAME)\nself.signup(self.ALBERT_EMAIL, self.ALBERT_NAME)\nself.admin_id = self.get_user_id_from_email(self.CURRICULUM_ADMIN_EMAIL)\nself.albert_id = self.get_user_id_from_email(self.ALBERT_EMAIL)\nself.albert = user_services.get_use... | <|body_start_0|>
super().setUp()
self.signup(self.CURRICULUM_ADMIN_EMAIL, self.CURRICULUM_ADMIN_USERNAME)
self.signup(self.ALBERT_EMAIL, self.ALBERT_NAME)
self.admin_id = self.get_user_id_from_email(self.CURRICULUM_ADMIN_EMAIL)
self.albert_id = self.get_user_id_from_email(self.AL... | Test functions for getting displayable featured exploration summary dicts. | FeaturedExplorationDisplayableSummariesTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeaturedExplorationDisplayableSummariesTest:
"""Test functions for getting displayable featured exploration summary dicts."""
def setUp(self) -> None:
"""Populate the database of explorations and their summaries. The sequence of events is: - (1) Albert creates EXP_ID_1. - (2) Albert ... | stack_v2_sparse_classes_10k_train_006302 | 47,358 | permissive | [
{
"docstring": "Populate the database of explorations and their summaries. The sequence of events is: - (1) Albert creates EXP_ID_1. - (2) Albert creates EXP_ID_2. - (3) Albert publishes EXP_ID_1. - (4) Albert publishes EXP_ID_2. - (5) Admin user is set up.",
"name": "setUp",
"signature": "def setUp(sel... | 3 | null | Implement the Python class `FeaturedExplorationDisplayableSummariesTest` described below.
Class description:
Test functions for getting displayable featured exploration summary dicts.
Method signatures and docstrings:
- def setUp(self) -> None: Populate the database of explorations and their summaries. The sequence o... | Implement the Python class `FeaturedExplorationDisplayableSummariesTest` described below.
Class description:
Test functions for getting displayable featured exploration summary dicts.
Method signatures and docstrings:
- def setUp(self) -> None: Populate the database of explorations and their summaries. The sequence o... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class FeaturedExplorationDisplayableSummariesTest:
"""Test functions for getting displayable featured exploration summary dicts."""
def setUp(self) -> None:
"""Populate the database of explorations and their summaries. The sequence of events is: - (1) Albert creates EXP_ID_1. - (2) Albert ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeaturedExplorationDisplayableSummariesTest:
"""Test functions for getting displayable featured exploration summary dicts."""
def setUp(self) -> None:
"""Populate the database of explorations and their summaries. The sequence of events is: - (1) Albert creates EXP_ID_1. - (2) Albert creates EXP_I... | the_stack_v2_python_sparse | core/domain/summary_services_test.py | oppia/oppia | train | 6,172 |
7bc8fcefad5c9c7badac3ce46a01619c4ce35c25 | [
"if year < _Persian.START_YEAR or year > _Persian.END_YEAR:\n return None\nday = 21\nif year % 4 == 1 and year >= 2029 or (year % 4 == 2 and year >= 2062) or (year % 4 == 3 and year >= 2095) or (year % 4 == 0 and 1996 <= year <= 2096):\n day = 20\nelif year % 4 == 2 and year <= 1926 or (year % 4 == 3 and year... | <|body_start_0|>
if year < _Persian.START_YEAR or year > _Persian.END_YEAR:
return None
day = 21
if year % 4 == 1 and year >= 2029 or (year % 4 == 2 and year >= 2062) or (year % 4 == 3 and year >= 2095) or (year % 4 == 0 and 1996 <= year <= 2096):
day = 20
elif ye... | Persian calendar (Solar Hijri) for 1901-2100 years. https://en.wikipedia.org/wiki/Solar_Hijri_calendar | _Persian | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Persian:
"""Persian calendar (Solar Hijri) for 1901-2100 years. https://en.wikipedia.org/wiki/Solar_Hijri_calendar"""
def new_year_date(self, year: int) -> Optional[date]:
"""Return Gregorian date of Persian new year (1 Farvardin) in a given Gregorian year."""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_006303 | 1,855 | permissive | [
{
"docstring": "Return Gregorian date of Persian new year (1 Farvardin) in a given Gregorian year.",
"name": "new_year_date",
"signature": "def new_year_date(self, year: int) -> Optional[date]"
},
{
"docstring": "Return Gregorian date of Persian day and month in a given Gregorian year.",
"na... | 2 | stack_v2_sparse_classes_30k_train_000331 | Implement the Python class `_Persian` described below.
Class description:
Persian calendar (Solar Hijri) for 1901-2100 years. https://en.wikipedia.org/wiki/Solar_Hijri_calendar
Method signatures and docstrings:
- def new_year_date(self, year: int) -> Optional[date]: Return Gregorian date of Persian new year (1 Farvar... | Implement the Python class `_Persian` described below.
Class description:
Persian calendar (Solar Hijri) for 1901-2100 years. https://en.wikipedia.org/wiki/Solar_Hijri_calendar
Method signatures and docstrings:
- def new_year_date(self, year: int) -> Optional[date]: Return Gregorian date of Persian new year (1 Farvar... | f8c90952bf409703d0af5d89a202e21a90e2317f | <|skeleton|>
class _Persian:
"""Persian calendar (Solar Hijri) for 1901-2100 years. https://en.wikipedia.org/wiki/Solar_Hijri_calendar"""
def new_year_date(self, year: int) -> Optional[date]:
"""Return Gregorian date of Persian new year (1 Farvardin) in a given Gregorian year."""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _Persian:
"""Persian calendar (Solar Hijri) for 1901-2100 years. https://en.wikipedia.org/wiki/Solar_Hijri_calendar"""
def new_year_date(self, year: int) -> Optional[date]:
"""Return Gregorian date of Persian new year (1 Farvardin) in a given Gregorian year."""
if year < _Persian.START_YE... | the_stack_v2_python_sparse | holidays/calendars/persian.py | dr-prodigy/python-holidays | train | 919 |
595542f64e8dbcdc6f9d8cf293b84c27dda263de | [
"json_dict = json.loads(request.body.decode())\nreceiver = json_dict.get('receiver')\nprovince_id = json_dict.get('province_id')\ncity_id = json_dict.get('city_id')\ndistrict_id = json_dict.get('district_id')\nplace = json_dict.get('place')\nmobile = json_dict.get('mobile')\ntel = json_dict.get('tel')\nemail = json... | <|body_start_0|>
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('province_id')
city_id = json_dict.get('city_id')
district_id = json_dict.get('district_id')
place = json_dict.get('place')
mobile = jso... | 更新地址 | UpdateDestoryAdressView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateDestoryAdressView:
"""更新地址"""
def put(self, request, address_id):
"""更新地址 :param request: :param address_id:修改删除 :return:"""
<|body_0|>
def delete(self, request, address_id):
"""删除地址"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
json_dic... | stack_v2_sparse_classes_10k_train_006304 | 22,758 | permissive | [
{
"docstring": "更新地址 :param request: :param address_id:修改删除 :return:",
"name": "put",
"signature": "def put(self, request, address_id)"
},
{
"docstring": "删除地址",
"name": "delete",
"signature": "def delete(self, request, address_id)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000269 | Implement the Python class `UpdateDestoryAdressView` described below.
Class description:
更新地址
Method signatures and docstrings:
- def put(self, request, address_id): 更新地址 :param request: :param address_id:修改删除 :return:
- def delete(self, request, address_id): 删除地址 | Implement the Python class `UpdateDestoryAdressView` described below.
Class description:
更新地址
Method signatures and docstrings:
- def put(self, request, address_id): 更新地址 :param request: :param address_id:修改删除 :return:
- def delete(self, request, address_id): 删除地址
<|skeleton|>
class UpdateDestoryAdressView:
"""更... | 2434231795b3319dfda60b19af18442ee5f6fa73 | <|skeleton|>
class UpdateDestoryAdressView:
"""更新地址"""
def put(self, request, address_id):
"""更新地址 :param request: :param address_id:修改删除 :return:"""
<|body_0|>
def delete(self, request, address_id):
"""删除地址"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpdateDestoryAdressView:
"""更新地址"""
def put(self, request, address_id):
"""更新地址 :param request: :param address_id:修改删除 :return:"""
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('province_id')
city_id ... | the_stack_v2_python_sparse | meiduo_project/meiduo_mall/meiduo_mall/apps/users/views.py | xlztongxue/meiduoshangcheng | train | 0 |
7aafc28155784d1966fb2b4a3b65535a81837578 | [
"pointer_a = headA\npointer_b = headB\nseen = set()\nwhile pointer_a is not None:\n seen.add(pointer_a)\n pointer_a = pointer_a.next\nwhile pointer_b is not None:\n if pointer_b in seen:\n return pointer_b\n pointer_b = pointer_b.next\nreturn None",
"pointer_a = headA\npointer_b = headB\nif poi... | <|body_start_0|>
pointer_a = headA
pointer_b = headB
seen = set()
while pointer_a is not None:
seen.add(pointer_a)
pointer_a = pointer_a.next
while pointer_b is not None:
if pointer_b in seen:
return pointer_b
pointe... | https://leetcode-cn.com/problems/intersection-of-two-linked-lists/ | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""https://leetcode-cn.com/problems/intersection-of-two-linked-lists/"""
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
"""哈希表法: https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/xiang-jiao-lian-biao-by-leetcode/"""
... | stack_v2_sparse_classes_10k_train_006305 | 4,375 | no_license | [
{
"docstring": "哈希表法: https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/xiang-jiao-lian-biao-by-leetcode/",
"name": "getIntersectionNode",
"signature": "def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode"
},
{
"docstring": "解:https://leetcode-cn.... | 2 | null | Implement the Python class `Solution` described below.
Class description:
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
Method signatures and docstrings:
- def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: 哈希表法: https://leetcode-cn.com/problems/intersection-of-two-linke... | Implement the Python class `Solution` described below.
Class description:
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
Method signatures and docstrings:
- def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: 哈希表法: https://leetcode-cn.com/problems/intersection-of-two-linke... | 3ea03cd8b1fa507553ebee4fd765c4cc4b5814b6 | <|skeleton|>
class Solution:
"""https://leetcode-cn.com/problems/intersection-of-two-linked-lists/"""
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
"""哈希表法: https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/xiang-jiao-lian-biao-by-leetcode/"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""https://leetcode-cn.com/problems/intersection-of-two-linked-lists/"""
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
"""哈希表法: https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/xiang-jiao-lian-biao-by-leetcode/"""
pointer_... | the_stack_v2_python_sparse | Intersection_of_Two_Linked_Lists_160.py | jay6413682/Leetcode | train | 0 |
b57df1e75351369793b1073e61ac2bd351abd0ef | [
"if not head or head.next:\n return head\nnew_head = self.reverse_(head.next)\nhead.next.next = new_head\nhead.next = None\nreturn new_head",
"prev = None\ncurr = head\nwhile curr:\n next_node = curr.next\n curr.next = prev\n prev = curr\n curr = next_node\nreturn prev"
] | <|body_start_0|>
if not head or head.next:
return head
new_head = self.reverse_(head.next)
head.next.next = new_head
head.next = None
return new_head
<|end_body_0|>
<|body_start_1|>
prev = None
curr = head
while curr:
next_node = c... | LinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkedList:
def reverse_(self, head: 'ListNode') -> 'ListNode':
"""Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param head: :return:"""
<|body_0|>
def reverse(self, head: 'ListNode') -> 'ListNode':
"""Approach: Iterative Time Complexity: O(N) Spa... | stack_v2_sparse_classes_10k_train_006306 | 1,231 | no_license | [
{
"docstring": "Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param head: :return:",
"name": "reverse_",
"signature": "def reverse_(self, head: 'ListNode') -> 'ListNode'"
},
{
"docstring": "Approach: Iterative Time Complexity: O(N) Space Complexity: O(1) :param head: :return:... | 2 | null | Implement the Python class `LinkedList` described below.
Class description:
Implement the LinkedList class.
Method signatures and docstrings:
- def reverse_(self, head: 'ListNode') -> 'ListNode': Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param head: :return:
- def reverse(self, head: 'ListNode... | Implement the Python class `LinkedList` described below.
Class description:
Implement the LinkedList class.
Method signatures and docstrings:
- def reverse_(self, head: 'ListNode') -> 'ListNode': Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param head: :return:
- def reverse(self, head: 'ListNode... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class LinkedList:
def reverse_(self, head: 'ListNode') -> 'ListNode':
"""Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param head: :return:"""
<|body_0|>
def reverse(self, head: 'ListNode') -> 'ListNode':
"""Approach: Iterative Time Complexity: O(N) Spa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LinkedList:
def reverse_(self, head: 'ListNode') -> 'ListNode':
"""Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param head: :return:"""
if not head or head.next:
return head
new_head = self.reverse_(head.next)
head.next.next = new_head
h... | the_stack_v2_python_sparse | goldman_sachs/reverse_linked_list.py | Shiv2157k/leet_code | train | 1 | |
b97c5d03774577aabae46632a1a9428a132df0c7 | [
"try:\n book = BookInfo.objects.get(pk=pk)\nexcept BookInfo.DoesNotExist:\n return HttpResponse(status=404)\ndata = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if book.image else ''}\nreturn JsonResponse(data)",
... | <|body_start_0|>
try:
book = BookInfo.objects.get(pk=pk)
except BookInfo.DoesNotExist:
return HttpResponse(status=404)
data = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if boo... | BookDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookDetailView:
def get(self, request, pk):
"""获取指定的图书信息"""
<|body_0|>
def put(self, request, pk):
"""修改指定的图书信息"""
<|body_1|>
def delete(self, request, pk):
"""删除指定的图书信息"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_10k_train_006307 | 4,373 | no_license | [
{
"docstring": "获取指定的图书信息",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "修改指定的图书信息",
"name": "put",
"signature": "def put(self, request, pk)"
},
{
"docstring": "删除指定的图书信息",
"name": "delete",
"signature": "def delete(self, request, pk)"
}
] | 3 | stack_v2_sparse_classes_30k_train_006028 | Implement the Python class `BookDetailView` described below.
Class description:
Implement the BookDetailView class.
Method signatures and docstrings:
- def get(self, request, pk): 获取指定的图书信息
- def put(self, request, pk): 修改指定的图书信息
- def delete(self, request, pk): 删除指定的图书信息 | Implement the Python class `BookDetailView` described below.
Class description:
Implement the BookDetailView class.
Method signatures and docstrings:
- def get(self, request, pk): 获取指定的图书信息
- def put(self, request, pk): 修改指定的图书信息
- def delete(self, request, pk): 删除指定的图书信息
<|skeleton|>
class BookDetailView:
def ... | f8ec0bec399253e481e16443ba9a3e45e61486f4 | <|skeleton|>
class BookDetailView:
def get(self, request, pk):
"""获取指定的图书信息"""
<|body_0|>
def put(self, request, pk):
"""修改指定的图书信息"""
<|body_1|>
def delete(self, request, pk):
"""删除指定的图书信息"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BookDetailView:
def get(self, request, pk):
"""获取指定的图书信息"""
try:
book = BookInfo.objects.get(pk=pk)
except BookInfo.DoesNotExist:
return HttpResponse(status=404)
data = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bre... | the_stack_v2_python_sparse | drf_demo/booktest/views-01-Django自定义RestAPI接口.py | cz495969281/2019_- | train | 0 | |
98d20027dc3eb270b1e9636165296c15b5482d38 | [
"pk = kwargs.get('pk')\nproj = Project.objects.filter(id=pk).first()\nif check_user_can_edit(proj, request.user):\n team_can_edit = check_user_teams_can_edit(proj, request.user)\n form = ProjectForm(instance=proj, can_edit=team_can_edit)\n return render(request, self.template_name, {'object': proj, 'form':... | <|body_start_0|>
pk = kwargs.get('pk')
proj = Project.objects.filter(id=pk).first()
if check_user_can_edit(proj, request.user):
team_can_edit = check_user_teams_can_edit(proj, request.user)
form = ProjectForm(instance=proj, can_edit=team_can_edit)
return rende... | View for editing the details of an existing Project instance. | ProjectEditView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectEditView:
"""View for editing the details of an existing Project instance."""
def get(self, request, *args, **kwargs):
"""Override default get request. So we can verify the user has edit privileges, either through super status or team membership."""
<|body_0|>
def... | stack_v2_sparse_classes_10k_train_006308 | 10,681 | no_license | [
{
"docstring": "Override default get request. So we can verify the user has edit privileges, either through super status or team membership.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Project Edit Form validation and redirect.",
"name": "form_v... | 2 | stack_v2_sparse_classes_30k_train_001197 | Implement the Python class `ProjectEditView` described below.
Class description:
View for editing the details of an existing Project instance.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Override default get request. So we can verify the user has edit privileges, either through super ... | Implement the Python class `ProjectEditView` described below.
Class description:
View for editing the details of an existing Project instance.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Override default get request. So we can verify the user has edit privileges, either through super ... | ee419afa3c9f4b9ef3b30b62b693cfac956ce5b4 | <|skeleton|>
class ProjectEditView:
"""View for editing the details of an existing Project instance."""
def get(self, request, *args, **kwargs):
"""Override default get request. So we can verify the user has edit privileges, either through super status or team membership."""
<|body_0|>
def... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProjectEditView:
"""View for editing the details of an existing Project instance."""
def get(self, request, *args, **kwargs):
"""Override default get request. So we can verify the user has edit privileges, either through super status or team membership."""
pk = kwargs.get('pk')
pr... | the_stack_v2_python_sparse | DataSearch/projects/views.py | USEPA/FoodWaste | train | 1 |
27804157bd4866469b89c0294fee607aa4b4d174 | [
"feat = BoundingBox(n_class=10, max_bbox_per_data=10)\nwith pytest.raises((ValueError, TypeError)):\n features = feat._create_from(bboxes=bboxes)",
"nCapacity = 10\nfeat = BoundingBox(n_class=5, max_bbox_per_data=nCapacity)\nfor nBox in range(1, 21):\n yx = np.random.randint(1000, size=(nBox, 2)) / 10\n ... | <|body_start_0|>
feat = BoundingBox(n_class=10, max_bbox_per_data=10)
with pytest.raises((ValueError, TypeError)):
features = feat._create_from(bboxes=bboxes)
<|end_body_0|>
<|body_start_1|>
nCapacity = 10
feat = BoundingBox(n_class=5, max_bbox_per_data=nCapacity)
fo... | TestBBoxFeatures | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBBoxFeatures:
def test_invalid_bbox_should_be_blocked(self, bboxes):
"""Invliad bbox should be blocked by _create_from"""
<|body_0|>
def test_encode_decode_bboxes(self):
"""Check encodied ymin, xmin, height, width, class correct"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_10k_train_006309 | 8,391 | no_license | [
{
"docstring": "Invliad bbox should be blocked by _create_from",
"name": "test_invalid_bbox_should_be_blocked",
"signature": "def test_invalid_bbox_should_be_blocked(self, bboxes)"
},
{
"docstring": "Check encodied ymin, xmin, height, width, class correct",
"name": "test_encode_decode_bboxes... | 2 | stack_v2_sparse_classes_30k_train_006404 | Implement the Python class `TestBBoxFeatures` described below.
Class description:
Implement the TestBBoxFeatures class.
Method signatures and docstrings:
- def test_invalid_bbox_should_be_blocked(self, bboxes): Invliad bbox should be blocked by _create_from
- def test_encode_decode_bboxes(self): Check encodied ymin, ... | Implement the Python class `TestBBoxFeatures` described below.
Class description:
Implement the TestBBoxFeatures class.
Method signatures and docstrings:
- def test_invalid_bbox_should_be_blocked(self, bboxes): Invliad bbox should be blocked by _create_from
- def test_encode_decode_bboxes(self): Check encodied ymin, ... | 5da5317cedd380c244f20a96213e883d6ef29de2 | <|skeleton|>
class TestBBoxFeatures:
def test_invalid_bbox_should_be_blocked(self, bboxes):
"""Invliad bbox should be blocked by _create_from"""
<|body_0|>
def test_encode_decode_bboxes(self):
"""Check encodied ymin, xmin, height, width, class correct"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestBBoxFeatures:
def test_invalid_bbox_should_be_blocked(self, bboxes):
"""Invliad bbox should be blocked by _create_from"""
feat = BoundingBox(n_class=10, max_bbox_per_data=10)
with pytest.raises((ValueError, TypeError)):
features = feat._create_from(bboxes=bboxes)
d... | the_stack_v2_python_sparse | Database/_unittests/test_features.py | MingRuey/mlbox | train | 2 | |
6175ea630661aec07348e26a9f78165f0cf043b7 | [
"self._mount_path = '/usr/local/qai/mnt'\nself._run_id = 1\nself._job_id = 1\nself._output_file_path = f'{self._mount_path}/ip/job_args/{self._job_id}/{self._run_id}/ait.input.json'\nself._ait_inventories = []\nself._ait_method_params = []\nself._ait_manifest_json = None\nwith open(manifest_path, encoding='utf-8') ... | <|body_start_0|>
self._mount_path = '/usr/local/qai/mnt'
self._run_id = 1
self._job_id = 1
self._output_file_path = f'{self._mount_path}/ip/job_args/{self._job_id}/{self._run_id}/ait.input.json'
self._ait_inventories = []
self._ait_method_params = []
self._ait_man... | ait.input.jsonを出力するためのクラス。 set関数で各項目を入力し、write関数でjsonを出力する。 あらかじめait.manifest.jsonを生成しておく必要がある。 Class for outputting ait.input.json. You input each item with the set function and output json with the write function. You must generate ait.manifest.json beforehand. | AITInputGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AITInputGenerator:
"""ait.input.jsonを出力するためのクラス。 set関数で各項目を入力し、write関数でjsonを出力する。 あらかじめait.manifest.jsonを生成しておく必要がある。 Class for outputting ait.input.json. You input each item with the set function and output json with the write function. You must generate ait.manifest.json beforehand."""
def... | stack_v2_sparse_classes_10k_train_006310 | 5,937 | permissive | [
{
"docstring": "コンストラクタ Constructor Args: manifest_path : ait.manifest.jsonのパス情報 Path information in ait.manifest.json",
"name": "__init__",
"signature": "def __init__(self, manifest_path: str)"
},
{
"docstring": "Inventories項目を設定する。 Set the Inventories item. Args: name (str) : Inventoriesの名称。ai... | 4 | stack_v2_sparse_classes_30k_train_004635 | Implement the Python class `AITInputGenerator` described below.
Class description:
ait.input.jsonを出力するためのクラス。 set関数で各項目を入力し、write関数でjsonを出力する。 あらかじめait.manifest.jsonを生成しておく必要がある。 Class for outputting ait.input.json. You input each item with the set function and output json with the write function. You must generate ai... | Implement the Python class `AITInputGenerator` described below.
Class description:
ait.input.jsonを出力するためのクラス。 set関数で各項目を入力し、write関数でjsonを出力する。 あらかじめait.manifest.jsonを生成しておく必要がある。 Class for outputting ait.input.json. You input each item with the set function and output json with the write function. You must generate ai... | 6444a7b4f22faffbfddd2ef2bfcfda5505ff677c | <|skeleton|>
class AITInputGenerator:
"""ait.input.jsonを出力するためのクラス。 set関数で各項目を入力し、write関数でjsonを出力する。 あらかじめait.manifest.jsonを生成しておく必要がある。 Class for outputting ait.input.json. You input each item with the set function and output json with the write function. You must generate ait.manifest.json beforehand."""
def... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AITInputGenerator:
"""ait.input.jsonを出力するためのクラス。 set関数で各項目を入力し、write関数でjsonを出力する。 あらかじめait.manifest.jsonを生成しておく必要がある。 Class for outputting ait.input.json. You input each item with the set function and output json with the write function. You must generate ait.manifest.json beforehand."""
def __init__(sel... | the_stack_v2_python_sparse | src/modules/ait_sdk/src/ait_sdk/common/files/ait_input_generator.py | aistairc/qunomon | train | 17 |
0274e7d795b46e40021b4930afbaf1b7a419833a | [
"url = 'http://www.zhichiwangluo.com/management/marketing/distribution/distribution-rule-management/distribution-rule-management-rule?id=EQBYDcBill'\nself.driver.get(url)\nif self.isDispalyed(self.loc12) == True:\n self.click(self.loc12)\nself.click(self.loc1)\nself.clear(self.loc2)\nself.sendKyes(self.loc2, fir... | <|body_start_0|>
url = 'http://www.zhichiwangluo.com/management/marketing/distribution/distribution-rule-management/distribution-rule-management-rule?id=EQBYDcBill'
self.driver.get(url)
if self.isDispalyed(self.loc12) == True:
self.click(self.loc12)
self.click(self.loc1)
... | 分销 | Distribuiton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Distribuiton:
"""分销"""
def distributionRule(self, first_Commission, second_Commission):
"""分销规则设置"""
<|body_0|>
def is_distrition_rule_sucess(self, _text):
"""是否添加成功"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
url = 'http://www.zhichiwangluo... | stack_v2_sparse_classes_10k_train_006311 | 4,645 | no_license | [
{
"docstring": "分销规则设置",
"name": "distributionRule",
"signature": "def distributionRule(self, first_Commission, second_Commission)"
},
{
"docstring": "是否添加成功",
"name": "is_distrition_rule_sucess",
"signature": "def is_distrition_rule_sucess(self, _text)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004639 | Implement the Python class `Distribuiton` described below.
Class description:
分销
Method signatures and docstrings:
- def distributionRule(self, first_Commission, second_Commission): 分销规则设置
- def is_distrition_rule_sucess(self, _text): 是否添加成功 | Implement the Python class `Distribuiton` described below.
Class description:
分销
Method signatures and docstrings:
- def distributionRule(self, first_Commission, second_Commission): 分销规则设置
- def is_distrition_rule_sucess(self, _text): 是否添加成功
<|skeleton|>
class Distribuiton:
"""分销"""
def distributionRule(sel... | 3b441375fade9ebff025054cedee107217fa2e98 | <|skeleton|>
class Distribuiton:
"""分销"""
def distributionRule(self, first_Commission, second_Commission):
"""分销规则设置"""
<|body_0|>
def is_distrition_rule_sucess(self, _text):
"""是否添加成功"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Distribuiton:
"""分销"""
def distributionRule(self, first_Commission, second_Commission):
"""分销规则设置"""
url = 'http://www.zhichiwangluo.com/management/marketing/distribution/distribution-rule-management/distribution-rule-management-rule?id=EQBYDcBill'
self.driver.get(url)
if ... | the_stack_v2_python_sparse | pages/distribution.py | srf123/zhichi | train | 0 |
ceca416be9714fd67227db40d9b7c4ea2b18ac6e | [
"super().__init__(*args, **kwargs)\ninput_size = sum((x.output_size for x in self._input_layers))\noutput_size = self.output_size\nself.hidden_state_index = self._network.add_recurrent_state(output_size)\nnum_gates = 2\nself._init_weight('layer_input/W', (input_size, output_size), scale=0.01, count=num_gates + 1)\n... | <|body_start_0|>
super().__init__(*args, **kwargs)
input_size = sum((x.output_size for x in self._input_layers))
output_size = self.output_size
self.hidden_state_index = self._network.add_recurrent_state(output_size)
num_gates = 2
self._init_weight('layer_input/W', (input... | Gated Recurrent Unit Layer K. Cho et al. (2014) Learning Phrase Representations Using RNN Encoder-Decoder for Statistical Machine Translation Proc. 2014 Conference on Empiricial Methods in Natural Language Processing | GRULayer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRULayer:
"""Gated Recurrent Unit Layer K. Cho et al. (2014) Learning Phrase Representations Using RNN Encoder-Decoder for Statistical Machine Translation Proc. 2014 Conference on Empiricial Methods in Natural Language Processing"""
def __init__(self, *args, **kwargs):
"""Initializes... | stack_v2_sparse_classes_10k_train_006312 | 8,227 | permissive | [
{
"docstring": "Initializes the parameters used by this layer. The weight matrices are concatenated so that they can be applied in a single parallel matrix operation. The same thing for bias vectors.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Crea... | 3 | stack_v2_sparse_classes_30k_train_001467 | Implement the Python class `GRULayer` described below.
Class description:
Gated Recurrent Unit Layer K. Cho et al. (2014) Learning Phrase Representations Using RNN Encoder-Decoder for Statistical Machine Translation Proc. 2014 Conference on Empiricial Methods in Natural Language Processing
Method signatures and docst... | Implement the Python class `GRULayer` described below.
Class description:
Gated Recurrent Unit Layer K. Cho et al. (2014) Learning Phrase Representations Using RNN Encoder-Decoder for Statistical Machine Translation Proc. 2014 Conference on Empiricial Methods in Natural Language Processing
Method signatures and docst... | 9904faec19ad5718470f21927229aad2656e5686 | <|skeleton|>
class GRULayer:
"""Gated Recurrent Unit Layer K. Cho et al. (2014) Learning Phrase Representations Using RNN Encoder-Decoder for Statistical Machine Translation Proc. 2014 Conference on Empiricial Methods in Natural Language Processing"""
def __init__(self, *args, **kwargs):
"""Initializes... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GRULayer:
"""Gated Recurrent Unit Layer K. Cho et al. (2014) Learning Phrase Representations Using RNN Encoder-Decoder for Statistical Machine Translation Proc. 2014 Conference on Empiricial Methods in Natural Language Processing"""
def __init__(self, *args, **kwargs):
"""Initializes the paramete... | the_stack_v2_python_sparse | theanolm/network/grulayer.py | senarvi/theanolm | train | 95 |
dc9944f1b1b3472fa50b0dc82455fb8e8d0c7f07 | [
"self.small = []\nself.large = []\nself.size = 0",
"heappush(self.small, -1 * heappushpop(self.large, num))\nself.size += 1\nwhile len(self.large) < len(self.small):\n heappush(self.large, -1 * heappop(self.small))",
"if self.size % 2:\n return float(self.large[0])\nelse:\n return float(self.large[0] +... | <|body_start_0|>
self.small = []
self.large = []
self.size = 0
<|end_body_0|>
<|body_start_1|>
heappush(self.small, -1 * heappushpop(self.large, num))
self.size += 1
while len(self.large) < len(self.small):
heappush(self.large, -1 * heappop(self.small))
<|end... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_10k_train_006313 | 1,833 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds a num into the data structure. :type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": "Returns the ... | 3 | stack_v2_sparse_classes_30k_train_001304 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | b4da922c4e8406c486760639b71e3ec50283ca43 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
self.small = []
self.large = []
self.size = 0
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
heappush(self.small, -1 * heappushpop(sel... | the_stack_v2_python_sparse | old_session/session_1/_295/_295_find_median_from_data_stream.py | YJL33/LeetCode | train | 3 | |
33684d71c7d1159b255c60d12c74aa03f8e028b0 | [
"self.s3_output_path = s3_output_path\nself.container_local_output_path = container_local_output_path\nself.hook_parameters = hook_parameters\nself.collection_configs = collection_configs",
"debugger_hook_config_request = {'S3OutputPath': self.s3_output_path}\nif self.container_local_output_path is not None:\n ... | <|body_start_0|>
self.s3_output_path = s3_output_path
self.container_local_output_path = container_local_output_path
self.hook_parameters = hook_parameters
self.collection_configs = collection_configs
<|end_body_0|>
<|body_start_1|>
debugger_hook_config_request = {'S3OutputPath'... | Create a Debugger hook configuration object to save the tensor for debugging. DebuggerHookConfig provides options to customize how debugging information is emitted and saved. This high-level DebuggerHookConfig class runs based on the `smdebug.SaveConfig <https://github.com/awslabs/sagemaker-debugger/blob/master/docs/ a... | DebuggerHookConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DebuggerHookConfig:
"""Create a Debugger hook configuration object to save the tensor for debugging. DebuggerHookConfig provides options to customize how debugging information is emitted and saved. This high-level DebuggerHookConfig class runs based on the `smdebug.SaveConfig <https://github.com/... | stack_v2_sparse_classes_10k_train_006314 | 42,015 | permissive | [
{
"docstring": "Initialize the DebuggerHookConfig instance. Args: s3_output_path (str or PipelineVariable): Optional. The location in Amazon S3 to store the output tensors. The default Debugger output path is created under the default output path of the :class:`~sagemaker.estimator.Estimator` class. For example... | 2 | stack_v2_sparse_classes_30k_train_003655 | Implement the Python class `DebuggerHookConfig` described below.
Class description:
Create a Debugger hook configuration object to save the tensor for debugging. DebuggerHookConfig provides options to customize how debugging information is emitted and saved. This high-level DebuggerHookConfig class runs based on the `... | Implement the Python class `DebuggerHookConfig` described below.
Class description:
Create a Debugger hook configuration object to save the tensor for debugging. DebuggerHookConfig provides options to customize how debugging information is emitted and saved. This high-level DebuggerHookConfig class runs based on the `... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class DebuggerHookConfig:
"""Create a Debugger hook configuration object to save the tensor for debugging. DebuggerHookConfig provides options to customize how debugging information is emitted and saved. This high-level DebuggerHookConfig class runs based on the `smdebug.SaveConfig <https://github.com/... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DebuggerHookConfig:
"""Create a Debugger hook configuration object to save the tensor for debugging. DebuggerHookConfig provides options to customize how debugging information is emitted and saved. This high-level DebuggerHookConfig class runs based on the `smdebug.SaveConfig <https://github.com/awslabs/sagem... | the_stack_v2_python_sparse | src/sagemaker/debugger/debugger.py | aws/sagemaker-python-sdk | train | 2,050 |
4e2a7659b3b97cda44731ce5fd901742d2d6a44c | [
"if operations not in ['f', 'b', 'fb', 'bf']:\n raise ValueError(\"'operations' parameter should be one of the following options: f, b, fb, bf.\")\nself.feature = next(self._parse_features(feature)())\nself.operations = operations\nself.value = value\nself.axis = axis",
"if not isinstance(data, np.ndarray) or ... | <|body_start_0|>
if operations not in ['f', 'b', 'fb', 'bf']:
raise ValueError("'operations' parameter should be one of the following options: f, b, fb, bf.")
self.feature = next(self._parse_features(feature)())
self.operations = operations
self.value = value
self.axi... | Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, nan, 8, 5, 5, 1, 0, 0, 0 'b': nan, nan, nan, ... | ValueFilloutTask | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueFilloutTask:
"""Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, n... | stack_v2_sparse_classes_10k_train_006315 | 8,688 | permissive | [
{
"docstring": ":param feature: A feature that must be value-filled. :type feature: an object supported by the :class:`FeatureParser<eolearn.core.utilities.FeatureParser>` :param operations: Fill directions, which should be one of ['f', 'b', 'fb', 'bf']. :type operations: str :param value: Which value to fill b... | 3 | stack_v2_sparse_classes_30k_train_001149 | Implement the Python class `ValueFilloutTask` described below.
Class description:
Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8... | Implement the Python class `ValueFilloutTask` described below.
Class description:
Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8... | 148189e2b92e06059b87f223b596255ccafac86d | <|skeleton|>
class ValueFilloutTask:
"""Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, n... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ValueFilloutTask:
"""Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, nan, 8, 5, 5, ... | the_stack_v2_python_sparse | features/eolearn/features/feature_manipulation.py | wouellette/eo-learn | train | 2 |
909f5bec612ec47064be4f0287042d18ba85f00d | [
"super(Criterion, self).__init__()\nself.par = opt\nself.n_classes = opt.n_classes\nself.n_centroids = opt.loss_softtriplet_n_centroids\nself.margin_delta = opt.loss_softtriplet_margin_delta\nself.gamma = opt.loss_softtriplet_gamma\nself.lam = opt.loss_softtriplet_lambda\nself.reg_weight = opt.loss_softtriplet_reg_... | <|body_start_0|>
super(Criterion, self).__init__()
self.par = opt
self.n_classes = opt.n_classes
self.n_centroids = opt.loss_softtriplet_n_centroids
self.margin_delta = opt.loss_softtriplet_margin_delta
self.gamma = opt.loss_softtriplet_gamma
self.lam = opt.loss_s... | Criterion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin."""
<|body_0|>
def forward(self, batch, labels, **kwargs):
"""Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels: nparray/list: For each element of the batch assigns a class [... | stack_v2_sparse_classes_10k_train_006316 | 2,944 | permissive | [
{
"docstring": "Args: margin: Triplet Margin.",
"name": "__init__",
"signature": "def __init__(self, opt)"
},
{
"docstring": "Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels: nparray/list: For each element of the batch assigns a class [0,...,C-1], shape: (BS x 1)",
... | 2 | stack_v2_sparse_classes_30k_train_004211 | Implement the Python class `Criterion` described below.
Class description:
Implement the Criterion class.
Method signatures and docstrings:
- def __init__(self, opt): Args: margin: Triplet Margin.
- def forward(self, batch, labels, **kwargs): Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels:... | Implement the Python class `Criterion` described below.
Class description:
Implement the Criterion class.
Method signatures and docstrings:
- def __init__(self, opt): Args: margin: Triplet Margin.
- def forward(self, batch, labels, **kwargs): Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels:... | 01a7220bac7ebb1e70416ef663f3ba7cee9e8bf5 | <|skeleton|>
class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin."""
<|body_0|>
def forward(self, batch, labels, **kwargs):
"""Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels: nparray/list: For each element of the batch assigns a class [... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin."""
super(Criterion, self).__init__()
self.par = opt
self.n_classes = opt.n_classes
self.n_centroids = opt.loss_softtriplet_n_centroids
self.margin_delta = opt.loss_softtriplet_margin_delta
... | the_stack_v2_python_sparse | criteria/softtriplet.py | chenyanlinzhugoushou/DCML | train | 0 | |
05c4191d762deb68bc788b4757c98bb85b127fbf | [
"instance = Data(template=validated_data['template'], title=validated_data['title'], user_id=str(validated_data['user'].id))\ninstance.xml_content = validated_data['xml_content']\ndata_api.upsert(instance, validated_data['user'])\ninstance.xml_content = validated_data['xml_content'].encode('utf-8')\nreturn instance... | <|body_start_0|>
instance = Data(template=validated_data['template'], title=validated_data['title'], user_id=str(validated_data['user'].id))
instance.xml_content = validated_data['xml_content']
data_api.upsert(instance, validated_data['user'])
instance.xml_content = validated_data['xml_c... | Data serializer | DataSerializer | [
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSerializer:
"""Data serializer"""
def create(self, validated_data):
"""Create and return a new `Data` instance, given the validated data."""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `Data` instance, given the val... | stack_v2_sparse_classes_10k_train_006317 | 2,557 | permissive | [
{
"docstring": "Create and return a new `Data` instance, given the validated data.",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Update and return an existing `Data` instance, given the validated data.",
"name": "update",
"signature": "def update(... | 2 | stack_v2_sparse_classes_30k_train_006203 | Implement the Python class `DataSerializer` described below.
Class description:
Data serializer
Method signatures and docstrings:
- def create(self, validated_data): Create and return a new `Data` instance, given the validated data.
- def update(self, instance, validated_data): Update and return an existing `Data` in... | Implement the Python class `DataSerializer` described below.
Class description:
Data serializer
Method signatures and docstrings:
- def create(self, validated_data): Create and return a new `Data` instance, given the validated data.
- def update(self, instance, validated_data): Update and return an existing `Data` in... | 568cb75a40ccff1d74a1a757866112535efd769a | <|skeleton|>
class DataSerializer:
"""Data serializer"""
def create(self, validated_data):
"""Create and return a new `Data` instance, given the validated data."""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `Data` instance, given the val... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DataSerializer:
"""Data serializer"""
def create(self, validated_data):
"""Create and return a new `Data` instance, given the validated data."""
instance = Data(template=validated_data['template'], title=validated_data['title'], user_id=str(validated_data['user'].id))
instance.xml... | the_stack_v2_python_sparse | core_main_app/rest/data/serializers.py | adilmania/core_main_app | train | 0 |
a45bd42e3b29a6af758443782d1d7d411982823b | [
"super(Encoder, self).__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(input_vocab, dm)\nself.positional_encoding = positional_encoding(max_seq_len, self.dm)\nself.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]\nself.dropout = tf.keras.layers.Dropout(drop_rate)",... | <|body_start_0|>
super(Encoder, self).__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(input_vocab, dm)
self.positional_encoding = positional_encoding(max_seq_len, self.dm)
self.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N... | Encoder class for machine translation | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Encoder class for machine translation"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""[summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] input_vocab ([type]): [... | stack_v2_sparse_classes_10k_train_006318 | 12,086 | no_license | [
{
"docstring": "[summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] input_vocab ([type]): [description] max_seq_len ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.",
"name": "__init__",
"signat... | 2 | stack_v2_sparse_classes_30k_train_001358 | Implement the Python class `Encoder` described below.
Class description:
Encoder class for machine translation
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): [summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [descriptio... | Implement the Python class `Encoder` described below.
Class description:
Encoder class for machine translation
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): [summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [descriptio... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class Encoder:
"""Encoder class for machine translation"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""[summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] input_vocab ([type]): [... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Encoder class for machine translation"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""[summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] input_vocab ([type]): [description] ... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
c459a5bfb6427bb215a67ce6c74b2e6f2cab813f | [
"self.size = len(words)\nself.word_pos = collections.defaultdict(list)\nfor i, word in enumerate(words):\n self.word_pos[word].append(i)",
"pos_list1 = self.word_pos[word1]\npos_list2 = self.word_pos[word2]\nshortest = self.size\nfor i in pos_list1:\n for j in pos_list2:\n if shortest > abs(i - j):\n... | <|body_start_0|>
self.size = len(words)
self.word_pos = collections.defaultdict(list)
for i, word in enumerate(words):
self.word_pos[word].append(i)
<|end_body_0|>
<|body_start_1|>
pos_list1 = self.word_pos[word1]
pos_list2 = self.word_pos[word2]
shortest = s... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many time... | stack_v2_sparse_classes_10k_train_006319 | 1,603 | no_license | [
{
"docstring": "Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters. Example: Assume that wo... | 2 | stack_v2_sparse_classes_30k_train_005604 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the s... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the s... | 08c6d27498e35f636045fed05a6f94b760ab69ca | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many time... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
"""Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with differe... | the_stack_v2_python_sparse | solutions/hashtable/244.Shortest.Word.Distance.II.py | ljia2/leetcode.py | train | 0 | |
c5cf172bfa629e34727c98ea9a2fb7530988ebf7 | [
"self.mean = mean\nself.std = std\nself.is_scale = is_scale\nself.is_channel_first = is_channel_first",
"im = im.astype(np.float32, copy=False)\nif self.is_channel_first:\n mean = np.array(self.mean)[:, np.newaxis, np.newaxis]\n std = np.array(self.std)[:, np.newaxis, np.newaxis]\nelse:\n mean = np.array... | <|body_start_0|>
self.mean = mean
self.std = std
self.is_scale = is_scale
self.is_channel_first = is_channel_first
<|end_body_0|>
<|body_start_1|>
im = im.astype(np.float32, copy=False)
if self.is_channel_first:
mean = np.array(self.mean)[:, np.newaxis, np.ne... | NormalizeImage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormalizeImage:
def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True, is_channel_first=True):
"""Args: mean (list): the pixel mean std (list): the pixel variance"""
<|body_0|>
def __call__(self, im):
"""Normalize the image. Operators: 1.(option... | stack_v2_sparse_classes_10k_train_006320 | 7,004 | permissive | [
{
"docstring": "Args: mean (list): the pixel mean std (list): the pixel variance",
"name": "__init__",
"signature": "def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True, is_channel_first=True)"
},
{
"docstring": "Normalize the image. Operators: 1.(optional) Scale the imag... | 2 | stack_v2_sparse_classes_30k_test_000234 | Implement the Python class `NormalizeImage` described below.
Class description:
Implement the NormalizeImage class.
Method signatures and docstrings:
- def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True, is_channel_first=True): Args: mean (list): the pixel mean std (list): the pixel variance
... | Implement the Python class `NormalizeImage` described below.
Class description:
Implement the NormalizeImage class.
Method signatures and docstrings:
- def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True, is_channel_first=True): Args: mean (list): the pixel mean std (list): the pixel variance
... | b402610a6f0b382a978e82473b541ea1fc6cf09a | <|skeleton|>
class NormalizeImage:
def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True, is_channel_first=True):
"""Args: mean (list): the pixel mean std (list): the pixel variance"""
<|body_0|>
def __call__(self, im):
"""Normalize the image. Operators: 1.(option... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NormalizeImage:
def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True, is_channel_first=True):
"""Args: mean (list): the pixel mean std (list): the pixel variance"""
self.mean = mean
self.std = std
self.is_scale = is_scale
self.is_channel_first = i... | the_stack_v2_python_sparse | modules/image/object_detection/ssd_vgg16_512_coco2017/data_feed.py | PaddlePaddle/PaddleHub | train | 12,914 | |
24946af70bd19f4df06148cc31a255e1e471b47b | [
"if not kwargs.get('obj_ids'):\n obj_model = facade.get_route_map_by_search(self.search)\n objects = obj_model['query_set']\n only_main_property = False\nelse:\n ids = kwargs.get('obj_ids').split(';')\n objects = facade.get_route_map_by_ids(ids)\n only_main_property = True\n obj_model = None\ns... | <|body_start_0|>
if not kwargs.get('obj_ids'):
obj_model = facade.get_route_map_by_search(self.search)
objects = obj_model['query_set']
only_main_property = False
else:
ids = kwargs.get('obj_ids').split(';')
objects = facade.get_route_map_by_id... | RouteMapDBView | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouteMapDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMaps by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new RouteMap."""
<|body_1|>
def put(self, request, *args, **kwargs):
"""Upda... | stack_v2_sparse_classes_10k_train_006321 | 9,414 | permissive | [
{
"docstring": "Returns a list of RouteMaps by ids ou dict.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Create new RouteMap.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Update RouteMap... | 4 | null | Implement the Python class `RouteMapDBView` described below.
Class description:
Implement the RouteMapDBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of RouteMaps by ids ou dict.
- def post(self, request, *args, **kwargs): Create new RouteMap.
- def put(self, ... | Implement the Python class `RouteMapDBView` described below.
Class description:
Implement the RouteMapDBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of RouteMaps by ids ou dict.
- def post(self, request, *args, **kwargs): Create new RouteMap.
- def put(self, ... | eb27e1d977a1c4bb1fee8fb51b8d8050c64696d9 | <|skeleton|>
class RouteMapDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMaps by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new RouteMap."""
<|body_1|>
def put(self, request, *args, **kwargs):
"""Upda... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RouteMapDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMaps by ids ou dict."""
if not kwargs.get('obj_ids'):
obj_model = facade.get_route_map_by_search(self.search)
objects = obj_model['query_set']
only_main_property = False
... | the_stack_v2_python_sparse | networkapi/api_route_map/v4/views.py | globocom/GloboNetworkAPI | train | 86 | |
dc0fe727283fd639cdf2132d9f18a4230a4f7707 | [
"wide_ftrs_sp_idx = tf.cast(wide_ftrs_sp_idx, dtype=tf.float32)\nif wide_ftrs_sp_val is None:\n wide_ftrs_sp_val = tf.ones(tf.shape(wide_ftrs_sp_idx), dtype=tf.float32)\nself._num_wide_sp = num_wide_sp\nself._padding_idx = padding_idx\nwith tf.variable_scope('wide', reuse=tf.AUTO_REUSE):\n self.ftrs_weight = ... | <|body_start_0|>
wide_ftrs_sp_idx = tf.cast(wide_ftrs_sp_idx, dtype=tf.float32)
if wide_ftrs_sp_val is None:
wide_ftrs_sp_val = tf.ones(tf.shape(wide_ftrs_sp_idx), dtype=tf.float32)
self._num_wide_sp = num_wide_sp
self._padding_idx = padding_idx
with tf.variable_scope... | Embedding model that performs embedding lookup and summation on sparse features | SparseEmbModel | [
"BSD-2-Clause",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseEmbModel:
"""Embedding model that performs embedding lookup and summation on sparse features"""
def __init__(self, num_wide_sp: int, wide_ftrs_sp_idx: tf.Tensor, sp_emb_size: int, wide_ftrs_sp_val: tf.Tensor=None, padding_idx: int=0, initializer=tf.contrib.layers.xavier_initializer()):... | stack_v2_sparse_classes_10k_train_006322 | 5,383 | permissive | [
{
"docstring": "Computes a embedding given wide feature indices and values If wide_ftrs_sp_val is specified, users should keep consistency between wide_ftrs_sp_idx and wide_ftrs_sp_val -- the value of wide_ftrs_sp_idx[i] should be wide_ftrs_sp_val[i]. CAVEAT: it is required that padding value = 0 for wide_ftrs_... | 2 | stack_v2_sparse_classes_30k_train_005428 | Implement the Python class `SparseEmbModel` described below.
Class description:
Embedding model that performs embedding lookup and summation on sparse features
Method signatures and docstrings:
- def __init__(self, num_wide_sp: int, wide_ftrs_sp_idx: tf.Tensor, sp_emb_size: int, wide_ftrs_sp_val: tf.Tensor=None, padd... | Implement the Python class `SparseEmbModel` described below.
Class description:
Embedding model that performs embedding lookup and summation on sparse features
Method signatures and docstrings:
- def __init__(self, num_wide_sp: int, wide_ftrs_sp_idx: tf.Tensor, sp_emb_size: int, wide_ftrs_sp_val: tf.Tensor=None, padd... | 38e7b74879debd8ae5f2685367c81cc3a8aa003b | <|skeleton|>
class SparseEmbModel:
"""Embedding model that performs embedding lookup and summation on sparse features"""
def __init__(self, num_wide_sp: int, wide_ftrs_sp_idx: tf.Tensor, sp_emb_size: int, wide_ftrs_sp_val: tf.Tensor=None, padding_idx: int=0, initializer=tf.contrib.layers.xavier_initializer()):... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SparseEmbModel:
"""Embedding model that performs embedding lookup and summation on sparse features"""
def __init__(self, num_wide_sp: int, wide_ftrs_sp_idx: tf.Tensor, sp_emb_size: int, wide_ftrs_sp_val: tf.Tensor=None, padding_idx: int=0, initializer=tf.contrib.layers.xavier_initializer()):
"""C... | the_stack_v2_python_sparse | src/detext/model/sp_emb_model.py | naimmalek/detext | train | 1 |
503c72178d8d2931ae0e3700e7ee3a0b5478a821 | [
"result = {'result': 'NG'}\ndata = request.get_json(force=True)\nif data:\n succsee, message = CtrlQuotations().feature_assign_group(data, quotation_id)\n if succsee:\n result = {'result': 'OK', 'content': message}\n else:\n result['error'] = message\nelse:\n result['error'] = '请不要传空数据'\nr... | <|body_start_0|>
result = {'result': 'NG'}
data = request.get_json(force=True)
if data:
succsee, message = CtrlQuotations().feature_assign_group(data, quotation_id)
if succsee:
result = {'result': 'OK', 'content': message}
else:
... | ApiFeatureAssign | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiFeatureAssign:
def post(self, quotation_id):
"""分配此报价下的feature :return:"""
<|body_0|>
def get(self, quotation_id):
"""获取此报价下的featureList历史 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = {'result': 'NG'}
data = request.g... | stack_v2_sparse_classes_10k_train_006323 | 10,406 | no_license | [
{
"docstring": "分配此报价下的feature :return:",
"name": "post",
"signature": "def post(self, quotation_id)"
},
{
"docstring": "获取此报价下的featureList历史 :return:",
"name": "get",
"signature": "def get(self, quotation_id)"
}
] | 2 | null | Implement the Python class `ApiFeatureAssign` described below.
Class description:
Implement the ApiFeatureAssign class.
Method signatures and docstrings:
- def post(self, quotation_id): 分配此报价下的feature :return:
- def get(self, quotation_id): 获取此报价下的featureList历史 :return: | Implement the Python class `ApiFeatureAssign` described below.
Class description:
Implement the ApiFeatureAssign class.
Method signatures and docstrings:
- def post(self, quotation_id): 分配此报价下的feature :return:
- def get(self, quotation_id): 获取此报价下的featureList历史 :return:
<|skeleton|>
class ApiFeatureAssign:
def ... | 64b31e7bdfcb8a4c95f0a8a607f0bcff576cec11 | <|skeleton|>
class ApiFeatureAssign:
def post(self, quotation_id):
"""分配此报价下的feature :return:"""
<|body_0|>
def get(self, quotation_id):
"""获取此报价下的featureList历史 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ApiFeatureAssign:
def post(self, quotation_id):
"""分配此报价下的feature :return:"""
result = {'result': 'NG'}
data = request.get_json(force=True)
if data:
succsee, message = CtrlQuotations().feature_assign_group(data, quotation_id)
if succsee:
... | the_stack_v2_python_sparse | koala/koala_server/app/api_1_0/api_quotations.py | lsn1183/web_project | train | 0 | |
70ddaab84676a0d72925d35e17cb2c281dc8f967 | [
"menu_domain = [('parent_id', '=', False)]\nif context.get('menu', None):\n menu_domain.append(('name', '=', context.get('menu')))\nreturn self.search(cr, uid, menu_domain, context=context)",
"fields = ['name', 'sequence', 'parent_id', 'action']\nmenu_root_ids = self.get_user_roots(cr, uid, context=context)\nm... | <|body_start_0|>
menu_domain = [('parent_id', '=', False)]
if context.get('menu', None):
menu_domain.append(('name', '=', context.get('menu')))
return self.search(cr, uid, menu_domain, context=context)
<|end_body_0|>
<|body_start_1|>
fields = ['name', 'sequence', 'parent_id'... | ir_ui_menu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ir_ui_menu:
def get_user_roots(self, cr, uid, context=None):
"""Return all root menu ids visible for the user. :return: the root menu ids :rtype: list(int)"""
<|body_0|>
def load_menu(self, cr, uid, context=None):
"""Loads all menu items (all applications and their s... | stack_v2_sparse_classes_10k_train_006324 | 4,502 | no_license | [
{
"docstring": "Return all root menu ids visible for the user. :return: the root menu ids :rtype: list(int)",
"name": "get_user_roots",
"signature": "def get_user_roots(self, cr, uid, context=None)"
},
{
"docstring": "Loads all menu items (all applications and their sub-menus). :return: the menu... | 4 | null | Implement the Python class `ir_ui_menu` described below.
Class description:
Implement the ir_ui_menu class.
Method signatures and docstrings:
- def get_user_roots(self, cr, uid, context=None): Return all root menu ids visible for the user. :return: the root menu ids :rtype: list(int)
- def load_menu(self, cr, uid, co... | Implement the Python class `ir_ui_menu` described below.
Class description:
Implement the ir_ui_menu class.
Method signatures and docstrings:
- def get_user_roots(self, cr, uid, context=None): Return all root menu ids visible for the user. :return: the root menu ids :rtype: list(int)
- def load_menu(self, cr, uid, co... | e8c21082c187f4639373b29a7a0905d069d770f2 | <|skeleton|>
class ir_ui_menu:
def get_user_roots(self, cr, uid, context=None):
"""Return all root menu ids visible for the user. :return: the root menu ids :rtype: list(int)"""
<|body_0|>
def load_menu(self, cr, uid, context=None):
"""Loads all menu items (all applications and their s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ir_ui_menu:
def get_user_roots(self, cr, uid, context=None):
"""Return all root menu ids visible for the user. :return: the root menu ids :rtype: list(int)"""
menu_domain = [('parent_id', '=', False)]
if context.get('menu', None):
menu_domain.append(('name', '=', context.ge... | the_stack_v2_python_sparse | pabi_auth_cas/ir_ui_menu.py | pabi2/pb2_addons | train | 6 | |
90f428307e171c6d8fd2dd07b7e3f5e62735fd0c | [
"super(TeardownSession, self).__init__(*args, **kwargs)\nself.tools = tools\nreturn",
"for tool in self.tools:\n tool.run()\nreturn"
] | <|body_start_0|>
super(TeardownSession, self).__init__(*args, **kwargs)
self.tools = tools
return
<|end_body_0|>
<|body_start_1|>
for tool in self.tools:
tool.run()
return
<|end_body_1|>
| The TearDown does whatever needs to be done after the test is completed. It iterates over the `tools` passed in to the constructor. Each tool's `run` method is called. Choosing tools and ordering them defines the TeardownSession algorithm. | TeardownSession | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeardownSession:
"""The TearDown does whatever needs to be done after the test is completed. It iterates over the `tools` passed in to the constructor. Each tool's `run` method is called. Choosing tools and ordering them defines the TeardownSession algorithm."""
def __init__(self, tools, *ar... | stack_v2_sparse_classes_10k_train_006325 | 780 | permissive | [
{
"docstring": ":param: - `tools`: a list of tools to run",
"name": "__init__",
"signature": "def __init__(self, tools, *args, **kwargs)"
},
{
"docstring": "Calls the run() method for each tool in `tools`",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002980 | Implement the Python class `TeardownSession` described below.
Class description:
The TearDown does whatever needs to be done after the test is completed. It iterates over the `tools` passed in to the constructor. Each tool's `run` method is called. Choosing tools and ordering them defines the TeardownSession algorithm... | Implement the Python class `TeardownSession` described below.
Class description:
The TearDown does whatever needs to be done after the test is completed. It iterates over the `tools` passed in to the constructor. Each tool's `run` method is called. Choosing tools and ordering them defines the TeardownSession algorithm... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class TeardownSession:
"""The TearDown does whatever needs to be done after the test is completed. It iterates over the `tools` passed in to the constructor. Each tool's `run` method is called. Choosing tools and ordering them defines the TeardownSession algorithm."""
def __init__(self, tools, *ar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TeardownSession:
"""The TearDown does whatever needs to be done after the test is completed. It iterates over the `tools` passed in to the constructor. Each tool's `run` method is called. Choosing tools and ordering them defines the TeardownSession algorithm."""
def __init__(self, tools, *args, **kwargs)... | the_stack_v2_python_sparse | apetools/proletarians/teardown.py | russell-n/oldape | train | 0 |
5e872aaf50142500d7a3573769ca37b9a7cc7d65 | [
"super(ResNetRFL, self).__init__()\nself.backbone = RFLBase(input_channel)\nself.out_channel = output_channel\nself.output_channel_block = [int(self.out_channel / 4), int(self.out_channel / 2), self.out_channel, self.out_channel]\nblock = BasicBlock\nlayers = [1, 2, 5, 3]\nself.inplanes = int(self.out_channel // 2)... | <|body_start_0|>
super(ResNetRFL, self).__init__()
self.backbone = RFLBase(input_channel)
self.out_channel = output_channel
self.output_channel_block = [int(self.out_channel / 4), int(self.out_channel / 2), self.out_channel, self.out_channel]
block = BasicBlock
layers = [... | Backbone network of the reciprocal feature learning in Ref [1] Ref [1]: Reciprocal Feature Learning via Explicit and Implicit Tasks in Scene Text Recognition. ICDAR-2021. | ResNetRFL | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNetRFL:
"""Backbone network of the reciprocal feature learning in Ref [1] Ref [1]: Reciprocal Feature Learning via Explicit and Implicit Tasks in Scene Text Recognition. ICDAR-2021."""
def __init__(self, input_channel, output_channel=512):
"""Args: input_channel (int): input chann... | stack_v2_sparse_classes_10k_train_006326 | 11,483 | permissive | [
{
"docstring": "Args: input_channel (int): input channel output_channel (int): output channel",
"name": "__init__",
"signature": "def __init__(self, input_channel, output_channel=512)"
},
{
"docstring": "Args: block (block): convolution block planes (int): input channels blocks (list): layers of... | 4 | stack_v2_sparse_classes_30k_train_003250 | Implement the Python class `ResNetRFL` described below.
Class description:
Backbone network of the reciprocal feature learning in Ref [1] Ref [1]: Reciprocal Feature Learning via Explicit and Implicit Tasks in Scene Text Recognition. ICDAR-2021.
Method signatures and docstrings:
- def __init__(self, input_channel, ou... | Implement the Python class `ResNetRFL` described below.
Class description:
Backbone network of the reciprocal feature learning in Ref [1] Ref [1]: Reciprocal Feature Learning via Explicit and Implicit Tasks in Scene Text Recognition. ICDAR-2021.
Method signatures and docstrings:
- def __init__(self, input_channel, ou... | fb47a96d1a38f5ce634c6f12d710ed5300cc89fc | <|skeleton|>
class ResNetRFL:
"""Backbone network of the reciprocal feature learning in Ref [1] Ref [1]: Reciprocal Feature Learning via Explicit and Implicit Tasks in Scene Text Recognition. ICDAR-2021."""
def __init__(self, input_channel, output_channel=512):
"""Args: input_channel (int): input chann... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResNetRFL:
"""Backbone network of the reciprocal feature learning in Ref [1] Ref [1]: Reciprocal Feature Learning via Explicit and Implicit Tasks in Scene Text Recognition. ICDAR-2021."""
def __init__(self, input_channel, output_channel=512):
"""Args: input_channel (int): input channel output_cha... | the_stack_v2_python_sparse | davarocr/davarocr/davar_rcg/models/backbones/ResNetRFL.py | OCRWorld/DAVAR-Lab-OCR | train | 0 |
3d298b52eda0cc5ae0f6f056f631ad9f50ae34c9 | [
"length = len(nums)\nself.d = {}\nself.a = nums\nself.build(0, length, 0)",
"if left == right - 1:\n self.d[p] = self.a[left]\n return\nmid = left + (right - left) // 2\nchdleft = 2 * p + 1\nchdright = 2 * p + 2\nself.build(left, mid, chdleft)\nself.build(mid, right, chdright)\nself.d[p] = self.d[chdleft] +... | <|body_start_0|>
length = len(nums)
self.d = {}
self.a = nums
self.build(0, length, 0)
<|end_body_0|>
<|body_start_1|>
if left == right - 1:
self.d[p] = self.a[left]
return
mid = left + (right - left) // 2
chdleft = 2 * p + 1
chdri... | 非完美二叉树版本, 即二分法分割区间 | segmentTree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class segmentTree:
"""非完美二叉树版本, 即二分法分割区间"""
def __init__(self, nums) -> None:
"""p 代表 [left, right) eg: 0 -> [0, length) 1 -> [0, mid) 2 -> [mid, length) 注意, 这里d的数据类型dict是更优选择, 因为对nums 进行递归的二分法分割区间, 会导致 二叉树并非是完全二叉树,会出现大量不连续的叶子结点,然而不连续的叶子结点仍然会占用索引空间 如果用list,这个索引必须有值 如果用dict, 则会节省很多索引空间 eg: ... | stack_v2_sparse_classes_10k_train_006327 | 4,234 | permissive | [
{
"docstring": "p 代表 [left, right) eg: 0 -> [0, length) 1 -> [0, mid) 2 -> [mid, length) 注意, 这里d的数据类型dict是更优选择, 因为对nums 进行递归的二分法分割区间, 会导致 二叉树并非是完全二叉树,会出现大量不连续的叶子结点,然而不连续的叶子结点仍然会占用索引空间 如果用list,这个索引必须有值 如果用dict, 则会节省很多索引空间 eg: 21 6 15 3 3 9 6 1 2 (3) 4 5 (6)",
"name": "__init__",
"signature": "def __init_... | 4 | null | Implement the Python class `segmentTree` described below.
Class description:
非完美二叉树版本, 即二分法分割区间
Method signatures and docstrings:
- def __init__(self, nums) -> None: p 代表 [left, right) eg: 0 -> [0, length) 1 -> [0, mid) 2 -> [mid, length) 注意, 这里d的数据类型dict是更优选择, 因为对nums 进行递归的二分法分割区间, 会导致 二叉树并非是完全二叉树,会出现大量不连续的叶子结点,然而不连... | Implement the Python class `segmentTree` described below.
Class description:
非完美二叉树版本, 即二分法分割区间
Method signatures and docstrings:
- def __init__(self, nums) -> None: p 代表 [left, right) eg: 0 -> [0, length) 1 -> [0, mid) 2 -> [mid, length) 注意, 这里d的数据类型dict是更优选择, 因为对nums 进行递归的二分法分割区间, 会导致 二叉树并非是完全二叉树,会出现大量不连续的叶子结点,然而不连... | 65549f72c565d9f11641c86d6cef9c7988805817 | <|skeleton|>
class segmentTree:
"""非完美二叉树版本, 即二分法分割区间"""
def __init__(self, nums) -> None:
"""p 代表 [left, right) eg: 0 -> [0, length) 1 -> [0, mid) 2 -> [mid, length) 注意, 这里d的数据类型dict是更优选择, 因为对nums 进行递归的二分法分割区间, 会导致 二叉树并非是完全二叉树,会出现大量不连续的叶子结点,然而不连续的叶子结点仍然会占用索引空间 如果用list,这个索引必须有值 如果用dict, 则会节省很多索引空间 eg: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class segmentTree:
"""非完美二叉树版本, 即二分法分割区间"""
def __init__(self, nums) -> None:
"""p 代表 [left, right) eg: 0 -> [0, length) 1 -> [0, mid) 2 -> [mid, length) 注意, 这里d的数据类型dict是更优选择, 因为对nums 进行递归的二分法分割区间, 会导致 二叉树并非是完全二叉树,会出现大量不连续的叶子结点,然而不连续的叶子结点仍然会占用索引空间 如果用list,这个索引必须有值 如果用dict, 则会节省很多索引空间 eg: 21 6 15 3 3 9... | the_stack_v2_python_sparse | utils/segmentTree.py | wisesky/LeetCode-Practice | train | 0 |
25a37b381847da5cc83a0ef0fb4ca098ce5af34f | [
"super(CFRHTMLBuilder, self).process_node(node, indexes=indexes)\nlabel_id = '-'.join(node['label'])\nnode['toc_id'] = '-'.join(self.id_prefix + node['label'][:2])\nnode['accepts_comments'] = label_id in self.diff_applier.diff\nnode['comments_calledout'] = label_id in self.diff_applier.diff\nhas_diff = label_id in ... | <|body_start_0|>
super(CFRHTMLBuilder, self).process_node(node, indexes=indexes)
label_id = '-'.join(node['label'])
node['toc_id'] = '-'.join(self.id_prefix + node['label'][:2])
node['accepts_comments'] = label_id in self.diff_applier.diff
node['comments_calledout'] = label_id in... | Generated HTML specifically related to changing CFR data, as displayed in a notice. This assumes self.diff_applier is set | CFRChangeHTMLBuilder | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CFRChangeHTMLBuilder:
"""Generated HTML specifically related to changing CFR data, as displayed in a notice. This assumes self.diff_applier is set"""
def process_node(self, node, indexes=None):
"""Overrides with custom, additional processing"""
<|body_0|>
def preprocess(... | stack_v2_sparse_classes_10k_train_006328 | 9,837 | permissive | [
{
"docstring": "Overrides with custom, additional processing",
"name": "process_node",
"signature": "def process_node(self, node, indexes=None)"
},
{
"docstring": "Pre-generate all of the \"paths\" associated with diffs; if there's a diff for 111-22-c-4-v, we'd capture (111,) (111, 22) (111, 22,... | 2 | stack_v2_sparse_classes_30k_train_004181 | Implement the Python class `CFRChangeHTMLBuilder` described below.
Class description:
Generated HTML specifically related to changing CFR data, as displayed in a notice. This assumes self.diff_applier is set
Method signatures and docstrings:
- def process_node(self, node, indexes=None): Overrides with custom, additio... | Implement the Python class `CFRChangeHTMLBuilder` described below.
Class description:
Generated HTML specifically related to changing CFR data, as displayed in a notice. This assumes self.diff_applier is set
Method signatures and docstrings:
- def process_node(self, node, indexes=None): Overrides with custom, additio... | 4035701a953409bbb1987d371edc6630fd97a862 | <|skeleton|>
class CFRChangeHTMLBuilder:
"""Generated HTML specifically related to changing CFR data, as displayed in a notice. This assumes self.diff_applier is set"""
def process_node(self, node, indexes=None):
"""Overrides with custom, additional processing"""
<|body_0|>
def preprocess(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CFRChangeHTMLBuilder:
"""Generated HTML specifically related to changing CFR data, as displayed in a notice. This assumes self.diff_applier is set"""
def process_node(self, node, indexes=None):
"""Overrides with custom, additional processing"""
super(CFRHTMLBuilder, self).process_node(nod... | the_stack_v2_python_sparse | regulations/generator/html_builder.py | fecgov/regulations-site | train | 1 |
b37ab6cdd367b1fa60d12ce33cc234d7a42c1eab | [
"if head == None:\n return False\np = head\nq = head.next\nwhile q != None:\n if p == q:\n return True\n p = p.next\n if q.next != None:\n q = q.next.next\n else:\n return False\nreturn False",
"while head:\n if head.val == 'bjfuvth':\n return True\n else:\n ... | <|body_start_0|>
if head == None:
return False
p = head
q = head.next
while q != None:
if p == q:
return True
p = p.next
if q.next != None:
q = q.next.next
else:
return False
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasCycle1(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def hasCycle(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if head == None:
return False
... | stack_v2_sparse_classes_10k_train_006329 | 1,291 | no_license | [
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "hasCycle1",
"signature": "def hasCycle1(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "hasCycle",
"signature": "def hasCycle(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle1(self, head): :type head: ListNode :rtype: bool
- def hasCycle(self, head): :type head: ListNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle1(self, head): :type head: ListNode :rtype: bool
- def hasCycle(self, head): :type head: ListNode :rtype: bool
<|skeleton|>
class Solution:
def hasCycle1(self, ... | 48b43999fb7e2ed82d922e1f64ac76f8fabe4baa | <|skeleton|>
class Solution:
def hasCycle1(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def hasCycle(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def hasCycle1(self, head):
""":type head: ListNode :rtype: bool"""
if head == None:
return False
p = head
q = head.next
while q != None:
if p == q:
return True
p = p.next
if q.next != None:
... | the_stack_v2_python_sparse | 141.py | saleed/LeetCode | train | 2 | |
b2753a5f6c12395a1e39148bb0beadd96b9e8c95 | [
"if faceEngine is not None:\n self.faceEngine = faceEngine\n self.estimatorsCollection = FaceEstimatorsCollection(faceEngine=self.faceEngine)\nself._faceDetector: FaceDetector = self.faceEngine.createFaceDetector(detectorType)",
"detectRes = self._faceDetector.detectOne(image, detectArea, True, True)\nif de... | <|body_start_0|>
if faceEngine is not None:
self.faceEngine = faceEngine
self.estimatorsCollection = FaceEstimatorsCollection(faceEngine=self.faceEngine)
self._faceDetector: FaceDetector = self.faceEngine.createFaceDetector(detectorType)
<|end_body_0|>
<|body_start_1|>
d... | High level face detector. Return *VLFaceDetection* instead simple *FaceDetection*. Attributes: estimatorsCollection (FaceEstimatorsCollection): face estimator collections for new detections. _faceDetector (FaceDetector): face detector faceEngine (VLFaceEngine): face engine for detector and estimators, default *FACE_ENG... | VLFaceDetector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VLFaceDetector:
"""High level face detector. Return *VLFaceDetection* instead simple *FaceDetection*. Attributes: estimatorsCollection (FaceEstimatorsCollection): face estimator collections for new detections. _faceDetector (FaceDetector): face detector faceEngine (VLFaceEngine): face engine for ... | stack_v2_sparse_classes_10k_train_006330 | 17,671 | permissive | [
{
"docstring": "Init. Args: detectorType: detector type faceEngine: face engine for detector and estimators",
"name": "__init__",
"signature": "def __init__(self, detectorType: DetectorType=DetectorType.FACE_DET_DEFAULT, faceEngine: Optional[VLFaceEngine]=None)"
},
{
"docstring": "Detect just on... | 5 | stack_v2_sparse_classes_30k_train_003806 | Implement the Python class `VLFaceDetector` described below.
Class description:
High level face detector. Return *VLFaceDetection* instead simple *FaceDetection*. Attributes: estimatorsCollection (FaceEstimatorsCollection): face estimator collections for new detections. _faceDetector (FaceDetector): face detector face... | Implement the Python class `VLFaceDetector` described below.
Class description:
High level face detector. Return *VLFaceDetection* instead simple *FaceDetection*. Attributes: estimatorsCollection (FaceEstimatorsCollection): face estimator collections for new detections. _faceDetector (FaceDetector): face detector face... | 3d06968ddc6177b330454cfc53116ece393b486d | <|skeleton|>
class VLFaceDetector:
"""High level face detector. Return *VLFaceDetection* instead simple *FaceDetection*. Attributes: estimatorsCollection (FaceEstimatorsCollection): face estimator collections for new detections. _faceDetector (FaceDetector): face detector faceEngine (VLFaceEngine): face engine for ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VLFaceDetector:
"""High level face detector. Return *VLFaceDetection* instead simple *FaceDetection*. Attributes: estimatorsCollection (FaceEstimatorsCollection): face estimator collections for new detections. _faceDetector (FaceDetector): face detector faceEngine (VLFaceEngine): face engine for detector and ... | the_stack_v2_python_sparse | lunavl/sdk/luna_faces.py | DeusAnimo/lunasdk | train | 1 |
b38989d148a7bdbe085c2511acd1689c1b1fa96c | [
"if minfo is None:\n minfo = {}\nsuper(ResetStatsMessage, self).__init__(minfo)\nself.IsSystemMessage = False\nself.IsForward = True\nself.IsReliable = True\nself.DomainList = minfo.get('DomainList', [])\nself.MetricList = minfo.get('MetricList', [])",
"result = super(ResetStatsMessage, self).dump()\nresult['D... | <|body_start_0|>
if minfo is None:
minfo = {}
super(ResetStatsMessage, self).__init__(minfo)
self.IsSystemMessage = False
self.IsForward = True
self.IsReliable = True
self.DomainList = minfo.get('DomainList', [])
self.MetricList = minfo.get('MetricList... | Reset stats messages are sent to a peer node to request it to reset statistics. Attributes: ResetStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. System messages have special delivery priority rules. IsForward (bool): Whether the message sho... | ResetStatsMessage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetStatsMessage:
"""Reset stats messages are sent to a peer node to request it to reset statistics. Attributes: ResetStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. System messages have special delivery priority rul... | stack_v2_sparse_classes_10k_train_006331 | 13,482 | permissive | [
{
"docstring": "Constructor for the ResetStatsMessage class. Args: minfo (dict): Dictionary of values for message fields.",
"name": "__init__",
"signature": "def __init__(self, minfo=None)"
},
{
"docstring": "Dumps a dict containing object attributes. Returns: dict: A mapping of object attribute... | 2 | stack_v2_sparse_classes_30k_val_000351 | Implement the Python class `ResetStatsMessage` described below.
Class description:
Reset stats messages are sent to a peer node to request it to reset statistics. Attributes: ResetStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. System mess... | Implement the Python class `ResetStatsMessage` described below.
Class description:
Reset stats messages are sent to a peer node to request it to reset statistics. Attributes: ResetStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. System mess... | 8f4ca1aab54ef420a0db10c8ca822ec8686cd423 | <|skeleton|>
class ResetStatsMessage:
"""Reset stats messages are sent to a peer node to request it to reset statistics. Attributes: ResetStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. System messages have special delivery priority rul... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResetStatsMessage:
"""Reset stats messages are sent to a peer node to request it to reset statistics. Attributes: ResetStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. System messages have special delivery priority rules. IsForward... | the_stack_v2_python_sparse | validator/gossip/messages/gossip_debug.py | aludvik/sawtooth-core | train | 0 |
6ac5c476eaa579b7296775513e26587a3aa7c648 | [
"length = len(prices)\nif length == 0:\n return 0\nresult = 0\nbuy = prices[0]\nsell = 0\nfor i in range(1, length):\n if sell == 0:\n diff = prices[i] - buy\n if diff <= 0:\n buy = prices[i]\n else:\n sell = prices[i]\n else:\n diff = prices[i] - sell\n ... | <|body_start_0|>
length = len(prices)
if length == 0:
return 0
result = 0
buy = prices[0]
sell = 0
for i in range(1, length):
if sell == 0:
diff = prices[i] - buy
if diff <= 0:
buy = prices[i]
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = len(prices)
if length =... | stack_v2_sparse_classes_10k_train_006332 | 1,400 | permissive | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit2",
"signature": "def maxProfit2(self, prices)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002383 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxPro... | c8bf33af30569177c5276ffcd72a8d93ba4c402a | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
length = len(prices)
if length == 0:
return 0
result = 0
buy = prices[0]
sell = 0
for i in range(1, length):
if sell == 0:
diff = pri... | the_stack_v2_python_sparse | 101-200/121-130/122-buyAndSell2/buyAndSell2.py | xuychen/Leetcode | train | 0 | |
406fa43d9b2f3a2ef8eaa479baa1f5e209a680eb | [
"left = start\nright = len(nums) - 1\ntotal = 0\nwhile left < right:\n if nums[left] + nums[right] < target:\n total += right - left\n left += 1\n else:\n right -= 1\nreturn total",
"nums = sorted(nums)\nres = 0\nfor i in range(len(nums) - 2):\n res += self.twoSumSmaller(nums, i + 1,... | <|body_start_0|>
left = start
right = len(nums) - 1
total = 0
while left < right:
if nums[left] + nums[right] < target:
total += right - left
left += 1
else:
right -= 1
return total
<|end_body_0|>
<|body_sta... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSumSmaller(self, nums, start, target):
""":type nums: List[int] :type start: int :type target: int :rtype: int"""
<|body_0|>
def threeSumSmaller(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_10k_train_006333 | 1,483 | no_license | [
{
"docstring": ":type nums: List[int] :type start: int :type target: int :rtype: int",
"name": "twoSumSmaller",
"signature": "def twoSumSmaller(self, nums, start, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "threeSumSmaller",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_006006 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSumSmaller(self, nums, start, target): :type nums: List[int] :type start: int :type target: int :rtype: int
- def threeSumSmaller(self, nums, target): :type nums: List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSumSmaller(self, nums, start, target): :type nums: List[int] :type start: int :type target: int :rtype: int
- def threeSumSmaller(self, nums, target): :type nums: List[int... | 7c2170aff7d129fbbf1d508a2644975e4106a6fe | <|skeleton|>
class Solution:
def twoSumSmaller(self, nums, start, target):
""":type nums: List[int] :type start: int :type target: int :rtype: int"""
<|body_0|>
def threeSumSmaller(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSumSmaller(self, nums, start, target):
""":type nums: List[int] :type start: int :type target: int :rtype: int"""
left = start
right = len(nums) - 1
total = 0
while left < right:
if nums[left] + nums[right] < target:
total +=... | the_stack_v2_python_sparse | Arrays and Strings/3SumSmaller.py | sid-verma/Coding-Interview-Questions | train | 0 | |
d1e5cdd2c43b933bf6c45b09e8e92bdd19d417f2 | [
"super(Repoquery, self).__init__(None)\nself.name = name\nself.query_type = query_type\nself.show_duplicates = show_duplicates\nself.match_version = match_version\nself.verbose = verbose\nif self.match_version:\n self.show_duplicates = True\nself.query_format = '%{version}|%{release}|%{arch}|%{repo}|%{version}-%... | <|body_start_0|>
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show_duplicates = show_duplicates
self.match_version = match_version
self.verbose = verbose
if self.match_version:
self.show_duplicates = True
... | Class to wrap the repoquery | Repoquery | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, verbose):
"""Constructor for YumList"""
<|body_0|>
def build_cmd(self):
"""build the repoquery cmd options"""
<|body_1|>
def process_ver... | stack_v2_sparse_classes_10k_train_006334 | 4,645 | permissive | [
{
"docstring": "Constructor for YumList",
"name": "__init__",
"signature": "def __init__(self, name, query_type, show_duplicates, match_version, verbose)"
},
{
"docstring": "build the repoquery cmd options",
"name": "build_cmd",
"signature": "def build_cmd(self)"
},
{
"docstring"... | 5 | null | Implement the Python class `Repoquery` described below.
Class description:
Class to wrap the repoquery
Method signatures and docstrings:
- def __init__(self, name, query_type, show_duplicates, match_version, verbose): Constructor for YumList
- def build_cmd(self): build the repoquery cmd options
- def process_version... | Implement the Python class `Repoquery` described below.
Class description:
Class to wrap the repoquery
Method signatures and docstrings:
- def __init__(self, name, query_type, show_duplicates, match_version, verbose): Constructor for YumList
- def build_cmd(self): build the repoquery cmd options
- def process_version... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, verbose):
"""Constructor for YumList"""
<|body_0|>
def build_cmd(self):
"""build the repoquery cmd options"""
<|body_1|>
def process_ver... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, verbose):
"""Constructor for YumList"""
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show_duplicates = show... | the_stack_v2_python_sparse | ansible/roles/lib_repoquery/build/src/repoquery.py | openshift/openshift-tools | train | 170 |
968026e1a57b999ee74cf8ed4c9dc0a6672036f5 | [
"def preOrderHelper(node, orderarr):\n if not node:\n orderarr.append('#')\n return\n orderarr.append(str(node.val))\n preOrderHelper(node.left, orderarr)\n preOrderHelper(node.right, orderarr)\ndic = {}\nret = []\n\ndef preOrderjudge(root):\n if root:\n orderarr = []\n pr... | <|body_start_0|>
def preOrderHelper(node, orderarr):
if not node:
orderarr.append('#')
return
orderarr.append(str(node.val))
preOrderHelper(node.left, orderarr)
preOrderHelper(node.right, orderarr)
dic = {}
ret = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicateSubtrees(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
<|body_0|>
def findDuplicateSubtrees2(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def ... | stack_v2_sparse_classes_10k_train_006335 | 2,356 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[TreeNode]",
"name": "findDuplicateSubtrees",
"signature": "def findDuplicateSubtrees(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[TreeNode]",
"name": "findDuplicateSubtrees2",
"signature": "def findDuplicateSubtrees2(... | 2 | stack_v2_sparse_classes_30k_train_006851 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicateSubtrees(self, root): :type root: TreeNode :rtype: List[TreeNode]
- def findDuplicateSubtrees2(self, root): :type root: TreeNode :rtype: List[TreeNode] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicateSubtrees(self, root): :type root: TreeNode :rtype: List[TreeNode]
- def findDuplicateSubtrees2(self, root): :type root: TreeNode :rtype: List[TreeNode]
<|skelet... | 85128e7d26157b3c36eb43868269de42ea2fcb98 | <|skeleton|>
class Solution:
def findDuplicateSubtrees(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
<|body_0|>
def findDuplicateSubtrees2(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicateSubtrees(self, root):
""":type root: TreeNode :rtype: List[TreeNode]"""
def preOrderHelper(node, orderarr):
if not node:
orderarr.append('#')
return
orderarr.append(str(node.val))
preOrderHelper(node... | the_stack_v2_python_sparse | src/findDuplicateSubtrees.py | jsdiuf/leetcode | train | 1 | |
b8c80844b883a41b90f6a6a0804e6319e8381189 | [
"Thread.__init__(self, name=name, daemon=daemon)\nself.study_name = study_name\nself.model_name = metric\nself.runs = runs\nself.budget = budget\nself.num_suggestions = num_suggestions\nself.dataset = dataset\nself.algorithm = Algorithm.instance(alg_name)\nself.space = self.__space(study_name)",
"data = Parameter... | <|body_start_0|>
Thread.__init__(self, name=name, daemon=daemon)
self.study_name = study_name
self.model_name = metric
self.runs = runs
self.budget = budget
self.num_suggestions = num_suggestions
self.dataset = dataset
self.algorithm = Algorithm.instance(a... | Suggestion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Suggestion:
def __init__(self, study_name, alg_name, metric, dataset, runs=5, budget=30, num_suggestions=10, name=None, daemon=True):
"""Initialize the suggestion worker. Args: :param study_name: name of the study :param alg_name: name of the algorithm :param metric: name of the model to... | stack_v2_sparse_classes_10k_train_006336 | 6,300 | no_license | [
{
"docstring": "Initialize the suggestion worker. Args: :param study_name: name of the study :param alg_name: name of the algorithm :param metric: name of the model to use as a metric :param dataset: name of the dataset to use with the model :param runs: how many times the algorithm is launched :param budget: b... | 4 | stack_v2_sparse_classes_30k_train_007347 | Implement the Python class `Suggestion` described below.
Class description:
Implement the Suggestion class.
Method signatures and docstrings:
- def __init__(self, study_name, alg_name, metric, dataset, runs=5, budget=30, num_suggestions=10, name=None, daemon=True): Initialize the suggestion worker. Args: :param study... | Implement the Python class `Suggestion` described below.
Class description:
Implement the Suggestion class.
Method signatures and docstrings:
- def __init__(self, study_name, alg_name, metric, dataset, runs=5, budget=30, num_suggestions=10, name=None, daemon=True): Initialize the suggestion worker. Args: :param study... | 27f861c09615aedfd96cffdebf7d9653f72b4d7b | <|skeleton|>
class Suggestion:
def __init__(self, study_name, alg_name, metric, dataset, runs=5, budget=30, num_suggestions=10, name=None, daemon=True):
"""Initialize the suggestion worker. Args: :param study_name: name of the study :param alg_name: name of the algorithm :param metric: name of the model to... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Suggestion:
def __init__(self, study_name, alg_name, metric, dataset, runs=5, budget=30, num_suggestions=10, name=None, daemon=True):
"""Initialize the suggestion worker. Args: :param study_name: name of the study :param alg_name: name of the algorithm :param metric: name of the model to use as a metr... | the_stack_v2_python_sparse | API/tasks.py | AndreaCorsini1/Ahmet | train | 1 | |
7445109bfe9000a2d2680b2b9da59ffe0e2c1b9e | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | An API for retrieving and managing error statistics as well as data for individual events. | ErrorStatsServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ErrorStatsServiceServicer:
"""An API for retrieving and managing error statistics as well as data for individual events."""
def ListGroupStats(self, request, context):
"""Lists the specified groups."""
<|body_0|>
def ListEvents(self, request, context):
"""Lists t... | stack_v2_sparse_classes_10k_train_006337 | 4,264 | no_license | [
{
"docstring": "Lists the specified groups.",
"name": "ListGroupStats",
"signature": "def ListGroupStats(self, request, context)"
},
{
"docstring": "Lists the specified events.",
"name": "ListEvents",
"signature": "def ListEvents(self, request, context)"
},
{
"docstring": "Delete... | 3 | stack_v2_sparse_classes_30k_train_003215 | Implement the Python class `ErrorStatsServiceServicer` described below.
Class description:
An API for retrieving and managing error statistics as well as data for individual events.
Method signatures and docstrings:
- def ListGroupStats(self, request, context): Lists the specified groups.
- def ListEvents(self, reque... | Implement the Python class `ErrorStatsServiceServicer` described below.
Class description:
An API for retrieving and managing error statistics as well as data for individual events.
Method signatures and docstrings:
- def ListGroupStats(self, request, context): Lists the specified groups.
- def ListEvents(self, reque... | d7424d21aa0dc121acc4d64b427ba365a3581a20 | <|skeleton|>
class ErrorStatsServiceServicer:
"""An API for retrieving and managing error statistics as well as data for individual events."""
def ListGroupStats(self, request, context):
"""Lists the specified groups."""
<|body_0|>
def ListEvents(self, request, context):
"""Lists t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ErrorStatsServiceServicer:
"""An API for retrieving and managing error statistics as well as data for individual events."""
def ListGroupStats(self, request, context):
"""Lists the specified groups."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not... | the_stack_v2_python_sparse | google/devtools/clouderrorreporting/v1beta1/error_stats_service_pb2_grpc.py | msachtler/bazel-event-protocol-parser | train | 1 |
006e1088e72201fab7eebd1409c025b5dba69403 | [
"if not root:\n return 'X'\nelse:\n return ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])",
"self.data = data\nif data[0] == 'X':\n return None\nelse:\n t = TreeNode(int(self.data[:self.data.find(',')]))\n t.left = self.deserialize(self.data[self.data.find(',') + 1... | <|body_start_0|>
if not root:
return 'X'
else:
return ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])
<|end_body_0|>
<|body_start_1|>
self.data = data
if data[0] == 'X':
return None
else:
t = TreeNo... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_006338 | 3,261 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_002996 | 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:... | 43a14e90b42ce1febb515e02cdd9d93781929173 | <|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_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return 'X'
else:
return ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])
def deserialize(self, data):
... | the_stack_v2_python_sparse | 297.py | sp-shaopeng/leetcode-practice | train | 0 | |
cb208f5b06e0a3683ece12eab844fb7c92966d80 | [
"if not head or not head.next:\n return head\nslow, fast = (head, head)\nwhile fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\nreturn slow",
"if not head or not head.next:\n return head\ncount = 0\ntemp = head\nwhile temp:\n count += 1\n temp = temp.next\nfor i in range... | <|body_start_0|>
if not head or not head.next:
return head
slow, fast = (head, head)
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow
<|end_body_0|>
<|body_start_1|>
if not head or not head.next:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def middle_linked_list(self, head: ListNode) -> ListNode:
"""找出中间结点 Args: head: 头结点 Returns: 中间结点"""
<|body_0|>
def middle_linked_list2(self, head: ListNode) -> ListNode:
"""找出中间结点 Args: head: 头结点 Returns: 中间结点"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_10k_train_006339 | 2,791 | permissive | [
{
"docstring": "找出中间结点 Args: head: 头结点 Returns: 中间结点",
"name": "middle_linked_list",
"signature": "def middle_linked_list(self, head: ListNode) -> ListNode"
},
{
"docstring": "找出中间结点 Args: head: 头结点 Returns: 中间结点",
"name": "middle_linked_list2",
"signature": "def middle_linked_list2(self... | 2 | stack_v2_sparse_classes_30k_train_006982 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def middle_linked_list(self, head: ListNode) -> ListNode: 找出中间结点 Args: head: 头结点 Returns: 中间结点
- def middle_linked_list2(self, head: ListNode) -> ListNode: 找出中间结点 Args: head: 头结点... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def middle_linked_list(self, head: ListNode) -> ListNode: 找出中间结点 Args: head: 头结点 Returns: 中间结点
- def middle_linked_list2(self, head: ListNode) -> ListNode: 找出中间结点 Args: head: 头结点... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def middle_linked_list(self, head: ListNode) -> ListNode:
"""找出中间结点 Args: head: 头结点 Returns: 中间结点"""
<|body_0|>
def middle_linked_list2(self, head: ListNode) -> ListNode:
"""找出中间结点 Args: head: 头结点 Returns: 中间结点"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def middle_linked_list(self, head: ListNode) -> ListNode:
"""找出中间结点 Args: head: 头结点 Returns: 中间结点"""
if not head or not head.next:
return head
slow, fast = (head, head)
while fast.next and fast.next.next:
slow = slow.next
fast = fas... | the_stack_v2_python_sparse | src/leetcodepython/list/middle_linked_list_876.py | zhangyu345293721/leetcode | train | 101 | |
73ca4a2b12aa08cca8fd79dbc1c793caf754d412 | [
"request = Request(request)\nresponse = RestResponse()\nuser_repository = UserRepository()\nrequest_serializer_manager = SerializerManager(GetUserSerializer)\nresponse_serializer_manager = SerializerManager(UserSerializer)\nuser_finder_controller = UserFinderController(request, response, user_repository, request_se... | <|body_start_0|>
request = Request(request)
response = RestResponse()
user_repository = UserRepository()
request_serializer_manager = SerializerManager(GetUserSerializer)
response_serializer_manager = SerializerManager(UserSerializer)
user_finder_controller = UserFinderCo... | User Api | UserApi | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserApi:
"""User Api"""
def get(self, request, _id: str=None):
"""Get User @param request: @type request: @param _id: @type _id: @return: @rtype:"""
<|body_0|>
def post(self, request, _id: str=None):
"""Post User @param request: request @type request: response @p... | stack_v2_sparse_classes_10k_train_006340 | 4,604 | permissive | [
{
"docstring": "Get User @param request: @type request: @param _id: @type _id: @return: @rtype:",
"name": "get",
"signature": "def get(self, request, _id: str=None)"
},
{
"docstring": "Post User @param request: request @type request: response @param _id: user id @type _id: int @return: post resp... | 4 | stack_v2_sparse_classes_30k_train_005356 | Implement the Python class `UserApi` described below.
Class description:
User Api
Method signatures and docstrings:
- def get(self, request, _id: str=None): Get User @param request: @type request: @param _id: @type _id: @return: @rtype:
- def post(self, request, _id: str=None): Post User @param request: request @type... | Implement the Python class `UserApi` described below.
Class description:
User Api
Method signatures and docstrings:
- def get(self, request, _id: str=None): Get User @param request: @type request: @param _id: @type _id: @return: @rtype:
- def post(self, request, _id: str=None): Post User @param request: request @type... | 8055927cb460bc40f3a2651c01a9d1da696177e8 | <|skeleton|>
class UserApi:
"""User Api"""
def get(self, request, _id: str=None):
"""Get User @param request: @type request: @param _id: @type _id: @return: @rtype:"""
<|body_0|>
def post(self, request, _id: str=None):
"""Post User @param request: request @type request: response @p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserApi:
"""User Api"""
def get(self, request, _id: str=None):
"""Get User @param request: @type request: @param _id: @type _id: @return: @rtype:"""
request = Request(request)
response = RestResponse()
user_repository = UserRepository()
request_serializer_manager =... | the_stack_v2_python_sparse | had/app/views/api/v1/users/user_api.py | eduardolujan/hexagonal_architecture_django | train | 5 |
31c7d54cb2ebf974366c31050cedde8cf2113d27 | [
"super(APL, self).__init__()\nself.a = nn.ParameterList([nn.Parameter(torch.tensor(0.2)) for _ in range(s)])\nself.b = nn.ParameterList([nn.Parameter(torch.tensor(0.5)) for _ in range(s)])\nself.s = s",
"part_1 = torch.clamp_min(input, min=0.0)\npart_2 = 0\nfor i in range(self.s):\n part_2 += self.a[i] * torch... | <|body_start_0|>
super(APL, self).__init__()
self.a = nn.ParameterList([nn.Parameter(torch.tensor(0.2)) for _ in range(s)])
self.b = nn.ParameterList([nn.Parameter(torch.tensor(0.5)) for _ in range(s)])
self.s = s
<|end_body_0|>
<|body_start_1|>
part_1 = torch.clamp_min(input, m... | APL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APL:
def __init__(self, s=1):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(APL, self).__init__()
self.a = nn.ParameterList([nn.Parameter(torch.... | stack_v2_sparse_classes_10k_train_006341 | 32,265 | no_license | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, s=1)"
},
{
"docstring": "Forward pass of the function.",
"name": "forward",
"signature": "def forward(self, input)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003867 | Implement the Python class `APL` described below.
Class description:
Implement the APL class.
Method signatures and docstrings:
- def __init__(self, s=1): Init method.
- def forward(self, input): Forward pass of the function. | Implement the Python class `APL` described below.
Class description:
Implement the APL class.
Method signatures and docstrings:
- def __init__(self, s=1): Init method.
- def forward(self, input): Forward pass of the function.
<|skeleton|>
class APL:
def __init__(self, s=1):
"""Init method."""
<|... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class APL:
def __init__(self, s=1):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class APL:
def __init__(self, s=1):
"""Init method."""
super(APL, self).__init__()
self.a = nn.ParameterList([nn.Parameter(torch.tensor(0.2)) for _ in range(s)])
self.b = nn.ParameterList([nn.Parameter(torch.tensor(0.5)) for _ in range(s)])
self.s = s
def forward(self, i... | the_stack_v2_python_sparse | generated/test_digantamisra98_Echo.py | jansel/pytorch-jit-paritybench | train | 35 | |
da4151eeaac8516893d2ed4a718c5a7076952036 | [
"with open('sat.json', 'r') as infile:\n self._sat = json.load(infile)['data']\nself._headers = ['DBN', 'School Name', 'Number of Test Takers', 'Critical Reading Mean', 'Mathematics Mean', 'Writing Mean']",
"with open('output.csv', 'w') as outfile:\n for i in range(0, 5):\n outfile.write(self._header... | <|body_start_0|>
with open('sat.json', 'r') as infile:
self._sat = json.load(infile)['data']
self._headers = ['DBN', 'School Name', 'Number of Test Takers', 'Critical Reading Mean', 'Mathematics Mean', 'Writing Mean']
<|end_body_0|>
<|body_start_1|>
with open('output.csv', 'w') as o... | SatData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SatData:
def __init__(self):
"""Initializes the SatData object and reads in the .json file"""
<|body_0|>
def save_as_csv(self, DBNs):
"""This method takes a list of district bureau numbers and saves a CSV file"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_006342 | 1,403 | no_license | [
{
"docstring": "Initializes the SatData object and reads in the .json file",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This method takes a list of district bureau numbers and saves a CSV file",
"name": "save_as_csv",
"signature": "def save_as_csv(self, DBNs... | 2 | stack_v2_sparse_classes_30k_train_004421 | Implement the Python class `SatData` described below.
Class description:
Implement the SatData class.
Method signatures and docstrings:
- def __init__(self): Initializes the SatData object and reads in the .json file
- def save_as_csv(self, DBNs): This method takes a list of district bureau numbers and saves a CSV fi... | Implement the Python class `SatData` described below.
Class description:
Implement the SatData class.
Method signatures and docstrings:
- def __init__(self): Initializes the SatData object and reads in the .json file
- def save_as_csv(self, DBNs): This method takes a list of district bureau numbers and saves a CSV fi... | 281749a4ac6961f146ebd9abaf79ccf641262619 | <|skeleton|>
class SatData:
def __init__(self):
"""Initializes the SatData object and reads in the .json file"""
<|body_0|>
def save_as_csv(self, DBNs):
"""This method takes a list of district bureau numbers and saves a CSV file"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SatData:
def __init__(self):
"""Initializes the SatData object and reads in the .json file"""
with open('sat.json', 'r') as infile:
self._sat = json.load(infile)['data']
self._headers = ['DBN', 'School Name', 'Number of Test Takers', 'Critical Reading Mean', 'Mathematics Me... | the_stack_v2_python_sparse | project 5/5c/SatData.py | huynmela/CS162 | train | 0 | |
0548ffb517685355435c788e71568318e6325441 | [
"self._config = config\nself._game_env = importlib.import_module(config['env_path'])\nself._FEATURES = {'board_history': {'size': config['history_step'] * config['planes_per_step'], 'function': self.get_board_history}, 'color': {'size': 1, 'function': lambda state: np.ones((1, state.height, state.width)) * (state.c... | <|body_start_0|>
self._config = config
self._game_env = importlib.import_module(config['env_path'])
self._FEATURES = {'board_history': {'size': config['history_step'] * config['planes_per_step'], 'function': self.get_board_history}, 'color': {'size': 1, 'function': lambda state: np.ones((1, stat... | a class to convert from AlphaGo GameState objects to tensors of one-hot features for NN inputs | StateTensorConverter | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StateTensorConverter:
"""a class to convert from AlphaGo GameState objects to tensors of one-hot features for NN inputs"""
def __init__(self, config, feature_list=None):
"""create a preprocessor object that will concatenate together the given list of features"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_006343 | 6,274 | permissive | [
{
"docstring": "create a preprocessor object that will concatenate together the given list of features",
"name": "__init__",
"signature": "def __init__(self, config, feature_list=None)"
},
{
"docstring": "A feature encoding WHITE and BLACK on separate planes of recent history_length states Args:... | 3 | stack_v2_sparse_classes_30k_train_004452 | Implement the Python class `StateTensorConverter` described below.
Class description:
a class to convert from AlphaGo GameState objects to tensors of one-hot features for NN inputs
Method signatures and docstrings:
- def __init__(self, config, feature_list=None): create a preprocessor object that will concatenate tog... | Implement the Python class `StateTensorConverter` described below.
Class description:
a class to convert from AlphaGo GameState objects to tensors of one-hot features for NN inputs
Method signatures and docstrings:
- def __init__(self, config, feature_list=None): create a preprocessor object that will concatenate tog... | 920162071c7a1557cbf45ffdecd840ee2b25b88f | <|skeleton|>
class StateTensorConverter:
"""a class to convert from AlphaGo GameState objects to tensors of one-hot features for NN inputs"""
def __init__(self, config, feature_list=None):
"""create a preprocessor object that will concatenate together the given list of features"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StateTensorConverter:
"""a class to convert from AlphaGo GameState objects to tensors of one-hot features for NN inputs"""
def __init__(self, config, feature_list=None):
"""create a preprocessor object that will concatenate together the given list of features"""
self._config = config
... | the_stack_v2_python_sparse | AlphaZero/processing/state_converter.py | water-vapor/AlphaZero | train | 9 |
2b67dd36d7dd1572f39286da85087c1741336de4 | [
"players_sufficient = len(self.players) >= 2\nif not players_sufficient:\n return False\nplayers_ready = all((p.ready for p in self.players.values()))\nif not players_ready:\n return False\nmap_specified = self.map_template is not None\nif not map_specified:\n return False\nreturn True",
"if player_oid i... | <|body_start_0|>
players_sufficient = len(self.players) >= 2
if not players_sufficient:
return False
players_ready = all((p.ready for p in self.players.values()))
if not players_ready:
return False
map_specified = self.map_template is not None
if n... | Object representing a pending game. Pending game means that the game has not been started. For a pending game to be ready to start, the game should have 2+ players and decide the map to play. | PendingGame | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PendingGame:
"""Object representing a pending game. Pending game means that the game has not been started. For a pending game to be ready to start, the game should have 2+ players and decide the map to play."""
def ready(self):
"""Check if the game is ready to be started. For the gam... | stack_v2_sparse_classes_10k_train_006344 | 3,604 | permissive | [
{
"docstring": "Check if the game is ready to be started. For the game to be ready to start, **ALL** of the following conditions must be fulfilled: - Player count >= 2 - All players are ready (``ready`` is set to ``True``) - Map to be used is specified :return: game is ready to be started or not",
"name": "... | 4 | null | Implement the Python class `PendingGame` described below.
Class description:
Object representing a pending game. Pending game means that the game has not been started. For a pending game to be ready to start, the game should have 2+ players and decide the map to play.
Method signatures and docstrings:
- def ready(sel... | Implement the Python class `PendingGame` described below.
Class description:
Object representing a pending game. Pending game means that the game has not been started. For a pending game to be ready to start, the game should have 2+ players and decide the map to play.
Method signatures and docstrings:
- def ready(sel... | c7da1e91783dce3a2b71b955b3a22b68db9056cf | <|skeleton|>
class PendingGame:
"""Object representing a pending game. Pending game means that the game has not been started. For a pending game to be ready to start, the game should have 2+ players and decide the map to play."""
def ready(self):
"""Check if the game is ready to be started. For the gam... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PendingGame:
"""Object representing a pending game. Pending game means that the game has not been started. For a pending game to be ready to start, the game should have 2+ players and decide the map to play."""
def ready(self):
"""Check if the game is ready to be started. For the game to be ready... | the_stack_v2_python_sparse | game/pkchess/game/pending.py | RxJellyBot/Jelly-Bot | train | 5 |
c4fc4e689e78eeb136fe092005f8c4d275915ec8 | [
"left = node.left != None\nright = node.right != None\nif not left and (not right):\n if cur_sum == node.val:\n foundSoFar.append(pathSoFar)\n return\nif left:\n self.helper(node.left, cur_sum - node.val, pathSoFar + [node.left.val], foundSoFar)\nif right:\n self.helper(node.right, cur_sum - node... | <|body_start_0|>
left = node.left != None
right = node.right != None
if not left and (not right):
if cur_sum == node.val:
foundSoFar.append(pathSoFar)
return
if left:
self.helper(node.left, cur_sum - node.val, pathSoFar + [node.left.val... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def helper(self, node, cur_sum, pathSoFar, foundSoFar):
""":type node: TreeNode :type cur_sum: int :type pathSoFar: List[int] :type foundSoFar: List[List[int]] :rtype: None? List[List[int]]?"""
<|body_0|>
def pathSum(self, root, cur_sum):
""":type root: Tre... | stack_v2_sparse_classes_10k_train_006345 | 1,181 | no_license | [
{
"docstring": ":type node: TreeNode :type cur_sum: int :type pathSoFar: List[int] :type foundSoFar: List[List[int]] :rtype: None? List[List[int]]?",
"name": "helper",
"signature": "def helper(self, node, cur_sum, pathSoFar, foundSoFar)"
},
{
"docstring": ":type root: TreeNode :type cur_sum: int... | 2 | stack_v2_sparse_classes_30k_train_004518 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, node, cur_sum, pathSoFar, foundSoFar): :type node: TreeNode :type cur_sum: int :type pathSoFar: List[int] :type foundSoFar: List[List[int]] :rtype: None? List[Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, node, cur_sum, pathSoFar, foundSoFar): :type node: TreeNode :type cur_sum: int :type pathSoFar: List[int] :type foundSoFar: List[List[int]] :rtype: None? List[Li... | dcf9768aeb120f3ad9925e407193e1a4b282a0a2 | <|skeleton|>
class Solution:
def helper(self, node, cur_sum, pathSoFar, foundSoFar):
""":type node: TreeNode :type cur_sum: int :type pathSoFar: List[int] :type foundSoFar: List[List[int]] :rtype: None? List[List[int]]?"""
<|body_0|>
def pathSum(self, root, cur_sum):
""":type root: Tre... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def helper(self, node, cur_sum, pathSoFar, foundSoFar):
""":type node: TreeNode :type cur_sum: int :type pathSoFar: List[int] :type foundSoFar: List[List[int]] :rtype: None? List[List[int]]?"""
left = node.left != None
right = node.right != None
if not left and (not r... | the_stack_v2_python_sparse | Path_Sum_II_Optimized.py | O5-2/leetcode | train | 0 | |
3c4b114a9c3eed4783d30677fe874c8ddcefa2dc | [
"super().__init__()\nself.action_bias = action_bias\nself.action_scale = action_scale\nself.shared_net = nn.Sequential(nn.Linear(input_shape[0], hidden_size), nn.ReLU(), nn.Linear(hidden_size, hidden_size), nn.ReLU())\nself.mean_layer = nn.Linear(hidden_size, n_actions)\nself.logstd_layer = nn.Linear(hidden_size, n... | <|body_start_0|>
super().__init__()
self.action_bias = action_bias
self.action_scale = action_scale
self.shared_net = nn.Sequential(nn.Linear(input_shape[0], hidden_size), nn.ReLU(), nn.Linear(hidden_size, hidden_size), nn.ReLU())
self.mean_layer = nn.Linear(hidden_size, n_action... | MLP network that outputs continuous value via Gaussian distribution. | ContinuousMLP | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContinuousMLP:
"""MLP network that outputs continuous value via Gaussian distribution."""
def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128, action_bias: int=0, action_scale: int=1) -> None:
"""Args: input_shape: observation shape of the environment n_a... | stack_v2_sparse_classes_10k_train_006346 | 15,112 | permissive | [
{
"docstring": "Args: input_shape: observation shape of the environment n_actions: dimension of actions in the environment hidden_size: size of hidden layers action_bias: the center of the action space action_scale: the scale of the action space",
"name": "__init__",
"signature": "def __init__(self, inp... | 3 | stack_v2_sparse_classes_30k_train_000300 | Implement the Python class `ContinuousMLP` described below.
Class description:
MLP network that outputs continuous value via Gaussian distribution.
Method signatures and docstrings:
- def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128, action_bias: int=0, action_scale: int=1) -> None: Ar... | Implement the Python class `ContinuousMLP` described below.
Class description:
MLP network that outputs continuous value via Gaussian distribution.
Method signatures and docstrings:
- def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128, action_bias: int=0, action_scale: int=1) -> None: Ar... | bdf311369b236c1e3d0336c7ed4ba249854f8606 | <|skeleton|>
class ContinuousMLP:
"""MLP network that outputs continuous value via Gaussian distribution."""
def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128, action_bias: int=0, action_scale: int=1) -> None:
"""Args: input_shape: observation shape of the environment n_a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ContinuousMLP:
"""MLP network that outputs continuous value via Gaussian distribution."""
def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128, action_bias: int=0, action_scale: int=1) -> None:
"""Args: input_shape: observation shape of the environment n_actions: dimen... | the_stack_v2_python_sparse | src/pl_bolts/models/rl/common/networks.py | Lightning-Universe/lightning-bolts | train | 76 |
02055af1047f82e7b662c7dcc569fd8084496232 | [
"self.ndims = ndims\nself.W_init = W_init\nself.W0 = None\nif W_init == 'zeros':\n self.W0 = tf.zeros([self.ndims + 1, 1], dtype=tf.float64)\nelif W_init == 'ones':\n self.W0 = tf.ones([self.ndims + 1, 1], dtype=tf.float64)\nelif W_init == 'uniform':\n self.W0 = tf.random_uniform([self.ndims + 1, 1], 0, 1,... | <|body_start_0|>
self.ndims = ndims
self.W_init = W_init
self.W0 = None
if W_init == 'zeros':
self.W0 = tf.zeros([self.ndims + 1, 1], dtype=tf.float64)
elif W_init == 'ones':
self.W0 = tf.ones([self.ndims + 1, 1], dtype=tf.float64)
elif W_init == '... | LogisticModel_TF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogisticModel_TF:
def __init__(self, ndims, W_init='zeros'):
"""Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector, self.W, based on the method specified in W_init. We assume that the FIRST index of Weight is the bias t... | stack_v2_sparse_classes_10k_train_006347 | 4,070 | no_license | [
{
"docstring": "Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector, self.W, based on the method specified in W_init. We assume that the FIRST index of Weight is the bias term, Weight = [Bias, W1, W2, W3, ...] where Wi correspnds to each featur... | 3 | stack_v2_sparse_classes_30k_train_001742 | Implement the Python class `LogisticModel_TF` described below.
Class description:
Implement the LogisticModel_TF class.
Method signatures and docstrings:
- def __init__(self, ndims, W_init='zeros'): Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector... | Implement the Python class `LogisticModel_TF` described below.
Class description:
Implement the LogisticModel_TF class.
Method signatures and docstrings:
- def __init__(self, ndims, W_init='zeros'): Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector... | 7726edd466bc8986a50b1e13590c132065ccb64d | <|skeleton|>
class LogisticModel_TF:
def __init__(self, ndims, W_init='zeros'):
"""Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector, self.W, based on the method specified in W_init. We assume that the FIRST index of Weight is the bias t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LogisticModel_TF:
def __init__(self, ndims, W_init='zeros'):
"""Initialize a logistic model. This function prepares an initialized logistic model. It will initialize the weight vector, self.W, based on the method specified in W_init. We assume that the FIRST index of Weight is the bias term, Weight = ... | the_stack_v2_python_sparse | MachineProblems/3_BinaryClassification/mp3/codefromtf/logistic_model.py | namanUIUC/MachineLearning | train | 10 | |
04ae1e6821d1937e43fe1fe110658070ecf36309 | [
"A.sort()\nfor i in range(len(A)):\n if not K:\n break\n if A[i] < 0:\n A[i] = -A[i]\n K -= 1\nif K % 2 == 0:\n return sum(A)\nelse:\n return sum(A) - 2 * min(A)",
"for i in range(K):\n idx = A.index(min(A))\n A[idx] = -A[idx]\nreturn sum(A)"
] | <|body_start_0|>
A.sort()
for i in range(len(A)):
if not K:
break
if A[i] < 0:
A[i] = -A[i]
K -= 1
if K % 2 == 0:
return sum(A)
else:
return sum(A) - 2 * min(A)
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestSumAfterKNegations(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_0|>
def largestSumAfterKNegations2(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_006348 | 1,756 | no_license | [
{
"docstring": ":type A: List[int] :type K: int :rtype: int",
"name": "largestSumAfterKNegations",
"signature": "def largestSumAfterKNegations(self, A, K)"
},
{
"docstring": ":type A: List[int] :type K: int :rtype: int",
"name": "largestSumAfterKNegations2",
"signature": "def largestSumA... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestSumAfterKNegations(self, A, K): :type A: List[int] :type K: int :rtype: int
- def largestSumAfterKNegations2(self, A, K): :type A: 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 largestSumAfterKNegations(self, A, K): :type A: List[int] :type K: int :rtype: int
- def largestSumAfterKNegations2(self, A, K): :type A: List[int] :type K: int :rtype: int
... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def largestSumAfterKNegations(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_0|>
def largestSumAfterKNegations2(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def largestSumAfterKNegations(self, A, K):
""":type A: List[int] :type K: int :rtype: int"""
A.sort()
for i in range(len(A)):
if not K:
break
if A[i] < 0:
A[i] = -A[i]
K -= 1
if K % 2 == 0:
... | the_stack_v2_python_sparse | python/1005.maximize-sum-of-array-after-k-negations.py | tainenko/Leetcode2019 | train | 5 | |
12e84cf753dbfd1107f1b67e9d6a8326fd3e054b | [
"file_name = base_name + '.hdf5'\noutput_path = output_directory + '/' + file_name\nphdLogger.info('hdf5 format: Writting %s' % file_name)\nwith h5py.File(output_path, 'w') as f:\n f.attrs['dt'] = integrator.dt\n f.attrs['time'] = integrator.time\n f.attrs['iteration'] = integrator.iteration\n particle_... | <|body_start_0|>
file_name = base_name + '.hdf5'
output_path = output_directory + '/' + file_name
phdLogger.info('hdf5 format: Writting %s' % file_name)
with h5py.File(output_path, 'w') as f:
f.attrs['dt'] = integrator.dt
f.attrs['time'] = integrator.time
... | Hdf5 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hdf5:
def write(self, base_name, output_directory, integrator):
"""Write simulation data to hdf5 file."""
<|body_0|>
def read(self, file_name):
"""Read hdf5 file of particles."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
file_name = base_name + '... | stack_v2_sparse_classes_10k_train_006349 | 3,485 | no_license | [
{
"docstring": "Write simulation data to hdf5 file.",
"name": "write",
"signature": "def write(self, base_name, output_directory, integrator)"
},
{
"docstring": "Read hdf5 file of particles.",
"name": "read",
"signature": "def read(self, file_name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006301 | Implement the Python class `Hdf5` described below.
Class description:
Implement the Hdf5 class.
Method signatures and docstrings:
- def write(self, base_name, output_directory, integrator): Write simulation data to hdf5 file.
- def read(self, file_name): Read hdf5 file of particles. | Implement the Python class `Hdf5` described below.
Class description:
Implement the Hdf5 class.
Method signatures and docstrings:
- def write(self, base_name, output_directory, integrator): Write simulation data to hdf5 file.
- def read(self, file_name): Read hdf5 file of particles.
<|skeleton|>
class Hdf5:
def... | 513b292ac721284cfd9018d53d78cb17772b7f07 | <|skeleton|>
class Hdf5:
def write(self, base_name, output_directory, integrator):
"""Write simulation data to hdf5 file."""
<|body_0|>
def read(self, file_name):
"""Read hdf5 file of particles."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Hdf5:
def write(self, base_name, output_directory, integrator):
"""Write simulation data to hdf5 file."""
file_name = base_name + '.hdf5'
output_path = output_directory + '/' + file_name
phdLogger.info('hdf5 format: Writting %s' % file_name)
with h5py.File(output_path, ... | the_stack_v2_python_sparse | phd/io/read_write.py.bak | phd-code/phd-code.github.io | train | 0 | |
8613b18e9a67bcfd19303ab3a8c2c958cbf23c7d | [
"self.logger = logging.getLogger(__name__)\nself.filename = filename\nif display is None:\n display = os.environ['DISPLAY']\nself.display = display\nif size is None:\n size = (1024, 768)\nself.size = size\nself.p = None",
"cmd = 'ffmpeg -y' + ' -video_size %sx%s' % self.size + ' -framerate 25' + ' -preset u... | <|body_start_0|>
self.logger = logging.getLogger(__name__)
self.filename = filename
if display is None:
display = os.environ['DISPLAY']
self.display = display
if size is None:
size = (1024, 768)
self.size = size
self.p = None
<|end_body_0|>... | WebRecordXvfb | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebRecordXvfb:
def __init__(self, filename, size=None, display=None):
"""record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (W,H) (ex. (1024,768)). display: the DISPLAY to record (ex. ':0.0')."""
<|body_0|>
def sta... | stack_v2_sparse_classes_10k_train_006350 | 3,050 | permissive | [
{
"docstring": "record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (W,H) (ex. (1024,768)). display: the DISPLAY to record (ex. ':0.0').",
"name": "__init__",
"signature": "def __init__(self, filename, size=None, display=None)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_003318 | Implement the Python class `WebRecordXvfb` described below.
Class description:
Implement the WebRecordXvfb class.
Method signatures and docstrings:
- def __init__(self, filename, size=None, display=None): record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (... | Implement the Python class `WebRecordXvfb` described below.
Class description:
Implement the WebRecordXvfb class.
Method signatures and docstrings:
- def __init__(self, filename, size=None, display=None): record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (... | 2ff506eb56ba00f035300862f8848e4168452a17 | <|skeleton|>
class WebRecordXvfb:
def __init__(self, filename, size=None, display=None):
"""record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (W,H) (ex. (1024,768)). display: the DISPLAY to record (ex. ':0.0')."""
<|body_0|>
def sta... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WebRecordXvfb:
def __init__(self, filename, size=None, display=None):
"""record an xvfb session running a test filename: the name of the file to save the recording to. size: 2-tuple of (W,H) (ex. (1024,768)). display: the DISPLAY to record (ex. ':0.0')."""
self.logger = logging.getLogger(__nam... | the_stack_v2_python_sparse | hubcheck/utils/record.py | ken2190/hubcheck | train | 0 | |
57b4459d36f9eababd4baff81bbd7ca1d6d9f1cb | [
"if root is None:\n return TreeNode(None)\nif p.val >= root.val and q.val <= root.val or (p.val <= root.val and q.val >= root.val):\n return root\nnodel = self.lowestCommonAncestor(root.left, p, q)\nnoder = self.lowestCommonAncestor(root.right, p, q)\nreturn nodel if noder.val is None else noder",
"if p.val... | <|body_start_0|>
if root is None:
return TreeNode(None)
if p.val >= root.val and q.val <= root.val or (p.val <= root.val and q.val >= root.val):
return root
nodel = self.lowestCommonAncestor(root.left, p, q)
noder = self.lowestCommonAncestor(root.right, p, q)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""考虑到二叉搜索树的特性,使用递归方法 当前节点的值大于等于p小于等于q或者大于等于q小于等于p时满足最近公共祖先"""
<|body_0|>
def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
... | stack_v2_sparse_classes_10k_train_006351 | 1,754 | no_license | [
{
"docstring": "考虑到二叉搜索树的特性,使用递归方法 当前节点的值大于等于p小于等于q或者大于等于q小于等于p时满足最近公共祖先",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode'"
},
{
"docstring": "考虑到二叉搜索树的特性,使用非递归方法",
"name": "lowestCommonAncestor1",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 考虑到二叉搜索树的特性,使用递归方法 当前节点的值大于等于p小于等于q或者大于等于q小于等于p时满足最近公共祖先
- def lowestCommonAncestor1... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 考虑到二叉搜索树的特性,使用递归方法 当前节点的值大于等于p小于等于q或者大于等于q小于等于p时满足最近公共祖先
- def lowestCommonAncestor1... | 95dddb78bccd169d9d219a473627361fe739ab5e | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""考虑到二叉搜索树的特性,使用递归方法 当前节点的值大于等于p小于等于q或者大于等于q小于等于p时满足最近公共祖先"""
<|body_0|>
def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""考虑到二叉搜索树的特性,使用递归方法 当前节点的值大于等于p小于等于q或者大于等于q小于等于p时满足最近公共祖先"""
if root is None:
return TreeNode(None)
if p.val >= root.val and q.val <= root.val or (p.val <= root.val and... | the_stack_v2_python_sparse | TreeOperation/lowestCommonAncestor.py | Philex5/codingPractice | train | 0 | |
1b09195ed75184e7317f225582e474fda33c717a | [
"self._center = _format_LatLng(lat, lng, precision)\nself._radius = radius\nedge_color = kwargs.get('edge_color')\nself._edge_color = _get_hex_color(edge_color) if edge_color is not None else None\nself._edge_alpha = kwargs.get('edge_alpha')\nself._edge_width = kwargs.get('edge_width')\nface_color = kwargs.get('fac... | <|body_start_0|>
self._center = _format_LatLng(lat, lng, precision)
self._radius = radius
edge_color = kwargs.get('edge_color')
self._edge_color = _get_hex_color(edge_color) if edge_color is not None else None
self._edge_alpha = kwargs.get('edge_alpha')
self._edge_width =... | _Circle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Circle:
def __init__(self, lat, lng, radius, precision, **kwargs):
"""Args: lat (float): Latitude of the center of the circle. lng (float): Longitude of the center of the circle. radius (int): Radius of the circle, in meters. precision (int): Number of digits after the decimal to round ... | stack_v2_sparse_classes_10k_train_006352 | 2,435 | permissive | [
{
"docstring": "Args: lat (float): Latitude of the center of the circle. lng (float): Longitude of the center of the circle. radius (int): Radius of the circle, in meters. precision (int): Number of digits after the decimal to round to for lat/lng values. Optional: Args: edge_color (str): Color of the circle's ... | 2 | stack_v2_sparse_classes_30k_train_004766 | Implement the Python class `_Circle` described below.
Class description:
Implement the _Circle class.
Method signatures and docstrings:
- def __init__(self, lat, lng, radius, precision, **kwargs): Args: lat (float): Latitude of the center of the circle. lng (float): Longitude of the center of the circle. radius (int)... | Implement the Python class `_Circle` described below.
Class description:
Implement the _Circle class.
Method signatures and docstrings:
- def __init__(self, lat, lng, radius, precision, **kwargs): Args: lat (float): Latitude of the center of the circle. lng (float): Longitude of the center of the circle. radius (int)... | 8654a5a370b5ec309e1282c457eaf375c3dcb4bb | <|skeleton|>
class _Circle:
def __init__(self, lat, lng, radius, precision, **kwargs):
"""Args: lat (float): Latitude of the center of the circle. lng (float): Longitude of the center of the circle. radius (int): Radius of the circle, in meters. precision (int): Number of digits after the decimal to round ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _Circle:
def __init__(self, lat, lng, radius, precision, **kwargs):
"""Args: lat (float): Latitude of the center of the circle. lng (float): Longitude of the center of the circle. radius (int): Radius of the circle, in meters. precision (int): Number of digits after the decimal to round to for lat/lng... | the_stack_v2_python_sparse | gmplot/drawables/symbols/circle.py | fishke22/gmplot | train | 0 | |
3106cb9233ae0604f22467633ca8f556cb0207f5 | [
"self._r1 = r1\nself._r2 = r2\nself._direction = direction",
"delev, dazim = self._direction\nr1 = self._r1\nr2 = self._r2\nx1 = -r1 * np.cos(elev) * np.cos(azim)\ny1 = -r1 * np.cos(elev) * np.sin(azim)\nz1 = r1 * np.sin(elev)\ndx1 = -np.cos(delev) * np.cos(dazim)\ndy1 = -np.cos(delev) * np.sin(dazim)\ndz1 = np.s... | <|body_start_0|>
self._r1 = r1
self._r2 = r2
self._direction = direction
<|end_body_0|>
<|body_start_1|>
delev, dazim = self._direction
r1 = self._r1
r2 = self._r2
x1 = -r1 * np.cos(elev) * np.cos(azim)
y1 = -r1 * np.cos(elev) * np.sin(azim)
z1 = ... | SphereToCylinderMap | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphereToCylinderMap:
def __init__(self, r1, r2, direction):
"""r1: sphere radius r2: cylinder radius direction: can be a tuple or a list of 2 elements elevation, azimuth"""
<|body_0|>
def map(self, elev, azim):
"""z = 0 corresponds to azimuth 0 or pi z = max at azimu... | stack_v2_sparse_classes_10k_train_006353 | 16,243 | permissive | [
{
"docstring": "r1: sphere radius r2: cylinder radius direction: can be a tuple or a list of 2 elements elevation, azimuth",
"name": "__init__",
"signature": "def __init__(self, r1, r2, direction)"
},
{
"docstring": "z = 0 corresponds to azimuth 0 or pi z = max at azimuth -pi/2 axes were chosen ... | 3 | stack_v2_sparse_classes_30k_train_000255 | Implement the Python class `SphereToCylinderMap` described below.
Class description:
Implement the SphereToCylinderMap class.
Method signatures and docstrings:
- def __init__(self, r1, r2, direction): r1: sphere radius r2: cylinder radius direction: can be a tuple or a list of 2 elements elevation, azimuth
- def map(... | Implement the Python class `SphereToCylinderMap` described below.
Class description:
Implement the SphereToCylinderMap class.
Method signatures and docstrings:
- def __init__(self, r1, r2, direction): r1: sphere radius r2: cylinder radius direction: can be a tuple or a list of 2 elements elevation, azimuth
- def map(... | fdab351e6c5530c8f051193158856ba6ef11d715 | <|skeleton|>
class SphereToCylinderMap:
def __init__(self, r1, r2, direction):
"""r1: sphere radius r2: cylinder radius direction: can be a tuple or a list of 2 elements elevation, azimuth"""
<|body_0|>
def map(self, elev, azim):
"""z = 0 corresponds to azimuth 0 or pi z = max at azimu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SphereToCylinderMap:
def __init__(self, r1, r2, direction):
"""r1: sphere radius r2: cylinder radius direction: can be a tuple or a list of 2 elements elevation, azimuth"""
self._r1 = r1
self._r2 = r2
self._direction = direction
def map(self, elev, azim):
"""z = 0 ... | the_stack_v2_python_sparse | retina/screen/map/mapimpl.py | neurokernel/retina | train | 5 | |
4ed696d2a0a4dac761c54325ba5b9e822c0a8d50 | [
"self.dynamics_net = ForwardModel(state_dim, action_dim)\nself.rewards_net = RewardModel(state_dim, action_dim)\nself.done_net = RewardModel(state_dim, action_dim)\nself.dyn_optimizer = tfa_optimizers.AdamW(learning_rate=learning_rate, weight_decay=weight_decay)\nself.reward_optimizer = tfa_optimizers.AdamW(learnin... | <|body_start_0|>
self.dynamics_net = ForwardModel(state_dim, action_dim)
self.rewards_net = RewardModel(state_dim, action_dim)
self.done_net = RewardModel(state_dim, action_dim)
self.dyn_optimizer = tfa_optimizers.AdamW(learning_rate=learning_rate, weight_decay=weight_decay)
self... | A class that learns models and estimated returns via rollouts. | ModelBased | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelBased:
"""A class that learns models and estimated returns via rollouts."""
def __init__(self, state_dim, action_dim, learning_rate, weight_decay):
"""Creates networks and optimizers for model based policy evaluation. Args: state_dim: State size. action_dim: Action size. learnin... | stack_v2_sparse_classes_10k_train_006354 | 7,358 | permissive | [
{
"docstring": "Creates networks and optimizers for model based policy evaluation. Args: state_dim: State size. action_dim: Action size. learning_rate: Critic learning rate. weight_decay: Weight decay.",
"name": "__init__",
"signature": "def __init__(self, state_dim, action_dim, learning_rate, weight_de... | 3 | stack_v2_sparse_classes_30k_train_005174 | Implement the Python class `ModelBased` described below.
Class description:
A class that learns models and estimated returns via rollouts.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, learning_rate, weight_decay): Creates networks and optimizers for model based policy evaluation. Args... | Implement the Python class `ModelBased` described below.
Class description:
A class that learns models and estimated returns via rollouts.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, learning_rate, weight_decay): Creates networks and optimizers for model based policy evaluation. Args... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ModelBased:
"""A class that learns models and estimated returns via rollouts."""
def __init__(self, state_dim, action_dim, learning_rate, weight_decay):
"""Creates networks and optimizers for model based policy evaluation. Args: state_dim: State size. action_dim: Action size. learnin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModelBased:
"""A class that learns models and estimated returns via rollouts."""
def __init__(self, state_dim, action_dim, learning_rate, weight_decay):
"""Creates networks and optimizers for model based policy evaluation. Args: state_dim: State size. action_dim: Action size. learning_rate: Criti... | the_stack_v2_python_sparse | policy_eval/model_based.py | Jimmy-INL/google-research | train | 1 |
6aa2408d55e4ec4f16425b0a398b320c73b2180b | [
"super().__init__(model)\nself.data = shap.kmeans(data, 25)\nself.explainer = shap.KernelExplainer(self.model, self.data, link=link)",
"shap_vals = self.explainer.shap_values(data_x[0], nsamples=10000, silent=True)\nif len(shap_vals) > 1:\n shap_value_at_label = shap_vals[label]\n final_shap_values = torch.... | <|body_start_0|>
super().__init__(model)
self.data = shap.kmeans(data, 25)
self.explainer = shap.KernelExplainer(self.model, self.data, link=link)
<|end_body_0|>
<|body_start_1|>
shap_vals = self.explainer.shap_values(data_x[0], nsamples=10000, silent=True)
if len(shap_vals) > 1... | The SHAP explainer | SHAPExplainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SHAPExplainer:
"""The SHAP explainer"""
def __init__(self, model, data: torch.FloatTensor, link: str='identity'):
"""Init. Args: model: model object data: pandas data frame or numpy array link: str, 'identity' or 'logit'"""
<|body_0|>
def get_explanation(self, data_x: np... | stack_v2_sparse_classes_10k_train_006355 | 1,864 | permissive | [
{
"docstring": "Init. Args: model: model object data: pandas data frame or numpy array link: str, 'identity' or 'logit'",
"name": "__init__",
"signature": "def __init__(self, model, data: torch.FloatTensor, link: str='identity')"
},
{
"docstring": "Gets the SHAP explanation. Returns SHAP values ... | 2 | stack_v2_sparse_classes_30k_train_004154 | Implement the Python class `SHAPExplainer` described below.
Class description:
The SHAP explainer
Method signatures and docstrings:
- def __init__(self, model, data: torch.FloatTensor, link: str='identity'): Init. Args: model: model object data: pandas data frame or numpy array link: str, 'identity' or 'logit'
- def ... | Implement the Python class `SHAPExplainer` described below.
Class description:
The SHAP explainer
Method signatures and docstrings:
- def __init__(self, model, data: torch.FloatTensor, link: str='identity'): Init. Args: model: model object data: pandas data frame or numpy array link: str, 'identity' or 'logit'
- def ... | 73612ebb3e72f4f8172380bab8c7ba941e70224b | <|skeleton|>
class SHAPExplainer:
"""The SHAP explainer"""
def __init__(self, model, data: torch.FloatTensor, link: str='identity'):
"""Init. Args: model: model object data: pandas data frame or numpy array link: str, 'identity' or 'logit'"""
<|body_0|>
def get_explanation(self, data_x: np... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SHAPExplainer:
"""The SHAP explainer"""
def __init__(self, model, data: torch.FloatTensor, link: str='identity'):
"""Init. Args: model: model object data: pandas data frame or numpy array link: str, 'identity' or 'logit'"""
super().__init__(model)
self.data = shap.kmeans(data, 25)... | the_stack_v2_python_sparse | explain/mega_explainer/shap_explainer.py | dylan-slack/TalkToModel | train | 84 |
c63cb5ee6c88757f99046e35bea84a5373ecc517 | [
"described = descriptor.describe_file_set([])\ndescribed.check_initialized()\nself.assertEquals(descriptor.FileSet(), described)",
"modules = [types.ModuleType('package1'), types.ModuleType('package1')]\nfile1 = descriptor.FileDescriptor()\nfile1.package = 'package1'\nfile2 = descriptor.FileDescriptor()\nfile2.pa... | <|body_start_0|>
described = descriptor.describe_file_set([])
described.check_initialized()
self.assertEquals(descriptor.FileSet(), described)
<|end_body_0|>
<|body_start_1|>
modules = [types.ModuleType('package1'), types.ModuleType('package1')]
file1 = descriptor.FileDescriptor... | Test describing multiple modules. | DescribeFileSetTest | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DescribeFileSetTest:
"""Test describing multiple modules."""
def testNoModules(self):
"""Test what happens when no modules provided."""
<|body_0|>
def testWithModules(self):
"""Test what happens when no modules provided."""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_006356 | 17,140 | permissive | [
{
"docstring": "Test what happens when no modules provided.",
"name": "testNoModules",
"signature": "def testNoModules(self)"
},
{
"docstring": "Test what happens when no modules provided.",
"name": "testWithModules",
"signature": "def testWithModules(self)"
}
] | 2 | null | Implement the Python class `DescribeFileSetTest` described below.
Class description:
Test describing multiple modules.
Method signatures and docstrings:
- def testNoModules(self): Test what happens when no modules provided.
- def testWithModules(self): Test what happens when no modules provided. | Implement the Python class `DescribeFileSetTest` described below.
Class description:
Test describing multiple modules.
Method signatures and docstrings:
- def testNoModules(self): Test what happens when no modules provided.
- def testWithModules(self): Test what happens when no modules provided.
<|skeleton|>
class D... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class DescribeFileSetTest:
"""Test describing multiple modules."""
def testNoModules(self):
"""Test what happens when no modules provided."""
<|body_0|>
def testWithModules(self):
"""Test what happens when no modules provided."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DescribeFileSetTest:
"""Test describing multiple modules."""
def testNoModules(self):
"""Test what happens when no modules provided."""
described = descriptor.describe_file_set([])
described.check_initialized()
self.assertEquals(descriptor.FileSet(), described)
def te... | the_stack_v2_python_sparse | third_party/google-endpoints/apitools/base/protorpclite/descriptor_test.py | catapult-project/catapult | train | 2,032 |
ac24005b755682207502677094ec755f52ade4b6 | [
"self.find(By.ID, self._username).send_keys('维恩1')\nself.find(By.ID, 'memberAdd_acctid').send_keys('1112221')\nself.find(By.ID, 'memberAdd_phone').send_keys('13199991233')\nself.find(By.CSS_SELECTOR, '.js_btn_save').click()\nreturn Contact(self.driver)",
"self.find(By.ID, self._username).send_keys('维恩2')\nself.fi... | <|body_start_0|>
self.find(By.ID, self._username).send_keys('维恩1')
self.find(By.ID, 'memberAdd_acctid').send_keys('1112221')
self.find(By.ID, 'memberAdd_phone').send_keys('13199991233')
self.find(By.CSS_SELECTOR, '.js_btn_save').click()
return Contact(self.driver)
<|end_body_0|>
... | AddMember | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddMember:
def add_member(self):
"""添加成员 :return:"""
<|body_0|>
def add_member_fail(self):
"""添加成员 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.find(By.ID, self._username).send_keys('维恩1')
self.find(By.ID, 'memberAdd_acctid'... | stack_v2_sparse_classes_10k_train_006357 | 1,055 | no_license | [
{
"docstring": "添加成员 :return:",
"name": "add_member",
"signature": "def add_member(self)"
},
{
"docstring": "添加成员 :return:",
"name": "add_member_fail",
"signature": "def add_member_fail(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000617 | Implement the Python class `AddMember` described below.
Class description:
Implement the AddMember class.
Method signatures and docstrings:
- def add_member(self): 添加成员 :return:
- def add_member_fail(self): 添加成员 :return: | Implement the Python class `AddMember` described below.
Class description:
Implement the AddMember class.
Method signatures and docstrings:
- def add_member(self): 添加成员 :return:
- def add_member_fail(self): 添加成员 :return:
<|skeleton|>
class AddMember:
def add_member(self):
"""添加成员 :return:"""
<|b... | e388800d432cd1d23ca5765abc1780d6394e1dbb | <|skeleton|>
class AddMember:
def add_member(self):
"""添加成员 :return:"""
<|body_0|>
def add_member_fail(self):
"""添加成员 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AddMember:
def add_member(self):
"""添加成员 :return:"""
self.find(By.ID, self._username).send_keys('维恩1')
self.find(By.ID, 'memberAdd_acctid').send_keys('1112221')
self.find(By.ID, 'memberAdd_phone').send_keys('13199991233')
self.find(By.CSS_SELECTOR, '.js_btn_save').click... | the_stack_v2_python_sparse | test_selenium/test_wework/page/add_member_page.py | ceshiren/HogwartsLG2 | train | 2 | |
2cb7875bec75f1dd54b2829700a5befe6aa410d2 | [
"sentinel_sectPr = self.get_or_add_sectPr()\nself.add_p().set_sectPr(sentinel_sectPr.clone())\nfor hdrftr_ref in sentinel_sectPr.xpath('w:headerReference|w:footerReference'):\n sentinel_sectPr.remove(hdrftr_ref)\nreturn sentinel_sectPr",
"if self.sectPr is not None:\n content_elms = self[:-1]\nelse:\n co... | <|body_start_0|>
sentinel_sectPr = self.get_or_add_sectPr()
self.add_p().set_sectPr(sentinel_sectPr.clone())
for hdrftr_ref in sentinel_sectPr.xpath('w:headerReference|w:footerReference'):
sentinel_sectPr.remove(hdrftr_ref)
return sentinel_sectPr
<|end_body_0|>
<|body_start_... | ``<w:body>``, the container element for the main document story in ``document.xml``. | CT_Body | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CT_Body:
"""``<w:body>``, the container element for the main document story in ``document.xml``."""
def add_section_break(self):
"""Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an exa... | stack_v2_sparse_classes_10k_train_006358 | 2,543 | permissive | [
{
"docstring": "Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an exact clone of the previous one, except that all header and footer references are removed (and are therefore now \"inherited\" from the prior secti... | 2 | stack_v2_sparse_classes_30k_train_005959 | Implement the Python class `CT_Body` described below.
Class description:
``<w:body>``, the container element for the main document story in ``document.xml``.
Method signatures and docstrings:
- def add_section_break(self): Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes... | Implement the Python class `CT_Body` described below.
Class description:
``<w:body>``, the container element for the main document story in ``document.xml``.
Method signatures and docstrings:
- def add_section_break(self): Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes... | 2bfcf6b9779bf1abd41e1bc42c27007127ddbefb | <|skeleton|>
class CT_Body:
"""``<w:body>``, the container element for the main document story in ``document.xml``."""
def add_section_break(self):
"""Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an exa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CT_Body:
"""``<w:body>``, the container element for the main document story in ``document.xml``."""
def add_section_break(self):
"""Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an exact clone of t... | the_stack_v2_python_sparse | anuvaad-etl/anuvaad-extractor/file_translator/etl-file-translator/docx/oxml/document.py | project-anuvaad/anuvaad | train | 41 |
26f763a7bd1b31dc5c83e3398c8ba2c586b7503c | [
"if not self.instance.pk:\n return True\nelif field in self.saved_data:\n return self.previous(field) != self.get_field_value(field)\nelse:\n raise FieldError('field \"%s\" not tracked' % field)",
"if not self.instance.pk:\n return {}\nsaved = self.saved_data.items()\ncurrent = self.current()\nreturn ... | <|body_start_0|>
if not self.instance.pk:
return True
elif field in self.saved_data:
return self.previous(field) != self.get_field_value(field)
else:
raise FieldError('field "%s" not tracked' % field)
<|end_body_0|>
<|body_start_1|>
if not self.instan... | ModelInstanceTracker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelInstanceTracker:
def has_changed(self, field):
"""Returns ``True`` if field has changed from currently saved value"""
<|body_0|>
def changed(self):
"""Returns dict of fields that changed since save (with old values)"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_10k_train_006359 | 7,971 | permissive | [
{
"docstring": "Returns ``True`` if field has changed from currently saved value",
"name": "has_changed",
"signature": "def has_changed(self, field)"
},
{
"docstring": "Returns dict of fields that changed since save (with old values)",
"name": "changed",
"signature": "def changed(self)"
... | 2 | null | Implement the Python class `ModelInstanceTracker` described below.
Class description:
Implement the ModelInstanceTracker class.
Method signatures and docstrings:
- def has_changed(self, field): Returns ``True`` if field has changed from currently saved value
- def changed(self): Returns dict of fields that changed si... | Implement the Python class `ModelInstanceTracker` described below.
Class description:
Implement the ModelInstanceTracker class.
Method signatures and docstrings:
- def has_changed(self, field): Returns ``True`` if field has changed from currently saved value
- def changed(self): Returns dict of fields that changed si... | ce2558602ddad31873d7129f25b1cc61895b9939 | <|skeleton|>
class ModelInstanceTracker:
def has_changed(self, field):
"""Returns ``True`` if field has changed from currently saved value"""
<|body_0|>
def changed(self):
"""Returns dict of fields that changed since save (with old values)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModelInstanceTracker:
def has_changed(self, field):
"""Returns ``True`` if field has changed from currently saved value"""
if not self.instance.pk:
return True
elif field in self.saved_data:
return self.previous(field) != self.get_field_value(field)
else... | the_stack_v2_python_sparse | myenv/lib/python3.5/site-packages/model_utils/tracker.py | rupeshparab/techscan | train | 1 | |
98a152319ddf2012901b851aee47a25d3c768f74 | [
"for i in range(rowIndex + 1):\n row = [1] * (i + 1)\n if i >= 2:\n for j in range(1, i):\n row[j] = tmp[j - 1] + tmp[j]\n tmp = row\nreturn tmp",
"row = [1] * (rowIndex + 1)\nif rowIndex >= 1:\n for i in range(1, rowIndex + 1):\n row[i] = row[i - 1] * (rowIndex + 1 - i) // i\... | <|body_start_0|>
for i in range(rowIndex + 1):
row = [1] * (i + 1)
if i >= 2:
for j in range(1, i):
row[j] = tmp[j - 1] + tmp[j]
tmp = row
return tmp
<|end_body_0|>
<|body_start_1|>
row = [1] * (rowIndex + 1)
if row... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_0|>
def getRow1(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in range(rowIndex + 1):
... | stack_v2_sparse_classes_10k_train_006360 | 672 | no_license | [
{
"docstring": ":type rowIndex: int :rtype: List[int]",
"name": "getRow",
"signature": "def getRow(self, rowIndex)"
},
{
"docstring": ":type rowIndex: int :rtype: List[int]",
"name": "getRow1",
"signature": "def getRow1(self, rowIndex)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007250 | 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 getRow1(self, rowIndex): :type rowIndex: int :rtype: List[int] | 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 getRow1(self, rowIndex): :type rowIndex: int :rtype: List[int]
<|skeleton|>
class Solution:
def getR... | b8ec1350e904665f1375c29a53f443ecf262d723 | <|skeleton|>
class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_0|>
def getRow1(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
for i in range(rowIndex + 1):
row = [1] * (i + 1)
if i >= 2:
for j in range(1, i):
row[j] = tmp[j - 1] + tmp[j]
tmp = row
return tmp... | the_stack_v2_python_sparse | leetcode/119杨辉三角II.py | ShawDa/Coding | train | 0 | |
00f37553afdeba66f893aa2794837c277f3902a8 | [
"if isinstance(config, DictConfig):\n config = OmegaConf.to_container(config, resolve=True)\n config = OmegaConf.create(config)\nif '_target_' in config:\n instance = hydra.utils.instantiate(config=config, **kwargs)\nelse:\n try:\n instance = cls(cfg=config, **kwargs)\n except:\n cfg = ... | <|body_start_0|>
if isinstance(config, DictConfig):
config = OmegaConf.to_container(config, resolve=True)
config = OmegaConf.create(config)
if '_target_' in config:
instance = hydra.utils.instantiate(config=config, **kwargs)
else:
try:
... | Helper Class to instantiate obj from config | Configurable | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configurable:
"""Helper Class to instantiate obj from config"""
def from_config_dict(cls, config: DictConfig, **kwargs):
"""Instantiates object using `DictConfig-based` configuration. You can optionally pass in extra `kwargs`"""
<|body_0|>
def to_config_dict(self) -> Dic... | stack_v2_sparse_classes_10k_train_006361 | 20,081 | permissive | [
{
"docstring": "Instantiates object using `DictConfig-based` configuration. You can optionally pass in extra `kwargs`",
"name": "from_config_dict",
"signature": "def from_config_dict(cls, config: DictConfig, **kwargs)"
},
{
"docstring": "Returns object's configuration to config dictionary",
... | 2 | stack_v2_sparse_classes_30k_train_007249 | Implement the Python class `Configurable` described below.
Class description:
Helper Class to instantiate obj from config
Method signatures and docstrings:
- def from_config_dict(cls, config: DictConfig, **kwargs): Instantiates object using `DictConfig-based` configuration. You can optionally pass in extra `kwargs`
-... | Implement the Python class `Configurable` described below.
Class description:
Helper Class to instantiate obj from config
Method signatures and docstrings:
- def from_config_dict(cls, config: DictConfig, **kwargs): Instantiates object using `DictConfig-based` configuration. You can optionally pass in extra `kwargs`
-... | 1da107e1dcf1f20d6da4ac3f126e22d409a7f92e | <|skeleton|>
class Configurable:
"""Helper Class to instantiate obj from config"""
def from_config_dict(cls, config: DictConfig, **kwargs):
"""Instantiates object using `DictConfig-based` configuration. You can optionally pass in extra `kwargs`"""
<|body_0|>
def to_config_dict(self) -> Dic... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Configurable:
"""Helper Class to instantiate obj from config"""
def from_config_dict(cls, config: DictConfig, **kwargs):
"""Instantiates object using `DictConfig-based` configuration. You can optionally pass in extra `kwargs`"""
if isinstance(config, DictConfig):
config = Omeg... | the_stack_v2_python_sparse | gale/core_classes.py | benihime91/gale | train | 5 |
afbc1ccabfb95936f9168a77bde4b0c32a1b2ce1 | [
"n = self.L = 0 if not matrix else len(matrix[0])\nm = len(matrix)\ntrees = self.trees = []\nfor i in xrange(m):\n tree = [0] * n + matrix[i]\n for i in xrange(n - 1, 0, -1):\n tree[i] = tree[i << 1] + tree[i << 1 | 1]\n trees += (tree,)",
"col += self.L\ntree = self.trees[row]\ntree[col] = val\nw... | <|body_start_0|>
n = self.L = 0 if not matrix else len(matrix[0])
m = len(matrix)
trees = self.trees = []
for i in xrange(m):
tree = [0] * n + matrix[i]
for i in xrange(n - 1, 0, -1):
tree[i] = tree[i << 1] + tree[i << 1 | 1]
trees += (... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]] n dimensional segment tree"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: None"""
<|body_1|>
def sumRegion(self, row1, col1, r... | stack_v2_sparse_classes_10k_train_006362 | 1,548 | no_license | [
{
"docstring": ":type matrix: List[List[int]] n dimensional segment tree",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row: int :type col: int :type val: int :rtype: None",
"name": "update",
"signature": "def update(self, row, col, val)"
},
... | 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]] n dimensional segment tree
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: Non... | 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]] n dimensional segment tree
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: Non... | edff905f63ab95cdd40447b27a9c449c9cefec37 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]] n dimensional segment tree"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: None"""
<|body_1|>
def sumRegion(self, row1, col1, r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]] n dimensional segment tree"""
n = self.L = 0 if not matrix else len(matrix[0])
m = len(matrix)
trees = self.trees = []
for i in xrange(m):
tree = [0] * n + matrix[i]
for i in... | the_stack_v2_python_sparse | _0308_Range_Sum_Query_2D_Mutable.py | mingweihe/leetcode | train | 3 | |
9a4c00d619d82d844d635139998715ae767075af | [
"self.grid_size_z = grid_size_z\nself.grid_size_y = grid_size_y\nself.grid_size_x = grid_size_x\nself.x_range = x_range\nself.y_range = x_range * (grid_size_y / grid_size_x)\nself.z_range = x_range * (grid_size_z / grid_size_x)\nself.dx = real_t(x_range / grid_size_x)\nself.num_threads = num_threads\nself.real_t = ... | <|body_start_0|>
self.grid_size_z = grid_size_z
self.grid_size_y = grid_size_y
self.grid_size_x = grid_size_x
self.x_range = x_range
self.y_range = x_range * (grid_size_y / grid_size_x)
self.z_range = x_range * (grid_size_z / grid_size_x)
self.dx = real_t(x_range ... | Class for solving unbounded Poisson in 3D via PyFFTW. | UnboundedPoissonSolverPYFFTW3D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnboundedPoissonSolverPYFFTW3D:
"""Class for solving unbounded Poisson in 3D via PyFFTW."""
def __init__(self, grid_size_z: int, grid_size_y: int, grid_size_x: int, x_range: float=1.0, num_threads: int=1, real_t: type=np.float64) -> None:
"""Class initialiser."""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_006363 | 6,969 | permissive | [
{
"docstring": "Class initialiser.",
"name": "__init__",
"signature": "def __init__(self, grid_size_z: int, grid_size_y: int, grid_size_x: int, x_range: float=1.0, num_threads: int=1, real_t: type=np.float64) -> None"
},
{
"docstring": "Construct the unbounded Greens function.",
"name": "_co... | 5 | stack_v2_sparse_classes_30k_train_006682 | Implement the Python class `UnboundedPoissonSolverPYFFTW3D` described below.
Class description:
Class for solving unbounded Poisson in 3D via PyFFTW.
Method signatures and docstrings:
- def __init__(self, grid_size_z: int, grid_size_y: int, grid_size_x: int, x_range: float=1.0, num_threads: int=1, real_t: type=np.flo... | Implement the Python class `UnboundedPoissonSolverPYFFTW3D` described below.
Class description:
Class for solving unbounded Poisson in 3D via PyFFTW.
Method signatures and docstrings:
- def __init__(self, grid_size_z: int, grid_size_y: int, grid_size_x: int, x_range: float=1.0, num_threads: int=1, real_t: type=np.flo... | 99a094e0d6e635e5b2385a69bdee239a4d1fb530 | <|skeleton|>
class UnboundedPoissonSolverPYFFTW3D:
"""Class for solving unbounded Poisson in 3D via PyFFTW."""
def __init__(self, grid_size_z: int, grid_size_y: int, grid_size_x: int, x_range: float=1.0, num_threads: int=1, real_t: type=np.float64) -> None:
"""Class initialiser."""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UnboundedPoissonSolverPYFFTW3D:
"""Class for solving unbounded Poisson in 3D via PyFFTW."""
def __init__(self, grid_size_z: int, grid_size_y: int, grid_size_x: int, x_range: float=1.0, num_threads: int=1, real_t: type=np.float64) -> None:
"""Class initialiser."""
self.grid_size_z = grid_s... | the_stack_v2_python_sparse | sopht/numeric/eulerian_grid_ops/poisson_solver_3d/UnboundedPoissonSolverPYFFTW3D.py | SophT-Team/SophT | train | 2 |
282f6d79c6959d08d6fd5239d8e89c988928b494 | [
"assert not self._initialized\npygame.init()\nself._initialized = True\nlogging.info('Initialized pygame')",
"pygame.quit()\nself._initialized = False\nlogging.info('Shut down pygame')"
] | <|body_start_0|>
assert not self._initialized
pygame.init()
self._initialized = True
logging.info('Initialized pygame')
<|end_body_0|>
<|body_start_1|>
pygame.quit()
self._initialized = False
logging.info('Shut down pygame')
<|end_body_1|>
| Initializes/shuts down pygame when constructed/destroyed Only one instance can be active at a time. | _pygameInstance | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _pygameInstance:
"""Initializes/shuts down pygame when constructed/destroyed Only one instance can be active at a time."""
def __init__(self):
"""Initialize pygame."""
<|body_0|>
def __del__(self):
"""Shut down pygame."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_10k_train_006364 | 3,054 | permissive | [
{
"docstring": "Initialize pygame.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Shut down pygame.",
"name": "__del__",
"signature": "def __del__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004412 | Implement the Python class `_pygameInstance` described below.
Class description:
Initializes/shuts down pygame when constructed/destroyed Only one instance can be active at a time.
Method signatures and docstrings:
- def __init__(self): Initialize pygame.
- def __del__(self): Shut down pygame. | Implement the Python class `_pygameInstance` described below.
Class description:
Initializes/shuts down pygame when constructed/destroyed Only one instance can be active at a time.
Method signatures and docstrings:
- def __init__(self): Initialize pygame.
- def __del__(self): Shut down pygame.
<|skeleton|>
class _py... | c7a147037b806058d18d9a200ffa4a14f3402d04 | <|skeleton|>
class _pygameInstance:
"""Initializes/shuts down pygame when constructed/destroyed Only one instance can be active at a time."""
def __init__(self):
"""Initialize pygame."""
<|body_0|>
def __del__(self):
"""Shut down pygame."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _pygameInstance:
"""Initializes/shuts down pygame when constructed/destroyed Only one instance can be active at a time."""
def __init__(self):
"""Initialize pygame."""
assert not self._initialized
pygame.init()
self._initialized = True
logging.info('Initialized pyg... | the_stack_v2_python_sparse | platform/pygame/event.py | gregr/old-and-miscellaneous | train | 2 |
3070ecbfb3bbaf03d8c0c35bfab713000f6f806d | [
"def heapify(nums, root, n):\n left = 2 * root + 1\n right = 2 * root + 2\n if left < n and nums[root] < nums[left]:\n largest = left\n else:\n largest = root\n if right < n and nums[largest] < nums[right]:\n largest = right\n if root != largest:\n nums[root], nums[larg... | <|body_start_0|>
def heapify(nums, root, n):
left = 2 * root + 1
right = 2 * root + 2
if left < n and nums[root] < nums[left]:
largest = left
else:
largest = root
if right < n and nums[largest] < nums[right]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def quicksortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead... | stack_v2_sparse_classes_10k_train_006365 | 4,451 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.",
"name": "qu... | 5 | stack_v2_sparse_classes_30k_val_000027 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
- def quicksortColors(self, nums): :type nums: List[int] :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
- def quicksortColors(self, nums): :type nums: List[int] :rty... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def quicksortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
def heapify(nums, root, n):
left = 2 * root + 1
right = 2 * root + 2
if left < n and nums[root] < nums[left]:
... | the_stack_v2_python_sparse | python/75.sort-colors.py | tainenko/Leetcode2019 | train | 5 | |
03cc23d3f602c96853711e63e49e476ef3adf910 | [
"if rec1[0] <= rec2[0] < rec2[2] <= rec1[2] and rec1[1] <= rec2[1] < rec2[3] <= rec1[3] or (rec2[0] <= rec1[0] < rec1[2] <= rec2[2] and rec2[1] <= rec1[1] < rec1[3] <= rec2[3]) or (rec2[0] <= rec1[0] <= rec2[2] and rec2[1] <= rec1[3] <= rec2[3]) or (rec1[0] <= rec2[0] <= rec1[2] and rec1[1] <= rec2[3] <= rec1[3]) o... | <|body_start_0|>
if rec1[0] <= rec2[0] < rec2[2] <= rec1[2] and rec1[1] <= rec2[1] < rec2[3] <= rec1[3] or (rec2[0] <= rec1[0] < rec1[2] <= rec2[2] and rec2[1] <= rec1[1] < rec1[3] <= rec2[3]) or (rec2[0] <= rec1[0] <= rec2[2] and rec2[1] <= rec1[3] <= rec2[3]) or (rec1[0] <= rec2[0] <= rec1[2] and rec1[1] <= r... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _isRectangleOverlap(self, rec1, rec2):
""":type rec1: List[int] :type rec2: List[int] :rtype: bool"""
<|body_0|>
def __isRectangleOverlap(self, rec1, rec2):
""":type rec1: List[int] :type rec2: List[int] :rtype: bool"""
<|body_1|>
def isRec... | stack_v2_sparse_classes_10k_train_006366 | 3,178 | permissive | [
{
"docstring": ":type rec1: List[int] :type rec2: List[int] :rtype: bool",
"name": "_isRectangleOverlap",
"signature": "def _isRectangleOverlap(self, rec1, rec2)"
},
{
"docstring": ":type rec1: List[int] :type rec2: List[int] :rtype: bool",
"name": "__isRectangleOverlap",
"signature": "d... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _isRectangleOverlap(self, rec1, rec2): :type rec1: List[int] :type rec2: List[int] :rtype: bool
- def __isRectangleOverlap(self, rec1, rec2): :type rec1: List[int] :type rec2... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _isRectangleOverlap(self, rec1, rec2): :type rec1: List[int] :type rec2: List[int] :rtype: bool
- def __isRectangleOverlap(self, rec1, rec2): :type rec1: List[int] :type rec2... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _isRectangleOverlap(self, rec1, rec2):
""":type rec1: List[int] :type rec2: List[int] :rtype: bool"""
<|body_0|>
def __isRectangleOverlap(self, rec1, rec2):
""":type rec1: List[int] :type rec2: List[int] :rtype: bool"""
<|body_1|>
def isRec... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def _isRectangleOverlap(self, rec1, rec2):
""":type rec1: List[int] :type rec2: List[int] :rtype: bool"""
if rec1[0] <= rec2[0] < rec2[2] <= rec1[2] and rec1[1] <= rec2[1] < rec2[3] <= rec1[3] or (rec2[0] <= rec1[0] < rec1[2] <= rec2[2] and rec2[1] <= rec1[1] < rec1[3] <= rec2[3]) or... | the_stack_v2_python_sparse | 836.rectangle-overlap.py | windard/leeeeee | train | 0 | |
e088a3e8bba98315e09e0a13a25074ca6c3c1d32 | [
"if n < 1 or n > 7:\n raise ValueError('Not a valid period. Must be 1-7')\nreturn np.array([elem for elem in cls.table[n - 1, :] if elem != ''])",
"if n < 1 or n > 18:\n raise ValueError('Not a valid group. Must be 1-18')\nreturn np.array([elem for elem in cls.table[:, n - 1] if elem != ''])",
"try:\n ... | <|body_start_0|>
if n < 1 or n > 7:
raise ValueError('Not a valid period. Must be 1-7')
return np.array([elem for elem in cls.table[n - 1, :] if elem != ''])
<|end_body_0|>
<|body_start_1|>
if n < 1 or n > 18:
raise ValueError('Not a valid group. Must be 1-18')
r... | PeriodicTable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeriodicTable:
def period(cls, n: int):
"""Period of the periodic table, with 1 being the first period Arguments: n (int): Returns: (np.ndarray(str)): Raises: (ValueError): If n is not valid period index"""
<|body_0|>
def group(cls, n: int):
"""Group of the periodic ... | stack_v2_sparse_classes_10k_train_006367 | 35,279 | permissive | [
{
"docstring": "Period of the periodic table, with 1 being the first period Arguments: n (int): Returns: (np.ndarray(str)): Raises: (ValueError): If n is not valid period index",
"name": "period",
"signature": "def period(cls, n: int)"
},
{
"docstring": "Group of the periodic table, with 1 being... | 4 | stack_v2_sparse_classes_30k_test_000001 | Implement the Python class `PeriodicTable` described below.
Class description:
Implement the PeriodicTable class.
Method signatures and docstrings:
- def period(cls, n: int): Period of the periodic table, with 1 being the first period Arguments: n (int): Returns: (np.ndarray(str)): Raises: (ValueError): If n is not v... | Implement the Python class `PeriodicTable` described below.
Class description:
Implement the PeriodicTable class.
Method signatures and docstrings:
- def period(cls, n: int): Period of the periodic table, with 1 being the first period Arguments: n (int): Returns: (np.ndarray(str)): Raises: (ValueError): If n is not v... | 6505d5bbbd1906f57e4102e13f177510f166bbed | <|skeleton|>
class PeriodicTable:
def period(cls, n: int):
"""Period of the periodic table, with 1 being the first period Arguments: n (int): Returns: (np.ndarray(str)): Raises: (ValueError): If n is not valid period index"""
<|body_0|>
def group(cls, n: int):
"""Group of the periodic ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PeriodicTable:
def period(cls, n: int):
"""Period of the periodic table, with 1 being the first period Arguments: n (int): Returns: (np.ndarray(str)): Raises: (ValueError): If n is not valid period index"""
if n < 1 or n > 7:
raise ValueError('Not a valid period. Must be 1-7')
... | the_stack_v2_python_sparse | autode/atoms.py | jdelev/autodE | train | 0 | |
e7ea4bd120e44b424738867167b890c97349557a | [
"super(Trainer, self).__init__(model, optimizer, resume, config, helios_run, experiment_folder)\nself.config = config\nsplit = config['data']['dataloader'].get('split', 0.9)\nsplitter = SplitDataset(split)\ntrain_set, valid_set = splitter(unlabelled)\ntrain_loader = DataLoader(dataset=train_set, **config['data']['d... | <|body_start_0|>
super(Trainer, self).__init__(model, optimizer, resume, config, helios_run, experiment_folder)
self.config = config
split = config['data']['dataloader'].get('split', 0.9)
splitter = SplitDataset(split)
train_set, valid_set = splitter(unlabelled)
train_loa... | Trainer class Note: Inherited from BaseTrainer. | Trainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trainer:
"""Trainer class Note: Inherited from BaseTrainer."""
def __init__(self, model, optimizer, resume, config, unlabelled, helios_run, experiment_folder=None, **kwargs):
"""Initialize the trainer. :param model: model to train. :param optimizer: optimizer to use for training. :pa... | stack_v2_sparse_classes_10k_train_006368 | 5,895 | no_license | [
{
"docstring": "Initialize the trainer. :param model: model to train. :param optimizer: optimizer to use for training. :param resume: path to a checkpoint to resume training. :param config: dictionary containing the configuration. :param unlabelled: unlabelled dataset to use for training the AE. :param helios_r... | 3 | stack_v2_sparse_classes_30k_train_004969 | Implement the Python class `Trainer` described below.
Class description:
Trainer class Note: Inherited from BaseTrainer.
Method signatures and docstrings:
- def __init__(self, model, optimizer, resume, config, unlabelled, helios_run, experiment_folder=None, **kwargs): Initialize the trainer. :param model: model to tr... | Implement the Python class `Trainer` described below.
Class description:
Trainer class Note: Inherited from BaseTrainer.
Method signatures and docstrings:
- def __init__(self, model, optimizer, resume, config, unlabelled, helios_run, experiment_folder=None, **kwargs): Initialize the trainer. :param model: model to tr... | 7979099152f6d509bac4aa0dab1660988b6388ac | <|skeleton|>
class Trainer:
"""Trainer class Note: Inherited from BaseTrainer."""
def __init__(self, model, optimizer, resume, config, unlabelled, helios_run, experiment_folder=None, **kwargs):
"""Initialize the trainer. :param model: model to train. :param optimizer: optimizer to use for training. :pa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Trainer:
"""Trainer class Note: Inherited from BaseTrainer."""
def __init__(self, model, optimizer, resume, config, unlabelled, helios_run, experiment_folder=None, **kwargs):
"""Initialize the trainer. :param model: model to train. :param optimizer: optimizer to use for training. :param resume: p... | the_stack_v2_python_sparse | trainer/trainer.py | josephdviviano/horoma | train | 1 |
ea9741d0003975c6d8a0b075fd2247a8476b1936 | [
"self.rects = rects\ncurSize = 0\nself.preSize = []\nfor rect in rects:\n curSize += (rect[2] - rect[0]) * (rect[3] - rect[1])\n self.preSize.append(curSize)\nself.totalSize = curSize",
"randWeight = random.randint(1, self.totalSize)\nstart = 0\nend = len(self.preSize) - 1\nidx = None\nwhile start < end:\n ... | <|body_start_0|>
self.rects = rects
curSize = 0
self.preSize = []
for rect in rects:
curSize += (rect[2] - rect[0]) * (rect[3] - rect[1])
self.preSize.append(curSize)
self.totalSize = curSize
<|end_body_0|>
<|body_start_1|>
randWeight = random.ran... | 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.rects = rects
curSize = 0
self.preSize = []
for rect... | stack_v2_sparse_classes_10k_train_006369 | 2,383 | 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_val_000206 | 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: ... | fd310ec0a989e003242f1840230aaac150f006f0 | <|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_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.rects = rects
curSize = 0
self.preSize = []
for rect in rects:
curSize += (rect[2] - rect[0]) * (rect[3] - rect[1])
self.preSize.append(curSize)
self.totalSize =... | the_stack_v2_python_sparse | 好咧,最后还是要搞google/medium/RandomPointinNonoverlappingRectangles497_WRONG.py | jing1988a/python_fb | train | 0 | |
ac1c3aa9e64d4773e93327f3808d8d8b03cb45b5 | [
"self.pi_means = means\nself.pi_variances = variances\nself.relative_weight = relative_weight\nself.weight = weight\nself.rev_KL = MFN_MFN_reverse_KLD(means, variances)\nself.KL = MFN_MFN_KLD(means, variances)",
"revKL = self.rev_KL(q_params, q_parser, converter)\nKL = self.KL(q_params, q_parser, converter)\nretu... | <|body_start_0|>
self.pi_means = means
self.pi_variances = variances
self.relative_weight = relative_weight
self.weight = weight
self.rev_KL = MFN_MFN_reverse_KLD(means, variances)
self.KL = MFN_MFN_KLD(means, variances)
<|end_body_0|>
<|body_start_1|>
revKL = se... | Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) relative_weight relative_weight * KLD(q||pi) + (1-relw) * KLD(pi||q) | MFN_MFN_JeffreysD | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MFN_MFN_JeffreysD:
"""Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) relative_weight relative_weight... | stack_v2_sparse_classes_10k_train_006370 | 14,750 | no_license | [
{
"docstring": "MFN for prior specified by vector of means & variances",
"name": "__init__",
"signature": "def __init__(self, means, variances, relative_weight=0.5, weight=1.0)"
},
{
"docstring": "Compute relative_weight * KLD(q||pi) + (1-relw) * KLD(pi||q)",
"name": "prior_retularizer",
... | 2 | stack_v2_sparse_classes_30k_train_001439 | Implement the Python class `MFN_MFN_JeffreysD` described below.
Class description:
Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each va... | Implement the Python class `MFN_MFN_JeffreysD` described below.
Class description:
Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each va... | 6e51c10227ca8300853f2341906503d072cc0685 | <|skeleton|>
class MFN_MFN_JeffreysD:
"""Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) relative_weight relative_weight... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MFN_MFN_JeffreysD:
"""Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) relative_weight relative_weight * KLD(q||pi)... | the_stack_v2_python_sparse | Divergence.py | JeremiasKnoblauch/GVI_consistency | train | 0 |
f18d06d8b9e9880a1789c2a424bcf440d6728b61 | [
"self.affix_canonical_form = affix_canonical_form\nself.pos_types = pos_types\nself.rules = rules",
"if pos not in self.pos_types:\n return None\nfor rule in self.rules:\n base = rule.get_base_form(lower)\n if base is not None:\n return base\nreturn None"
] | <|body_start_0|>
self.affix_canonical_form = affix_canonical_form
self.pos_types = pos_types
self.rules = rules
<|end_body_0|>
<|body_start_1|>
if pos not in self.pos_types:
return None
for rule in self.rules:
base = rule.get_base_form(lower)
... | SuffixGroup | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuffixGroup:
def __init__(self, affix_canonical_form: str, pos_types: str, rules: Sequence[SuffixRule]):
""":param affix_canonical_form: :param pos_types: a string of pos types separated by '|' :param rules:"""
<|body_0|>
def get_base_form(self, lower: str, pos: str):
... | stack_v2_sparse_classes_10k_train_006371 | 1,754 | permissive | [
{
"docstring": ":param affix_canonical_form: :param pos_types: a string of pos types separated by '|' :param rules:",
"name": "__init__",
"signature": "def __init__(self, affix_canonical_form: str, pos_types: str, rules: Sequence[SuffixRule])"
},
{
"docstring": "If pos_types contains the input p... | 2 | stack_v2_sparse_classes_30k_train_000891 | Implement the Python class `SuffixGroup` described below.
Class description:
Implement the SuffixGroup class.
Method signatures and docstrings:
- def __init__(self, affix_canonical_form: str, pos_types: str, rules: Sequence[SuffixRule]): :param affix_canonical_form: :param pos_types: a string of pos types separated b... | Implement the Python class `SuffixGroup` described below.
Class description:
Implement the SuffixGroup class.
Method signatures and docstrings:
- def __init__(self, affix_canonical_form: str, pos_types: str, rules: Sequence[SuffixRule]): :param affix_canonical_form: :param pos_types: a string of pos types separated b... | 78c00ec098d7626fd29ca49a9aef28950fabfed9 | <|skeleton|>
class SuffixGroup:
def __init__(self, affix_canonical_form: str, pos_types: str, rules: Sequence[SuffixRule]):
""":param affix_canonical_form: :param pos_types: a string of pos types separated by '|' :param rules:"""
<|body_0|>
def get_base_form(self, lower: str, pos: str):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SuffixGroup:
def __init__(self, affix_canonical_form: str, pos_types: str, rules: Sequence[SuffixRule]):
""":param affix_canonical_form: :param pos_types: a string of pos types separated by '|' :param rules:"""
self.affix_canonical_form = affix_canonical_form
self.pos_types = pos_types... | the_stack_v2_python_sparse | elit/component/lemmatization/english/suffix_group.py | elitcloud/elit | train | 38 | |
f4e97a3530d6646bd1d2cffb5af78109dcc98901 | [
"super().__init__(input_format=Text)\nself.filebase = filebase\nself.flush = flush\nself.time_format = time_format\nself.date_format = date_format\nself.current_date = None\nself.current_filename = None\nself.writer = None",
"if record is None:\n return\ntry:\n time_str = record.split()[0]\n ts = timesta... | <|body_start_0|>
super().__init__(input_format=Text)
self.filebase = filebase
self.flush = flush
self.time_format = time_format
self.date_format = date_format
self.current_date = None
self.current_filename = None
self.writer = None
<|end_body_0|>
<|body_s... | Write to the specified file. If filename is empty, write to stdout. | LogfileWriter | [
"MIT",
"CC-BY-NC-4.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogfileWriter:
"""Write to the specified file. If filename is empty, write to stdout."""
def __init__(self, filebase=None, flush=True, time_format=timestamp.TIME_FORMAT, date_format=timestamp.DATE_FORMAT):
"""Write timestamped text records to file. Base filename will have date append... | stack_v2_sparse_classes_10k_train_006372 | 2,568 | permissive | [
{
"docstring": "Write timestamped text records to file. Base filename will have date appended, in keeping with R2R format recommendations (http://www.rvdata.us/operators/directory). When timestamped date on records rolls over to next day, create new file with new date suffix. ``` filebase Base name of file to w... | 2 | stack_v2_sparse_classes_30k_train_004519 | Implement the Python class `LogfileWriter` described below.
Class description:
Write to the specified file. If filename is empty, write to stdout.
Method signatures and docstrings:
- def __init__(self, filebase=None, flush=True, time_format=timestamp.TIME_FORMAT, date_format=timestamp.DATE_FORMAT): Write timestamped ... | Implement the Python class `LogfileWriter` described below.
Class description:
Write to the specified file. If filename is empty, write to stdout.
Method signatures and docstrings:
- def __init__(self, filebase=None, flush=True, time_format=timestamp.TIME_FORMAT, date_format=timestamp.DATE_FORMAT): Write timestamped ... | ba77d3958075abd21ff94a396e4a97879962ac0c | <|skeleton|>
class LogfileWriter:
"""Write to the specified file. If filename is empty, write to stdout."""
def __init__(self, filebase=None, flush=True, time_format=timestamp.TIME_FORMAT, date_format=timestamp.DATE_FORMAT):
"""Write timestamped text records to file. Base filename will have date append... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LogfileWriter:
"""Write to the specified file. If filename is empty, write to stdout."""
def __init__(self, filebase=None, flush=True, time_format=timestamp.TIME_FORMAT, date_format=timestamp.DATE_FORMAT):
"""Write timestamped text records to file. Base filename will have date appended, in keepin... | the_stack_v2_python_sparse | logger/writers/logfile_writer.py | timburbank/openrvdas | train | 0 |
cf220edcc0b38784d639e8c22fc16fae5eb008b0 | [
"errors = {}\nuser = attrs['user']\nnew_email = attrs['new_email']\npassword = attrs.pop('password')\nif user.email == new_email:\n errors['email'] = 'Provided email address is same as your current one'\nelif User.objects.filter(email=new_email).exists():\n errors['email'] = 'Invalid email address'\nif errors... | <|body_start_0|>
errors = {}
user = attrs['user']
new_email = attrs['new_email']
password = attrs.pop('password')
if user.email == new_email:
errors['email'] = 'Provided email address is same as your current one'
elif User.objects.filter(email=new_email).exist... | Serializer for starting a user email change | ChangeEmailRequestCreateSerializer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeEmailRequestCreateSerializer:
"""Serializer for starting a user email change"""
def validate(self, attrs):
"""Validate the change request"""
<|body_0|>
def create(self, validated_data):
"""Create the email change request"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_10k_train_006373 | 16,669 | permissive | [
{
"docstring": "Validate the change request",
"name": "validate",
"signature": "def validate(self, attrs)"
},
{
"docstring": "Create the email change request",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003989 | Implement the Python class `ChangeEmailRequestCreateSerializer` described below.
Class description:
Serializer for starting a user email change
Method signatures and docstrings:
- def validate(self, attrs): Validate the change request
- def create(self, validated_data): Create the email change request | Implement the Python class `ChangeEmailRequestCreateSerializer` described below.
Class description:
Serializer for starting a user email change
Method signatures and docstrings:
- def validate(self, attrs): Validate the change request
- def create(self, validated_data): Create the email change request
<|skeleton|>
c... | c5d9cda4e1ed87463da74d7956f1e1f9258f365c | <|skeleton|>
class ChangeEmailRequestCreateSerializer:
"""Serializer for starting a user email change"""
def validate(self, attrs):
"""Validate the change request"""
<|body_0|>
def create(self, validated_data):
"""Create the email change request"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChangeEmailRequestCreateSerializer:
"""Serializer for starting a user email change"""
def validate(self, attrs):
"""Validate the change request"""
errors = {}
user = attrs['user']
new_email = attrs['new_email']
password = attrs.pop('password')
if user.email... | the_stack_v2_python_sparse | users/serializers.py | mitodl/mitxpro | train | 12 |
9e87621a742cc27090abe201cb9d9ce1d4ee1b53 | [
"li = values[0].strip().split()\nif len(li) == 1:\n li.append('')\nbefore, after = (li[0], li[1])\nsim1 = self.similiarity(key, before)\nsim2 = self.similiarity(key, after)\nif sim1 >= sim2:\n self.outputcollector.collect(key, before)\nelse:\n self.outputcollector.collect(key, after)",
"n = min(len(name1... | <|body_start_0|>
li = values[0].strip().split()
if len(li) == 1:
li.append('')
before, after = (li[0], li[1])
sim1 = self.similiarity(key, before)
sim2 = self.similiarity(key, after)
if sim1 >= sim2:
self.outputcollector.collect(key, before)
... | find the most simliar name for the given name, from the name before and after it e.g. (Adam, Ada Adams) -> (Adam, Ada) | Name2SimiliarName | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Name2SimiliarName:
"""find the most simliar name for the given name, from the name before and after it e.g. (Adam, Ada Adams) -> (Adam, Ada)"""
def reduce(self, key, values):
"""find the most simliar name for the given name @param key: the given name @param values: the name before an... | stack_v2_sparse_classes_10k_train_006374 | 1,271 | permissive | [
{
"docstring": "find the most simliar name for the given name @param key: the given name @param values: the name before and after the given name",
"name": "reduce",
"signature": "def reduce(self, key, values)"
},
{
"docstring": "compute the similarity between name1 and name2 e.g. similiarity(\"A... | 2 | null | Implement the Python class `Name2SimiliarName` described below.
Class description:
find the most simliar name for the given name, from the name before and after it e.g. (Adam, Ada Adams) -> (Adam, Ada)
Method signatures and docstrings:
- def reduce(self, key, values): find the most simliar name for the given name @pa... | Implement the Python class `Name2SimiliarName` described below.
Class description:
find the most simliar name for the given name, from the name before and after it e.g. (Adam, Ada Adams) -> (Adam, Ada)
Method signatures and docstrings:
- def reduce(self, key, values): find the most simliar name for the given name @pa... | 95d1806e2f4e89e960b76a685b1fba2eaa7d5142 | <|skeleton|>
class Name2SimiliarName:
"""find the most simliar name for the given name, from the name before and after it e.g. (Adam, Ada Adams) -> (Adam, Ada)"""
def reduce(self, key, values):
"""find the most simliar name for the given name @param key: the given name @param values: the name before an... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Name2SimiliarName:
"""find the most simliar name for the given name, from the name before and after it e.g. (Adam, Ada Adams) -> (Adam, Ada)"""
def reduce(self, key, values):
"""find the most simliar name for the given name @param key: the given name @param values: the name before and after the g... | the_stack_v2_python_sparse | nltk_contrib/hadoop/name_similarity/similiar_name_reducer.py | nltk/nltk_contrib | train | 145 |
98dd2b184bbfe2fcf26fa4d033ee2db1c859827f | [
"print('Incoming get')\nprint(request.data)\ndata = {'headers': {'content-type': 'application/json'}, 'body': [{'id': '2checkoutcom', 'name': '2Checkout.com', 'checkoutUrl': 'https://sleeky-pay.netlify.app/index.html'}]}\nreturn Response(data)",
"print('Incoming post')\nprint(request.data)\ndata = [{'id': '2check... | <|body_start_0|>
print('Incoming get')
print(request.data)
data = {'headers': {'content-type': 'application/json'}, 'body': [{'id': '2checkoutcom', 'name': '2Checkout.com', 'checkoutUrl': 'https://sleeky-pay.netlify.app/index.html'}]}
return Response(data)
<|end_body_0|>
<|body_start_1|... | * Requires token authentication. | PaymentMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaymentMethods:
"""* Requires token authentication."""
def get(self, request, format=None):
"""Docs"""
<|body_0|>
def post(self, request, format=None):
"""Docs"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
print('Incoming get')
print(r... | stack_v2_sparse_classes_10k_train_006375 | 5,024 | no_license | [
{
"docstring": "Docs",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Docs",
"name": "post",
"signature": "def post(self, request, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006346 | Implement the Python class `PaymentMethods` described below.
Class description:
* Requires token authentication.
Method signatures and docstrings:
- def get(self, request, format=None): Docs
- def post(self, request, format=None): Docs | Implement the Python class `PaymentMethods` described below.
Class description:
* Requires token authentication.
Method signatures and docstrings:
- def get(self, request, format=None): Docs
- def post(self, request, format=None): Docs
<|skeleton|>
class PaymentMethods:
"""* Requires token authentication."""
... | d1ba4723c0ee8774ed70b8a1d163d10b3dcef28e | <|skeleton|>
class PaymentMethods:
"""* Requires token authentication."""
def get(self, request, format=None):
"""Docs"""
<|body_0|>
def post(self, request, format=None):
"""Docs"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PaymentMethods:
"""* Requires token authentication."""
def get(self, request, format=None):
"""Docs"""
print('Incoming get')
print(request.data)
data = {'headers': {'content-type': 'application/json'}, 'body': [{'id': '2checkoutcom', 'name': '2Checkout.com', 'checkoutUrl':... | the_stack_v2_python_sparse | meshhairline/app.py | LogicalAddress/meshhairline | train | 0 |
5cee8f5de037c00a8a219bd097bcd41da9b85faa | [
"self.value_dict = {}\nfor i in range(len(nums)):\n if nums[i]:\n self.value_dict[i] = nums[i]",
"a_value_dict = self.value_dict\nb_value_dict = vec.value_dict\ntemp_value = 0\nif len(a_value_dict) > len(b_value_dict):\n b_value_dict, a_value_dict = (a_value_dict, b_value_dict)\nfor key, value in a_v... | <|body_start_0|>
self.value_dict = {}
for i in range(len(nums)):
if nums[i]:
self.value_dict[i] = nums[i]
<|end_body_0|>
<|body_start_1|>
a_value_dict = self.value_dict
b_value_dict = vec.value_dict
temp_value = 0
if len(a_value_dict) > len(b_... | SparseVector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseVector:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def dotProduct(self, vec):
""":type vec: 'SparseVector' :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.value_dict = {}
for i in range(len(nums))... | stack_v2_sparse_classes_10k_train_006376 | 1,129 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type vec: 'SparseVector' :rtype: int",
"name": "dotProduct",
"signature": "def dotProduct(self, vec)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000127 | Implement the Python class `SparseVector` described below.
Class description:
Implement the SparseVector class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def dotProduct(self, vec): :type vec: 'SparseVector' :rtype: int | Implement the Python class `SparseVector` described below.
Class description:
Implement the SparseVector class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def dotProduct(self, vec): :type vec: 'SparseVector' :rtype: int
<|skeleton|>
class SparseVector:
def __init__(sel... | dc45210cb2cc50bfefd8c21c865e6ee2163a022a | <|skeleton|>
class SparseVector:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def dotProduct(self, vec):
""":type vec: 'SparseVector' :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SparseVector:
def __init__(self, nums):
""":type nums: List[int]"""
self.value_dict = {}
for i in range(len(nums)):
if nums[i]:
self.value_dict[i] = nums[i]
def dotProduct(self, vec):
""":type vec: 'SparseVector' :rtype: int"""
a_value_d... | the_stack_v2_python_sparse | practice/solution/1570_dot_product_of_two_sparse_vectors.py | kesarb/leetcode-summary-python | train | 0 | |
b619429225550e61792ce602d9b0aec879ed60d2 | [
"rval = []\nfor group in trans.sa_session.query(trans.app.model.Group).filter(trans.app.model.Group.table.c.deleted == false()):\n if trans.user_is_admin:\n item = group.to_dict(value_mapper={'id': trans.security.encode_id})\n encoded_id = trans.security.encode_id(group.id)\n item['url'] = u... | <|body_start_0|>
rval = []
for group in trans.sa_session.query(trans.app.model.Group).filter(trans.app.model.Group.table.c.deleted == false()):
if trans.user_is_admin:
item = group.to_dict(value_mapper={'id': trans.security.encode_id})
encoded_id = trans.secur... | GroupAPIController | [
"CC-BY-2.5",
"AFL-2.1",
"AFL-3.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupAPIController:
def index(self, trans, **kwd):
"""GET /api/groups Displays a collection (list) of groups."""
<|body_0|>
def create(self, trans, payload, **kwd):
"""POST /api/groups Creates a new group."""
<|body_1|>
def show(self, trans, id, **kwd):
... | stack_v2_sparse_classes_10k_train_006377 | 5,197 | permissive | [
{
"docstring": "GET /api/groups Displays a collection (list) of groups.",
"name": "index",
"signature": "def index(self, trans, **kwd)"
},
{
"docstring": "POST /api/groups Creates a new group.",
"name": "create",
"signature": "def create(self, trans, payload, **kwd)"
},
{
"docstr... | 4 | null | Implement the Python class `GroupAPIController` described below.
Class description:
Implement the GroupAPIController class.
Method signatures and docstrings:
- def index(self, trans, **kwd): GET /api/groups Displays a collection (list) of groups.
- def create(self, trans, payload, **kwd): POST /api/groups Creates a n... | Implement the Python class `GroupAPIController` described below.
Class description:
Implement the GroupAPIController class.
Method signatures and docstrings:
- def index(self, trans, **kwd): GET /api/groups Displays a collection (list) of groups.
- def create(self, trans, payload, **kwd): POST /api/groups Creates a n... | d194520fdfe08e48c0b3d0d2299cd2adcb8f5952 | <|skeleton|>
class GroupAPIController:
def index(self, trans, **kwd):
"""GET /api/groups Displays a collection (list) of groups."""
<|body_0|>
def create(self, trans, payload, **kwd):
"""POST /api/groups Creates a new group."""
<|body_1|>
def show(self, trans, id, **kwd):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GroupAPIController:
def index(self, trans, **kwd):
"""GET /api/groups Displays a collection (list) of groups."""
rval = []
for group in trans.sa_session.query(trans.app.model.Group).filter(trans.app.model.Group.table.c.deleted == false()):
if trans.user_is_admin:
... | the_stack_v2_python_sparse | lib/galaxy/webapps/galaxy/api/groups.py | bwlang/galaxy | train | 0 | |
2af110be3a2908a5ef3ba5560175723561726fdc | [
"try:\n self.detach(logger)\nexcept ValueError:\n pass\nlogger.addHandler(self)",
"existing_handlers = [h for h in logger.handlers if self == h]\nif not existing_handlers:\n raise ValueError('Handler not found on logger: %s: %s' % (logger, self))\nfor h in existing_handlers:\n pylogger.debug('Removing... | <|body_start_0|>
try:
self.detach(logger)
except ValueError:
pass
logger.addHandler(self)
<|end_body_0|>
<|body_start_1|>
existing_handlers = [h for h in logger.handlers if self == h]
if not existing_handlers:
raise ValueError('Handler not fou... | Mixin for custom logging handlers. | LoggerPluginMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggerPluginMixin:
"""Mixin for custom logging handlers."""
def attach(self, logger):
"""Attach this logging handler to logger after first removing any similar logging handlers. @type logger: logging.Logger instance @param logger: Logger to which this handler will be attached."""
... | stack_v2_sparse_classes_10k_train_006378 | 5,064 | no_license | [
{
"docstring": "Attach this logging handler to logger after first removing any similar logging handlers. @type logger: logging.Logger instance @param logger: Logger to which this handler will be attached.",
"name": "attach",
"signature": "def attach(self, logger)"
},
{
"docstring": "Detach this ... | 2 | null | Implement the Python class `LoggerPluginMixin` described below.
Class description:
Mixin for custom logging handlers.
Method signatures and docstrings:
- def attach(self, logger): Attach this logging handler to logger after first removing any similar logging handlers. @type logger: logging.Logger instance @param logg... | Implement the Python class `LoggerPluginMixin` described below.
Class description:
Mixin for custom logging handlers.
Method signatures and docstrings:
- def attach(self, logger): Attach this logging handler to logger after first removing any similar logging handlers. @type logger: logging.Logger instance @param logg... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class LoggerPluginMixin:
"""Mixin for custom logging handlers."""
def attach(self, logger):
"""Attach this logging handler to logger after first removing any similar logging handlers. @type logger: logging.Logger instance @param logger: Logger to which this handler will be attached."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LoggerPluginMixin:
"""Mixin for custom logging handlers."""
def attach(self, logger):
"""Attach this logging handler to logger after first removing any similar logging handlers. @type logger: logging.Logger instance @param logger: Logger to which this handler will be attached."""
try:
... | the_stack_v2_python_sparse | SystemTesting/pylib/vmware/common/logging_handlers.py | Cloudxtreme/MyProject | train | 0 |
554ae97c8208d1dba00268b3fa54c725d7ebd40c | [
"context = req.environ['nova.context']\ncompute_nodes = objects.ComputeNodeList.get_all(context)\nresults = {}\nfor node in compute_nodes:\n results[node.uuid] = {}\n results[node.uuid]['id'] = node.id\n results[node.uuid]['host'] = node.host\nreturn results",
"context = req.environ['nova.context']\ncomp... | <|body_start_0|>
context = req.environ['nova.context']
compute_nodes = objects.ComputeNodeList.get_all(context)
results = {}
for node in compute_nodes:
results[node.uuid] = {}
results[node.uuid]['id'] = node.id
results[node.uuid]['host'] = node.host
... | Flavor controller for the OpenStack API. | FlavorsController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlavorsController:
"""Flavor controller for the OpenStack API."""
def index(self, req):
"""Return all flavors in brief."""
<|body_0|>
def detail(self, req):
"""Return all flavors in detail."""
<|body_1|>
def show(self, req, id):
"""Return dat... | stack_v2_sparse_classes_10k_train_006379 | 3,546 | no_license | [
{
"docstring": "Return all flavors in brief.",
"name": "index",
"signature": "def index(self, req)"
},
{
"docstring": "Return all flavors in detail.",
"name": "detail",
"signature": "def detail(self, req)"
},
{
"docstring": "Return data about the given flavor id.",
"name": "s... | 3 | stack_v2_sparse_classes_30k_train_003931 | Implement the Python class `FlavorsController` described below.
Class description:
Flavor controller for the OpenStack API.
Method signatures and docstrings:
- def index(self, req): Return all flavors in brief.
- def detail(self, req): Return all flavors in detail.
- def show(self, req, id): Return data about the giv... | Implement the Python class `FlavorsController` described below.
Class description:
Flavor controller for the OpenStack API.
Method signatures and docstrings:
- def index(self, req): Return all flavors in brief.
- def detail(self, req): Return all flavors in detail.
- def show(self, req, id): Return data about the giv... | 61d4e0ccd7328a6aa543af3b75e5f7fedf98bf8e | <|skeleton|>
class FlavorsController:
"""Flavor controller for the OpenStack API."""
def index(self, req):
"""Return all flavors in brief."""
<|body_0|>
def detail(self, req):
"""Return all flavors in detail."""
<|body_1|>
def show(self, req, id):
"""Return dat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FlavorsController:
"""Flavor controller for the OpenStack API."""
def index(self, req):
"""Return all flavors in brief."""
context = req.environ['nova.context']
compute_nodes = objects.ComputeNodeList.get_all(context)
results = {}
for node in compute_nodes:
... | the_stack_v2_python_sparse | nova/api/openstack/compute/slaves.py | KevinKaiQian/polar-bear | train | 2 |
6bdc62e4e294afedd8066db2a224373c030a7c6f | [
"super(ProtocolMapperTestBase, self).setUp()\nself.Reinitialize(path_method='my_method', content_type='application/x-google-protobuf')\nself.request_message = Request1()\nself.request_message.integer_field = 1\nself.request_message.string_field = u'something'\nself.request_message.enum_field = Enum1.VAL1\nself.resp... | <|body_start_0|>
super(ProtocolMapperTestBase, self).setUp()
self.Reinitialize(path_method='my_method', content_type='application/x-google-protobuf')
self.request_message = Request1()
self.request_message.integer_field = 1
self.request_message.string_field = u'something'
... | Base class for basic protocol mapper tests. | ProtocolMapperTestBase | [
"Apache-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtocolMapperTestBase:
"""Base class for basic protocol mapper tests."""
def setUp(self):
"""Reinitialize test specifically for protocol buffer mapper."""
<|body_0|>
def testBuildRequest(self):
"""Test request building."""
<|body_1|>
def testBuildRe... | stack_v2_sparse_classes_10k_train_006380 | 46,517 | permissive | [
{
"docstring": "Reinitialize test specifically for protocol buffer mapper.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test request building.",
"name": "testBuildRequest",
"signature": "def testBuildRequest(self)"
},
{
"docstring": "Test response building... | 4 | stack_v2_sparse_classes_30k_test_000393 | Implement the Python class `ProtocolMapperTestBase` described below.
Class description:
Base class for basic protocol mapper tests.
Method signatures and docstrings:
- def setUp(self): Reinitialize test specifically for protocol buffer mapper.
- def testBuildRequest(self): Test request building.
- def testBuildRespon... | Implement the Python class `ProtocolMapperTestBase` described below.
Class description:
Base class for basic protocol mapper tests.
Method signatures and docstrings:
- def setUp(self): Reinitialize test specifically for protocol buffer mapper.
- def testBuildRequest(self): Test request building.
- def testBuildRespon... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class ProtocolMapperTestBase:
"""Base class for basic protocol mapper tests."""
def setUp(self):
"""Reinitialize test specifically for protocol buffer mapper."""
<|body_0|>
def testBuildRequest(self):
"""Test request building."""
<|body_1|>
def testBuildRe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProtocolMapperTestBase:
"""Base class for basic protocol mapper tests."""
def setUp(self):
"""Reinitialize test specifically for protocol buffer mapper."""
super(ProtocolMapperTestBase, self).setUp()
self.Reinitialize(path_method='my_method', content_type='application/x-google-pro... | the_stack_v2_python_sparse | third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/webapp/service_handlers_test.py | metux/chromium-suckless | train | 5 |
5921326e3a36218c3c37822de5eb911fbdd8a9e4 | [
"dummy = ListNode(0)\ndummy.next = head\npre = dummy\ncur_lst = self.generate_lst(pre.next, k)\nwhile pre and (not None in cur_lst):\n temp = cur_lst[-1].next\n pre.next = cur_lst[-1]\n for i in reversed(xrange(k)):\n if i == 0:\n cur_lst[i].next = temp\n else:\n cur_lst... | <|body_start_0|>
dummy = ListNode(0)
dummy.next = head
pre = dummy
cur_lst = self.generate_lst(pre.next, k)
while pre and (not None in cur_lst):
temp = cur_lst[-1].next
pre.next = cur_lst[-1]
for i in reversed(xrange(k)):
if i =... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseKGroup(self, head, k):
"""List O(k*n) :param head: a ListNode :param k: an integer :return: ListNode"""
<|body_0|>
def generate_lst(self, node, k):
"""Helpder :param node: ListNode :param k: integer :return: list"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_10k_train_006381 | 1,813 | permissive | [
{
"docstring": "List O(k*n) :param head: a ListNode :param k: an integer :return: ListNode",
"name": "reverseKGroup",
"signature": "def reverseKGroup(self, head, k)"
},
{
"docstring": "Helpder :param node: ListNode :param k: integer :return: list",
"name": "generate_lst",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_006004 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseKGroup(self, head, k): List O(k*n) :param head: a ListNode :param k: an integer :return: ListNode
- def generate_lst(self, node, k): Helpder :param node: ListNode :par... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseKGroup(self, head, k): List O(k*n) :param head: a ListNode :param k: an integer :return: ListNode
- def generate_lst(self, node, k): Helpder :param node: ListNode :par... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def reverseKGroup(self, head, k):
"""List O(k*n) :param head: a ListNode :param k: an integer :return: ListNode"""
<|body_0|>
def generate_lst(self, node, k):
"""Helpder :param node: ListNode :param k: integer :return: list"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseKGroup(self, head, k):
"""List O(k*n) :param head: a ListNode :param k: an integer :return: ListNode"""
dummy = ListNode(0)
dummy.next = head
pre = dummy
cur_lst = self.generate_lst(pre.next, k)
while pre and (not None in cur_lst):
... | the_stack_v2_python_sparse | 024 Reverse Nodes in k-Group.py | Aminaba123/LeetCode | train | 1 | |
457a7d82f0b57ddb3d2132ac0cb0979a32d3a6c8 | [
"trie = Trie(d)\nwords = sentence.split(' ')\nfor i in range(len(words)):\n root = trie.find(words[i])\n if len(root) > 0:\n words[i] = root\nreturn ' '.join(words)",
"def replace(word):\n best = word\n for r in cache[ord(word[0]) - 97]:\n if len(r) < len(best) and word.startswith(r):\n ... | <|body_start_0|>
trie = Trie(d)
words = sentence.split(' ')
for i in range(len(words)):
root = trie.find(words[i])
if len(root) > 0:
words[i] = root
return ' '.join(words)
<|end_body_0|>
<|body_start_1|>
def replace(word):
best... | Solution_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_1:
def replaceWords(self, d, sentence):
""":type dict: List[str] :type sentence: str :rtype: str"""
<|body_0|>
def replaceWords_1(self, roots, sentence):
""":type dict: List[str] :type sentence: str :rtype: str 89ms"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_006382 | 4,252 | no_license | [
{
"docstring": ":type dict: List[str] :type sentence: str :rtype: str",
"name": "replaceWords",
"signature": "def replaceWords(self, d, sentence)"
},
{
"docstring": ":type dict: List[str] :type sentence: str :rtype: str 89ms",
"name": "replaceWords_1",
"signature": "def replaceWords_1(se... | 2 | null | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def replaceWords(self, d, sentence): :type dict: List[str] :type sentence: str :rtype: str
- def replaceWords_1(self, roots, sentence): :type dict: List[str] :type sentence: ... | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def replaceWords(self, d, sentence): :type dict: List[str] :type sentence: str :rtype: str
- def replaceWords_1(self, roots, sentence): :type dict: List[str] :type sentence: ... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution_1:
def replaceWords(self, d, sentence):
""":type dict: List[str] :type sentence: str :rtype: str"""
<|body_0|>
def replaceWords_1(self, roots, sentence):
""":type dict: List[str] :type sentence: str :rtype: str 89ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution_1:
def replaceWords(self, d, sentence):
""":type dict: List[str] :type sentence: str :rtype: str"""
trie = Trie(d)
words = sentence.split(' ')
for i in range(len(words)):
root = trie.find(words[i])
if len(root) > 0:
words[i] = ro... | the_stack_v2_python_sparse | ReplaceWords_MID_648.py | 953250587/leetcode-python | train | 2 | |
ed6846288a524d9c4ff3d0845cb649df844a5b93 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ClonePostRequestBody()",
"from ....models.clonable_team_parts import ClonableTeamParts\nfrom ....models.team_visibility_type import TeamVisibilityType\nfrom ....models.clonable_team_parts import ClonableTeamParts\nfrom ....models.team_... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ClonePostRequestBody()
<|end_body_0|>
<|body_start_1|>
from ....models.clonable_team_parts import ClonableTeamParts
from ....models.team_visibility_type import TeamVisibilityType
... | ClonePostRequestBody | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClonePostRequestBody:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClonePostRequestBody:
"""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 ... | stack_v2_sparse_classes_10k_train_006383 | 3,899 | 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: ClonePostRequestBody",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | null | Implement the Python class `ClonePostRequestBody` described below.
Class description:
Implement the ClonePostRequestBody class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClonePostRequestBody: Creates a new instance of the appropriate class based o... | Implement the Python class `ClonePostRequestBody` described below.
Class description:
Implement the ClonePostRequestBody class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClonePostRequestBody: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ClonePostRequestBody:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClonePostRequestBody:
"""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 ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClonePostRequestBody:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClonePostRequestBody:
"""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... | the_stack_v2_python_sparse | msgraph/generated/teams/item/clone/clone_post_request_body.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
5c79c54386411207cfef6f34ce542db22f47cd5f | [
"self.m1 = defaultdict(list)\nself.m2 = {}\nself.nextid = 0",
"present = val in self.m1\nself.m1[val].append(self.nextid)\nself.m2[self.nextid] = val\nself.nextid += 1\nreturn not present",
"if val in self.m1:\n nid = self.m1[val].pop()\n if len(self.m1[val]) == 0:\n self.m1.pop(val)\n self.m2.p... | <|body_start_0|>
self.m1 = defaultdict(list)
self.m2 = {}
self.nextid = 0
<|end_body_0|>
<|body_start_1|>
present = val in self.m1
self.m1[val].append(self.nextid)
self.m2[self.nextid] = val
self.nextid += 1
return not present
<|end_body_1|>
<|body_start... | RandomizedSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_006384 | 3,207 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool",
"name": "insert",
"signature": ... | 4 | stack_v2_sparse_classes_30k_train_002944 | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the set. Returns true if the set did not already contain the specif... | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the set. Returns true if the set did not already contain the specif... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
self.m1 = defaultdict(list)
self.m2 = {}
self.nextid = 0
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type... | the_stack_v2_python_sparse | I/InsertDeleteGetRandomO1-Duplicatesallowed.py | bssrdf/pyleet | train | 2 | |
18b238101321757398c88053606e09c1b0546cab | [
"company = self.env.company\nbranch_ids = self.env.user.branch_ids\nbranch = branch_ids.filtered(lambda branch: branch.company_id == company)\nreturn [('id', 'in', branch.ids)]",
"self.default_account_id = False\nself.suspense_account_id = False\nself.profit_account_id = False\nself.loss_account_id = False"
] | <|body_start_0|>
company = self.env.company
branch_ids = self.env.user.branch_ids
branch = branch_ids.filtered(lambda branch: branch.company_id == company)
return [('id', 'in', branch.ids)]
<|end_body_0|>
<|body_start_1|>
self.default_account_id = False
self.suspense_acc... | inherited account journal | AccountJournal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountJournal:
"""inherited account journal"""
def _get_branch_domain(self):
"""methode to get branch domain"""
<|body_0|>
def onchange_branch_id(self):
"""onchange methode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
company = self.env.comp... | stack_v2_sparse_classes_10k_train_006385 | 4,321 | no_license | [
{
"docstring": "methode to get branch domain",
"name": "_get_branch_domain",
"signature": "def _get_branch_domain(self)"
},
{
"docstring": "onchange methode",
"name": "onchange_branch_id",
"signature": "def onchange_branch_id(self)"
}
] | 2 | null | Implement the Python class `AccountJournal` described below.
Class description:
inherited account journal
Method signatures and docstrings:
- def _get_branch_domain(self): methode to get branch domain
- def onchange_branch_id(self): onchange methode | Implement the Python class `AccountJournal` described below.
Class description:
inherited account journal
Method signatures and docstrings:
- def _get_branch_domain(self): methode to get branch domain
- def onchange_branch_id(self): onchange methode
<|skeleton|>
class AccountJournal:
"""inherited account journal... | 4b1bcb8f17aad44fe9c80a8180eb0128e6bb2c14 | <|skeleton|>
class AccountJournal:
"""inherited account journal"""
def _get_branch_domain(self):
"""methode to get branch domain"""
<|body_0|>
def onchange_branch_id(self):
"""onchange methode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AccountJournal:
"""inherited account journal"""
def _get_branch_domain(self):
"""methode to get branch domain"""
company = self.env.company
branch_ids = self.env.user.branch_ids
branch = branch_ids.filtered(lambda branch: branch.company_id == company)
return [('id'... | the_stack_v2_python_sparse | multi_branch_base/models/branch_account_journal.py | CybroOdoo/CybroAddons | train | 209 |
3fb62d5061ddee8cd773e3d70b35af53732b9114 | [
"self.input_size = input_size\nself.output_size = output_size\nself.mem_size = mem_size\nself.mem_width = mem_width\nself.layer_sizes = layer_sizes\nself.num_heads = num_heads\nself.W_read_list = [init_weights(shape=(self.mem_width, 4 * self.layer_sizes[0]), name='W_read_%d' % h) for h in range(self.num_heads)]\nse... | <|body_start_0|>
self.input_size = input_size
self.output_size = output_size
self.mem_size = mem_size
self.mem_width = mem_width
self.layer_sizes = layer_sizes
self.num_heads = num_heads
self.W_read_list = [init_weights(shape=(self.mem_width, 4 * self.layer_sizes[... | ControllerLSTM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerLSTM:
def __init__(self, input_size=8, output_size=8, mem_size=128, mem_width=20, layer_sizes=[100], num_heads=3):
""":type input_size: int :param input_size: the input size of outside input :type output_size: int :param output_size: the output size of outside output :type mem_... | stack_v2_sparse_classes_10k_train_006386 | 6,110 | no_license | [
{
"docstring": ":type input_size: int :param input_size: the input size of outside input :type output_size: int :param output_size: the output size of outside output :type mem_size: int :param mem_size: rows of the memory matrix :type mem_width: int :param mem_width: length of each row in the memory matrix :typ... | 2 | stack_v2_sparse_classes_30k_train_003572 | Implement the Python class `ControllerLSTM` described below.
Class description:
Implement the ControllerLSTM class.
Method signatures and docstrings:
- def __init__(self, input_size=8, output_size=8, mem_size=128, mem_width=20, layer_sizes=[100], num_heads=3): :type input_size: int :param input_size: the input size o... | Implement the Python class `ControllerLSTM` described below.
Class description:
Implement the ControllerLSTM class.
Method signatures and docstrings:
- def __init__(self, input_size=8, output_size=8, mem_size=128, mem_width=20, layer_sizes=[100], num_heads=3): :type input_size: int :param input_size: the input size o... | f10abd01b5e1b855c169575353ce5a3027b413c6 | <|skeleton|>
class ControllerLSTM:
def __init__(self, input_size=8, output_size=8, mem_size=128, mem_width=20, layer_sizes=[100], num_heads=3):
""":type input_size: int :param input_size: the input size of outside input :type output_size: int :param output_size: the output size of outside output :type mem_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ControllerLSTM:
def __init__(self, input_size=8, output_size=8, mem_size=128, mem_width=20, layer_sizes=[100], num_heads=3):
""":type input_size: int :param input_size: the input size of outside input :type output_size: int :param output_size: the output size of outside output :type mem_size: int :par... | the_stack_v2_python_sparse | RL/turing-machine/layers/controller.py | BigeyeDestroyer/rnn-project | train | 7 | |
c5afd837def6a6ec93ab77a5746a49b3d3ffd86d | [
"self.name = name\nconv2d = functools.partial(LayerConv, stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope)\navg_pool = functools.partial(downscale, n=2)\nnc_in, nc_out = n\nwith tf.variable_scope(self.name):\n self.path1_blocks = []\n with tf.variable_scope('bb_path1'):\n layer... | <|body_start_0|>
self.name = name
conv2d = functools.partial(LayerConv, stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope)
avg_pool = functools.partial(downscale, n=2)
nc_in, nc_out = n
with tf.variable_scope(self.name):
self.path1_blocks = []
... | BasicBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicBlock:
def __init__(self, name, n, activation=functools.partial(tf.nn.leaky_relu, alpha=0.2), norm_layer=None, padding='SAME', use_scaling=True, relu_slope=1.0):
"""Layer constructor. Args: TODO"""
<|body_0|>
def __call__(self, x_init):
"""Apply layer to tensor ... | stack_v2_sparse_classes_10k_train_006387 | 13,442 | permissive | [
{
"docstring": "Layer constructor. Args: TODO",
"name": "__init__",
"signature": "def __init__(self, name, n, activation=functools.partial(tf.nn.leaky_relu, alpha=0.2), norm_layer=None, padding='SAME', use_scaling=True, relu_slope=1.0)"
},
{
"docstring": "Apply layer to tensor x.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_005249 | Implement the Python class `BasicBlock` described below.
Class description:
Implement the BasicBlock class.
Method signatures and docstrings:
- def __init__(self, name, n, activation=functools.partial(tf.nn.leaky_relu, alpha=0.2), norm_layer=None, padding='SAME', use_scaling=True, relu_slope=1.0): Layer constructor. ... | Implement the Python class `BasicBlock` described below.
Class description:
Implement the BasicBlock class.
Method signatures and docstrings:
- def __init__(self, name, n, activation=functools.partial(tf.nn.leaky_relu, alpha=0.2), norm_layer=None, padding='SAME', use_scaling=True, relu_slope=1.0): Layer constructor. ... | 091d6ae9e087cf5a6e18b00bce7d8f7ede9d9d08 | <|skeleton|>
class BasicBlock:
def __init__(self, name, n, activation=functools.partial(tf.nn.leaky_relu, alpha=0.2), norm_layer=None, padding='SAME', use_scaling=True, relu_slope=1.0):
"""Layer constructor. Args: TODO"""
<|body_0|>
def __call__(self, x_init):
"""Apply layer to tensor ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BasicBlock:
def __init__(self, name, n, activation=functools.partial(tf.nn.leaky_relu, alpha=0.2), norm_layer=None, padding='SAME', use_scaling=True, relu_slope=1.0):
"""Layer constructor. Args: TODO"""
self.name = name
conv2d = functools.partial(LayerConv, stride=1, padding=padding, u... | the_stack_v2_python_sparse | layers.py | MoustafaMeshry/StEP | train | 6 | |
a6332afc6bedaf9475623a46cd20ab564ad094dd | [
"with open(HTML5.JQUERY_LOAD_HELPER) as f:\n load_jquery_js = f.read()\ndriver.execute_async_script(load_jquery_js, jquery_url)",
"HTML5.__load_jquery(driver)\nwith open(HTML5.DRAG_AND_DROP_HELPER) as f:\n drag_and_drop_js = f.read()\ndrag_and_drop_command = \"$('{draggable}').simulateDragDrop({{ dropTarget... | <|body_start_0|>
with open(HTML5.JQUERY_LOAD_HELPER) as f:
load_jquery_js = f.read()
driver.execute_async_script(load_jquery_js, jquery_url)
<|end_body_0|>
<|body_start_1|>
HTML5.__load_jquery(driver)
with open(HTML5.DRAG_AND_DROP_HELPER) as f:
drag_and_drop_js =... | HTML5 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTML5:
def __load_jquery(driver, jquery_url=JQUERY_URL):
""":param driver: WebDriver object :param jquery_url: STRING, url from which to import jq :return: None"""
<|body_0|>
def drag_and_drop(driver, draggable, droppable):
""":param driver: WebDriver object :param d... | stack_v2_sparse_classes_10k_train_006388 | 2,733 | no_license | [
{
"docstring": ":param driver: WebDriver object :param jquery_url: STRING, url from which to import jq :return: None",
"name": "__load_jquery",
"signature": "def __load_jquery(driver, jquery_url=JQUERY_URL)"
},
{
"docstring": ":param driver: WebDriver object :param draggable: STRING, selector ht... | 2 | stack_v2_sparse_classes_30k_train_006060 | Implement the Python class `HTML5` described below.
Class description:
Implement the HTML5 class.
Method signatures and docstrings:
- def __load_jquery(driver, jquery_url=JQUERY_URL): :param driver: WebDriver object :param jquery_url: STRING, url from which to import jq :return: None
- def drag_and_drop(driver, dragg... | Implement the Python class `HTML5` described below.
Class description:
Implement the HTML5 class.
Method signatures and docstrings:
- def __load_jquery(driver, jquery_url=JQUERY_URL): :param driver: WebDriver object :param jquery_url: STRING, url from which to import jq :return: None
- def drag_and_drop(driver, dragg... | 44e6013622c5f09e0a390de6e7a94c9c253eb00f | <|skeleton|>
class HTML5:
def __load_jquery(driver, jquery_url=JQUERY_URL):
""":param driver: WebDriver object :param jquery_url: STRING, url from which to import jq :return: None"""
<|body_0|>
def drag_and_drop(driver, draggable, droppable):
""":param driver: WebDriver object :param d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HTML5:
def __load_jquery(driver, jquery_url=JQUERY_URL):
""":param driver: WebDriver object :param jquery_url: STRING, url from which to import jq :return: None"""
with open(HTML5.JQUERY_LOAD_HELPER) as f:
load_jquery_js = f.read()
driver.execute_async_script(load_jquery_js... | the_stack_v2_python_sparse | advance-selenium-1/test_drag_and_drop.py | lindafanglizhi/seleniumforpython | train | 0 | |
6e57c2fcd6212da0ad38e9cd29c7f4d32e859712 | [
"super().__init__(*args, **kwargs)\ninput_size = sum((x.output_size for x in self._input_layers))\noutput_size = self.output_size\nif input_size != output_size:\n raise ValueError('Highway network layer cannot change the number of connections.')\nself._init_weight('input/W', (input_size, output_size), scale=0.01... | <|body_start_0|>
super().__init__(*args, **kwargs)
input_size = sum((x.output_size for x in self._input_layers))
output_size = self.output_size
if input_size != output_size:
raise ValueError('Highway network layer cannot change the number of connections.')
self._init_... | Highway Network Layer with Hyperbolic Tangent Activation R. K. Srivastava (2015) Highway Networks ICML 2015 Deep Learning Workshop | HighwayLayer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HighwayLayer:
"""Highway Network Layer with Hyperbolic Tangent Activation R. K. Srivastava (2015) Highway Networks ICML 2015 Deep Learning Workshop"""
def __init__(self, *args, **kwargs):
"""Initializes the parameters for this layer."""
<|body_0|>
def create_structure(se... | stack_v2_sparse_classes_10k_train_006389 | 2,081 | permissive | [
{
"docstring": "Initializes the parameters for this layer.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Creates the symbolic graph of this layer. Sets self.output to a symbolic matrix that describes the output of this layer.",
"name": "create_st... | 2 | stack_v2_sparse_classes_30k_train_005834 | Implement the Python class `HighwayLayer` described below.
Class description:
Highway Network Layer with Hyperbolic Tangent Activation R. K. Srivastava (2015) Highway Networks ICML 2015 Deep Learning Workshop
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initializes the parameters for this ... | Implement the Python class `HighwayLayer` described below.
Class description:
Highway Network Layer with Hyperbolic Tangent Activation R. K. Srivastava (2015) Highway Networks ICML 2015 Deep Learning Workshop
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initializes the parameters for this ... | 9904faec19ad5718470f21927229aad2656e5686 | <|skeleton|>
class HighwayLayer:
"""Highway Network Layer with Hyperbolic Tangent Activation R. K. Srivastava (2015) Highway Networks ICML 2015 Deep Learning Workshop"""
def __init__(self, *args, **kwargs):
"""Initializes the parameters for this layer."""
<|body_0|>
def create_structure(se... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HighwayLayer:
"""Highway Network Layer with Hyperbolic Tangent Activation R. K. Srivastava (2015) Highway Networks ICML 2015 Deep Learning Workshop"""
def __init__(self, *args, **kwargs):
"""Initializes the parameters for this layer."""
super().__init__(*args, **kwargs)
input_size... | the_stack_v2_python_sparse | theanolm/network/highwaylayer.py | senarvi/theanolm | train | 95 |
251ad93753c985faa78c2fd3e4807b6fd486ac80 | [
"if not nums:\n return []\ncnt = {}\nfor i in range(len(nums)):\n if nums[i] not in cnt:\n cnt[nums[i]] = 1\n else:\n cnt[nums[i]] += 1\nreturn [key for key, value in sorted(cnt.items(), key=lambda x: x[1], reverse=True)][:k]",
"counts = collections.Counter(nums)\nprint(counts)\nheap = []\n... | <|body_start_0|>
if not nums:
return []
cnt = {}
for i in range(len(nums)):
if nums[i] not in cnt:
cnt[nums[i]] = 1
else:
cnt[nums[i]] += 1
return [key for key, value in sorted(cnt.items(), key=lambda x: x[1], reverse=Tr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def topKFrequent2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_006390 | 1,371 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "topKFrequent",
"signature": "def topKFrequent(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "topKFrequent2",
"signature": "def topKFrequent2(self, nums, k)"... | 2 | stack_v2_sparse_classes_30k_train_001814 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def topKFrequent2(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def topKFrequent2(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
<|... | 4960986edae561c1f9f32f3c97ce144f976d7844 | <|skeleton|>
class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def topKFrequent2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
if not nums:
return []
cnt = {}
for i in range(len(nums)):
if nums[i] not in cnt:
cnt[nums[i]] = 1
else:
cnt... | the_stack_v2_python_sparse | hash_table/top_k_frequent_elements.py | AlexSchumi/Algorithms | train | 0 | |
f13a3854175dbf3ac1dc5746c9ff21377f2a12d5 | [
"def print_error_usage(message):\n error_msg = str('ArgumentError # %s\\n\\nUsage:' % message + self.usage)\n sys.stderr.write(error_msg)\n sys.exit(2)\nself.exit(print_error_usage(message))",
"def print_error_usage(message):\n sys.stderr.write(message)\n sys.exit(2)\nself.exit(print_error_usage(me... | <|body_start_0|>
def print_error_usage(message):
error_msg = str('ArgumentError # %s\n\nUsage:' % message + self.usage)
sys.stderr.write(error_msg)
sys.exit(2)
self.exit(print_error_usage(message))
<|end_body_0|>
<|body_start_1|>
def print_error_usage(message... | DESCRIPTION: Child class from ArgumentParser, used to customize the error message. | CustomParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomParser:
"""DESCRIPTION: Child class from ArgumentParser, used to customize the error message."""
def error(self, message):
"""DESCRIPTION: Function which overrides the original error from argparse"""
<|body_0|>
def general_error(self, message):
"""DESCRIPTI... | stack_v2_sparse_classes_10k_train_006391 | 13,513 | permissive | [
{
"docstring": "DESCRIPTION: Function which overrides the original error from argparse",
"name": "error",
"signature": "def error(self, message)"
},
{
"docstring": "DESCRIPTION: Function which overrides the original error from argparse",
"name": "general_error",
"signature": "def general... | 2 | stack_v2_sparse_classes_30k_train_002016 | Implement the Python class `CustomParser` described below.
Class description:
DESCRIPTION: Child class from ArgumentParser, used to customize the error message.
Method signatures and docstrings:
- def error(self, message): DESCRIPTION: Function which overrides the original error from argparse
- def general_error(self... | Implement the Python class `CustomParser` described below.
Class description:
DESCRIPTION: Child class from ArgumentParser, used to customize the error message.
Method signatures and docstrings:
- def error(self, message): DESCRIPTION: Function which overrides the original error from argparse
- def general_error(self... | 62bbb20d15c78d2554d7258bdae655452ac826c7 | <|skeleton|>
class CustomParser:
"""DESCRIPTION: Child class from ArgumentParser, used to customize the error message."""
def error(self, message):
"""DESCRIPTION: Function which overrides the original error from argparse"""
<|body_0|>
def general_error(self, message):
"""DESCRIPTI... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomParser:
"""DESCRIPTION: Child class from ArgumentParser, used to customize the error message."""
def error(self, message):
"""DESCRIPTION: Function which overrides the original error from argparse"""
def print_error_usage(message):
error_msg = str('ArgumentError # %s\n\n... | the_stack_v2_python_sparse | rbkcli/interface/rbk_cli.py | rubrikinc/rbkcli | train | 12 |
8e73fe7b8dd0aceaaa4c0739085c488d2649a286 | [
"new_category = SpecificationCategory(name=validated_data.get('name'), car=validated_data.get('car'))\nnew_category.save()\nreturn new_category",
"instance.name = validated_data.get('name', instance.name)\ninstance.car = validated_data.get('car', instance.car)\ninstance.save()\nreturn instance"
] | <|body_start_0|>
new_category = SpecificationCategory(name=validated_data.get('name'), car=validated_data.get('car'))
new_category.save()
return new_category
<|end_body_0|>
<|body_start_1|>
instance.name = validated_data.get('name', instance.name)
instance.car = validated_data.g... | SpecificationCategorySerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecificationCategorySerializer:
def create(self, validated_data):
"""create and return new 'SpecificationCategory' instance"""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `SpecificationCategory` instance"""
<|body_... | stack_v2_sparse_classes_10k_train_006392 | 6,342 | no_license | [
{
"docstring": "create and return new 'SpecificationCategory' instance",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Update and return an existing `SpecificationCategory` instance",
"name": "update",
"signature": "def update(self, instance, valida... | 2 | stack_v2_sparse_classes_30k_train_002565 | Implement the Python class `SpecificationCategorySerializer` described below.
Class description:
Implement the SpecificationCategorySerializer class.
Method signatures and docstrings:
- def create(self, validated_data): create and return new 'SpecificationCategory' instance
- def update(self, instance, validated_data... | Implement the Python class `SpecificationCategorySerializer` described below.
Class description:
Implement the SpecificationCategorySerializer class.
Method signatures and docstrings:
- def create(self, validated_data): create and return new 'SpecificationCategory' instance
- def update(self, instance, validated_data... | dba8d1fdb96889e41328e792816a4968cbeb1ed4 | <|skeleton|>
class SpecificationCategorySerializer:
def create(self, validated_data):
"""create and return new 'SpecificationCategory' instance"""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `SpecificationCategory` instance"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SpecificationCategorySerializer:
def create(self, validated_data):
"""create and return new 'SpecificationCategory' instance"""
new_category = SpecificationCategory(name=validated_data.get('name'), car=validated_data.get('car'))
new_category.save()
return new_category
def ... | the_stack_v2_python_sparse | cars_web/cars_app/serializers.py | Ignisor/cars_scrapper | train | 0 | |
dd131b4529eceb1fb14c02010b498f83e901062d | [
"self.g = g\nself.visited = [False] * self.g.get_size()\nself.vertex_group = [0] * self.g.get_size()",
"if self.visited[v]:\n return\nself.visited[v] = True\nself.vertex_group[v] = group\nfor vertex in self.g.adj(v):\n self.dfs(vertex, group)",
"group = 0\nfor i in range(len(self.visited)):\n if not se... | <|body_start_0|>
self.g = g
self.visited = [False] * self.g.get_size()
self.vertex_group = [0] * self.g.get_size()
<|end_body_0|>
<|body_start_1|>
if self.visited[v]:
return
self.visited[v] = True
self.vertex_group[v] = group
for vertex in self.g.adj(... | class to compute connected components of given graph | ConnectedComponents | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectedComponents:
"""class to compute connected components of given graph"""
def __init__(self, g: Graph):
"""init with a graph :param g: Graph"""
<|body_0|>
def dfs(self, v: int, group: int):
"""dfs to mark components from the same group Complexity O(E + V) :... | stack_v2_sparse_classes_10k_train_006393 | 1,418 | no_license | [
{
"docstring": "init with a graph :param g: Graph",
"name": "__init__",
"signature": "def __init__(self, g: Graph)"
},
{
"docstring": "dfs to mark components from the same group Complexity O(E + V) :param v: starting vertex :param group: current group number",
"name": "dfs",
"signature":... | 4 | stack_v2_sparse_classes_30k_train_000039 | Implement the Python class `ConnectedComponents` described below.
Class description:
class to compute connected components of given graph
Method signatures and docstrings:
- def __init__(self, g: Graph): init with a graph :param g: Graph
- def dfs(self, v: int, group: int): dfs to mark components from the same group ... | Implement the Python class `ConnectedComponents` described below.
Class description:
class to compute connected components of given graph
Method signatures and docstrings:
- def __init__(self, g: Graph): init with a graph :param g: Graph
- def dfs(self, v: int, group: int): dfs to mark components from the same group ... | e24f1a422a998672d1e78ba6bc23dfa5836e3a51 | <|skeleton|>
class ConnectedComponents:
"""class to compute connected components of given graph"""
def __init__(self, g: Graph):
"""init with a graph :param g: Graph"""
<|body_0|>
def dfs(self, v: int, group: int):
"""dfs to mark components from the same group Complexity O(E + V) :... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConnectedComponents:
"""class to compute connected components of given graph"""
def __init__(self, g: Graph):
"""init with a graph :param g: Graph"""
self.g = g
self.visited = [False] * self.g.get_size()
self.vertex_group = [0] * self.g.get_size()
def dfs(self, v: int... | the_stack_v2_python_sparse | graphs/connected_components.py | mkozel92/algos_py | train | 1 |
8f45220716cfdf9575c2221252cdea69b86ef8c6 | [
"RAMSTKWorkView.__init__(self, controller, module='Function')\nself._lst_assess_labels[1].append(_(u'Total Mode Count:'))\nself._function_id = None\nself.txtModeCount = ramstk.RAMSTKEntry(width=125, editable=False, bold=True, tooltip=_(u'Displays the total number of failure modes associated with the selected Functi... | <|body_start_0|>
RAMSTKWorkView.__init__(self, controller, module='Function')
self._lst_assess_labels[1].append(_(u'Total Mode Count:'))
self._function_id = None
self.txtModeCount = ramstk.RAMSTKEntry(width=125, editable=False, bold=True, tooltip=_(u'Displays the total number of failure ... | Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_id: the ID of the Function currently being displayed. | AssessmentResults | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssessmentResults:
"""Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_id: the ID of the Function currently bei... | stack_v2_sparse_classes_10k_train_006394 | 16,082 | permissive | [
{
"docstring": "Initialize the Work View for the Function package. :param controller: the RAMSTK master data controller instance. :type controller: :class:`ramstk.RAMSTK.RAMSTK`",
"name": "__init__",
"signature": "def __init__(self, controller, **kwargs)"
},
{
"docstring": "Load the Function Ass... | 4 | stack_v2_sparse_classes_30k_train_007283 | Implement the Python class `AssessmentResults` described below.
Class description:
Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_i... | Implement the Python class `AssessmentResults` described below.
Class description:
Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_i... | 488ffed8b842399ddcae93007de6c6f1dda23d05 | <|skeleton|>
class AssessmentResults:
"""Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_id: the ID of the Function currently bei... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AssessmentResults:
"""Display Function attribute data in the RAMSTK Work Book. The Function Assessment Results view displays all the assessment results for the selected Function. The attributes of a Function Assessment Results View are: :ivar int _function_id: the ID of the Function currently being displayed.... | the_stack_v2_python_sparse | src/ramstk/gui/gtk/workviews/Function.py | JmiXIII/ramstk | train | 0 |
95c82addde9a37044f1ca314017a74cd486dea12 | [
"if len(array) == 0:\n return False\nrownum = len(array)\ncolnum = len(array[0])\ni = colnum - 1\nj = 0\nwhile i >= 0 and j < rownum:\n if array[j][i] < target:\n j += 1\n elif array[j][i] > target:\n i -= 1\n else:\n return True\nreturn False",
"if not matrix or len(matrix) == 0:... | <|body_start_0|>
if len(array) == 0:
return False
rownum = len(array)
colnum = len(array[0])
i = colnum - 1
j = 0
while i >= 0 and j < rownum:
if array[j][i] < target:
j += 1
elif array[j][i] > target:
i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def Find(self, array, target):
"""是否存在"""
<|body_0|>
def searchMatrix(self, matrix, target):
"""输出个数"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(array) == 0:
return False
rownum = len(array)
colnum = ... | stack_v2_sparse_classes_10k_train_006395 | 2,335 | no_license | [
{
"docstring": "是否存在",
"name": "Find",
"signature": "def Find(self, array, target)"
},
{
"docstring": "输出个数",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003508 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Find(self, array, target): 是否存在
- def searchMatrix(self, matrix, target): 输出个数 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Find(self, array, target): 是否存在
- def searchMatrix(self, matrix, target): 输出个数
<|skeleton|>
class Solution:
def Find(self, array, target):
"""是否存在"""
<|... | ae191a449619418e3eba23f18574c7841e7ba52a | <|skeleton|>
class Solution:
def Find(self, array, target):
"""是否存在"""
<|body_0|>
def searchMatrix(self, matrix, target):
"""输出个数"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def Find(self, array, target):
"""是否存在"""
if len(array) == 0:
return False
rownum = len(array)
colnum = len(array[0])
i = colnum - 1
j = 0
while i >= 0 and j < rownum:
if array[j][i] < target:
j += 1
... | the_stack_v2_python_sparse | target_offer/two_dimensions_search.py | zealfory/dive_python | train | 0 | |
09c4ab2c86549fb08d887dd75c27cfa0ca4b18e5 | [
"if not head:\n return False\ntortoise = head\nhare = head.next\nwhile hare and hare.next and (tortoise != hare):\n tortoise = tortoise.next\n hare = hare.next.next\nreturn tortoise == hare",
"if not head:\n return False\nk = lam = 1\ntortoise = head\nhare = head.next\nwhile hare and tortoise != hare:... | <|body_start_0|>
if not head:
return False
tortoise = head
hare = head.next
while hare and hare.next and (tortoise != hare):
tortoise = tortoise.next
hare = hare.next.next
return tortoise == hare
<|end_body_0|>
<|body_start_1|>
if not ... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasCycle1(self, head):
"""Floyd's Tortoise and Hare (44ms)"""
<|body_0|>
def hasCycle2(self, head):
"""Brent's algorithm (40ms)"""
<|body_1|>
def hasCycle3(self, head):
"""Hashtable (36ms)"""
<|body_2|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_10k_train_006396 | 1,916 | permissive | [
{
"docstring": "Floyd's Tortoise and Hare (44ms)",
"name": "hasCycle1",
"signature": "def hasCycle1(self, head)"
},
{
"docstring": "Brent's algorithm (40ms)",
"name": "hasCycle2",
"signature": "def hasCycle2(self, head)"
},
{
"docstring": "Hashtable (36ms)",
"name": "hasCycle... | 3 | stack_v2_sparse_classes_30k_train_006519 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle1(self, head): Floyd's Tortoise and Hare (44ms)
- def hasCycle2(self, head): Brent's algorithm (40ms)
- def hasCycle3(self, head): Hashtable (36ms) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle1(self, head): Floyd's Tortoise and Hare (44ms)
- def hasCycle2(self, head): Brent's algorithm (40ms)
- def hasCycle3(self, head): Hashtable (36ms)
<|skeleton|>
clas... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def hasCycle1(self, head):
"""Floyd's Tortoise and Hare (44ms)"""
<|body_0|>
def hasCycle2(self, head):
"""Brent's algorithm (40ms)"""
<|body_1|>
def hasCycle3(self, head):
"""Hashtable (36ms)"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def hasCycle1(self, head):
"""Floyd's Tortoise and Hare (44ms)"""
if not head:
return False
tortoise = head
hare = head.next
while hare and hare.next and (tortoise != hare):
tortoise = tortoise.next
hare = hare.next.next
... | the_stack_v2_python_sparse | leetcode/0141_linked_list_cycle.py | chaosWsF/Python-Practice | train | 1 | |
744b85f377a0d84048fbf5c614a594194706623f | [
"processed = 0\nfor base in queryset:\n base.ResetNames()\n processed += 1\nself.message_user(request, '%s reset.' % GetMessageBit(processed))",
"processed = 0\nfor base in queryset:\n base.stateManaged = 'new'\n base.ResetNames()\n processed += 1\nself.message_user(request, '%s reset and marked as... | <|body_start_0|>
processed = 0
for base in queryset:
base.ResetNames()
processed += 1
self.message_user(request, '%s reset.' % GetMessageBit(processed))
<|end_body_0|>
<|body_start_1|>
processed = 0
for base in queryset:
base.stateManaged = 'n... | XrumerBaseRawAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XrumerBaseRawAdmin:
def ResetNames(self, request, queryset):
"""Сбрасываем имена"""
<|body_0|>
def ResetNamesAndNew(self, request, queryset):
"""Сбрасываем имена и помечаем как новые"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
processed = 0
... | stack_v2_sparse_classes_10k_train_006397 | 29,849 | no_license | [
{
"docstring": "Сбрасываем имена",
"name": "ResetNames",
"signature": "def ResetNames(self, request, queryset)"
},
{
"docstring": "Сбрасываем имена и помечаем как новые",
"name": "ResetNamesAndNew",
"signature": "def ResetNamesAndNew(self, request, queryset)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002985 | Implement the Python class `XrumerBaseRawAdmin` described below.
Class description:
Implement the XrumerBaseRawAdmin class.
Method signatures and docstrings:
- def ResetNames(self, request, queryset): Сбрасываем имена
- def ResetNamesAndNew(self, request, queryset): Сбрасываем имена и помечаем как новые | Implement the Python class `XrumerBaseRawAdmin` described below.
Class description:
Implement the XrumerBaseRawAdmin class.
Method signatures and docstrings:
- def ResetNames(self, request, queryset): Сбрасываем имена
- def ResetNamesAndNew(self, request, queryset): Сбрасываем имена и помечаем как новые
<|skeleton|>... | d2771bf04aa187dda6d468883a5a167237589369 | <|skeleton|>
class XrumerBaseRawAdmin:
def ResetNames(self, request, queryset):
"""Сбрасываем имена"""
<|body_0|>
def ResetNamesAndNew(self, request, queryset):
"""Сбрасываем имена и помечаем как новые"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class XrumerBaseRawAdmin:
def ResetNames(self, request, queryset):
"""Сбрасываем имена"""
processed = 0
for base in queryset:
base.ResetNames()
processed += 1
self.message_user(request, '%s reset.' % GetMessageBit(processed))
def ResetNamesAndNew(self, re... | the_stack_v2_python_sparse | doorsadmin/admin.py | cash2one/doorscenter | train | 0 | |
ea7efe3f2db967c8ca5e0efb5874d60d5c33f20b | [
"self.queue = [0] * k\nself.headIndex = 0\nself.count = 0\nself.capacity = k\nself.queueLock = Lock()",
"with self.queueLock:\n if self.count == self.capacity:\n return False\n self.queue[(self.headIndex + self.count) % self.capacity] = value\n self.count += 1\nreturn True"
] | <|body_start_0|>
self.queue = [0] * k
self.headIndex = 0
self.count = 0
self.capacity = k
self.queueLock = Lock()
<|end_body_0|>
<|body_start_1|>
with self.queueLock:
if self.count == self.capacity:
return False
self.queue[(self.he... | MyCircularQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyCircularQueue:
def __init__(self, k: int):
"""Initialize your data structure here. Set the size of the queue to be k."""
<|body_0|>
def enQueue(self, value: int) -> bool:
"""Insert an element into the circular queue. Return true if the operation is successful."""
... | stack_v2_sparse_classes_10k_train_006398 | 18,175 | no_license | [
{
"docstring": "Initialize your data structure here. Set the size of the queue to be k.",
"name": "__init__",
"signature": "def __init__(self, k: int)"
},
{
"docstring": "Insert an element into the circular queue. Return true if the operation is successful.",
"name": "enQueue",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_004643 | Implement the Python class `MyCircularQueue` described below.
Class description:
Implement the MyCircularQueue class.
Method signatures and docstrings:
- def __init__(self, k: int): Initialize your data structure here. Set the size of the queue to be k.
- def enQueue(self, value: int) -> bool: Insert an element into ... | Implement the Python class `MyCircularQueue` described below.
Class description:
Implement the MyCircularQueue class.
Method signatures and docstrings:
- def __init__(self, k: int): Initialize your data structure here. Set the size of the queue to be k.
- def enQueue(self, value: int) -> bool: Insert an element into ... | 035ef08434fa1ca781a6fb2f9eed3538b7d20c02 | <|skeleton|>
class MyCircularQueue:
def __init__(self, k: int):
"""Initialize your data structure here. Set the size of the queue to be k."""
<|body_0|>
def enQueue(self, value: int) -> bool:
"""Insert an element into the circular queue. Return true if the operation is successful."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyCircularQueue:
def __init__(self, k: int):
"""Initialize your data structure here. Set the size of the queue to be k."""
self.queue = [0] * k
self.headIndex = 0
self.count = 0
self.capacity = k
self.queueLock = Lock()
def enQueue(self, value: int) -> bool... | the_stack_v2_python_sparse | leetcode_python/Queue/design_circular_queue.py | yennanliu/CS_basics | train | 64 | |
b7bc715fd7b6460deea4fbf804552d2a1260175c | [
"self.bonding_mode = bonding_mode\nself.name = name\nself.slaves = slaves",
"if dictionary is None:\n return None\nbonding_mode = dictionary.get('bondingMode')\nname = dictionary.get('name')\nslaves = dictionary.get('slaves')\nreturn cls(bonding_mode, name, slaves)"
] | <|body_start_0|>
self.bonding_mode = bonding_mode
self.name = name
self.slaves = slaves
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
bonding_mode = dictionary.get('bondingMode')
name = dictionary.get('name')
slaves = dictionary.g... | Implementation of the 'CreateBondParameters' model. Specifies the parameters needed to create a bond. Attributes: bonding_mode (BondingModeEnum): Specifies the bonding mode to use for this bond. If not specified, this value will default to 'kActiveBackup'. 'kActiveBackup' indicates active backup bonding mode. 'k802_3ad... | CreateBondParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateBondParameters:
"""Implementation of the 'CreateBondParameters' model. Specifies the parameters needed to create a bond. Attributes: bonding_mode (BondingModeEnum): Specifies the bonding mode to use for this bond. If not specified, this value will default to 'kActiveBackup'. 'kActiveBackup'... | stack_v2_sparse_classes_10k_train_006399 | 2,083 | permissive | [
{
"docstring": "Constructor for the CreateBondParameters class",
"name": "__init__",
"signature": "def __init__(self, bonding_mode=None, name=None, slaves=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of t... | 2 | null | Implement the Python class `CreateBondParameters` described below.
Class description:
Implementation of the 'CreateBondParameters' model. Specifies the parameters needed to create a bond. Attributes: bonding_mode (BondingModeEnum): Specifies the bonding mode to use for this bond. If not specified, this value will defa... | Implement the Python class `CreateBondParameters` described below.
Class description:
Implementation of the 'CreateBondParameters' model. Specifies the parameters needed to create a bond. Attributes: bonding_mode (BondingModeEnum): Specifies the bonding mode to use for this bond. If not specified, this value will defa... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CreateBondParameters:
"""Implementation of the 'CreateBondParameters' model. Specifies the parameters needed to create a bond. Attributes: bonding_mode (BondingModeEnum): Specifies the bonding mode to use for this bond. If not specified, this value will default to 'kActiveBackup'. 'kActiveBackup'... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CreateBondParameters:
"""Implementation of the 'CreateBondParameters' model. Specifies the parameters needed to create a bond. Attributes: bonding_mode (BondingModeEnum): Specifies the bonding mode to use for this bond. If not specified, this value will default to 'kActiveBackup'. 'kActiveBackup' indicates ac... | the_stack_v2_python_sparse | cohesity_management_sdk/models/create_bond_parameters.py | cohesity/management-sdk-python | train | 24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.