blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
07a38fd2bfc24ed0d923d82cc913f499d588b27b | [
"self.cfg = cfg\nself.operations = []\nself.operations.append((I18N['INSTALL_ALL_MSG'], lambda cfg: list(map(lambda db: installDatabase(cfg, db), cfg['databases']))))\nfor i in range(len(cfg['databases'])):\n self.operations.append((I18N['INSTALL_MSG'] + cfg['databases'][i], lambda cfg, i=i: installDatabase(cfg,... | <|body_start_0|>
self.cfg = cfg
self.operations = []
self.operations.append((I18N['INSTALL_ALL_MSG'], lambda cfg: list(map(lambda db: installDatabase(cfg, db), cfg['databases']))))
for i in range(len(cfg['databases'])):
self.operations.append((I18N['INSTALL_MSG'] + cfg['datab... | Encapsulates the main menu in a Menu object. Slots: cfg - the configuration dictionary operations - a list of operations. Each operation is a 2-tuple of (operation name, operation functor) | Menu | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menu:
"""Encapsulates the main menu in a Menu object. Slots: cfg - the configuration dictionary operations - a list of operations. Each operation is a 2-tuple of (operation name, operation functor)"""
def __init__(self, cfg):
"""Creates a new Menu Object"""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_003600 | 11,443 | permissive | [
{
"docstring": "Creates a new Menu Object",
"name": "__init__",
"signature": "def __init__(self, cfg)"
},
{
"docstring": "Optionally clears the screen based upon config values, and then prints the menu.",
"name": "printMenu",
"signature": "def printMenu(self)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_009675 | Implement the Python class `Menu` described below.
Class description:
Encapsulates the main menu in a Menu object. Slots: cfg - the configuration dictionary operations - a list of operations. Each operation is a 2-tuple of (operation name, operation functor)
Method signatures and docstrings:
- def __init__(self, cfg)... | Implement the Python class `Menu` described below.
Class description:
Encapsulates the main menu in a Menu object. Slots: cfg - the configuration dictionary operations - a list of operations. Each operation is a 2-tuple of (operation name, operation functor)
Method signatures and docstrings:
- def __init__(self, cfg)... | 41c519f6cdef5a1c68b369e760781652ece7fec9 | <|skeleton|>
class Menu:
"""Encapsulates the main menu in a Menu object. Slots: cfg - the configuration dictionary operations - a list of operations. Each operation is a 2-tuple of (operation name, operation functor)"""
def __init__(self, cfg):
"""Creates a new Menu Object"""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Menu:
"""Encapsulates the main menu in a Menu object. Slots: cfg - the configuration dictionary operations - a list of operations. Each operation is a 2-tuple of (operation name, operation functor)"""
def __init__(self, cfg):
"""Creates a new Menu Object"""
self.cfg = cfg
self.ope... | the_stack_v2_python_sparse | data/sql/setup.py | anhstudios/swganh | train | 33 |
659efd91148603fed144815a63ec21ebb0e090de | [
"data: int = 122345\noutput: bool = True\nresult = adjacent(data)\nself.assertEqual(result, output)\ndata: int = 123789\noutput: bool = False\nresult = adjacent(data)\nself.assertEqual(result, output)",
"data: int = 111123\noutput: bool = True\nresult = not_decreasing(data)\nself.assertEqual(result, output)\ndata... | <|body_start_0|>
data: int = 122345
output: bool = True
result = adjacent(data)
self.assertEqual(result, output)
data: int = 123789
output: bool = False
result = adjacent(data)
self.assertEqual(result, output)
<|end_body_0|>
<|body_start_1|>
data:... | () | TestAoC04 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAoC04:
"""()"""
def test_adjacent(self):
"""()"""
<|body_0|>
def test_not_decreasing(self):
"""()"""
<|body_1|>
def test_strict_adjacent(self):
"""()"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
data: int = 122345
... | stack_v2_sparse_classes_36k_train_003601 | 1,768 | no_license | [
{
"docstring": "()",
"name": "test_adjacent",
"signature": "def test_adjacent(self)"
},
{
"docstring": "()",
"name": "test_not_decreasing",
"signature": "def test_not_decreasing(self)"
},
{
"docstring": "()",
"name": "test_strict_adjacent",
"signature": "def test_strict_a... | 3 | stack_v2_sparse_classes_30k_train_020449 | Implement the Python class `TestAoC04` described below.
Class description:
()
Method signatures and docstrings:
- def test_adjacent(self): ()
- def test_not_decreasing(self): ()
- def test_strict_adjacent(self): () | Implement the Python class `TestAoC04` described below.
Class description:
()
Method signatures and docstrings:
- def test_adjacent(self): ()
- def test_not_decreasing(self): ()
- def test_strict_adjacent(self): ()
<|skeleton|>
class TestAoC04:
"""()"""
def test_adjacent(self):
"""()"""
<|bo... | 4c49273b8f9846ccd2df54c2249a63bb4f8a4ddd | <|skeleton|>
class TestAoC04:
"""()"""
def test_adjacent(self):
"""()"""
<|body_0|>
def test_not_decreasing(self):
"""()"""
<|body_1|>
def test_strict_adjacent(self):
"""()"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAoC04:
"""()"""
def test_adjacent(self):
"""()"""
data: int = 122345
output: bool = True
result = adjacent(data)
self.assertEqual(result, output)
data: int = 123789
output: bool = False
result = adjacent(data)
self.assertEqual(re... | the_stack_v2_python_sparse | test_aoc_04.py | iveL91/Advent-of-Code-2019 | train | 0 |
671b07b2a96ca2c97db82e9acb52bc9cbb24f953 | [
"if num < 3:\n return False\nreturn 1162261467 % num == 0 and num > 2",
"import math\nif 3 ** round(math.log(num, 3)) == num:\n return True\nelse:\n return False"
] | <|body_start_0|>
if num < 3:
return False
return 1162261467 % num == 0 and num > 2
<|end_body_0|>
<|body_start_1|>
import math
if 3 ** round(math.log(num, 3)) == num:
return True
else:
return False
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfThree(self, num):
""":param num:int :return: bool"""
<|body_0|>
def isPowerOfThree(self, num):
""":param num:int :return: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if num < 3:
return False
return... | stack_v2_sparse_classes_36k_train_003602 | 813 | no_license | [
{
"docstring": ":param num:int :return: bool",
"name": "isPowerOfThree",
"signature": "def isPowerOfThree(self, num)"
},
{
"docstring": ":param num:int :return: bool",
"name": "isPowerOfThree",
"signature": "def isPowerOfThree(self, num)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfThree(self, num): :param num:int :return: bool
- def isPowerOfThree(self, num): :param num:int :return: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfThree(self, num): :param num:int :return: bool
- def isPowerOfThree(self, num): :param num:int :return: bool
<|skeleton|>
class Solution:
def isPowerOfThree(se... | 4f2802d4773eddd2a2e06e61c51463056886b730 | <|skeleton|>
class Solution:
def isPowerOfThree(self, num):
""":param num:int :return: bool"""
<|body_0|>
def isPowerOfThree(self, num):
""":param num:int :return: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPowerOfThree(self, num):
""":param num:int :return: bool"""
if num < 3:
return False
return 1162261467 % num == 0 and num > 2
def isPowerOfThree(self, num):
""":param num:int :return: bool"""
import math
if 3 ** round(math.log(nu... | the_stack_v2_python_sparse | leetcode/42_isPowerOfThree.py | Yara7L/python_algorithm | train | 0 | |
d2cc9af48a46838e0fdef45dd0decc63a0770982 | [
"if not nums:\n return []\nresults = set()\nfor i in range(len(nums) - 2):\n first = nums[i]\n t = target - first\n head = i + 1\n if head >= len(nums):\n break\n tail = len(nums) - 1\n while head < tail:\n current = nums[head] + nums[tail]\n if current > t:\n ta... | <|body_start_0|>
if not nums:
return []
results = set()
for i in range(len(nums) - 2):
first = nums[i]
t = target - first
head = i + 1
if head >= len(nums):
break
tail = len(nums) - 1
while head <... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums, target):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_003603 | 1,215 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]",
"name": "fourSum",
"signature": "def fourSum(self, nums, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013958 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums, target): :type nums: List[int] :rtype: List[List[int]]
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums, target): :type nums: List[int] :rtype: List[List[int]]
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]... | 675b94fa5da8d40f0ea79efe6d3ef1393221425f | <|skeleton|>
class Solution:
def threeSum(self, nums, target):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum(self, nums, target):
""":type nums: List[int] :rtype: List[List[int]]"""
if not nums:
return []
results = set()
for i in range(len(nums) - 2):
first = nums[i]
t = target - first
head = i + 1
if h... | the_stack_v2_python_sparse | 018_four_sum/four_sum.py | Web-Dev-Collaborative/Leetcode-JS-PY-MD | train | 0 | |
210fb917c2ab111e331499a860120ac911a1f75a | [
"self.N = prime\nself.g = 2\nself.k = 3\nself.server = server",
"out = queue.Queue()\ninp = queue.Queue()\nself.server.authenticate(email, A, out, inp)\nsalt, B = inp.get()\nif DEBUG:\n print('CLIENT: salt: ' + str(c1.asciitohex(salt)))\n print('CLIENT: B: ' + str(B))\nif A % self.N != 0:\n raise ValueEr... | <|body_start_0|>
self.N = prime
self.g = 2
self.k = 3
self.server = server
<|end_body_0|>
<|body_start_1|>
out = queue.Queue()
inp = queue.Queue()
self.server.authenticate(email, A, out, inp)
salt, B = inp.get()
if DEBUG:
print('CLIENT... | SRPClientA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SRPClientA:
def __init__(self, prime, server):
"""Initializes the class with a provided NIST prime and a server to communicate with. Accepts a malicious value for A to send to the server. Args: prime (int): The NIST prime used by both client and server server (SRPServer): The server to t... | stack_v2_sparse_classes_36k_train_003604 | 3,270 | no_license | [
{
"docstring": "Initializes the class with a provided NIST prime and a server to communicate with. Accepts a malicious value for A to send to the server. Args: prime (int): The NIST prime used by both client and server server (SRPServer): The server to talk to",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_train_017108 | Implement the Python class `SRPClientA` described below.
Class description:
Implement the SRPClientA class.
Method signatures and docstrings:
- def __init__(self, prime, server): Initializes the class with a provided NIST prime and a server to communicate with. Accepts a malicious value for A to send to the server. A... | Implement the Python class `SRPClientA` described below.
Class description:
Implement the SRPClientA class.
Method signatures and docstrings:
- def __init__(self, prime, server): Initializes the class with a provided NIST prime and a server to communicate with. Accepts a malicious value for A to send to the server. A... | 5119b857927d604a6e0ab074e5f000f3f2ac4ee1 | <|skeleton|>
class SRPClientA:
def __init__(self, prime, server):
"""Initializes the class with a provided NIST prime and a server to communicate with. Accepts a malicious value for A to send to the server. Args: prime (int): The NIST prime used by both client and server server (SRPServer): The server to t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SRPClientA:
def __init__(self, prime, server):
"""Initializes the class with a provided NIST prime and a server to communicate with. Accepts a malicious value for A to send to the server. Args: prime (int): The NIST prime used by both client and server server (SRPServer): The server to talk to"""
... | the_stack_v2_python_sparse | cryptopals-py/set5/c37.py | aasparks/cryptopals-py-rkt | train | 1 | |
e29d37f279733ea606033c869a9d1ee48b514618 | [
"total_value = price * quantity\nself.product.update({'name': name, 'type': product_type, 'available_qty': quantity, 'sell_order': [], 'purchase_order': [], 'profit_loss': 0, 'valuation_price': total_value, 'purchase_value': total_value, 'sell_value': 0})\nif self.product['type'].lower() == 'service':\n self.pro... | <|body_start_0|>
total_value = price * quantity
self.product.update({'name': name, 'type': product_type, 'available_qty': quantity, 'sell_order': [], 'purchase_order': [], 'profit_loss': 0, 'valuation_price': total_value, 'purchase_value': total_value, 'sell_value': 0})
if self.product['type'].l... | Class Handles all operation on Product | Product | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Product:
"""Class Handles all operation on Product"""
def __init__(self, name, product_type, quantity, price):
"""func :- Defines product name, type and quantity. params :- product Name -string params :- product Type - string params :- product Quantity - integer params :- product pri... | stack_v2_sparse_classes_36k_train_003605 | 4,417 | no_license | [
{
"docstring": "func :- Defines product name, type and quantity. params :- product Name -string params :- product Type - string params :- product Quantity - integer params :- product price - integer returns :- nothing.",
"name": "__init__",
"signature": "def __init__(self, name, product_type, quantity, ... | 3 | stack_v2_sparse_classes_30k_train_014347 | Implement the Python class `Product` described below.
Class description:
Class Handles all operation on Product
Method signatures and docstrings:
- def __init__(self, name, product_type, quantity, price): func :- Defines product name, type and quantity. params :- product Name -string params :- product Type - string p... | Implement the Python class `Product` described below.
Class description:
Class Handles all operation on Product
Method signatures and docstrings:
- def __init__(self, name, product_type, quantity, price): func :- Defines product name, type and quantity. params :- product Name -string params :- product Type - string p... | 08668c834bdb4aee3abafdedc9126bba7aa041b8 | <|skeleton|>
class Product:
"""Class Handles all operation on Product"""
def __init__(self, name, product_type, quantity, price):
"""func :- Defines product name, type and quantity. params :- product Name -string params :- product Type - string params :- product Quantity - integer params :- product pri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Product:
"""Class Handles all operation on Product"""
def __init__(self, name, product_type, quantity, price):
"""func :- Defines product name, type and quantity. params :- product Name -string params :- product Type - string params :- product Quantity - integer params :- product price - integer ... | the_stack_v2_python_sparse | productNew.py | maulikb-emipro/Python-Training | train | 0 |
e509b7b53ad9e5acaf716f8d481527db22f97b1e | [
"current_user = User.objects.get(pk=request.auth.user.id)\ntry:\n company = Company.objects.get(pk=request.data['company'], user=current_user)\nexcept Company.DoesNotExist as ex:\n return Response({'reason': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\nnote = CompanyNote()\nnote.author = current_user\nnote... | <|body_start_0|>
current_user = User.objects.get(pk=request.auth.user.id)
try:
company = Company.objects.get(pk=request.data['company'], user=current_user)
except Company.DoesNotExist as ex:
return Response({'reason': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)
... | CompanyNoteView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompanyNoteView:
def create(self, request):
"""Handle POST requests to create new company note"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET requests for a specific company note"""
<|body_1|>
def list(self, request):
"""Handle... | stack_v2_sparse_classes_36k_train_003606 | 3,708 | no_license | [
{
"docstring": "Handle POST requests to create new company note",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Handle GET requests for a specific company note",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
},
{
"docstrin... | 5 | stack_v2_sparse_classes_30k_train_010642 | Implement the Python class `CompanyNoteView` described below.
Class description:
Implement the CompanyNoteView class.
Method signatures and docstrings:
- def create(self, request): Handle POST requests to create new company note
- def retrieve(self, request, pk=None): Handle GET requests for a specific company note
-... | Implement the Python class `CompanyNoteView` described below.
Class description:
Implement the CompanyNoteView class.
Method signatures and docstrings:
- def create(self, request): Handle POST requests to create new company note
- def retrieve(self, request, pk=None): Handle GET requests for a specific company note
-... | 12cb34b9a290a8445e8baaa6c454dd386a01fe29 | <|skeleton|>
class CompanyNoteView:
def create(self, request):
"""Handle POST requests to create new company note"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET requests for a specific company note"""
<|body_1|>
def list(self, request):
"""Handle... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompanyNoteView:
def create(self, request):
"""Handle POST requests to create new company note"""
current_user = User.objects.get(pk=request.auth.user.id)
try:
company = Company.objects.get(pk=request.data['company'], user=current_user)
except Company.DoesNotExist a... | the_stack_v2_python_sparse | apptrakzapi/views/company_note.py | nswalters/AppTrakz-API | train | 0 | |
09222643100a3693261a4aa64611fff7bd981946 | [
"try:\n return Post.objects.get(id=id)\nexcept Post.DoesNotExist:\n raise Http404",
"postObject = self.get_object(id)\nresponse = self.serializer_class(postObject)\nreturn Response(response.data)",
"posts = self.get_object(id)\nposts.delete()\nreturn Response(status=status.HTTP_204_NO_CONTENT)"
] | <|body_start_0|>
try:
return Post.objects.get(id=id)
except Post.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
postObject = self.get_object(id)
response = self.serializer_class(postObject)
return Response(response.data)
<|end_body_1|>
<|bod... | This class is an API for geting newsfeed posts information. | PostViewDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostViewDetail:
"""This class is an API for geting newsfeed posts information."""
def get_object(self, id):
"""Get post by id. Args: id: id of post. Return: post object."""
<|body_0|>
def get(self, request, id=None, format=None):
"""Get single post object by id. ... | stack_v2_sparse_classes_36k_train_003607 | 17,464 | no_license | [
{
"docstring": "Get post by id. Args: id: id of post. Return: post object.",
"name": "get_object",
"signature": "def get_object(self, id)"
},
{
"docstring": "Get single post object by id. Args: request: Django Rest Framework request object. id: id of post. format: pattern for Web APIs. Return: S... | 3 | stack_v2_sparse_classes_30k_train_008041 | Implement the Python class `PostViewDetail` described below.
Class description:
This class is an API for geting newsfeed posts information.
Method signatures and docstrings:
- def get_object(self, id): Get post by id. Args: id: id of post. Return: post object.
- def get(self, request, id=None, format=None): Get singl... | Implement the Python class `PostViewDetail` described below.
Class description:
This class is an API for geting newsfeed posts information.
Method signatures and docstrings:
- def get_object(self, id): Get post by id. Args: id: id of post. Return: post object.
- def get(self, request, id=None, format=None): Get singl... | 1d01b8133669208cdd35d4aa61a41521ecd52720 | <|skeleton|>
class PostViewDetail:
"""This class is an API for geting newsfeed posts information."""
def get_object(self, id):
"""Get post by id. Args: id: id of post. Return: post object."""
<|body_0|>
def get(self, request, id=None, format=None):
"""Get single post object by id. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostViewDetail:
"""This class is an API for geting newsfeed posts information."""
def get_object(self, id):
"""Get post by id. Args: id: id of post. Return: post object."""
try:
return Post.objects.get(id=id)
except Post.DoesNotExist:
raise Http404
def... | the_stack_v2_python_sparse | newsfeed/views.py | whsatku/social | train | 10 |
a001bc8ff039637f1c41cf1d0d4b1381fc1f5945 | [
"self.__detailed_help = kwargs.pop('detailed_help', None)\nself.__args = args\nself.__kwargs = kwargs",
"name = self.__args[0]\nfor flag in parser.flag_args:\n if name in flag.option_strings:\n return flag\nreturn None",
"arg = parser.add_argument(*self.__args, **self.__kwargs)\nif self.__detailed_hel... | <|body_start_0|>
self.__detailed_help = kwargs.pop('detailed_help', None)
self.__args = args
self.__kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
name = self.__args[0]
for flag in parser.flag_args:
if name in flag.option_strings:
return flag
... | A class that allows you to save an argument configuration for reuse. | Argument | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Argument:
"""A class that allows you to save an argument configuration for reuse."""
def __init__(self, *args, **kwargs):
"""Creates the argument. Args: *args: The positional args to parser.add_argument. **kwargs: The keyword args to parser.add_argument."""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_003608 | 25,896 | permissive | [
{
"docstring": "Creates the argument. Args: *args: The positional args to parser.add_argument. **kwargs: The keyword args to parser.add_argument.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Returns the flag object in parser.",
"name": "__GetFla... | 5 | stack_v2_sparse_classes_30k_test_000267 | Implement the Python class `Argument` described below.
Class description:
A class that allows you to save an argument configuration for reuse.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Creates the argument. Args: *args: The positional args to parser.add_argument. **kwargs: The keyword a... | Implement the Python class `Argument` described below.
Class description:
A class that allows you to save an argument configuration for reuse.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Creates the argument. Args: *args: The positional args to parser.add_argument. **kwargs: The keyword a... | c98b58aeb0994e011df960163541e9379ae7ea06 | <|skeleton|>
class Argument:
"""A class that allows you to save an argument configuration for reuse."""
def __init__(self, *args, **kwargs):
"""Creates the argument. Args: *args: The positional args to parser.add_argument. **kwargs: The keyword args to parser.add_argument."""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Argument:
"""A class that allows you to save an argument configuration for reuse."""
def __init__(self, *args, **kwargs):
"""Creates the argument. Args: *args: The positional args to parser.add_argument. **kwargs: The keyword args to parser.add_argument."""
self.__detailed_help = kwargs.p... | the_stack_v2_python_sparse | google-cloud-sdk/.install/.backup/lib/googlecloudsdk/calliope/base.py | KaranToor/MA450 | train | 1 |
a1a6ecad3576c22de04821910bc99c8f0b31148d | [
"if len(numbers) <= 1:\n return None\nd = {}\nindex1 = -1\nindex2 = -1\nfor i in range(len(numbers)):\n if numbers[i] not in d:\n d[target - numbers[i]] = i\n else:\n index1 = d[numbers[i]]\n index2 = i\nif index1 < index2:\n return [index1 + 1, index2 + 1]\nelse:\n return [index... | <|body_start_0|>
if len(numbers) <= 1:
return None
d = {}
index1 = -1
index2 = -1
for i in range(len(numbers)):
if numbers[i] not in d:
d[target - numbers[i]] = i
else:
index1 = d[numbers[i]]
inde... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_003609 | 999 | no_license | [
{
"docstring": ":type numbers: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, numbers, target)"
},
{
"docstring": ":type numbers: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, numbers, ta... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :rtype: List[int]
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :rtype: List[int]
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :r... | bd8df12c0d4afd048cf1b58b04c27fa1f3622769 | <|skeleton|>
class Solution:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
if len(numbers) <= 1:
return None
d = {}
index1 = -1
index2 = -1
for i in range(len(numbers)):
if numbers[i] not in d:
... | the_stack_v2_python_sparse | 167_two_sum_II_input_array_is_sorted.py | aojugg/leetcode | train | 0 | |
ab87269cb25a751db5b14e4c1fe2914a25778318 | [
"self._clip_obs = clip_obs\nself._obs_shape = mdp_info.observation_space.shape\nself._obs_runstand = RunningStandardization(shape=self._obs_shape, alpha=alpha)\nself._add_save_attr(_clip_obs='primitive', _obs_shape='primitive', _obs_runstand='mushroom')",
"assert obs.shape == self._obs_shape, 'Values given to run... | <|body_start_0|>
self._clip_obs = clip_obs
self._obs_shape = mdp_info.observation_space.shape
self._obs_runstand = RunningStandardization(shape=self._obs_shape, alpha=alpha)
self._add_save_attr(_clip_obs='primitive', _obs_shape='primitive', _obs_runstand='mushroom')
<|end_body_0|>
<|bod... | Preprocess observations from the environment using a running standardization. | StandardizationPreprocessor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StandardizationPreprocessor:
"""Preprocess observations from the environment using a running standardization."""
def __init__(self, mdp_info, clip_obs=10.0, alpha=1e-32):
"""Constructor. Args: mdp_info (MDPInfo): information of the MDP; clip_obs (float, 10.): values to clip the norma... | stack_v2_sparse_classes_36k_train_003610 | 4,016 | permissive | [
{
"docstring": "Constructor. Args: mdp_info (MDPInfo): information of the MDP; clip_obs (float, 10.): values to clip the normalized observations; alpha (float, 1e-32): moving average catchup parameter for the normalization.",
"name": "__init__",
"signature": "def __init__(self, mdp_info, clip_obs=10.0, ... | 2 | stack_v2_sparse_classes_30k_train_015833 | Implement the Python class `StandardizationPreprocessor` described below.
Class description:
Preprocess observations from the environment using a running standardization.
Method signatures and docstrings:
- def __init__(self, mdp_info, clip_obs=10.0, alpha=1e-32): Constructor. Args: mdp_info (MDPInfo): information of... | Implement the Python class `StandardizationPreprocessor` described below.
Class description:
Preprocess observations from the environment using a running standardization.
Method signatures and docstrings:
- def __init__(self, mdp_info, clip_obs=10.0, alpha=1e-32): Constructor. Args: mdp_info (MDPInfo): information of... | 2decae31459a3481130afe1263bc0a5ba7954a99 | <|skeleton|>
class StandardizationPreprocessor:
"""Preprocess observations from the environment using a running standardization."""
def __init__(self, mdp_info, clip_obs=10.0, alpha=1e-32):
"""Constructor. Args: mdp_info (MDPInfo): information of the MDP; clip_obs (float, 10.): values to clip the norma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StandardizationPreprocessor:
"""Preprocess observations from the environment using a running standardization."""
def __init__(self, mdp_info, clip_obs=10.0, alpha=1e-32):
"""Constructor. Args: mdp_info (MDPInfo): information of the MDP; clip_obs (float, 10.): values to clip the normalized observa... | the_stack_v2_python_sparse | mushroom_rl/utils/preprocessors.py | MushroomRL/mushroom-rl | train | 477 |
40c3e9c5b05431090bdf1d9b5420c19236a8b429 | [
"super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=TIME_BETWEEN_UPDATES)\nself.session = async_get_clientsession(hass)\nself._camera_api = TrafikverketCamera(self.session, entry.data[CONF_API_KEY])\nself._location = entry.data[CONF_LOCATION]",
"camera_data: CameraInfo\nimage: bytes | None = None\ntry:\... | <|body_start_0|>
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=TIME_BETWEEN_UPDATES)
self.session = async_get_clientsession(hass)
self._camera_api = TrafikverketCamera(self.session, entry.data[CONF_API_KEY])
self._location = entry.data[CONF_LOCATION]
<|end_body_0|>
<|body... | A Trafikverket Data Update Coordinator. | TVDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TVDataUpdateCoordinator:
"""A Trafikverket Data Update Coordinator."""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialize the Trafikverket coordinator."""
<|body_0|>
async def _async_update_data(self) -> CameraData:
"""Fetch data f... | stack_v2_sparse_classes_36k_train_003611 | 2,648 | permissive | [
{
"docstring": "Initialize the Trafikverket coordinator.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None"
},
{
"docstring": "Fetch data from Trafikverket.",
"name": "_async_update_data",
"signature": "async def _async_update_data(se... | 2 | null | Implement the Python class `TVDataUpdateCoordinator` described below.
Class description:
A Trafikverket Data Update Coordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: Initialize the Trafikverket coordinator.
- async def _async_update_data(self) -> Cam... | Implement the Python class `TVDataUpdateCoordinator` described below.
Class description:
A Trafikverket Data Update Coordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: Initialize the Trafikverket coordinator.
- async def _async_update_data(self) -> Cam... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class TVDataUpdateCoordinator:
"""A Trafikverket Data Update Coordinator."""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialize the Trafikverket coordinator."""
<|body_0|>
async def _async_update_data(self) -> CameraData:
"""Fetch data f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TVDataUpdateCoordinator:
"""A Trafikverket Data Update Coordinator."""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialize the Trafikverket coordinator."""
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=TIME_BETWEEN_UPDATES)
self.sessio... | the_stack_v2_python_sparse | homeassistant/components/trafikverket_camera/coordinator.py | home-assistant/core | train | 35,501 |
c6ecad7c9bc715608d3d6bc8a4637b1614f45874 | [
"def f(n, m):\n if n == 0:\n return 0\n x = f(n - 1, m)\n return (m + x) % n\nreturn f(n, m)",
"f = 0\nfor i in range(2, n + 1):\n f = (m + f) % i\nreturn f"
] | <|body_start_0|>
def f(n, m):
if n == 0:
return 0
x = f(n - 1, m)
return (m + x) % n
return f(n, m)
<|end_body_0|>
<|body_start_1|>
f = 0
for i in range(2, n + 1):
f = (m + f) % i
return f
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lastRemaining(self, n: int, m: int) -> int:
"""题目可以描述为:给定一个长度为 n 的序列,每次向后数 m 个元素并删除, 那么最终留下的是第几个元素? 如果我们知道对于一个长度 n-1的序列,留下的是第几个元素,那么我们就 可以由此计算出长度为 n 的序列的答案。 算法: 首先,长度为 n 的序列会先删除第 m%n 个元素,然后剩下一个长度为 n-1 的序列。那么我们可以递归的求解 f(n-1, m),就可以知道对于剩下的 n-1 个 元素,最终会留下第几个元素,我们设答案为 x = f(n-1... | stack_v2_sparse_classes_36k_train_003612 | 2,799 | no_license | [
{
"docstring": "题目可以描述为:给定一个长度为 n 的序列,每次向后数 m 个元素并删除, 那么最终留下的是第几个元素? 如果我们知道对于一个长度 n-1的序列,留下的是第几个元素,那么我们就 可以由此计算出长度为 n 的序列的答案。 算法: 首先,长度为 n 的序列会先删除第 m%n 个元素,然后剩下一个长度为 n-1 的序列。那么我们可以递归的求解 f(n-1, m),就可以知道对于剩下的 n-1 个 元素,最终会留下第几个元素,我们设答案为 x = f(n-1, m) 由于我们删除了第 m%n 个元素,将序列的长度变为 n-1,当我们知道了 f(n-1, m) 对应的答案 x 之后,我们也就可以... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lastRemaining(self, n: int, m: int) -> int: 题目可以描述为:给定一个长度为 n 的序列,每次向后数 m 个元素并删除, 那么最终留下的是第几个元素? 如果我们知道对于一个长度 n-1的序列,留下的是第几个元素,那么我们就 可以由此计算出长度为 n 的序列的答案。 算法: 首先,长度为 n 的序列会先删除... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lastRemaining(self, n: int, m: int) -> int: 题目可以描述为:给定一个长度为 n 的序列,每次向后数 m 个元素并删除, 那么最终留下的是第几个元素? 如果我们知道对于一个长度 n-1的序列,留下的是第几个元素,那么我们就 可以由此计算出长度为 n 的序列的答案。 算法: 首先,长度为 n 的序列会先删除... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def lastRemaining(self, n: int, m: int) -> int:
"""题目可以描述为:给定一个长度为 n 的序列,每次向后数 m 个元素并删除, 那么最终留下的是第几个元素? 如果我们知道对于一个长度 n-1的序列,留下的是第几个元素,那么我们就 可以由此计算出长度为 n 的序列的答案。 算法: 首先,长度为 n 的序列会先删除第 m%n 个元素,然后剩下一个长度为 n-1 的序列。那么我们可以递归的求解 f(n-1, m),就可以知道对于剩下的 n-1 个 元素,最终会留下第几个元素,我们设答案为 x = f(n-1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lastRemaining(self, n: int, m: int) -> int:
"""题目可以描述为:给定一个长度为 n 的序列,每次向后数 m 个元素并删除, 那么最终留下的是第几个元素? 如果我们知道对于一个长度 n-1的序列,留下的是第几个元素,那么我们就 可以由此计算出长度为 n 的序列的答案。 算法: 首先,长度为 n 的序列会先删除第 m%n 个元素,然后剩下一个长度为 n-1 的序列。那么我们可以递归的求解 f(n-1, m),就可以知道对于剩下的 n-1 个 元素,最终会留下第几个元素,我们设答案为 x = f(n-1, m) 由于我们删除了第 ... | the_stack_v2_python_sparse | 剑指offer/PythonVersion/62_圆圈中最后剩下的数字.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
039a02876a53822555a92d2e6769794782ed609d | [
"value = self.initial.get(field_name, field.initial)\nif callable(value) and (not issubclass(value, CriterionEvaluator)):\n value = value()\nreturn value",
"data = super().clean()\nhas_required_action = bool(data.get('required_action'))\nhas_stake = bool(data.get('required_action_stake'))\nif any([has_required... | <|body_start_0|>
value = self.initial.get(field_name, field.initial)
if callable(value) and (not issubclass(value, CriterionEvaluator)):
value = value()
return value
<|end_body_0|>
<|body_start_1|>
data = super().clean()
has_required_action = bool(data.get('required_... | CriterionAdminForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CriterionAdminForm:
def get_initial_for_field(self, field, field_name):
"""Prevent Evaluator choice to be instanciated. In the legacy's version of this function, callable values are, well, called. But since we have a custom field that should return `CriterionEvaluator` subclasses, we don... | stack_v2_sparse_classes_36k_train_003613 | 4,031 | permissive | [
{
"docstring": "Prevent Evaluator choice to be instanciated. In the legacy's version of this function, callable values are, well, called. But since we have a custom field that should return `CriterionEvaluator` subclasses, we don't want the form to actually instanciate those classes.",
"name": "get_initial_... | 2 | stack_v2_sparse_classes_30k_train_002225 | Implement the Python class `CriterionAdminForm` described below.
Class description:
Implement the CriterionAdminForm class.
Method signatures and docstrings:
- def get_initial_for_field(self, field, field_name): Prevent Evaluator choice to be instanciated. In the legacy's version of this function, callable values are... | Implement the Python class `CriterionAdminForm` described below.
Class description:
Implement the CriterionAdminForm class.
Method signatures and docstrings:
- def get_initial_for_field(self, field, field_name): Prevent Evaluator choice to be instanciated. In the legacy's version of this function, callable values are... | 3a08f780e149e900c9031f47e5e0aa983707e384 | <|skeleton|>
class CriterionAdminForm:
def get_initial_for_field(self, field, field_name):
"""Prevent Evaluator choice to be instanciated. In the legacy's version of this function, callable values are, well, called. But since we have a custom field that should return `CriterionEvaluator` subclasses, we don... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CriterionAdminForm:
def get_initial_for_field(self, field, field_name):
"""Prevent Evaluator choice to be instanciated. In the legacy's version of this function, callable values are, well, called. But since we have a custom field that should return `CriterionEvaluator` subclasses, we don't want the fo... | the_stack_v2_python_sparse | envergo/moulinette/admin.py | MTES-MCT/envergo | train | 3 | |
435b2f192cd22e0af748734c701b465bcc46ee9f | [
"agent = request.user.userinfo.agent\ndata = {'qs_token': agent.qs_token, 'qs_token_secret': agent.qs_token_secret, 'qs_api_timeout': agent.qs_api_timeout}\nreturn Response({'status': 200, 'msg': '获取成功', 'data': data})",
"agent = request.user.userinfo.agent\napiobj = serializers.SetAPISerializers(instance=agent, ... | <|body_start_0|>
agent = request.user.userinfo.agent
data = {'qs_token': agent.qs_token, 'qs_token_secret': agent.qs_token_secret, 'qs_api_timeout': agent.qs_api_timeout}
return Response({'status': 200, 'msg': '获取成功', 'data': data})
<|end_body_0|>
<|body_start_1|>
agent = request.user.u... | API接口信息设置 | SetApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetApi:
"""API接口信息设置"""
def get(self, request):
"""获取API接口数据"""
<|body_0|>
def put(self, request):
"""修改接口信息设置 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
agent = request.user.userinfo.agent
data = {'qs_token... | stack_v2_sparse_classes_36k_train_003614 | 32,690 | no_license | [
{
"docstring": "获取API接口数据",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "修改接口信息设置 :param request: :return:",
"name": "put",
"signature": "def put(self, request)"
}
] | 2 | null | Implement the Python class `SetApi` described below.
Class description:
API接口信息设置
Method signatures and docstrings:
- def get(self, request): 获取API接口数据
- def put(self, request): 修改接口信息设置 :param request: :return: | Implement the Python class `SetApi` described below.
Class description:
API接口信息设置
Method signatures and docstrings:
- def get(self, request): 获取API接口数据
- def put(self, request): 修改接口信息设置 :param request: :return:
<|skeleton|>
class SetApi:
"""API接口信息设置"""
def get(self, request):
"""获取API接口数据"""
... | d6e025d7e9d9e3aecfd399c77f376130edd8a2df | <|skeleton|>
class SetApi:
"""API接口信息设置"""
def get(self, request):
"""获取API接口数据"""
<|body_0|>
def put(self, request):
"""修改接口信息设置 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SetApi:
"""API接口信息设置"""
def get(self, request):
"""获取API接口数据"""
agent = request.user.userinfo.agent
data = {'qs_token': agent.qs_token, 'qs_token_secret': agent.qs_token_secret, 'qs_api_timeout': agent.qs_api_timeout}
return Response({'status': 200, 'msg': '获取成功', 'data': ... | the_stack_v2_python_sparse | soc_system/views/set_views.py | sundw2015/841 | train | 4 |
371179e6514b54357ee195df91e5f463c8224baf | [
"from __builtin__ import xrange\nmmin = 0\ntt = 0\nmmax = float('-inf')\nfor i in xrange(len(nums)):\n tt += nums[i]\n mmax = max(mmax, tt - mmin)\n mmin = min(mmin, tt)\nreturn mmax",
"maxsum = float('-inf')\nminsum = 0\nlocalSum = 0\nfor n in nums:\n localSum += n\n maxsum = max(maxsum, localSum ... | <|body_start_0|>
from __builtin__ import xrange
mmin = 0
tt = 0
mmax = float('-inf')
for i in xrange(len(nums)):
tt += nums[i]
mmax = max(mmax, tt - mmin)
mmin = min(mmin, tt)
return mmax
<|end_body_0|>
<|body_start_1|>
maxsum ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int 連續累加概念。 將最小的複數減去 其後的便是連續最大和。 注意! 仍要紀錄最大值! 因為即使和都是正數 仍有最大和的正數!"""
<|body_0|>
def rewrite(self, nums):
""":type nums: List[int] :rtype: int 連續累加概念。 將最小的複數減去 其後的便是連續最大和。 注意! 仍要紀錄最大值! 因為即使和都是正數 仍... | stack_v2_sparse_classes_36k_train_003615 | 1,825 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int 連續累加概念。 將最小的複數減去 其後的便是連續最大和。 注意! 仍要紀錄最大值! 因為即使和都是正數 仍有最大和的正數!",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int 連續累加概念。 將最小的複數減去 其後的便是連續最大和。 注意! 仍要紀錄最大值! 因為即使和都是正數 仍有最大和的正數!",... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int 連續累加概念。 將最小的複數減去 其後的便是連續最大和。 注意! 仍要紀錄最大值! 因為即使和都是正數 仍有最大和的正數!
- def rewrite(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 maxSubArray(self, nums): :type nums: List[int] :rtype: int 連續累加概念。 將最小的複數減去 其後的便是連續最大和。 注意! 仍要紀錄最大值! 因為即使和都是正數 仍有最大和的正數!
- def rewrite(self, nums): :type nums: List[int] :rty... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int 連續累加概念。 將最小的複數減去 其後的便是連續最大和。 注意! 仍要紀錄最大值! 因為即使和都是正數 仍有最大和的正數!"""
<|body_0|>
def rewrite(self, nums):
""":type nums: List[int] :rtype: int 連續累加概念。 將最小的複數減去 其後的便是連續最大和。 注意! 仍要紀錄最大值! 因為即使和都是正數 仍... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int 連續累加概念。 將最小的複數減去 其後的便是連續最大和。 注意! 仍要紀錄最大值! 因為即使和都是正數 仍有最大和的正數!"""
from __builtin__ import xrange
mmin = 0
tt = 0
mmax = float('-inf')
for i in xrange(len(nums)):
tt += nums[i]... | the_stack_v2_python_sparse | co_fb/53_Maximum_Subarray.py | vsdrun/lc_public | train | 6 | |
d256efe468435e4379bee6afbfaa693f587e717c | [
"data = json.loads(self.load_content(url))\nif type(data) is list:\n data = [self._flatten_dict(x) for x in data]\n return [json_normalize(data)]\nelse:\n return [json_normalize(self._flatten_dict(data))]",
"out = {}\n\ndef flatten(x, name=''):\n if type(x) is dict:\n for a in x:\n f... | <|body_start_0|>
data = json.loads(self.load_content(url))
if type(data) is list:
data = [self._flatten_dict(x) for x in data]
return [json_normalize(data)]
else:
return [json_normalize(self._flatten_dict(data))]
<|end_body_0|>
<|body_start_1|>
out = ... | JSONParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONParser:
def get_all(self, url: str) -> typing.List[pd.DataFrame]:
"""Parses json and returns result Params: - url: (str) Returns: - result: (list)"""
<|body_0|>
def _flatten_dict(d: dict) -> typing.Dict:
"""Flattens a dictionary and returns the flattented dict Pa... | stack_v2_sparse_classes_36k_train_003616 | 1,327 | permissive | [
{
"docstring": "Parses json and returns result Params: - url: (str) Returns: - result: (list)",
"name": "get_all",
"signature": "def get_all(self, url: str) -> typing.List[pd.DataFrame]"
},
{
"docstring": "Flattens a dictionary and returns the flattented dict Params: - d: (dict) Dictionary to be... | 2 | null | Implement the Python class `JSONParser` described below.
Class description:
Implement the JSONParser class.
Method signatures and docstrings:
- def get_all(self, url: str) -> typing.List[pd.DataFrame]: Parses json and returns result Params: - url: (str) Returns: - result: (list)
- def _flatten_dict(d: dict) -> typing... | Implement the Python class `JSONParser` described below.
Class description:
Implement the JSONParser class.
Method signatures and docstrings:
- def get_all(self, url: str) -> typing.List[pd.DataFrame]: Parses json and returns result Params: - url: (str) Returns: - result: (list)
- def _flatten_dict(d: dict) -> typing... | c00f950a6e299457b486ea9ca25a1c70960f373b | <|skeleton|>
class JSONParser:
def get_all(self, url: str) -> typing.List[pd.DataFrame]:
"""Parses json and returns result Params: - url: (str) Returns: - result: (list)"""
<|body_0|>
def _flatten_dict(d: dict) -> typing.Dict:
"""Flattens a dictionary and returns the flattented dict Pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JSONParser:
def get_all(self, url: str) -> typing.List[pd.DataFrame]:
"""Parses json and returns result Params: - url: (str) Returns: - result: (list)"""
data = json.loads(self.load_content(url))
if type(data) is list:
data = [self._flatten_dict(x) for x in data]
... | the_stack_v2_python_sparse | datamart/materializers/parsers/json_parser.py | usc-isi-i2/datamart | train | 7 | |
d3d0422bbd5eb2937afc6c090eab49d4c8170f69 | [
"item = super().transform_record(pid, record, links_factory=links_factory, **kwargs)\nfilter_circulation(item)\nreturn item",
"hit = super().transform_search_hit(pid, record_hit, links_factory=links_factory, **kwargs)\nfilter_circulation(hit)\nreturn hit"
] | <|body_start_0|>
item = super().transform_record(pid, record, links_factory=links_factory, **kwargs)
filter_circulation(item)
return item
<|end_body_0|>
<|body_start_1|>
hit = super().transform_search_hit(pid, record_hit, links_factory=links_factory, **kwargs)
filter_circulation... | Serialize and filter item circulation status. | ItemCSVSerializer | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemCSVSerializer:
"""Serialize and filter item circulation status."""
def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
<|body_0|>
def transform_search_hit(self, pid, record_hit, links_fact... | stack_v2_sparse_classes_36k_train_003617 | 2,583 | permissive | [
{
"docstring": "Transform record into an intermediate representation.",
"name": "transform_record",
"signature": "def transform_record(self, pid, record, links_factory=None, **kwargs)"
},
{
"docstring": "Transform search result hit into an intermediate representation.",
"name": "transform_se... | 2 | null | Implement the Python class `ItemCSVSerializer` described below.
Class description:
Serialize and filter item circulation status.
Method signatures and docstrings:
- def transform_record(self, pid, record, links_factory=None, **kwargs): Transform record into an intermediate representation.
- def transform_search_hit(s... | Implement the Python class `ItemCSVSerializer` described below.
Class description:
Serialize and filter item circulation status.
Method signatures and docstrings:
- def transform_record(self, pid, record, links_factory=None, **kwargs): Transform record into an intermediate representation.
- def transform_search_hit(s... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class ItemCSVSerializer:
"""Serialize and filter item circulation status."""
def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
<|body_0|>
def transform_search_hit(self, pid, record_hit, links_fact... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItemCSVSerializer:
"""Serialize and filter item circulation status."""
def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
item = super().transform_record(pid, record, links_factory=links_factory, **kwargs)
... | the_stack_v2_python_sparse | invenio_app_ils/items/serializers/item.py | inveniosoftware/invenio-app-ils | train | 64 |
0a78dbd276f421b761245e918da2c394cde1c727 | [
"q = Q()\nfor field in search_fields:\n kwargs = {field: search_key}\n q = q | Q(**kwargs)\nreturn q",
"q = Q()\nif search:\n searches = search.split()\n for search_key in searches:\n q = q & self.q_for_search_field(search_key, search_fields)\nreturn q",
"if not search_fields:\n search_fie... | <|body_start_0|>
q = Q()
for field in search_fields:
kwargs = {field: search_key}
q = q | Q(**kwargs)
return q
<|end_body_0|>
<|body_start_1|>
q = Q()
if search:
searches = search.split()
for search_key in searches:
... | This will be subclassed by both the Object Manager and the QuerySet. By doing it this way, you can chain these functions, along with filter(). A simpler approach would define these in MyClassManager(models.Manager), but won't let you chain them, as the result of each is a QuerySet, not a Manager. See http://stackoverfl... | SearchMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchMixin:
"""This will be subclassed by both the Object Manager and the QuerySet. By doing it this way, you can chain these functions, along with filter(). A simpler approach would define these in MyClassManager(models.Manager), but won't let you chain them, as the result of each is a QuerySet... | stack_v2_sparse_classes_36k_train_003618 | 12,516 | permissive | [
{
"docstring": "Given a search key from the search text, return the Q object which you can filter on, to show only objects containing this key.",
"name": "q_for_search_field",
"signature": "def q_for_search_field(self, search_key, search_fields)"
},
{
"docstring": "Given the text from the search... | 3 | null | Implement the Python class `SearchMixin` described below.
Class description:
This will be subclassed by both the Object Manager and the QuerySet. By doing it this way, you can chain these functions, along with filter(). A simpler approach would define these in MyClassManager(models.Manager), but won't let you chain th... | Implement the Python class `SearchMixin` described below.
Class description:
This will be subclassed by both the Object Manager and the QuerySet. By doing it this way, you can chain these functions, along with filter(). A simpler approach would define these in MyClassManager(models.Manager), but won't let you chain th... | 3d3f5a53efe32c721c34d7e48267328a4e9e8402 | <|skeleton|>
class SearchMixin:
"""This will be subclassed by both the Object Manager and the QuerySet. By doing it this way, you can chain these functions, along with filter(). A simpler approach would define these in MyClassManager(models.Manager), but won't let you chain them, as the result of each is a QuerySet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchMixin:
"""This will be subclassed by both the Object Manager and the QuerySet. By doing it this way, you can chain these functions, along with filter(). A simpler approach would define these in MyClassManager(models.Manager), but won't let you chain them, as the result of each is a QuerySet, not a Manag... | the_stack_v2_python_sparse | draalcore/models/base_manager.py | jojanper/draalcore | train | 1 |
bd57c8c3a2954ec8ce319dc67205c2a7e27456fb | [
"result = factual_client.resolve(name='primanti brothers', town='pittsburgh', state='PA', latitude=40.45, longitude=-79.98).get_resolved_result()\nself.assertIsNotNone(result)\nself.assertEquals(result['name'], 'Primanti Brothers')\nself.assertEquals(result['postcode'], '15222')\nresult = factual_client.resolve(nam... | <|body_start_0|>
result = factual_client.resolve(name='primanti brothers', town='pittsburgh', state='PA', latitude=40.45, longitude=-79.98).get_resolved_result()
self.assertIsNotNone(result)
self.assertEquals(result['name'], 'Primanti Brothers')
self.assertEquals(result['postcode'], '152... | FactualResolveTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactualResolveTest:
def test_successful_request(self):
"""Tests response from a few Resolve API calls known to work"""
<|body_0|>
def test_unsuccessful_request(self):
"""Tests response from a few Resolve API calls known to not work"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_003619 | 18,595 | no_license | [
{
"docstring": "Tests response from a few Resolve API calls known to work",
"name": "test_successful_request",
"signature": "def test_successful_request(self)"
},
{
"docstring": "Tests response from a few Resolve API calls known to not work",
"name": "test_unsuccessful_request",
"signatu... | 2 | stack_v2_sparse_classes_30k_val_000870 | Implement the Python class `FactualResolveTest` described below.
Class description:
Implement the FactualResolveTest class.
Method signatures and docstrings:
- def test_successful_request(self): Tests response from a few Resolve API calls known to work
- def test_unsuccessful_request(self): Tests response from a few ... | Implement the Python class `FactualResolveTest` described below.
Class description:
Implement the FactualResolveTest class.
Method signatures and docstrings:
- def test_successful_request(self): Tests response from a few Resolve API calls known to work
- def test_unsuccessful_request(self): Tests response from a few ... | 3ed85e856a026001a1d91d09d31d944c64704824 | <|skeleton|>
class FactualResolveTest:
def test_successful_request(self):
"""Tests response from a few Resolve API calls known to work"""
<|body_0|>
def test_unsuccessful_request(self):
"""Tests response from a few Resolve API calls known to not work"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FactualResolveTest:
def test_successful_request(self):
"""Tests response from a few Resolve API calls known to work"""
result = factual_client.resolve(name='primanti brothers', town='pittsburgh', state='PA', latitude=40.45, longitude=-79.98).get_resolved_result()
self.assertIsNotNone(r... | the_stack_v2_python_sparse | scenable/outsourcing/apitools/tests.py | gregarious/betasite | train | 0 | |
0b1c91fd509992b40aea3ca0efb760f960c52cb3 | [
"super().__init__(mpg, vin)\nself.__length = length\nself.__num_rooms = num_rooms",
"spacing = ' '\ndescript = 'length(feet):' + format(self.__length, '>3') + spacing + 'rooms:' + format(self.__num_rooms, '>2') + spacing + Vehicle.getDescription(self)\nreturn descript"
] | <|body_start_0|>
super().__init__(mpg, vin)
self.__length = length
self.__num_rooms = num_rooms
<|end_body_0|>
<|body_start_1|>
spacing = ' '
descript = 'length(feet):' + format(self.__length, '>3') + spacing + 'rooms:' + format(self.__num_rooms, '>2') + spacing + Vehicle.getD... | This class is a subtype of the Vehicle class. Contains additional attributes length and num of rooms storage capacity. Supports polymorphic behavior of method getDescription. | Truck | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Truck:
"""This class is a subtype of the Vehicle class. Contains additional attributes length and num of rooms storage capacity. Supports polymorphic behavior of method getDescription."""
def __init__(self, mpg, length, num_rooms, vin):
"""Initializes with mpg, length, num_rooms, vin... | stack_v2_sparse_classes_36k_train_003620 | 918 | no_license | [
{
"docstring": "Initializes with mpg, length, num_rooms, vin.",
"name": "__init__",
"signature": "def __init__(self, mpg, length, num_rooms, vin)"
},
{
"docstring": "Returns complete description of truck.",
"name": "getDescription",
"signature": "def getDescription(self)"
}
] | 2 | null | Implement the Python class `Truck` described below.
Class description:
This class is a subtype of the Vehicle class. Contains additional attributes length and num of rooms storage capacity. Supports polymorphic behavior of method getDescription.
Method signatures and docstrings:
- def __init__(self, mpg, length, num_... | Implement the Python class `Truck` described below.
Class description:
This class is a subtype of the Vehicle class. Contains additional attributes length and num of rooms storage capacity. Supports polymorphic behavior of method getDescription.
Method signatures and docstrings:
- def __init__(self, mpg, length, num_... | 38c2cecae00dcb238808aa0a6f92cf4be36f001b | <|skeleton|>
class Truck:
"""This class is a subtype of the Vehicle class. Contains additional attributes length and num of rooms storage capacity. Supports polymorphic behavior of method getDescription."""
def __init__(self, mpg, length, num_rooms, vin):
"""Initializes with mpg, length, num_rooms, vin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Truck:
"""This class is a subtype of the Vehicle class. Contains additional attributes length and num of rooms storage capacity. Supports polymorphic behavior of method getDescription."""
def __init__(self, mpg, length, num_rooms, vin):
"""Initializes with mpg, length, num_rooms, vin."""
... | the_stack_v2_python_sparse | vehicle reservation/truck.py | sumanes4u/Anaconda-Projects | train | 0 |
41dbaa4784397caab500635b32d3fb139f83c1b6 | [
"root_copy = root\nself.result = []\n\ndef visit(root):\n if root.left:\n visit(root.left)\n self.result.append(root.val)\n if root.right:\n visit(root.right)\n\ndef change(root):\n if root.left:\n change(root.left)\n root.val = self.result[self.start]\n self.start += 1\n i... | <|body_start_0|>
root_copy = root
self.result = []
def visit(root):
if root.left:
visit(root.left)
self.result.append(root.val)
if root.right:
visit(root.right)
def change(root):
if root.left:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 215ms"""
<|body_0|>
def recoverTree_1(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place inst... | stack_v2_sparse_classes_36k_train_003621 | 3,724 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 215ms",
"name": "recoverTree",
"signature": "def recoverTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 125ms",
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recoverTree(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 215ms
- def recoverTree_1(self, root): :type root: TreeNode :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recoverTree(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 215ms
- def recoverTree_1(self, root): :type root: TreeNode :... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 215ms"""
<|body_0|>
def recoverTree_1(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place inst... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. 215ms"""
root_copy = root
self.result = []
def visit(root):
if root.left:
visit(root.left)
self.result.appe... | the_stack_v2_python_sparse | RecoverBinarySearchTree_HARD_99.py | 953250587/leetcode-python | train | 2 | |
68b3da295bb8e119b85a1856a60d04612e630295 | [
"if x < 0:\n return False\ndigit = 1\nwhile x / digit >= 10:\n digit *= 10\nwhile x != 0:\n left = x / digit\n right = x % 10\n if left != right:\n return False\n x = x % digit / 10\n digit /= 100\nreturn True",
"if x < 0:\n return False\noriginal_x = x\nreversed = 0\nwhile x > 0:\n... | <|body_start_0|>
if x < 0:
return False
digit = 1
while x / digit >= 10:
digit *= 10
while x != 0:
left = x / digit
right = x % 10
if left != right:
return False
x = x % digit / 10
digit /... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
<|body_0|>
def isPalindrome1(self, x):
""":type x: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x < 0:
return False
digit = 1
whi... | stack_v2_sparse_classes_36k_train_003622 | 1,275 | no_license | [
{
"docstring": ":type x: int :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, x)"
},
{
"docstring": ":type x: int :rtype: bool",
"name": "isPalindrome1",
"signature": "def isPalindrome1(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001082 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x): :type x: int :rtype: bool
- def isPalindrome1(self, x): :type x: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x): :type x: int :rtype: bool
- def isPalindrome1(self, x): :type x: int :rtype: bool
<|skeleton|>
class Solution:
def isPalindrome(self, x):
... | eaeeb9ad2d8cf2a60517cd86f42b30678b5ad2f8 | <|skeleton|>
class Solution:
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
<|body_0|>
def isPalindrome1(self, x):
""":type x: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
if x < 0:
return False
digit = 1
while x / digit >= 10:
digit *= 10
while x != 0:
left = x / digit
right = x % 10
if left != right:
... | the_stack_v2_python_sparse | Python/9. Palindrome Number.py | maiwen/LeetCode | train | 0 | |
5f5f1bcec45a0c98deb62d8df1cb3a9b2adc02b2 | [
"self.dynamodb = boto3.client('dynamodb', region_name=region)\nself.table = table_name\nself.max_items = max_items\nself.worker_num = worker_num\nself.num_workers = num_workers\nif worker_num >= num_workers:\n raise ValueError('worker_num must be less than num_workers')",
"exclusive_start_key = None\ndone = Fa... | <|body_start_0|>
self.dynamodb = boto3.client('dynamodb', region_name=region)
self.table = table_name
self.max_items = max_items
self.worker_num = worker_num
self.num_workers = num_workers
if worker_num >= num_workers:
raise ValueError('worker_num must be less... | Adds lookup key to legacy items in the S3 index table. The lookup key is collection&experiment&channel&resolution. A global secondary index (GSI) will use the lookup key to allow finding all cuboids that belong to a particular channel via a DynamoDB query. An instance of this class may be used as one worker in a parall... | LookupKeyWriter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LookupKeyWriter:
"""Adds lookup key to legacy items in the S3 index table. The lookup key is collection&experiment&channel&resolution. A global secondary index (GSI) will use the lookup key to allow finding all cuboids that belong to a particular channel via a DynamoDB query. An instance of this ... | stack_v2_sparse_classes_36k_train_003623 | 9,145 | permissive | [
{
"docstring": "Constructor. If parallelizing, supply worker_num and num_workers. See the AWS documentation for parallel scan here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.ParallelScan Args: table_name (str): Name of Dynamo S3 index table to operate on. region (str): AWS ... | 4 | stack_v2_sparse_classes_30k_test_001116 | Implement the Python class `LookupKeyWriter` described below.
Class description:
Adds lookup key to legacy items in the S3 index table. The lookup key is collection&experiment&channel&resolution. A global secondary index (GSI) will use the lookup key to allow finding all cuboids that belong to a particular channel via... | Implement the Python class `LookupKeyWriter` described below.
Class description:
Adds lookup key to legacy items in the S3 index table. The lookup key is collection&experiment&channel&resolution. A global secondary index (GSI) will use the lookup key to allow finding all cuboids that belong to a particular channel via... | 44d41e2b7a7b961e55746e1a5527d5419a74c2ce | <|skeleton|>
class LookupKeyWriter:
"""Adds lookup key to legacy items in the S3 index table. The lookup key is collection&experiment&channel&resolution. A global secondary index (GSI) will use the lookup key to allow finding all cuboids that belong to a particular channel via a DynamoDB query. An instance of this ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LookupKeyWriter:
"""Adds lookup key to legacy items in the S3 index table. The lookup key is collection&experiment&channel&resolution. A global secondary index (GSI) will use the lookup key to allow finding all cuboids that belong to a particular channel via a DynamoDB query. An instance of this class may be ... | the_stack_v2_python_sparse | spdb/spatialdb/utils/add_lookup_keys_to_s3_index.py | jhuapl-boss/spdb | train | 6 |
ac5495659c703eaf21bbb892bd562988171ff67b | [
"super(RNN, self).__init__()\nself.output_size = output_size\nself.n_layers = n_layers\nself.hidden_dim = hidden_dim\nself.embedding = nn.Embedding(vocab_size, embedding_dim)\nself.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=dropout, batch_first=True)\nself.fc = nn.Linear(hidden_dim, output_size)\ns... | <|body_start_0|>
super(RNN, self).__init__()
self.output_size = output_size
self.n_layers = n_layers
self.hidden_dim = hidden_dim
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=dropout, batch_first... | RNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNN:
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary) :param output_size: The number of output dimension... | stack_v2_sparse_classes_36k_train_003624 | 11,384 | permissive | [
{
"docstring": "Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary) :param output_size: The number of output dimensions of the neural network :param embedding_dim: The size of embeddings, should you choose to use them :param hidd... | 3 | stack_v2_sparse_classes_30k_train_012976 | Implement the Python class `RNN` described below.
Class description:
Implement the RNN class.
Method signatures and docstrings:
- def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5): Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the ne... | Implement the Python class `RNN` described below.
Class description:
Implement the RNN class.
Method signatures and docstrings:
- def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5): Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the ne... | b9b54564f94aadfc3c71ff513da0f05ef85d22a8 | <|skeleton|>
class RNN:
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary) :param output_size: The number of output dimension... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNN:
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary) :param output_size: The number of output dimensions of the neura... | the_stack_v2_python_sparse | dl/pytorch/rnn/tv_script.py | xta0/Python-Playground | train | 0 | |
1e94021d38c5d2029e9155dcc343fd2a906882f4 | [
"if not self.is_visible(source, overrides):\n return\ntag = self.get_property('tag', source, overrides)\nshow_line = self.get_property('show_line', source, overrides)\nshow_points = self.get_property('show_points', source, overrides)\nshow_area = self.get_property('show_area', source, overrides)\nspacing = self.... | <|body_start_0|>
if not self.is_visible(source, overrides):
return
tag = self.get_property('tag', source, overrides)
show_line = self.get_property('show_line', source, overrides)
show_points = self.get_property('show_points', source, overrides)
show_area = self.get_pr... | Band glyph provides basic functionality to draw x-sorted data points as a filled band of varying thickness. To plot data as a line the 'show_line' property must be set to True. Similarly, to display individual points, the 'show_points' property must be set to True. If set to UNDEF, and line is enabled, the points are a... | Band | [
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Band:
"""Band glyph provides basic functionality to draw x-sorted data points as a filled band of varying thickness. To plot data as a line the 'show_line' property must be set to True. Similarly, to display individual points, the 'show_points' property must be set to True. If set to UNDEF, and l... | stack_v2_sparse_classes_36k_train_003625 | 8,734 | permissive | [
{
"docstring": "Uses given canvas to draw the glyph.",
"name": "draw",
"signature": "def draw(self, canvas, source=UNDEF, **overrides)"
},
{
"docstring": "Draws band area.",
"name": "_draw_area",
"signature": "def _draw_area(self, canvas, source, overrides, x_coords, y1_coords, y2_coords... | 4 | null | Implement the Python class `Band` described below.
Class description:
Band glyph provides basic functionality to draw x-sorted data points as a filled band of varying thickness. To plot data as a line the 'show_line' property must be set to True. Similarly, to display individual points, the 'show_points' property must... | Implement the Python class `Band` described below.
Class description:
Band glyph provides basic functionality to draw x-sorted data points as a filled band of varying thickness. To plot data as a line the 'show_line' property must be set to True. Similarly, to display individual points, the 'show_points' property must... | d59b1bc056f3037b7b7ab635b6deb41120612965 | <|skeleton|>
class Band:
"""Band glyph provides basic functionality to draw x-sorted data points as a filled band of varying thickness. To plot data as a line the 'show_line' property must be set to True. Similarly, to display individual points, the 'show_points' property must be set to True. If set to UNDEF, and l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Band:
"""Band glyph provides basic functionality to draw x-sorted data points as a filled band of varying thickness. To plot data as a line the 'show_line' property must be set to True. Similarly, to display individual points, the 'show_points' property must be set to True. If set to UNDEF, and line is enable... | the_stack_v2_python_sparse | pero/glyphs/band.py | xxao/pero | train | 31 |
1e174db90be2a847d657b207c5e3e078888b4b81 | [
"i = 0\nm = 0\nwhile i < len(words):\n j = i + 1\n while j < len(words):\n f = True\n for c in words[i]:\n if c in words[j]:\n f = False\n break\n if f:\n m = max(m, len(words[i]) * len(words[j]))\n j += 1\n i += 1\nreturn m",
... | <|body_start_0|>
i = 0
m = 0
while i < len(words):
j = i + 1
while j < len(words):
f = True
for c in words[i]:
if c in words[j]:
f = False
break
if f:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProduct1(self, words):
""":type words: List[str] :rtype: int"""
<|body_0|>
def maxProduct(self, words):
""":type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i = 0
m = 0
while i < len(... | stack_v2_sparse_classes_36k_train_003626 | 1,149 | no_license | [
{
"docstring": ":type words: List[str] :rtype: int",
"name": "maxProduct1",
"signature": "def maxProduct1(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: int",
"name": "maxProduct",
"signature": "def maxProduct(self, words)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct1(self, words): :type words: List[str] :rtype: int
- def maxProduct(self, words): :type words: List[str] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct1(self, words): :type words: List[str] :rtype: int
- def maxProduct(self, words): :type words: List[str] :rtype: int
<|skeleton|>
class Solution:
def maxProdu... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def maxProduct1(self, words):
""":type words: List[str] :rtype: int"""
<|body_0|>
def maxProduct(self, words):
""":type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProduct1(self, words):
""":type words: List[str] :rtype: int"""
i = 0
m = 0
while i < len(words):
j = i + 1
while j < len(words):
f = True
for c in words[i]:
if c in words[j]:
... | the_stack_v2_python_sparse | py/leetcode/318.py | wfeng1991/learnpy | train | 0 | |
367c40e01e9713e2bc8fb95f70782af58a0d4ce2 | [
"dataSet = pd.read_csv('')\ndataSetNP = np.array(dataSet)\ntrainData = dataSetNP[:, 0:dataSetNP.shape[1] - 1]\nlabels = dataSetNP[:, dataSetNP.shape[1] - 1]\nreturn (trainData, labels)",
"labels = list(labels)\np_y = {}\nfor label in labels:\n p_y[label] = labels.count(label) / float(len(labels))\np_xy = {}\nf... | <|body_start_0|>
dataSet = pd.read_csv('')
dataSetNP = np.array(dataSet)
trainData = dataSetNP[:, 0:dataSetNP.shape[1] - 1]
labels = dataSetNP[:, dataSetNP.shape[1] - 1]
return (trainData, labels)
<|end_body_0|>
<|body_start_1|>
labels = list(labels)
p_y = {}
... | NaiveBayes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NaiveBayes:
def getTrainSet(self):
"""将数据转化为训练数据和标签 :return:"""
<|body_0|>
def classify(self, trainData, labels, features):
"""求labels中每个label的先验概率 :param trainData: 训练数据 :param labels: 标签 :param features: 特征 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_003627 | 4,259 | no_license | [
{
"docstring": "将数据转化为训练数据和标签 :return:",
"name": "getTrainSet",
"signature": "def getTrainSet(self)"
},
{
"docstring": "求labels中每个label的先验概率 :param trainData: 训练数据 :param labels: 标签 :param features: 特征 :return:",
"name": "classify",
"signature": "def classify(self, trainData, labels, fea... | 2 | stack_v2_sparse_classes_30k_train_004110 | Implement the Python class `NaiveBayes` described below.
Class description:
Implement the NaiveBayes class.
Method signatures and docstrings:
- def getTrainSet(self): 将数据转化为训练数据和标签 :return:
- def classify(self, trainData, labels, features): 求labels中每个label的先验概率 :param trainData: 训练数据 :param labels: 标签 :param features... | Implement the Python class `NaiveBayes` described below.
Class description:
Implement the NaiveBayes class.
Method signatures and docstrings:
- def getTrainSet(self): 将数据转化为训练数据和标签 :return:
- def classify(self, trainData, labels, features): 求labels中每个label的先验概率 :param trainData: 训练数据 :param labels: 标签 :param features... | 354e7664b46615c325ca3852686ea027be8738c3 | <|skeleton|>
class NaiveBayes:
def getTrainSet(self):
"""将数据转化为训练数据和标签 :return:"""
<|body_0|>
def classify(self, trainData, labels, features):
"""求labels中每个label的先验概率 :param trainData: 训练数据 :param labels: 标签 :param features: 特征 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NaiveBayes:
def getTrainSet(self):
"""将数据转化为训练数据和标签 :return:"""
dataSet = pd.read_csv('')
dataSetNP = np.array(dataSet)
trainData = dataSetNP[:, 0:dataSetNP.shape[1] - 1]
labels = dataSetNP[:, dataSetNP.shape[1] - 1]
return (trainData, labels)
def classify(... | the_stack_v2_python_sparse | learning_py3.6/PYML/ml_ten_famours_algorithm/native_bayes_algorithm.py | bigdushao/python3.6 | train | 0 | |
10ecbaf1cfa151fa8a537c81efc3d9b7f87b0d7b | [
"dist = []\nfor i in range(len(points)):\n dist.append(abs(math.sqrt((points[i][0] - 0) ** 2 + (points[i][1] - 0) ** 2)))\ncount = 0\nres = []\nusedIdx = set()\nwhile count < K:\n minSoFar = float('inf')\n selectedIdx = -1\n for m in range(len(dist)):\n if dist[m] < minSoFar and m not in usedIdx:... | <|body_start_0|>
dist = []
for i in range(len(points)):
dist.append(abs(math.sqrt((points[i][0] - 0) ** 2 + (points[i][1] - 0) ** 2)))
count = 0
res = []
usedIdx = set()
while count < K:
minSoFar = float('inf')
selectedIdx = -1
... | https://leetcode.com/problems/k-closest-points-to-origin/ formula: dist=sqrt((x2-x1)^2+(y2-y1)^2) | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/k-closest-points-to-origin/ formula: dist=sqrt((x2-x1)^2+(y2-y1)^2)"""
def kClosest(self, points, K):
""":type points: List[List[int]] :type K: int :rtype: List[List[int]]"""
<|body_0|>
def kClosest2(self, points, K):
""... | stack_v2_sparse_classes_36k_train_003628 | 1,531 | no_license | [
{
"docstring": ":type points: List[List[int]] :type K: int :rtype: List[List[int]]",
"name": "kClosest",
"signature": "def kClosest(self, points, K)"
},
{
"docstring": ":type points: List[List[int]] :type K: int :rtype: List[List[int]]",
"name": "kClosest2",
"signature": "def kClosest2(s... | 2 | stack_v2_sparse_classes_30k_train_001350 | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/k-closest-points-to-origin/ formula: dist=sqrt((x2-x1)^2+(y2-y1)^2)
Method signatures and docstrings:
- def kClosest(self, points, K): :type points: List[List[int]] :type K: int :rtype: List[List[int]]
- def kClose... | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/k-closest-points-to-origin/ formula: dist=sqrt((x2-x1)^2+(y2-y1)^2)
Method signatures and docstrings:
- def kClosest(self, points, K): :type points: List[List[int]] :type K: int :rtype: List[List[int]]
- def kClose... | 54d3d9530b25272d4a2e5dc33e7035c44f506dc5 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/k-closest-points-to-origin/ formula: dist=sqrt((x2-x1)^2+(y2-y1)^2)"""
def kClosest(self, points, K):
""":type points: List[List[int]] :type K: int :rtype: List[List[int]]"""
<|body_0|>
def kClosest2(self, points, K):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""https://leetcode.com/problems/k-closest-points-to-origin/ formula: dist=sqrt((x2-x1)^2+(y2-y1)^2)"""
def kClosest(self, points, K):
""":type points: List[List[int]] :type K: int :rtype: List[List[int]]"""
dist = []
for i in range(len(points)):
dist.append(... | the_stack_v2_python_sparse | old/Session002/General/KClosestPointstoOrigin.py | MaxIakovliev/algorithms | train | 0 |
da8f6f62d785321fd59b494899853f6691fdfe50 | [
"if business_exec_algo is not None:\n assert isinstance(business_exec_algo, ExecutableAlgo), 'Expects Implementation type for argument business_obj in ImplementationWs constructor'\nself.__mdl = business_exec_algo",
"status = dict()\nif self.__mdl is not None:\n start_execution_date = self.__mdl.get_start_e... | <|body_start_0|>
if business_exec_algo is not None:
assert isinstance(business_exec_algo, ExecutableAlgo), 'Expects Implementation type for argument business_obj in ImplementationWs constructor'
self.__mdl = business_exec_algo
<|end_body_0|>
<|body_start_1|>
status = dict()
... | The ExecutableAlgoWs is a wrapper of resource ExecutableAlgo: brings services for the web services concerned with ExecutableAlgo | ExecutableAlgoWs | [
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"LGPL-3.0-or-later",
"Zlib",
"BSD-3-Clause",
"Python-2.0",
"ZPL-2.0",
"LicenseRef-scancode-openssl-exception-lgpl3.0plus",
"ZPL-2.1",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecutableAlgoWs:
"""The ExecutableAlgoWs is a wrapper of resource ExecutableAlgo: brings services for the web services concerned with ExecutableAlgo"""
def __init__(self, business_exec_algo):
"""Constructor"""
<|body_0|>
def to_dict(self):
"""returns a dictionar... | stack_v2_sparse_classes_36k_train_003629 | 3,525 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, business_exec_algo)"
},
{
"docstring": "returns a dictionary Json-serializable for the ExecutableAlgoWs wrapping the ExecutableAlgo",
"name": "to_dict",
"signature": "def to_dict(self)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_016987 | Implement the Python class `ExecutableAlgoWs` described below.
Class description:
The ExecutableAlgoWs is a wrapper of resource ExecutableAlgo: brings services for the web services concerned with ExecutableAlgo
Method signatures and docstrings:
- def __init__(self, business_exec_algo): Constructor
- def to_dict(self)... | Implement the Python class `ExecutableAlgoWs` described below.
Class description:
The ExecutableAlgoWs is a wrapper of resource ExecutableAlgo: brings services for the web services concerned with ExecutableAlgo
Method signatures and docstrings:
- def __init__(self, business_exec_algo): Constructor
- def to_dict(self)... | 0b04ab448faf1ffdc89687268c6192e69d61f890 | <|skeleton|>
class ExecutableAlgoWs:
"""The ExecutableAlgoWs is a wrapper of resource ExecutableAlgo: brings services for the web services concerned with ExecutableAlgo"""
def __init__(self, business_exec_algo):
"""Constructor"""
<|body_0|>
def to_dict(self):
"""returns a dictionar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExecutableAlgoWs:
"""The ExecutableAlgoWs is a wrapper of resource ExecutableAlgo: brings services for the web services concerned with ExecutableAlgo"""
def __init__(self, business_exec_algo):
"""Constructor"""
if business_exec_algo is not None:
assert isinstance(business_exec... | the_stack_v2_python_sparse | src/ikats/processing/apps/algo/execute/models/ws/algo.py | IKATS/ikats-pybase | train | 0 |
10fc9321325ff983425ab8585dd390d70c3e5554 | [
"ub = str(n)\n\n@lru_cache(None)\ndef dp(i, relaxed):\n if i == len(ub):\n return 1\n ret = 0\n for d in digits:\n if relaxed or d < ub[i]:\n ret += dp(i + 1, True)\n elif d == ub[i]:\n ret += dp(i + 1, False)\n return ret\nret = dp(0, False)\nfor i in range(1,... | <|body_start_0|>
ub = str(n)
@lru_cache(None)
def dp(i, relaxed):
if i == len(ub):
return 1
ret = 0
for d in digits:
if relaxed or d < ub[i]:
ret += dp(i + 1, True)
elif d == ub[i]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
"""Time complexity: O(n) Space complexity: O(n)"""
<|body_0|>
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
"""Time complexity: O(n) Space complexity: O(1)"""
<|bo... | stack_v2_sparse_classes_36k_train_003630 | 3,328 | no_license | [
{
"docstring": "Time complexity: O(n) Space complexity: O(n)",
"name": "atMostNGivenDigitSet",
"signature": "def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int"
},
{
"docstring": "Time complexity: O(n) Space complexity: O(1)",
"name": "atMostNGivenDigitSet",
"signature": "d... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: Time complexity: O(n) Space complexity: O(n)
- def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: Time complexity: O(n) Space complexity: O(n)
- def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
"""Time complexity: O(n) Space complexity: O(n)"""
<|body_0|>
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
"""Time complexity: O(n) Space complexity: O(1)"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
"""Time complexity: O(n) Space complexity: O(n)"""
ub = str(n)
@lru_cache(None)
def dp(i, relaxed):
if i == len(ub):
return 1
ret = 0
for d in digits... | the_stack_v2_python_sparse | leetcode/solved/938_Numbers_At_Most_N_Given_Digit_Set/solution.py | sungminoh/algorithms | train | 0 | |
a14e815148051ff5488155247a274d32c3c34a63 | [
"self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(self.X, self.X)",
"sqdist = np.sum(X1 ** 2, 1).reshape(-1, 1) + np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)\ncov_K_M = self.sigma_f ** 2 * np.exp(-0.5 / self.l ** 2 * sqdist)\nreturn cov_K_M"
] | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(self.X, self.X)
<|end_body_0|>
<|body_start_1|>
sqdist = np.sum(X1 ** 2, 1).reshape(-1, 1) + np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)
cov_K_M = self.sigma_f *... | Class that represents a noiseless 1D Gaussian process | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""Class that represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor initializing method Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box functio... | stack_v2_sparse_classes_36k_train_003631 | 1,654 | no_license | [
{
"docstring": "Class constructor initializing method Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function Y_init is a numpy.ndarray of shape (t, 1) representing the outputs of the black-box function for each input in X_init t is the number of initi... | 2 | stack_v2_sparse_classes_30k_train_009980 | Implement the Python class `GaussianProcess` described below.
Class description:
Class that represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Class constructor initializing method Args: X_init is a numpy.ndarray of shape (t, 1) represent... | Implement the Python class `GaussianProcess` described below.
Class description:
Class that represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Class constructor initializing method Args: X_init is a numpy.ndarray of shape (t, 1) represent... | e8a98d85b3bfd5665cb04bec9ee8c3eb23d6bd58 | <|skeleton|>
class GaussianProcess:
"""Class that represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor initializing method Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box functio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcess:
"""Class that represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor initializing method Args: X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function Y_init is a... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/0-gp.py | AndrewMiranda/holbertonschool-machine_learning-1 | train | 0 |
3e889150e6eb1ea1efac6e168fe3e5e0dde6c8bf | [
"self.player1 = player1\nself.player2 = player2\nself.game = game\nself.display = display",
"players = [self.player1, self.player1, self.player1]\ncurPlayer = 1\nboard = self.game.getInitBoard_fix_sonet(sonete, sequences, nround)\nit = 0\nwhile self.game.getGameEnded(board, curPlayer) == 0:\n it += 1\n if v... | <|body_start_0|>
self.player1 = player1
self.player2 = player2
self.game = game
self.display = display
<|end_body_0|>
<|body_start_1|>
players = [self.player1, self.player1, self.player1]
curPlayer = 1
board = self.game.getInitBoard_fix_sonet(sonete, sequences, n... | An Arena class where any 2 agents can be pit against each other. | Arena | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Arena:
"""An Arena class where any 2 agents can be pit against each other."""
def __init__(self, player1, player2, game, display=None):
"""Input: player 1,2: two functions that takes board as input, return action game: Game object display: a function that takes board as input and pri... | stack_v2_sparse_classes_36k_train_003632 | 3,337 | permissive | [
{
"docstring": "Input: player 1,2: two functions that takes board as input, return action game: Game object display: a function that takes board as input and prints it (e.g. display in othello/OthelloGame). Is necessary for verbose mode. see othello/OthelloPlayers.py for an example. See pit.py for pitting human... | 3 | stack_v2_sparse_classes_30k_train_011703 | Implement the Python class `Arena` described below.
Class description:
An Arena class where any 2 agents can be pit against each other.
Method signatures and docstrings:
- def __init__(self, player1, player2, game, display=None): Input: player 1,2: two functions that takes board as input, return action game: Game obj... | Implement the Python class `Arena` described below.
Class description:
An Arena class where any 2 agents can be pit against each other.
Method signatures and docstrings:
- def __init__(self, player1, player2, game, display=None): Input: player 1,2: two functions that takes board as input, return action game: Game obj... | 2ba6f153e428227fcf6f27080bdd0183d395ef64 | <|skeleton|>
class Arena:
"""An Arena class where any 2 agents can be pit against each other."""
def __init__(self, player1, player2, game, display=None):
"""Input: player 1,2: two functions that takes board as input, return action game: Game object display: a function that takes board as input and pri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Arena:
"""An Arena class where any 2 agents can be pit against each other."""
def __init__(self, player1, player2, game, display=None):
"""Input: player 1,2: two functions that takes board as input, return action game: Game object display: a function that takes board as input and prints it (e.g. ... | the_stack_v2_python_sparse | alpha-zero-general_one_step/Arena_2.py | rubenrtorrado/NLP | train | 0 |
d855ea2ef9fcb7c557bc3e28a610f3d96bb5651a | [
"self._rules = tuple()\nfor rule in rules:\n if rule.matcher is None:\n matcher = BaseMatcher()\n elif isinstance(rule.matcher, BaseMatcher):\n matcher = rule.matcher\n elif isinstance(rule.matcher, basestring):\n matcher = default_matcher(rule.matcher)\n else:\n raise ValueE... | <|body_start_0|>
self._rules = tuple()
for rule in rules:
if rule.matcher is None:
matcher = BaseMatcher()
elif isinstance(rule.matcher, BaseMatcher):
matcher = rule.matcher
elif isinstance(rule.matcher, basestring):
mat... | Rules Manager | RulesManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RulesManager:
"""Rules Manager"""
def __init__(self, rules, spider, default_matcher=UrlRegexMatcher):
"""Initialize rules using spider and default matcher"""
<|body_0|>
def get_rule_from_request(self, request):
"""Returns first rule that matches given Request"""
... | stack_v2_sparse_classes_36k_train_003633 | 3,671 | permissive | [
{
"docstring": "Initialize rules using spider and default matcher",
"name": "__init__",
"signature": "def __init__(self, rules, spider, default_matcher=UrlRegexMatcher)"
},
{
"docstring": "Returns first rule that matches given Request",
"name": "get_rule_from_request",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_018253 | Implement the Python class `RulesManager` described below.
Class description:
Rules Manager
Method signatures and docstrings:
- def __init__(self, rules, spider, default_matcher=UrlRegexMatcher): Initialize rules using spider and default matcher
- def get_rule_from_request(self, request): Returns first rule that matc... | Implement the Python class `RulesManager` described below.
Class description:
Rules Manager
Method signatures and docstrings:
- def __init__(self, rules, spider, default_matcher=UrlRegexMatcher): Initialize rules using spider and default matcher
- def get_rule_from_request(self, request): Returns first rule that matc... | 6f82ea19de1e61ef71373817f2ca9687b900744d | <|skeleton|>
class RulesManager:
"""Rules Manager"""
def __init__(self, rules, spider, default_matcher=UrlRegexMatcher):
"""Initialize rules using spider and default matcher"""
<|body_0|>
def get_rule_from_request(self, request):
"""Returns first rule that matches given Request"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RulesManager:
"""Rules Manager"""
def __init__(self, rules, spider, default_matcher=UrlRegexMatcher):
"""Initialize rules using spider and default matcher"""
self._rules = tuple()
for rule in rules:
if rule.matcher is None:
matcher = BaseMatcher()
... | the_stack_v2_python_sparse | scrapy/contrib_exp/crawlspider/rules.py | herberthamaral/scrapy | train | 1 |
1fd3df75c10d36e98b55f70b15405946134b0ccd | [
"def recursiveHelper(curr):\n nonlocal serializedStr\n if curr is None:\n serializedStr += 'None,'\n return\n else:\n serializedStr += str(curr.val) + ','\n recursiveHelper(curr.left)\n recursiveHelper(curr.right)\nserializedStr = ''\nrecursiveHelper(root)\nreturn seriali... | <|body_start_0|>
def recursiveHelper(curr):
nonlocal serializedStr
if curr is None:
serializedStr += 'None,'
return
else:
serializedStr += str(curr.val) + ','
recursiveHelper(curr.left)
recursiveH... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_003634 | 1,265 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | a7b31b2deaaac24470e6337690b5d6df481bc04b | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def recursiveHelper(curr):
nonlocal serializedStr
if curr is None:
serializedStr += 'None,'
return
else:
... | the_stack_v2_python_sparse | Archive/Facebook/Trees & Graphs/serializeAndDeserializeTree.py | adalloul0928/Leetcode_Hell | train | 0 | |
735a4a88359008fb3f847e443511087e590b76f7 | [
"self.is_leaf = is_leaf\nself.keys = []\nself.children = []",
"if self.is_leaf:\n return 'Leaf BTreeNode with {0} keys\\n\\tK:{1}\\n\\tC:{2}\\n'.format(len(self.keys), self.keys, self.children)\nelse:\n return 'Internal BTreeNode with {0} keys, {1} children\\n\\tK:{2}\\n\\n'.format(len(self.keys), len(self.... | <|body_start_0|>
self.is_leaf = is_leaf
self.keys = []
self.children = []
<|end_body_0|>
<|body_start_1|>
if self.is_leaf:
return 'Leaf BTreeNode with {0} keys\n\tK:{1}\n\tC:{2}\n'.format(len(self.keys), self.keys, self.children)
else:
return 'Internal BT... | A node in BTree | BTreeNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BTreeNode:
"""A node in BTree"""
def __init__(self, is_leaf=False):
"""init BTreeNode Args: is_leaf: If the node is the leaf node Returns: None Raises: None"""
<|body_0|>
def __str__(self):
"""__str__ Args: Returns: string Raises: None"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_003635 | 5,727 | no_license | [
{
"docstring": "init BTreeNode Args: is_leaf: If the node is the leaf node Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, is_leaf=False)"
},
{
"docstring": "__str__ Args: Returns: string Raises: None",
"name": "__str__",
"signature": "def __str__(self)"... | 2 | null | Implement the Python class `BTreeNode` described below.
Class description:
A node in BTree
Method signatures and docstrings:
- def __init__(self, is_leaf=False): init BTreeNode Args: is_leaf: If the node is the leaf node Returns: None Raises: None
- def __str__(self): __str__ Args: Returns: string Raises: None | Implement the Python class `BTreeNode` described below.
Class description:
A node in BTree
Method signatures and docstrings:
- def __init__(self, is_leaf=False): init BTreeNode Args: is_leaf: If the node is the leaf node Returns: None Raises: None
- def __str__(self): __str__ Args: Returns: string Raises: None
<|ske... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class BTreeNode:
"""A node in BTree"""
def __init__(self, is_leaf=False):
"""init BTreeNode Args: is_leaf: If the node is the leaf node Returns: None Raises: None"""
<|body_0|>
def __str__(self):
"""__str__ Args: Returns: string Raises: None"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BTreeNode:
"""A node in BTree"""
def __init__(self, is_leaf=False):
"""init BTreeNode Args: is_leaf: If the node is the leaf node Returns: None Raises: None"""
self.is_leaf = is_leaf
self.keys = []
self.children = []
def __str__(self):
"""__str__ Args: Returns... | the_stack_v2_python_sparse | python/common/btree.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
29332eda41af11728f21c7e66841662542305f18 | [
"self.threshold = threshold\nself.alpha = alpha\nself.verbose = verbose\nself.max_epoch = max_epoch\nself.epoch_errors = []\nself.nn = NeuralNetwork()\ninput_layer = Layer()\noutput_layer = Layer()\ninput_layer.add(Neuron(Neuron.Type.Bias))\nfor i in range(n_inputs):\n input_layer.add(Neuron(Neuron.Type.Direct))... | <|body_start_0|>
self.threshold = threshold
self.alpha = alpha
self.verbose = verbose
self.max_epoch = max_epoch
self.epoch_errors = []
self.nn = NeuralNetwork()
input_layer = Layer()
output_layer = Layer()
input_layer.add(Neuron(Neuron.Type.Bias))... | Implementation of class Perceptron, whose goal is to execute perceptron learning algorithm. It inherits NNClassifier class. | Perceptron | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Perceptron:
"""Implementation of class Perceptron, whose goal is to execute perceptron learning algorithm. It inherits NNClassifier class."""
def __init__(self, n_inputs, n_outputs, threshold=0.1, alpha=1.0, verbose=False, max_epoch=20):
"""Constructor of a new object 'Perceptron'. :... | stack_v2_sparse_classes_36k_train_003636 | 5,090 | permissive | [
{
"docstring": "Constructor of a new object 'Perceptron'. :param n_inputs: Number of inputs of the neural network :param n_outputs: Number of outputs of the neural network :param alpha: (Optional) Learning parameter alpha. Default=0.1 :param threshold: (Optional) Threshold. The algorithm activation function dep... | 3 | null | Implement the Python class `Perceptron` described below.
Class description:
Implementation of class Perceptron, whose goal is to execute perceptron learning algorithm. It inherits NNClassifier class.
Method signatures and docstrings:
- def __init__(self, n_inputs, n_outputs, threshold=0.1, alpha=1.0, verbose=False, m... | Implement the Python class `Perceptron` described below.
Class description:
Implementation of class Perceptron, whose goal is to execute perceptron learning algorithm. It inherits NNClassifier class.
Method signatures and docstrings:
- def __init__(self, n_inputs, n_outputs, threshold=0.1, alpha=1.0, verbose=False, m... | c047e41d086f3028ec78ac3a663b9848862e52df | <|skeleton|>
class Perceptron:
"""Implementation of class Perceptron, whose goal is to execute perceptron learning algorithm. It inherits NNClassifier class."""
def __init__(self, n_inputs, n_outputs, threshold=0.1, alpha=1.0, verbose=False, max_epoch=20):
"""Constructor of a new object 'Perceptron'. :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Perceptron:
"""Implementation of class Perceptron, whose goal is to execute perceptron learning algorithm. It inherits NNClassifier class."""
def __init__(self, n_inputs, n_outputs, threshold=0.1, alpha=1.0, verbose=False, max_epoch=20):
"""Constructor of a new object 'Perceptron'. :param n_input... | the_stack_v2_python_sparse | 5_Curso/Neurocomputación/Prácticas/Practica1/assignment1/neuro_clfs/Perceptron.py | AlejandroSantorum/Apuntes_Mat_IngInf | train | 29 |
bd718d8b37f1acdab2f99917f36e36d98dd9537b | [
"rule_id = request.GET.get('rule_id', '0')\nrules = CouponRule.objects.filter(owner=request.manager, id=rule_id)\nc = RequestContext(request, {'first_nav_name': FIRST_NAV_NAME, 'second_navs': export.get_promotion_and_apps_second_navs(request), 'second_nav_name': export.MALL_PROMOTION_SECOND_NAV, 'third_nav_name': e... | <|body_start_0|>
rule_id = request.GET.get('rule_id', '0')
rules = CouponRule.objects.filter(owner=request.manager, id=rule_id)
c = RequestContext(request, {'first_nav_name': FIRST_NAV_NAME, 'second_navs': export.get_promotion_and_apps_second_navs(request), 'second_nav_name': export.MALL_PROMOTI... | CouponInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CouponInfo:
def get(request):
"""添加库存页面"""
<|body_0|>
def api_post(request):
"""增加库存"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rule_id = request.GET.get('rule_id', '0')
rules = CouponRule.objects.filter(owner=request.manager, id=rule_i... | stack_v2_sparse_classes_36k_train_003637 | 16,819 | no_license | [
{
"docstring": "添加库存页面",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "增加库存",
"name": "api_post",
"signature": "def api_post(request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002895 | Implement the Python class `CouponInfo` described below.
Class description:
Implement the CouponInfo class.
Method signatures and docstrings:
- def get(request): 添加库存页面
- def api_post(request): 增加库存 | Implement the Python class `CouponInfo` described below.
Class description:
Implement the CouponInfo class.
Method signatures and docstrings:
- def get(request): 添加库存页面
- def api_post(request): 增加库存
<|skeleton|>
class CouponInfo:
def get(request):
"""添加库存页面"""
<|body_0|>
def api_post(reques... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class CouponInfo:
def get(request):
"""添加库存页面"""
<|body_0|>
def api_post(request):
"""增加库存"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CouponInfo:
def get(request):
"""添加库存页面"""
rule_id = request.GET.get('rule_id', '0')
rules = CouponRule.objects.filter(owner=request.manager, id=rule_id)
c = RequestContext(request, {'first_nav_name': FIRST_NAV_NAME, 'second_navs': export.get_promotion_and_apps_second_navs(requ... | the_stack_v2_python_sparse | weapp/mall/promotion/coupon.py | chengdg/weizoom | train | 1 | |
72e365b959c1cd6aec2927d4b10361517de9c055 | [
"self.middle = middle\nself.timeout = timeout\nself.locations = locations",
"to_do = plan['visit']\nfor loc in to_do:\n position = self.locations[loc]\n arrived = self.middle.do({'go_to': position, 'timeout': self.timeout})\n self.display(1, 'Arrived at', loc, arrived)"
] | <|body_start_0|>
self.middle = middle
self.timeout = timeout
self.locations = locations
<|end_body_0|>
<|body_start_1|>
to_do = plan['visit']
for loc in to_do:
position = self.locations[loc]
arrived = self.middle.do({'go_to': position, 'timeout': self.tim... | Rob_top_layer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rob_top_layer:
def __init__(self, middle, timeout=200, locations={'mail': (-5, 10), 'o103': (50, 10), 'o109': (100, 10), 'storage': (101, 51)}):
"""middle is the middle layer timeout is the number of steps the middle layer goes before giving up locations is a loc:pos dictionary where loc... | stack_v2_sparse_classes_36k_train_003638 | 3,349 | no_license | [
{
"docstring": "middle is the middle layer timeout is the number of steps the middle layer goes before giving up locations is a loc:pos dictionary where loc is a named location, and pos is an (x,y) position.",
"name": "__init__",
"signature": "def __init__(self, middle, timeout=200, locations={'mail': (... | 2 | stack_v2_sparse_classes_30k_train_008491 | Implement the Python class `Rob_top_layer` described below.
Class description:
Implement the Rob_top_layer class.
Method signatures and docstrings:
- def __init__(self, middle, timeout=200, locations={'mail': (-5, 10), 'o103': (50, 10), 'o109': (100, 10), 'storage': (101, 51)}): middle is the middle layer timeout is ... | Implement the Python class `Rob_top_layer` described below.
Class description:
Implement the Rob_top_layer class.
Method signatures and docstrings:
- def __init__(self, middle, timeout=200, locations={'mail': (-5, 10), 'o103': (50, 10), 'o109': (100, 10), 'storage': (101, 51)}): middle is the middle layer timeout is ... | 479d6120b75ac0ff602f032474cad440cadd9f31 | <|skeleton|>
class Rob_top_layer:
def __init__(self, middle, timeout=200, locations={'mail': (-5, 10), 'o103': (50, 10), 'o109': (100, 10), 'storage': (101, 51)}):
"""middle is the middle layer timeout is the number of steps the middle layer goes before giving up locations is a loc:pos dictionary where loc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rob_top_layer:
def __init__(self, middle, timeout=200, locations={'mail': (-5, 10), 'o103': (50, 10), 'o109': (100, 10), 'storage': (101, 51)}):
"""middle is the middle layer timeout is the number of steps the middle layer goes before giving up locations is a loc:pos dictionary where loc is a named lo... | the_stack_v2_python_sparse | ass1/aipython/agentTop.py | fckphil/COMP9814 | train | 5 | |
6054d4546b89cf5f69a90fe5a87df736fea407b3 | [
"super(ContainerSpec, cls)._ApplyFlags(config_values, flag_values)\nif flag_values['image'].present:\n config_values['image'] = flag_values.image\nif flag_values['static_container_image'].present:\n config_values['static_image'] = flag_values.static_container_image",
"result = super(ContainerSpec, cls)._Get... | <|body_start_0|>
super(ContainerSpec, cls)._ApplyFlags(config_values, flag_values)
if flag_values['image'].present:
config_values['image'] = flag_values.image
if flag_values['static_container_image'].present:
config_values['static_image'] = flag_values.static_container_im... | Class containing options for creating containers. | ContainerSpec | [
"Apache-2.0",
"GPL-2.0-only",
"LicenseRef-scancode-public-domain",
"Classpath-exception-2.0",
"AGPL-3.0-only",
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContainerSpec:
"""Class containing options for creating containers."""
def _ApplyFlags(cls, config_values, flag_values):
"""Apply flag settings to the container spec."""
<|body_0|>
def _GetOptionDecoderConstructions(cls):
"""Gets decoder classes and constructor a... | stack_v2_sparse_classes_36k_train_003639 | 22,185 | permissive | [
{
"docstring": "Apply flag settings to the container spec.",
"name": "_ApplyFlags",
"signature": "def _ApplyFlags(cls, config_values, flag_values)"
},
{
"docstring": "Gets decoder classes and constructor args for each configurable option. Can be overridden by derived classes to add options or im... | 2 | null | Implement the Python class `ContainerSpec` described below.
Class description:
Class containing options for creating containers.
Method signatures and docstrings:
- def _ApplyFlags(cls, config_values, flag_values): Apply flag settings to the container spec.
- def _GetOptionDecoderConstructions(cls): Gets decoder clas... | Implement the Python class `ContainerSpec` described below.
Class description:
Class containing options for creating containers.
Method signatures and docstrings:
- def _ApplyFlags(cls, config_values, flag_values): Apply flag settings to the container spec.
- def _GetOptionDecoderConstructions(cls): Gets decoder clas... | 86ff6a8c3aaf2407f6692d207208b7c60bca0d2f | <|skeleton|>
class ContainerSpec:
"""Class containing options for creating containers."""
def _ApplyFlags(cls, config_values, flag_values):
"""Apply flag settings to the container spec."""
<|body_0|>
def _GetOptionDecoderConstructions(cls):
"""Gets decoder classes and constructor a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContainerSpec:
"""Class containing options for creating containers."""
def _ApplyFlags(cls, config_values, flag_values):
"""Apply flag settings to the container spec."""
super(ContainerSpec, cls)._ApplyFlags(config_values, flag_values)
if flag_values['image'].present:
... | the_stack_v2_python_sparse | perfkitbenchmarker/container_service.py | sylvanasbeta/PerfKitBenchmarker | train | 1 |
aa6953f701a6695492254eaf213c58ed26689ed6 | [
"sexy.IconEntry.__init__(self)\nself.__gobject_init__()\nself._handler_changed = self.connect_after('changed', self._on_changed)\nself.connect('icon-pressed', self._on_icon_pressed)\nimage = gtk.Image()\npixbuf = icon_theme.load_icon(gtk.STOCK_CLEAR, gtk.ICON_SIZE_MENU, 0)\nimage.set_from_pixbuf(pixbuf)\nself.set_i... | <|body_start_0|>
sexy.IconEntry.__init__(self)
self.__gobject_init__()
self._handler_changed = self.connect_after('changed', self._on_changed)
self.connect('icon-pressed', self._on_icon_pressed)
image = gtk.Image()
pixbuf = icon_theme.load_icon(gtk.STOCK_CLEAR, gtk.ICON_S... | SearchEntry | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchEntry:
def __init__(self, icon_theme):
"""Creates an enhanced IconEntry that supports a time out when typing and uses a different background colour when the search is active"""
<|body_0|>
def _on_icon_pressed(self, widget, icon, mouse_button):
"""Emit the terms... | stack_v2_sparse_classes_36k_train_003640 | 4,000 | no_license | [
{
"docstring": "Creates an enhanced IconEntry that supports a time out when typing and uses a different background colour when the search is active",
"name": "__init__",
"signature": "def __init__(self, icon_theme)"
},
{
"docstring": "Emit the terms-changed signal without any time out when the c... | 4 | stack_v2_sparse_classes_30k_train_017756 | Implement the Python class `SearchEntry` described below.
Class description:
Implement the SearchEntry class.
Method signatures and docstrings:
- def __init__(self, icon_theme): Creates an enhanced IconEntry that supports a time out when typing and uses a different background colour when the search is active
- def _o... | Implement the Python class `SearchEntry` described below.
Class description:
Implement the SearchEntry class.
Method signatures and docstrings:
- def __init__(self, icon_theme): Creates an enhanced IconEntry that supports a time out when typing and uses a different background colour when the search is active
- def _o... | d08f7bf370a82b6970387bb9f165d374a9d9092b | <|skeleton|>
class SearchEntry:
def __init__(self, icon_theme):
"""Creates an enhanced IconEntry that supports a time out when typing and uses a different background colour when the search is active"""
<|body_0|>
def _on_icon_pressed(self, widget, icon, mouse_button):
"""Emit the terms... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchEntry:
def __init__(self, icon_theme):
"""Creates an enhanced IconEntry that supports a time out when typing and uses a different background colour when the search is active"""
sexy.IconEntry.__init__(self)
self.__gobject_init__()
self._handler_changed = self.connect_afte... | the_stack_v2_python_sparse | usr/share/pyshared/AppInstall/widgets/SearchEntry.py | haniokasai/netwalker-rootfs | train | 2 | |
c884dd266eb3c1cecf302774bc47e794f5bd24f2 | [
"self.pool = object()\nself.nodes = {'nodes': []}\nself.clock = Clock()\nself.get_calls = 0\n\nclass FakeTreq(object):\n\n @classmethod\n def get(cls, url, headers, pool):\n self.get_calls += 1\n self.assertIs(self.pool, pool)\n self.assertEqual(['token'], headers.get('x-auth-token'))\n ... | <|body_start_0|>
self.pool = object()
self.nodes = {'nodes': []}
self.clock = Clock()
self.get_calls = 0
class FakeTreq(object):
@classmethod
def get(cls, url, headers, pool):
self.get_calls += 1
self.assertIs(self.pool, p... | Tests for :func:`CloudLoadBalancer.wait_for_nodes`. | WaitForNodesTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WaitForNodesTestCase:
"""Tests for :func:`CloudLoadBalancer.wait_for_nodes`."""
def setUp(self):
"""Set up fake pool, clock, treq, responses, and RCS."""
<|body_0|>
def test_retries_until_matcher_matches(self):
"""If the matcher does not matches the load balancer... | stack_v2_sparse_classes_36k_train_003641 | 18,654 | permissive | [
{
"docstring": "Set up fake pool, clock, treq, responses, and RCS.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "If the matcher does not matches the load balancer state, retries until it does.",
"name": "test_retries_until_matcher_matches",
"signature": "def test_r... | 3 | stack_v2_sparse_classes_30k_train_016550 | Implement the Python class `WaitForNodesTestCase` described below.
Class description:
Tests for :func:`CloudLoadBalancer.wait_for_nodes`.
Method signatures and docstrings:
- def setUp(self): Set up fake pool, clock, treq, responses, and RCS.
- def test_retries_until_matcher_matches(self): If the matcher does not matc... | Implement the Python class `WaitForNodesTestCase` described below.
Class description:
Tests for :func:`CloudLoadBalancer.wait_for_nodes`.
Method signatures and docstrings:
- def setUp(self): Set up fake pool, clock, treq, responses, and RCS.
- def test_retries_until_matcher_matches(self): If the matcher does not matc... | 7199cdd67255fe116dbcbedea660c13453671134 | <|skeleton|>
class WaitForNodesTestCase:
"""Tests for :func:`CloudLoadBalancer.wait_for_nodes`."""
def setUp(self):
"""Set up fake pool, clock, treq, responses, and RCS."""
<|body_0|>
def test_retries_until_matcher_matches(self):
"""If the matcher does not matches the load balancer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WaitForNodesTestCase:
"""Tests for :func:`CloudLoadBalancer.wait_for_nodes`."""
def setUp(self):
"""Set up fake pool, clock, treq, responses, and RCS."""
self.pool = object()
self.nodes = {'nodes': []}
self.clock = Clock()
self.get_calls = 0
class FakeTreq... | the_stack_v2_python_sparse | otter/integration/lib/test_cloud_load_balancer.py | rackerlabs/otter | train | 20 |
4a1067d22edebd9066945a9626f60e6ec529575a | [
"super().__init__()\nself.epsilon = epsilon\nself._empty_dag1 = qiskit.converters.circuit_to_dag(QuantumCircuit(1))\nself._empty_dag2 = qiskit.converters.circuit_to_dag(QuantumCircuit(2))\nself.mod2pi = modulo2pi",
"def modulo_2pi(x):\n x = float(x)\n return np.mod(x + np.pi, 2 * np.pi) - np.pi\nfor node in... | <|body_start_0|>
super().__init__()
self.epsilon = epsilon
self._empty_dag1 = qiskit.converters.circuit_to_dag(QuantumCircuit(1))
self._empty_dag2 = qiskit.converters.circuit_to_dag(QuantumCircuit(2))
self.mod2pi = modulo2pi
<|end_body_0|>
<|body_start_1|>
def modulo_2pi... | Return a circuit with small rotation gates removed. | RemoveSmallRotations | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoveSmallRotations:
"""Return a circuit with small rotation gates removed."""
def __init__(self, epsilon: float=0, modulo2pi=False):
"""Remove all small rotations from a circuit Args: epsilon: Threshold for rotation angle to be removed modulo2pi: If True, then rotations multiples o... | stack_v2_sparse_classes_36k_train_003642 | 14,382 | permissive | [
{
"docstring": "Remove all small rotations from a circuit Args: epsilon: Threshold for rotation angle to be removed modulo2pi: If True, then rotations multiples of 2pi are removed as well",
"name": "__init__",
"signature": "def __init__(self, epsilon: float=0, modulo2pi=False)"
},
{
"docstring":... | 2 | null | Implement the Python class `RemoveSmallRotations` described below.
Class description:
Return a circuit with small rotation gates removed.
Method signatures and docstrings:
- def __init__(self, epsilon: float=0, modulo2pi=False): Remove all small rotations from a circuit Args: epsilon: Threshold for rotation angle to ... | Implement the Python class `RemoveSmallRotations` described below.
Class description:
Return a circuit with small rotation gates removed.
Method signatures and docstrings:
- def __init__(self, epsilon: float=0, modulo2pi=False): Remove all small rotations from a circuit Args: epsilon: Threshold for rotation angle to ... | 208c9c53309e10484e9883d537b53282cb83a43d | <|skeleton|>
class RemoveSmallRotations:
"""Return a circuit with small rotation gates removed."""
def __init__(self, epsilon: float=0, modulo2pi=False):
"""Remove all small rotations from a circuit Args: epsilon: Threshold for rotation angle to be removed modulo2pi: If True, then rotations multiples o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RemoveSmallRotations:
"""Return a circuit with small rotation gates removed."""
def __init__(self, epsilon: float=0, modulo2pi=False):
"""Remove all small rotations from a circuit Args: epsilon: Threshold for rotation angle to be removed modulo2pi: If True, then rotations multiples of 2pi are rem... | the_stack_v2_python_sparse | src/qtt/qiskit/passes.py | QuTech-Delft/qtt | train | 58 |
15a21a8a303a417f323b668f94fc5a3e709e0ce7 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | ChatlogsServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChatlogsServicer:
"""Missing associated documentation comment in .proto file."""
def Create(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def Load(self, request, context):
"""Missing associated documentation co... | stack_v2_sparse_classes_36k_train_003643 | 3,816 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Create",
"signature": "def Create(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Load",
"signature": "def Load(self, request, context)"
}... | 2 | stack_v2_sparse_classes_30k_train_011159 | Implement the Python class `ChatlogsServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Create(self, request, context): Missing associated documentation comment in .proto file.
- def Load(self, request, context): Missing associ... | Implement the Python class `ChatlogsServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Create(self, request, context): Missing associated documentation comment in .proto file.
- def Load(self, request, context): Missing associ... | 47195f1e153bcf11df6cad0ea2f375206c010bbb | <|skeleton|>
class ChatlogsServicer:
"""Missing associated documentation comment in .proto file."""
def Create(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def Load(self, request, context):
"""Missing associated documentation co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChatlogsServicer:
"""Missing associated documentation comment in .proto file."""
def Create(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | dbots/protos/chatlogs_pb2_grpc.py | julien777z/pylib | train | 0 |
7f036376eb6a439bae7ab6ac06f31b6bd1d00a55 | [
"if params.shape[-1] != 4 or len(params.shape) > 2:\n raise ValueError('params must be of shape (B, 4) for PINHOLE Camera')\nsuper().__init__(AffineTransform(), Z1Projection(), image_size, params)",
"z = zeros_like(self.fx)\nrow1 = stack((self.fx, z, self.cx), -1)\nrow2 = stack((z, self.fy, self.cy), -1)\nrow3... | <|body_start_0|>
if params.shape[-1] != 4 or len(params.shape) > 2:
raise ValueError('params must be of shape (B, 4) for PINHOLE Camera')
super().__init__(AffineTransform(), Z1Projection(), image_size, params)
<|end_body_0|>
<|body_start_1|>
z = zeros_like(self.fx)
row1 = st... | Class to represent Pinhole Camera Model. The pinhole camera model describes the mathematical relationship between the coordinates of a point in three-dimensional space and its projection onto the image plane of an ideal pinhole camera, where the camera aperture is described as a point and no lenses are used to focus li... | PinholeModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PinholeModel:
"""Class to represent Pinhole Camera Model. The pinhole camera model describes the mathematical relationship between the coordinates of a point in three-dimensional space and its projection onto the image plane of an ideal pinhole camera, where the camera aperture is described as a ... | stack_v2_sparse_classes_36k_train_003644 | 11,694 | permissive | [
{
"docstring": "Constructor method for PinholeModel class. Args: image_size: Image size params: Camera parameters of shape :math:`(B, 4)` of the form :math:`(fx, fy, cx, cy)`.",
"name": "__init__",
"signature": "def __init__(self, image_size: ImageSize, params: Tensor) -> None"
},
{
"docstring":... | 3 | null | Implement the Python class `PinholeModel` described below.
Class description:
Class to represent Pinhole Camera Model. The pinhole camera model describes the mathematical relationship between the coordinates of a point in three-dimensional space and its projection onto the image plane of an ideal pinhole camera, where... | Implement the Python class `PinholeModel` described below.
Class description:
Class to represent Pinhole Camera Model. The pinhole camera model describes the mathematical relationship between the coordinates of a point in three-dimensional space and its projection onto the image plane of an ideal pinhole camera, where... | 1e0f8baa7318c05b17ea6dbb48605691bca8972f | <|skeleton|>
class PinholeModel:
"""Class to represent Pinhole Camera Model. The pinhole camera model describes the mathematical relationship between the coordinates of a point in three-dimensional space and its projection onto the image plane of an ideal pinhole camera, where the camera aperture is described as a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PinholeModel:
"""Class to represent Pinhole Camera Model. The pinhole camera model describes the mathematical relationship between the coordinates of a point in three-dimensional space and its projection onto the image plane of an ideal pinhole camera, where the camera aperture is described as a point and no ... | the_stack_v2_python_sparse | kornia/sensors/camera/camera_model.py | kornia/kornia | train | 7,351 |
03da9c6c04bd8634e8a95e84bc109533341d5c14 | [
"size = self.size\nif size is None:\n return None\nreturn size.val",
"symbol = self.symbol\nif symbol is None:\n return None\nreturn symbol.val"
] | <|body_start_0|>
size = self.size
if size is None:
return None
return size.val
<|end_body_0|>
<|body_start_1|>
symbol = self.symbol
if symbol is None:
return None
return symbol.val
<|end_body_1|>
| `c:marker` custom element class, containing visual properties for a data point marker on line-type charts. | CT_Marker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CT_Marker:
"""`c:marker` custom element class, containing visual properties for a data point marker on line-type charts."""
def size_val(self):
"""Return the value of `./c:size/@val`, specifying the size of this marker in points. Returns |None| if no `c:size` element is present or it... | stack_v2_sparse_classes_36k_train_003645 | 1,857 | permissive | [
{
"docstring": "Return the value of `./c:size/@val`, specifying the size of this marker in points. Returns |None| if no `c:size` element is present or its val attribute is not present.",
"name": "size_val",
"signature": "def size_val(self)"
},
{
"docstring": "Return the value of `./c:symbol/@val... | 2 | null | Implement the Python class `CT_Marker` described below.
Class description:
`c:marker` custom element class, containing visual properties for a data point marker on line-type charts.
Method signatures and docstrings:
- def size_val(self): Return the value of `./c:size/@val`, specifying the size of this marker in point... | Implement the Python class `CT_Marker` described below.
Class description:
`c:marker` custom element class, containing visual properties for a data point marker on line-type charts.
Method signatures and docstrings:
- def size_val(self): Return the value of `./c:size/@val`, specifying the size of this marker in point... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class CT_Marker:
"""`c:marker` custom element class, containing visual properties for a data point marker on line-type charts."""
def size_val(self):
"""Return the value of `./c:size/@val`, specifying the size of this marker in points. Returns |None| if no `c:size` element is present or it... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CT_Marker:
"""`c:marker` custom element class, containing visual properties for a data point marker on line-type charts."""
def size_val(self):
"""Return the value of `./c:size/@val`, specifying the size of this marker in points. Returns |None| if no `c:size` element is present or its val attribu... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/pptx/oxml/chart/marker.py | ryfeus/lambda-packs | train | 1,283 |
d47e08ac43aed895951c46cee49548e75beaea94 | [
"self.logging = logging.getLogger(self.__class__.__name__)\nself.parse_message(message)\nself.logging.debug('Msg content: [{}]'.format(self.message_contents))\nself.msg_size = len(self.message_contents.encode('utf-8'))\nself.filename = filename\nreturn",
"header_pattern = '^[\\\\w-]+:'\ncurrent_header = ''\nfor l... | <|body_start_0|>
self.logging = logging.getLogger(self.__class__.__name__)
self.parse_message(message)
self.logging.debug('Msg content: [{}]'.format(self.message_contents))
self.msg_size = len(self.message_contents.encode('utf-8'))
self.filename = filename
return
<|end_bo... | Mail Message Object | Message | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Message:
"""Mail Message Object"""
def __init__(self, message: str, filename: str):
"""Creates a new message object"""
<|body_0|>
def parse_message(self, message: str):
"""Parses the message into the class object contents :message: String to parse into a message ... | stack_v2_sparse_classes_36k_train_003646 | 2,120 | no_license | [
{
"docstring": "Creates a new message object",
"name": "__init__",
"signature": "def __init__(self, message: str, filename: str)"
},
{
"docstring": "Parses the message into the class object contents :message: String to parse into a message object",
"name": "parse_message",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_003452 | Implement the Python class `Message` described below.
Class description:
Mail Message Object
Method signatures and docstrings:
- def __init__(self, message: str, filename: str): Creates a new message object
- def parse_message(self, message: str): Parses the message into the class object contents :message: String to ... | Implement the Python class `Message` described below.
Class description:
Mail Message Object
Method signatures and docstrings:
- def __init__(self, message: str, filename: str): Creates a new message object
- def parse_message(self, message: str): Parses the message into the class object contents :message: String to ... | c2c2977c250a5be19446c61e318eded18e69743c | <|skeleton|>
class Message:
"""Mail Message Object"""
def __init__(self, message: str, filename: str):
"""Creates a new message object"""
<|body_0|>
def parse_message(self, message: str):
"""Parses the message into the class object contents :message: String to parse into a message ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Message:
"""Mail Message Object"""
def __init__(self, message: str, filename: str):
"""Creates a new message object"""
self.logging = logging.getLogger(self.__class__.__name__)
self.parse_message(message)
self.logging.debug('Msg content: [{}]'.format(self.message_contents)... | the_stack_v2_python_sparse | Program1-POP3/libs/Messages.py | Kiro47/S20-CS4461-Programs | train | 0 |
8cf5f2d249f33c5bf2ee43bee2de57f7c5c4993c | [
"self.aws_kms = aws_kms\nself.azure_kms = azure_kms\nself.cryptsoft_kms = cryptsoft_kms\nself.id = id\nself.key_name = key_name\nself.ownership_context = ownership_context\nself.server_name = server_name\nself.server_type = server_type\nself.usage_type = usage_type\nself.vault_id_list = vault_id_list\nself.view_box... | <|body_start_0|>
self.aws_kms = aws_kms
self.azure_kms = azure_kms
self.cryptsoft_kms = cryptsoft_kms
self.id = id
self.key_name = key_name
self.ownership_context = ownership_context
self.server_name = server_name
self.server_type = server_type
sel... | Implementation of the 'KmsCreateRequestParameters' model. TODO: type description here. Attributes: aws_kms (AwsKmsConfiguration): AWS KMS conifg. azure_kms (AzureKmsConfiguration): Azure KMS config. cryptsoft_kms (CryptsoftKmsConfiguration): Cryptsoft KMS config. id (long|int): The Id of a KMS server. key_name (string)... | KmsCreateRequestParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KmsCreateRequestParameters:
"""Implementation of the 'KmsCreateRequestParameters' model. TODO: type description here. Attributes: aws_kms (AwsKmsConfiguration): AWS KMS conifg. azure_kms (AzureKmsConfiguration): Azure KMS config. cryptsoft_kms (CryptsoftKmsConfiguration): Cryptsoft KMS config. id... | stack_v2_sparse_classes_36k_train_003647 | 5,086 | permissive | [
{
"docstring": "Constructor for the KmsCreateRequestParameters class",
"name": "__init__",
"signature": "def __init__(self, aws_kms=None, azure_kms=None, cryptsoft_kms=None, id=None, key_name=None, ownership_context=None, server_name=None, server_type=None, usage_type=None, vault_id_list=None, view_box_... | 2 | null | Implement the Python class `KmsCreateRequestParameters` described below.
Class description:
Implementation of the 'KmsCreateRequestParameters' model. TODO: type description here. Attributes: aws_kms (AwsKmsConfiguration): AWS KMS conifg. azure_kms (AzureKmsConfiguration): Azure KMS config. cryptsoft_kms (CryptsoftKmsC... | Implement the Python class `KmsCreateRequestParameters` described below.
Class description:
Implementation of the 'KmsCreateRequestParameters' model. TODO: type description here. Attributes: aws_kms (AwsKmsConfiguration): AWS KMS conifg. azure_kms (AzureKmsConfiguration): Azure KMS config. cryptsoft_kms (CryptsoftKmsC... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class KmsCreateRequestParameters:
"""Implementation of the 'KmsCreateRequestParameters' model. TODO: type description here. Attributes: aws_kms (AwsKmsConfiguration): AWS KMS conifg. azure_kms (AzureKmsConfiguration): Azure KMS config. cryptsoft_kms (CryptsoftKmsConfiguration): Cryptsoft KMS config. id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KmsCreateRequestParameters:
"""Implementation of the 'KmsCreateRequestParameters' model. TODO: type description here. Attributes: aws_kms (AwsKmsConfiguration): AWS KMS conifg. azure_kms (AzureKmsConfiguration): Azure KMS config. cryptsoft_kms (CryptsoftKmsConfiguration): Cryptsoft KMS config. id (long|int): ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/kms_create_request_parameters.py | cohesity/management-sdk-python | train | 24 |
5f5a88a059fd3d6df54ff8a0e4454da822710f3d | [
"super().__init__(self.PARAMS, parameters)\nself.column_order = parameters['column_order']\nself.ignore_missing = parameters['ignore_missing']\nself.keep_others = parameters['keep_others']",
"df_new = df.copy()\ncurrent_columns = list(df_new.columns)\nmissing_columns = set(self.column_order).difference(set(df_new... | <|body_start_0|>
super().__init__(self.PARAMS, parameters)
self.column_order = parameters['column_order']
self.ignore_missing = parameters['ignore_missing']
self.keep_others = parameters['keep_others']
<|end_body_0|>
<|body_start_1|>
df_new = df.copy()
current_columns = ... | Reorder columns in a tabular file. Required parameters: column_order (*list*): The names of the columns to be reordered. ignore_missing (*bool*): If false and a column in column_order is not in df, skip the column keep_others (*bool*): If true, columns not in column_order are placed at end. | ReorderColumnsOp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReorderColumnsOp:
"""Reorder columns in a tabular file. Required parameters: column_order (*list*): The names of the columns to be reordered. ignore_missing (*bool*): If false and a column in column_order is not in df, skip the column keep_others (*bool*): If true, columns not in column_order are... | stack_v2_sparse_classes_36k_train_003648 | 2,847 | permissive | [
{
"docstring": "Constructor for reorder columns operation. Parameters: parameters (dict): Dictionary with the parameter values for required and optional parameters. :raises KeyError: - If a required parameter is missing. - If an unexpected parameter is provided. :raises TypeError: - If a parameter has the wrong... | 2 | stack_v2_sparse_classes_30k_train_015262 | Implement the Python class `ReorderColumnsOp` described below.
Class description:
Reorder columns in a tabular file. Required parameters: column_order (*list*): The names of the columns to be reordered. ignore_missing (*bool*): If false and a column in column_order is not in df, skip the column keep_others (*bool*): I... | Implement the Python class `ReorderColumnsOp` described below.
Class description:
Reorder columns in a tabular file. Required parameters: column_order (*list*): The names of the columns to be reordered. ignore_missing (*bool*): If false and a column in column_order is not in df, skip the column keep_others (*bool*): I... | b871cae44bdf0ee68c688562c3b0af50b93343f5 | <|skeleton|>
class ReorderColumnsOp:
"""Reorder columns in a tabular file. Required parameters: column_order (*list*): The names of the columns to be reordered. ignore_missing (*bool*): If false and a column in column_order is not in df, skip the column keep_others (*bool*): If true, columns not in column_order are... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReorderColumnsOp:
"""Reorder columns in a tabular file. Required parameters: column_order (*list*): The names of the columns to be reordered. ignore_missing (*bool*): If false and a column in column_order is not in df, skip the column keep_others (*bool*): If true, columns not in column_order are placed at en... | the_stack_v2_python_sparse | hed/tools/remodeling/operations/reorder_columns_op.py | hed-standard/hed-python | train | 5 |
32400b804cd97bfff8b87d952c34e7e5088be414 | [
"self.num_centroids = int(NC)\nself.Nmaxiter = int(Nmaxiter)\nself.tolerance = tolerance\nself.sigma = sigma\nself.C = C\nself.NmaxiterGD = NmaxiterGD\nself.eta = eta\nsuper().__init__(comms, logger, verbose)\n'\\n # Initialize Kmeans first\\n self.kmeans_master = Kmeans_Master(self.comms, self.logger... | <|body_start_0|>
self.num_centroids = int(NC)
self.Nmaxiter = int(Nmaxiter)
self.tolerance = tolerance
self.sigma = sigma
self.C = C
self.NmaxiterGD = NmaxiterGD
self.eta = eta
super().__init__(comms, logger, verbose)
'\n # Initialize Kmeans... | This class implements SVM, run at Master node. It inherits from :class:`POM3_CommonML_Master`. | SVM_Master | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SVM_Master:
"""This class implements SVM, run at Master node. It inherits from :class:`POM3_CommonML_Master`."""
def __init__(self, comms, logger, verbose=False, NC=None, Nmaxiter=None, tolerance=None, sigma=None, C=None, NmaxiterGD=None, eta=None):
"""Create a :class:`SVM_Master` in... | stack_v2_sparse_classes_36k_train_003649 | 18,427 | permissive | [
{
"docstring": "Create a :class:`SVM_Master` instance. Parameters ---------- comms: :class:`Comms_master` Object providing communication functionalities. logger: :class:`mylogging.Logger` Logging object instance. verbose: boolean Indicates whether to print messages on screen nor not. NC: int Number of support v... | 4 | stack_v2_sparse_classes_30k_train_004018 | Implement the Python class `SVM_Master` described below.
Class description:
This class implements SVM, run at Master node. It inherits from :class:`POM3_CommonML_Master`.
Method signatures and docstrings:
- def __init__(self, comms, logger, verbose=False, NC=None, Nmaxiter=None, tolerance=None, sigma=None, C=None, Nm... | Implement the Python class `SVM_Master` described below.
Class description:
This class implements SVM, run at Master node. It inherits from :class:`POM3_CommonML_Master`.
Method signatures and docstrings:
- def __init__(self, comms, logger, verbose=False, NC=None, Nmaxiter=None, tolerance=None, sigma=None, C=None, Nm... | ccc0a7674a04ae0d00bedc38893b33184c5f68c6 | <|skeleton|>
class SVM_Master:
"""This class implements SVM, run at Master node. It inherits from :class:`POM3_CommonML_Master`."""
def __init__(self, comms, logger, verbose=False, NC=None, Nmaxiter=None, tolerance=None, sigma=None, C=None, NmaxiterGD=None, eta=None):
"""Create a :class:`SVM_Master` in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SVM_Master:
"""This class implements SVM, run at Master node. It inherits from :class:`POM3_CommonML_Master`."""
def __init__(self, comms, logger, verbose=False, NC=None, Nmaxiter=None, tolerance=None, sigma=None, C=None, NmaxiterGD=None, eta=None):
"""Create a :class:`SVM_Master` instance. Param... | the_stack_v2_python_sparse | MMLL/models/POM3/SVM/SVM.py | Musketeer-H2020/MMLL-Robust | train | 0 |
7fff115d8f6b206f43540daefa8b5f29055d61aa | [
"post_url = 'http://www.renren.com/PLogin.do'\nform_data = {'email': '670566875@qq.com', 'password': 'rr9877'}\nyield scrapy.FormRequest(post_url, formdata=form_data, callback=self.parse)",
"urls = ['http://www.renren.com/893897109/profile', 'http://www.renren.com/890297976/profile']\nfor url in urls:\n yield ... | <|body_start_0|>
post_url = 'http://www.renren.com/PLogin.do'
form_data = {'email': '670566875@qq.com', 'password': 'rr9877'}
yield scrapy.FormRequest(post_url, formdata=form_data, callback=self.parse)
<|end_body_0|>
<|body_start_1|>
urls = ['http://www.renren.com/893897109/profile', 'h... | RenrenSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RenrenSpider:
def start_requests(self):
"""登录并发送登录的post请求,登录成功则记录cookie"""
<|body_0|>
def parse(self, response):
"""直接发送好友的页面请求,scrapy会自动传递cookie"""
<|body_1|>
def parse_page(self, response):
"""处理每个好友页面的response响应"""
<|body_2|>
<|end_sk... | stack_v2_sparse_classes_36k_train_003650 | 1,448 | no_license | [
{
"docstring": "登录并发送登录的post请求,登录成功则记录cookie",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "直接发送好友的页面请求,scrapy会自动传递cookie",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "处理每个好友页面的response响应",
"name": "pars... | 3 | null | Implement the Python class `RenrenSpider` described below.
Class description:
Implement the RenrenSpider class.
Method signatures and docstrings:
- def start_requests(self): 登录并发送登录的post请求,登录成功则记录cookie
- def parse(self, response): 直接发送好友的页面请求,scrapy会自动传递cookie
- def parse_page(self, response): 处理每个好友页面的response响应 | Implement the Python class `RenrenSpider` described below.
Class description:
Implement the RenrenSpider class.
Method signatures and docstrings:
- def start_requests(self): 登录并发送登录的post请求,登录成功则记录cookie
- def parse(self, response): 直接发送好友的页面请求,scrapy会自动传递cookie
- def parse_page(self, response): 处理每个好友页面的response响应
<... | 298869fa9fb0291b9e364fbf4a6d8bd992840eb2 | <|skeleton|>
class RenrenSpider:
def start_requests(self):
"""登录并发送登录的post请求,登录成功则记录cookie"""
<|body_0|>
def parse(self, response):
"""直接发送好友的页面请求,scrapy会自动传递cookie"""
<|body_1|>
def parse_page(self, response):
"""处理每个好友页面的response响应"""
<|body_2|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RenrenSpider:
def start_requests(self):
"""登录并发送登录的post请求,登录成功则记录cookie"""
post_url = 'http://www.renren.com/PLogin.do'
form_data = {'email': '670566875@qq.com', 'password': 'rr9877'}
yield scrapy.FormRequest(post_url, formdata=form_data, callback=self.parse)
def parse(sel... | the_stack_v2_python_sparse | Scrapy/Renren/Renren/Renren/spiders/renren_login.py | AssassinHotstrip/personal_spider_pra | train | 0 | |
2f3a43ab7610f3425b5a914020cd5e9b7bb41dd5 | [
"RegexpLemmatizer.__init__(self, regexps, backoff)\nself._regexs = [(re.compile(regexp), pattern) for regexp, pattern in regexps]\nself.default = default",
"for pattern, replace in self._regexs:\n if re.search(pattern, tokens[index]):\n if self.default:\n return self.default\n else:\n ... | <|body_start_0|>
RegexpLemmatizer.__init__(self, regexps, backoff)
self._regexs = [(re.compile(regexp), pattern) for regexp, pattern in regexps]
self.default = default
<|end_body_0|>
<|body_start_1|>
for pattern, replace in self._regexs:
if re.search(pattern, tokens[index]):... | RomanNumeralLemmatizer | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RomanNumeralLemmatizer:
def __init__(self, regexps=rn_patterns, default=None, backoff=None):
"""RomanNumeralLemmatizer"""
<|body_0|>
def choose_lemma(self, tokens, index, history):
"""Test case for customized rules-based improvements to lemmatizer using regex; differ... | stack_v2_sparse_classes_36k_train_003651 | 23,254 | permissive | [
{
"docstring": "RomanNumeralLemmatizer",
"name": "__init__",
"signature": "def __init__(self, regexps=rn_patterns, default=None, backoff=None)"
},
{
"docstring": "Test case for customized rules-based improvements to lemmatizer using regex; differs from base RegexpLemmatizer in that it returns th... | 2 | stack_v2_sparse_classes_30k_train_005017 | Implement the Python class `RomanNumeralLemmatizer` described below.
Class description:
Implement the RomanNumeralLemmatizer class.
Method signatures and docstrings:
- def __init__(self, regexps=rn_patterns, default=None, backoff=None): RomanNumeralLemmatizer
- def choose_lemma(self, tokens, index, history): Test cas... | Implement the Python class `RomanNumeralLemmatizer` described below.
Class description:
Implement the RomanNumeralLemmatizer class.
Method signatures and docstrings:
- def __init__(self, regexps=rn_patterns, default=None, backoff=None): RomanNumeralLemmatizer
- def choose_lemma(self, tokens, index, history): Test cas... | 085420eaed7055fbcb311714eebb67861fd1b241 | <|skeleton|>
class RomanNumeralLemmatizer:
def __init__(self, regexps=rn_patterns, default=None, backoff=None):
"""RomanNumeralLemmatizer"""
<|body_0|>
def choose_lemma(self, tokens, index, history):
"""Test case for customized rules-based improvements to lemmatizer using regex; differ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RomanNumeralLemmatizer:
def __init__(self, regexps=rn_patterns, default=None, backoff=None):
"""RomanNumeralLemmatizer"""
RegexpLemmatizer.__init__(self, regexps, backoff)
self._regexs = [(re.compile(regexp), pattern) for regexp, pattern in regexps]
self.default = default
... | the_stack_v2_python_sparse | cltk/lemmatize/latin/backoff.py | jerryfrancis-97/cltk | train | 1 | |
3f0895d61a88bf95f9a735b81ae22a28666e2003 | [
"self.agents = {'creator': User(1234, 'foo@bar.baz', endorsements=[('astro-ph', 'GA')]), 'client': Client(5678), 'proxy': None}\nself.token = 'asdf1234'\nself.headers = {}",
"preserve_exceptions_and_events(mock_events)\nurl_for.return_value = '/foo/'\nuser = User(1234, 'foo@bar.baz')\nmock_events.save.return_valu... | <|body_start_0|>
self.agents = {'creator': User(1234, 'foo@bar.baz', endorsements=[('astro-ph', 'GA')]), 'client': Client(5678), 'proxy': None}
self.token = 'asdf1234'
self.headers = {}
<|end_body_0|>
<|body_start_1|>
preserve_exceptions_and_events(mock_events)
url_for.return_va... | Tests for :func:`.submission.update_submission`. | TestUpdateSubmission | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUpdateSubmission:
"""Tests for :func:`.submission.update_submission`."""
def setUp(self):
"""Create some fake request data."""
<|body_0|>
def test_update_submission_with_valid_data(self, mock_events, url_for):
"""Update a submission with valid data."""
... | stack_v2_sparse_classes_36k_train_003652 | 11,936 | permissive | [
{
"docstring": "Create some fake request data.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Update a submission with valid data.",
"name": "test_update_submission_with_valid_data",
"signature": "def test_update_submission_with_valid_data(self, mock_events, url_for... | 6 | stack_v2_sparse_classes_30k_train_007341 | Implement the Python class `TestUpdateSubmission` described below.
Class description:
Tests for :func:`.submission.update_submission`.
Method signatures and docstrings:
- def setUp(self): Create some fake request data.
- def test_update_submission_with_valid_data(self, mock_events, url_for): Update a submission with ... | Implement the Python class `TestUpdateSubmission` described below.
Class description:
Tests for :func:`.submission.update_submission`.
Method signatures and docstrings:
- def setUp(self): Create some fake request data.
- def test_update_submission_with_valid_data(self, mock_events, url_for): Update a submission with ... | 6077ce4e0685d67ce7010800083a898857158112 | <|skeleton|>
class TestUpdateSubmission:
"""Tests for :func:`.submission.update_submission`."""
def setUp(self):
"""Create some fake request data."""
<|body_0|>
def test_update_submission_with_valid_data(self, mock_events, url_for):
"""Update a submission with valid data."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestUpdateSubmission:
"""Tests for :func:`.submission.update_submission`."""
def setUp(self):
"""Create some fake request data."""
self.agents = {'creator': User(1234, 'foo@bar.baz', endorsements=[('astro-ph', 'GA')]), 'client': Client(5678), 'proxy': None}
self.token = 'asdf1234'... | the_stack_v2_python_sparse | metadata/metadata/controllers/submission/tests.py | arXiv/arxiv-submission-core | train | 14 |
a5428b1a799611dac61e81dbc7ee2f8a16a80f57 | [
"queryset = super().get_queryset().select_related('part')\nqueryset = build.serializers.BuildSerializer.annotate_queryset(queryset)\nreturn queryset",
"dataset = build.admin.BuildResource().export(queryset=queryset)\nfiledata = dataset.export(export_format)\nfilename = f'InvenTree_BuildOrders.{export_format}'\nre... | <|body_start_0|>
queryset = super().get_queryset().select_related('part')
queryset = build.serializers.BuildSerializer.annotate_queryset(queryset)
return queryset
<|end_body_0|>
<|body_start_1|>
dataset = build.admin.BuildResource().export(queryset=queryset)
filedata = dataset.e... | API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object | BuildList | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildList:
"""API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object"""
def get_queryset(self):
"""Override the queryset filtering, as some of the fields don't natively play nicely with DRF."""
<|body... | stack_v2_sparse_classes_36k_train_003653 | 20,912 | permissive | [
{
"docstring": "Override the queryset filtering, as some of the fields don't natively play nicely with DRF.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Download the queryset data as a file.",
"name": "download_queryset",
"signature": "def download_q... | 4 | stack_v2_sparse_classes_30k_val_000121 | Implement the Python class `BuildList` described below.
Class description:
API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object
Method signatures and docstrings:
- def get_queryset(self): Override the queryset filtering, as some of the fiel... | Implement the Python class `BuildList` described below.
Class description:
API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object
Method signatures and docstrings:
- def get_queryset(self): Override the queryset filtering, as some of the fiel... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class BuildList:
"""API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object"""
def get_queryset(self):
"""Override the queryset filtering, as some of the fields don't natively play nicely with DRF."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuildList:
"""API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object"""
def get_queryset(self):
"""Override the queryset filtering, as some of the fields don't natively play nicely with DRF."""
queryset = super().... | the_stack_v2_python_sparse | InvenTree/build/api.py | inventree/InvenTree | train | 3,077 |
b7125ee4085eaa9bb16722583bf045bf9c6f40b6 | [
"from django.conf.urls import patterns, url\nurls = super(RecurrenceRuleAdmin, self).get_urls()\nmy_urls = patterns('', url('^preview/$', self.admin_site.admin_view(self.preview), name='icekit_events_recurrencerule_preview'))\nreturn my_urls + urls",
"recurrence_rule = request.POST.get('recurrence_rule')\nlimit =... | <|body_start_0|>
from django.conf.urls import patterns, url
urls = super(RecurrenceRuleAdmin, self).get_urls()
my_urls = patterns('', url('^preview/$', self.admin_site.admin_view(self.preview), name='icekit_events_recurrencerule_preview'))
return my_urls + urls
<|end_body_0|>
<|body_sta... | RecurrenceRuleAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecurrenceRuleAdmin:
def get_urls(self):
"""Add a preview URL."""
<|body_0|>
def preview(self, request):
"""Return a occurrences in JSON format up until the configured limit."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from django.conf.urls impo... | stack_v2_sparse_classes_36k_train_003654 | 14,586 | permissive | [
{
"docstring": "Add a preview URL.",
"name": "get_urls",
"signature": "def get_urls(self)"
},
{
"docstring": "Return a occurrences in JSON format up until the configured limit.",
"name": "preview",
"signature": "def preview(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010555 | Implement the Python class `RecurrenceRuleAdmin` described below.
Class description:
Implement the RecurrenceRuleAdmin class.
Method signatures and docstrings:
- def get_urls(self): Add a preview URL.
- def preview(self, request): Return a occurrences in JSON format up until the configured limit. | Implement the Python class `RecurrenceRuleAdmin` described below.
Class description:
Implement the RecurrenceRuleAdmin class.
Method signatures and docstrings:
- def get_urls(self): Add a preview URL.
- def preview(self, request): Return a occurrences in JSON format up until the configured limit.
<|skeleton|>
class ... | c507ea5b1864303732c53ad7c5800571fca5fa94 | <|skeleton|>
class RecurrenceRuleAdmin:
def get_urls(self):
"""Add a preview URL."""
<|body_0|>
def preview(self, request):
"""Return a occurrences in JSON format up until the configured limit."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecurrenceRuleAdmin:
def get_urls(self):
"""Add a preview URL."""
from django.conf.urls import patterns, url
urls = super(RecurrenceRuleAdmin, self).get_urls()
my_urls = patterns('', url('^preview/$', self.admin_site.admin_view(self.preview), name='icekit_events_recurrencerule_... | the_stack_v2_python_sparse | icekit_events/admin.py | ic-labs/django-icekit | train | 53 | |
ba0056016d10d8c466db1acd4a11a8e246679d48 | [
"if not self.is_valid():\n return False\ntry:\n resume_id = self.params.get('resume_id')\n with advisory_lock('resume_{}_contact'.format(resume_id)):\n with transaction.atomic():\n contact_id = self.params.get('id')\n if contact_id:\n contact = Contact.objects.ge... | <|body_start_0|>
if not self.is_valid():
return False
try:
resume_id = self.params.get('resume_id')
with advisory_lock('resume_{}_contact'.format(resume_id)):
with transaction.atomic():
contact_id = self.params.get('id')
... | Form for resume's contact information. :param resume_id: Resume object link :params email: Prefered user email :param phone: Prefered phone number :param phone_comment: Comment for the phone number :param social_networks: key-value store for the social networks :return True/False whether or not form was submitted | ContactForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContactForm:
"""Form for resume's contact information. :param resume_id: Resume object link :params email: Prefered user email :param phone: Prefered phone number :param phone_comment: Comment for the phone number :param social_networks: key-value store for the social networks :return True/False ... | stack_v2_sparse_classes_36k_train_003655 | 2,860 | no_license | [
{
"docstring": "Validate form and create contact.",
"name": "submit",
"signature": "def submit(self)"
},
{
"docstring": "Set unique index errors into the form errors.",
"name": "_set_uniq_errors",
"signature": "def _set_uniq_errors(self, e)"
},
{
"docstring": "Set attributes for ... | 3 | stack_v2_sparse_classes_30k_train_004728 | Implement the Python class `ContactForm` described below.
Class description:
Form for resume's contact information. :param resume_id: Resume object link :params email: Prefered user email :param phone: Prefered phone number :param phone_comment: Comment for the phone number :param social_networks: key-value store for ... | Implement the Python class `ContactForm` described below.
Class description:
Form for resume's contact information. :param resume_id: Resume object link :params email: Prefered user email :param phone: Prefered phone number :param phone_comment: Comment for the phone number :param social_networks: key-value store for ... | 252b0ebd77eefbcc945a0efc3068cc3421f46d5f | <|skeleton|>
class ContactForm:
"""Form for resume's contact information. :param resume_id: Resume object link :params email: Prefered user email :param phone: Prefered phone number :param phone_comment: Comment for the phone number :param social_networks: key-value store for the social networks :return True/False ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContactForm:
"""Form for resume's contact information. :param resume_id: Resume object link :params email: Prefered user email :param phone: Prefered phone number :param phone_comment: Comment for the phone number :param social_networks: key-value store for the social networks :return True/False whether or no... | the_stack_v2_python_sparse | app/resumes/forms/contact.py | vsokoltsov/Interview360Server | train | 2 |
cd6fa2a09f410daab5aef4c9d0b23e4dde2f12f0 | [
"queue = collections.deque([root])\noutput = []\nwhile queue:\n top = queue.popleft()\n if top:\n output.append(str(top.val))\n queue.append(top.left)\n queue.append(top.right)\n else:\n output.append('null')\nreturn ','.join(output)",
"queue = collections.deque(data.split(','... | <|body_start_0|>
queue = collections.deque([root])
output = []
while queue:
top = queue.popleft()
if top:
output.append(str(top.val))
queue.append(top.left)
queue.append(top.right)
else:
output.ap... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_003656 | 1,571 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 88ccd910dfdb0e6ca6a70fa2d37906c31f4b3d70 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
queue = collections.deque([root])
output = []
while queue:
top = queue.popleft()
if top:
output.append(str(top.val))
... | the_stack_v2_python_sparse | practice/hard/0297-Serialize_and_Deserialize_Binary_Tree.py | mattjp/leetcode | train | 0 | |
4e86bf27f8829c5cda1ee3a6136dd85d1a1eca94 | [
"self.keyspace_metadata = keyspace\nself.max_metrics_per_pattern = max_metrics_per_pattern\nself.max_queries_per_pattern = max_queries_per_pattern",
"filters = lucene.translate_to_lucene_filter(components)\ncql = 'SELECT name FROM %s.%s' % (self.keyspace_metadata, table)\nif filters:\n cql += \" WHERE expr(%s_... | <|body_start_0|>
self.keyspace_metadata = keyspace
self.max_metrics_per_pattern = max_metrics_per_pattern
self.max_queries_per_pattern = max_queries_per_pattern
<|end_body_0|>
<|body_start_1|>
filters = lucene.translate_to_lucene_filter(components)
cql = 'SELECT name FROM %s.%s'... | Cassandra SASI Query generator. | CassandraStratioLucene | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CassandraStratioLucene:
"""Cassandra SASI Query generator."""
def __init__(self, keyspace, max_queries_per_pattern, max_metrics_per_pattern):
"""Initialize the query generator."""
<|body_0|>
def generate_queries(self, table, components):
"""Generate queries based... | stack_v2_sparse_classes_36k_train_003657 | 2,921 | permissive | [
{
"docstring": "Initialize the query generator.",
"name": "__init__",
"signature": "def __init__(self, keyspace, max_queries_per_pattern, max_metrics_per_pattern)"
},
{
"docstring": "Generate queries based on components.",
"name": "generate_queries",
"signature": "def generate_queries(se... | 3 | stack_v2_sparse_classes_30k_train_010910 | Implement the Python class `CassandraStratioLucene` described below.
Class description:
Cassandra SASI Query generator.
Method signatures and docstrings:
- def __init__(self, keyspace, max_queries_per_pattern, max_metrics_per_pattern): Initialize the query generator.
- def generate_queries(self, table, components): G... | Implement the Python class `CassandraStratioLucene` described below.
Class description:
Cassandra SASI Query generator.
Method signatures and docstrings:
- def __init__(self, keyspace, max_queries_per_pattern, max_metrics_per_pattern): Initialize the query generator.
- def generate_queries(self, table, components): G... | 1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30 | <|skeleton|>
class CassandraStratioLucene:
"""Cassandra SASI Query generator."""
def __init__(self, keyspace, max_queries_per_pattern, max_metrics_per_pattern):
"""Initialize the query generator."""
<|body_0|>
def generate_queries(self, table, components):
"""Generate queries based... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CassandraStratioLucene:
"""Cassandra SASI Query generator."""
def __init__(self, keyspace, max_queries_per_pattern, max_metrics_per_pattern):
"""Initialize the query generator."""
self.keyspace_metadata = keyspace
self.max_metrics_per_pattern = max_metrics_per_pattern
self... | the_stack_v2_python_sparse | biggraphite/drivers/cassandra_stratio_lucene.py | criteo/biggraphite | train | 129 |
0df171673b8338464d988aacc90d42ec6dc03b02 | [
"policy = policy_fn(ACT_SPACE_SIZE, **policy_fn_arguments)\nobs = fake_observations(BATCH_SIZE)\ndata = policy(obs)\nself.assertIsNotNone(data)\nself.assertEqual(len(data), 3)\naction, log_prob, entropy = data\nself.assertEqual(log_prob.shape, (BATCH_SIZE,))\nself.assertEqual(entropy.shape, (BATCH_SIZE,))\nif polic... | <|body_start_0|>
policy = policy_fn(ACT_SPACE_SIZE, **policy_fn_arguments)
obs = fake_observations(BATCH_SIZE)
data = policy(obs)
self.assertIsNotNone(data)
self.assertEqual(len(data), 3)
action, log_prob, entropy = data
self.assertEqual(log_prob.shape, (BATCH_SIZ... | Common class to run tests for policies. | PoliciesTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoliciesTest:
"""Common class to run tests for policies."""
def test_policy(self, policy_fn, policy_fn_arguments, policy_type):
"""Test if policy return types are good."""
<|body_0|>
def test_normal_policies_learnable_variables(self):
"""Make sure that fixed_std ... | stack_v2_sparse_classes_36k_train_003658 | 3,873 | permissive | [
{
"docstring": "Test if policy return types are good.",
"name": "test_policy",
"signature": "def test_policy(self, policy_fn, policy_fn_arguments, policy_type)"
},
{
"docstring": "Make sure that fixed_std will not learn the standard deviation.",
"name": "test_normal_policies_learnable_variab... | 2 | stack_v2_sparse_classes_30k_test_000896 | Implement the Python class `PoliciesTest` described below.
Class description:
Common class to run tests for policies.
Method signatures and docstrings:
- def test_policy(self, policy_fn, policy_fn_arguments, policy_type): Test if policy return types are good.
- def test_normal_policies_learnable_variables(self): Make... | Implement the Python class `PoliciesTest` described below.
Class description:
Common class to run tests for policies.
Method signatures and docstrings:
- def test_policy(self, policy_fn, policy_fn_arguments, policy_type): Test if policy return types are good.
- def test_normal_policies_learnable_variables(self): Make... | 96c99bc67ce40559c61bdb6110f625671fc96055 | <|skeleton|>
class PoliciesTest:
"""Common class to run tests for policies."""
def test_policy(self, policy_fn, policy_fn_arguments, policy_type):
"""Test if policy return types are good."""
<|body_0|>
def test_normal_policies_learnable_variables(self):
"""Make sure that fixed_std ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PoliciesTest:
"""Common class to run tests for policies."""
def test_policy(self, policy_fn, policy_fn_arguments, policy_type):
"""Test if policy return types are good."""
policy = policy_fn(ACT_SPACE_SIZE, **policy_fn_arguments)
obs = fake_observations(BATCH_SIZE)
data = ... | the_stack_v2_python_sparse | eager_pg/policies_test.py | muskanmahajan37/policy-learning-landscape | train | 0 |
5ac042dc48bba532baa5ab488df8b05abf4fd49a | [
"self.docs = []\nself.autoExpire = autoExpire\nself.autoCleanup = autoCleanup",
"if self.autoCleanup:\n self.purgeExpired()\ngmtime = gmtimeSeconds()\nreport = {'gmtime': gmtime, 'uuid': uuid, 'timestamp': encodeTimestamp(gmtime), 'entry': entry, 'task': task}\nself.docs.append(report)",
"gmtime = gmtimeSeco... | <|body_start_0|>
self.docs = []
self.autoExpire = autoExpire
self.autoCleanup = autoCleanup
<|end_body_0|>
<|body_start_1|>
if self.autoCleanup:
self.purgeExpired()
gmtime = gmtimeSeconds()
report = {'gmtime': gmtime, 'uuid': uuid, 'timestamp': encodeTimestam... | MSPileupReport class represents MSPileup report object(s) | MSPileupReport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MSPileupReport:
"""MSPileupReport class represents MSPileup report object(s)"""
def __init__(self, autoExpire=3600, autoCleanup=False):
"""Constructor for MSPileup object"""
<|body_0|>
def addEntry(self, task, uuid, entry):
"""Add new entry into MSPileup document... | stack_v2_sparse_classes_36k_train_003659 | 2,046 | permissive | [
{
"docstring": "Constructor for MSPileup object",
"name": "__init__",
"signature": "def __init__(self, autoExpire=3600, autoCleanup=False)"
},
{
"docstring": "Add new entry into MSPileup documents :param task: task name :param uuid: unique id of the entry :param entry: entry message or any other... | 5 | null | Implement the Python class `MSPileupReport` described below.
Class description:
MSPileupReport class represents MSPileup report object(s)
Method signatures and docstrings:
- def __init__(self, autoExpire=3600, autoCleanup=False): Constructor for MSPileup object
- def addEntry(self, task, uuid, entry): Add new entry i... | Implement the Python class `MSPileupReport` described below.
Class description:
MSPileupReport class represents MSPileup report object(s)
Method signatures and docstrings:
- def __init__(self, autoExpire=3600, autoCleanup=False): Constructor for MSPileup object
- def addEntry(self, task, uuid, entry): Add new entry i... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class MSPileupReport:
"""MSPileupReport class represents MSPileup report object(s)"""
def __init__(self, autoExpire=3600, autoCleanup=False):
"""Constructor for MSPileup object"""
<|body_0|>
def addEntry(self, task, uuid, entry):
"""Add new entry into MSPileup document... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MSPileupReport:
"""MSPileupReport class represents MSPileup report object(s)"""
def __init__(self, autoExpire=3600, autoCleanup=False):
"""Constructor for MSPileup object"""
self.docs = []
self.autoExpire = autoExpire
self.autoCleanup = autoCleanup
def addEntry(self, ... | the_stack_v2_python_sparse | src/python/WMCore/MicroService/MSPileup/DataStructs/MSPileupReport.py | vkuznet/WMCore | train | 0 |
131350f4ad7bf131b87eaae5d725f6166d1d243e | [
"self.history = {}\nself.current_word = ''\nfor i in range(len(sentences)):\n self.history[sentences[i]] = times[i]",
"output = []\nif c == '#':\n self.history.update({self.current_word: self.history.get(self.current_word, 0) + 1})\n self.current_word = ''\nelse:\n result = []\n self.current_word +... | <|body_start_0|>
self.history = {}
self.current_word = ''
for i in range(len(sentences)):
self.history[sentences[i]] = times[i]
<|end_body_0|>
<|body_start_1|>
output = []
if c == '#':
self.history.update({self.current_word: self.history.get(self.current_... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.history = {}
... | stack_v2_sparse_classes_36k_train_003660 | 3,452 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | null | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | dc47ee290352473d28243b43ec6f0e5b6bdec828 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
self.history = {}
self.current_word = ''
for i in range(len(sentences)):
self.history[sentences[i]] = times[i]
def input(self, c):
""":type... | the_stack_v2_python_sparse | Amazon/Design/Design Search Autocomplete System.py | probaku1234/LeetCodeAlgorithmSolution | train | 0 | |
bf742786af27126827742e560b85c36298c91104 | [
"pos = self.binaryToDecimal(pos)\nif pos == 0:\n return 0\nelif pos == 1:\n return 2\nelif pos == 2:\n return 8\nelif pos == 3:\n return 6\nelif pos == 4 or pos == 8 or pos == 12:\n return 1\nelif pos == 5 or pos == 9 or pos == 13:\n return 5\nelif pos == 6 or pos == 10 or pos == 14:\n return 7... | <|body_start_0|>
pos = self.binaryToDecimal(pos)
if pos == 0:
return 0
elif pos == 1:
return 2
elif pos == 2:
return 8
elif pos == 3:
return 6
elif pos == 4 or pos == 8 or pos == 12:
return 1
elif pos == ... | 区域与块对应关系 | RegionMap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegionMap:
"""区域与块对应关系"""
def regionMap(self, pos):
"""区域对应关系"""
<|body_0|>
def unitMap(self, pos):
"""单元对应关系"""
<|body_1|>
def binaryToDecimal(self, binArray):
"""二进制转化为十进制"""
<|body_2|>
def GetRegion(self, posArray):
""... | stack_v2_sparse_classes_36k_train_003661 | 1,564 | no_license | [
{
"docstring": "区域对应关系",
"name": "regionMap",
"signature": "def regionMap(self, pos)"
},
{
"docstring": "单元对应关系",
"name": "unitMap",
"signature": "def unitMap(self, pos)"
},
{
"docstring": "二进制转化为十进制",
"name": "binaryToDecimal",
"signature": "def binaryToDecimal(self, bin... | 4 | null | Implement the Python class `RegionMap` described below.
Class description:
区域与块对应关系
Method signatures and docstrings:
- def regionMap(self, pos): 区域对应关系
- def unitMap(self, pos): 单元对应关系
- def binaryToDecimal(self, binArray): 二进制转化为十进制
- def GetRegion(self, posArray): 获取位置 | Implement the Python class `RegionMap` described below.
Class description:
区域与块对应关系
Method signatures and docstrings:
- def regionMap(self, pos): 区域对应关系
- def unitMap(self, pos): 单元对应关系
- def binaryToDecimal(self, binArray): 二进制转化为十进制
- def GetRegion(self, posArray): 获取位置
<|skeleton|>
class RegionMap:
"""区域与块对应关... | 42ba71e5c134295c54d22cda73dd03af3af739e4 | <|skeleton|>
class RegionMap:
"""区域与块对应关系"""
def regionMap(self, pos):
"""区域对应关系"""
<|body_0|>
def unitMap(self, pos):
"""单元对应关系"""
<|body_1|>
def binaryToDecimal(self, binArray):
"""二进制转化为十进制"""
<|body_2|>
def GetRegion(self, posArray):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegionMap:
"""区域与块对应关系"""
def regionMap(self, pos):
"""区域对应关系"""
pos = self.binaryToDecimal(pos)
if pos == 0:
return 0
elif pos == 1:
return 2
elif pos == 2:
return 8
elif pos == 3:
return 6
elif pos =... | the_stack_v2_python_sparse | VideoSampling/RegionMap.py | oneApple/NewNetWorkDepartMent | train | 1 |
b04fd945061f57090941fd0c5021759af2ae09ba | [
"PermShkMinNext = np.min(self.IncShkDstn.atoms[0])\nTranShkMinNext = np.min(self.IncShkDstn.atoms[1])\nself.BoroCnstNat = (self.solution_next.attrs['m_nrm_min'] - TranShkMinNext) * (self.params.PermGroFac * PermShkMinNext) / self.params.Rfree",
"next_state = {}\nnext_state['mNrm'] = post_state['aNrm'] * params.Rf... | <|body_start_0|>
PermShkMinNext = np.min(self.IncShkDstn.atoms[0])
TranShkMinNext = np.min(self.IncShkDstn.atoms[1])
self.BoroCnstNat = (self.solution_next.attrs['m_nrm_min'] - TranShkMinNext) * (self.params.PermGroFac * PermShkMinNext) / self.params.Rfree
<|end_body_0|>
<|body_start_1|>
... | Solver for IndShockLabeledType. | ConsIndShockLabeledSolver | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsIndShockLabeledSolver:
"""Solver for IndShockLabeledType."""
def calculate_borrowing_constraint(self):
"""Calculate the minimum allowable value of money resources in this period. This is different from the perfect foresight natural borrowing constraint because of the presence of ... | stack_v2_sparse_classes_36k_train_003662 | 40,507 | permissive | [
{
"docstring": "Calculate the minimum allowable value of money resources in this period. This is different from the perfect foresight natural borrowing constraint because of the presence of income uncertainty.",
"name": "calculate_borrowing_constraint",
"signature": "def calculate_borrowing_constraint(s... | 4 | stack_v2_sparse_classes_30k_val_000974 | Implement the Python class `ConsIndShockLabeledSolver` described below.
Class description:
Solver for IndShockLabeledType.
Method signatures and docstrings:
- def calculate_borrowing_constraint(self): Calculate the minimum allowable value of money resources in this period. This is different from the perfect foresight... | Implement the Python class `ConsIndShockLabeledSolver` described below.
Class description:
Solver for IndShockLabeledType.
Method signatures and docstrings:
- def calculate_borrowing_constraint(self): Calculate the minimum allowable value of money resources in this period. This is different from the perfect foresight... | 7ce7138b6d9617a28fd4448936be3d61acad21d8 | <|skeleton|>
class ConsIndShockLabeledSolver:
"""Solver for IndShockLabeledType."""
def calculate_borrowing_constraint(self):
"""Calculate the minimum allowable value of money resources in this period. This is different from the perfect foresight natural borrowing constraint because of the presence of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConsIndShockLabeledSolver:
"""Solver for IndShockLabeledType."""
def calculate_borrowing_constraint(self):
"""Calculate the minimum allowable value of money resources in this period. This is different from the perfect foresight natural borrowing constraint because of the presence of income uncert... | the_stack_v2_python_sparse | HARK/ConsumptionSaving/ConsLabeledModel.py | econ-ark/HARK | train | 315 |
6c76187299f7f913d3618943e30784bd2e5744f4 | [
"result = {'id': self.id, 'createDateTime': model_utils.format_ts(self.create_ts), 'registrationId': self.registration_id, 'reportData': self.report_data, 'reportType': self.report_type}\nif self.doc_storage_url:\n result['documentStorageURL'] = self.doc_storage_url\nreturn result",
"try:\n db.session.add(s... | <|body_start_0|>
result = {'id': self.id, 'createDateTime': model_utils.format_ts(self.create_ts), 'registrationId': self.registration_id, 'reportData': self.report_data, 'reportType': self.report_type}
if self.doc_storage_url:
result['documentStorageURL'] = self.doc_storage_url
retu... | This class maintains MHR registration report information. | MhrRegistrationReport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MhrRegistrationReport:
"""This class maintains MHR registration report information."""
def json(self) -> dict:
"""Return the verification report information as a json object."""
<|body_0|>
def save(self):
"""Render a record of mhr registration report information ... | stack_v2_sparse_classes_36k_train_003663 | 3,564 | permissive | [
{
"docstring": "Return the verification report information as a json object.",
"name": "json",
"signature": "def json(self) -> dict"
},
{
"docstring": "Render a record of mhr registration report information to the local cache.",
"name": "save",
"signature": "def save(self)"
},
{
... | 5 | null | Implement the Python class `MhrRegistrationReport` described below.
Class description:
This class maintains MHR registration report information.
Method signatures and docstrings:
- def json(self) -> dict: Return the verification report information as a json object.
- def save(self): Render a record of mhr registratio... | Implement the Python class `MhrRegistrationReport` described below.
Class description:
This class maintains MHR registration report information.
Method signatures and docstrings:
- def json(self) -> dict: Return the verification report information as a json object.
- def save(self): Render a record of mhr registratio... | af1a4458bb78c16ecca484514d4bd0d1d8c24b5d | <|skeleton|>
class MhrRegistrationReport:
"""This class maintains MHR registration report information."""
def json(self) -> dict:
"""Return the verification report information as a json object."""
<|body_0|>
def save(self):
"""Render a record of mhr registration report information ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MhrRegistrationReport:
"""This class maintains MHR registration report information."""
def json(self) -> dict:
"""Return the verification report information as a json object."""
result = {'id': self.id, 'createDateTime': model_utils.format_ts(self.create_ts), 'registrationId': self.regist... | the_stack_v2_python_sparse | mhr_api/src/mhr_api/models/mhr_registration_report.py | bcgov/ppr | train | 4 |
59b536f874545d188c6553b216f1b8244d745607 | [
"l_obj = IrrigationZoneData()\nXmlConfigTools.read_base_object_xml(l_obj, p_xml)\nl_obj.Duration = PutGetXML.get_time_from_xml(p_xml, 'Duration')\nl_obj.EmitterCount = PutGetXML.get_int_from_xml(p_xml, 'EmitterCount', 0)\nl_obj.EmitterType = PutGetXML.get_text_from_xml(p_xml, 'EmitterType')\nl_obj.Next = PutGetXML.... | <|body_start_0|>
l_obj = IrrigationZoneData()
XmlConfigTools.read_base_object_xml(l_obj, p_xml)
l_obj.Duration = PutGetXML.get_time_from_xml(p_xml, 'Duration')
l_obj.EmitterCount = PutGetXML.get_int_from_xml(p_xml, 'EmitterCount', 0)
l_obj.EmitterType = PutGetXML.get_text_from_xm... | Xml | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Xml:
def _read_one_zone(p_xml):
"""@param p_xml: XML information for one Zone. @return: an IrrigationZone object filled in with data from the XML passed in"""
<|body_0|>
def _write_one_zone(p_obj):
"""@param p_obj: is one zone object @return the XML for one Zone"""
... | stack_v2_sparse_classes_36k_train_003664 | 6,327 | no_license | [
{
"docstring": "@param p_xml: XML information for one Zone. @return: an IrrigationZone object filled in with data from the XML passed in",
"name": "_read_one_zone",
"signature": "def _read_one_zone(p_xml)"
},
{
"docstring": "@param p_obj: is one zone object @return the XML for one Zone",
"na... | 6 | null | Implement the Python class `Xml` described below.
Class description:
Implement the Xml class.
Method signatures and docstrings:
- def _read_one_zone(p_xml): @param p_xml: XML information for one Zone. @return: an IrrigationZone object filled in with data from the XML passed in
- def _write_one_zone(p_obj): @param p_o... | Implement the Python class `Xml` described below.
Class description:
Implement the Xml class.
Method signatures and docstrings:
- def _read_one_zone(p_xml): @param p_xml: XML information for one Zone. @return: an IrrigationZone object filled in with data from the XML passed in
- def _write_one_zone(p_obj): @param p_o... | 8ccbbd1494b7b33ff5099d321cda634fbb254ceb | <|skeleton|>
class Xml:
def _read_one_zone(p_xml):
"""@param p_xml: XML information for one Zone. @return: an IrrigationZone object filled in with data from the XML passed in"""
<|body_0|>
def _write_one_zone(p_obj):
"""@param p_obj: is one zone object @return the XML for one Zone"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Xml:
def _read_one_zone(p_xml):
"""@param p_xml: XML information for one Zone. @return: an IrrigationZone object filled in with data from the XML passed in"""
l_obj = IrrigationZoneData()
XmlConfigTools.read_base_object_xml(l_obj, p_xml)
l_obj.Duration = PutGetXML.get_time_from... | the_stack_v2_python_sparse | Project/src/Modules/House/Irrigation/irrigation_xml.py | bopopescu/PyHouse | train | 0 | |
ea92aca8b46c3388f67c9d72671ba2e698f2ebcf | [
"super(EditUserForm, self).__init__(*args, **kwargs)\nif self.instance.is_superuser:\n self.fields['is_admin'].initial = True",
"user = super(EditUserForm, self).save(commit=False)\nif self.cleaned_data['is_admin']:\n user.is_superuser = True\nif commit:\n user.save()\nreturn user"
] | <|body_start_0|>
super(EditUserForm, self).__init__(*args, **kwargs)
if self.instance.is_superuser:
self.fields['is_admin'].initial = True
<|end_body_0|>
<|body_start_1|>
user = super(EditUserForm, self).save(commit=False)
if self.cleaned_data['is_admin']:
user.i... | Class for creating a new user | EditUserForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditUserForm:
"""Class for creating a new user"""
def __init__(self, *args, **kwargs):
"""Override init to customise the UserCreationForm widget class appearance"""
<|body_0|>
def save(self, commit=True):
"""Override save to make user a superuser"""
<|bod... | stack_v2_sparse_classes_36k_train_003665 | 30,652 | permissive | [
{
"docstring": "Override init to customise the UserCreationForm widget class appearance",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Override save to make user a superuser",
"name": "save",
"signature": "def save(self, commit=True)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007057 | Implement the Python class `EditUserForm` described below.
Class description:
Class for creating a new user
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Override init to customise the UserCreationForm widget class appearance
- def save(self, commit=True): Override save to make user a super... | Implement the Python class `EditUserForm` described below.
Class description:
Class for creating a new user
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Override init to customise the UserCreationForm widget class appearance
- def save(self, commit=True): Override save to make user a super... | fdff8b8ddc202c53edda2a509a50c4e83013474d | <|skeleton|>
class EditUserForm:
"""Class for creating a new user"""
def __init__(self, *args, **kwargs):
"""Override init to customise the UserCreationForm widget class appearance"""
<|body_0|>
def save(self, commit=True):
"""Override save to make user a superuser"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditUserForm:
"""Class for creating a new user"""
def __init__(self, *args, **kwargs):
"""Override init to customise the UserCreationForm widget class appearance"""
super(EditUserForm, self).__init__(*args, **kwargs)
if self.instance.is_superuser:
self.fields['is_admin... | the_stack_v2_python_sparse | rse/forms.py | RSE-Sheffield/RSEAdmin | train | 22 |
db27e91a31aa202373aea10ca485ebbcc510c6f2 | [
"for value in my_results:\n try:\n with patch('builtins.input', return_value=str(value)):\n game = SubtractSquareGame(True)\n ite_result = minimax_iterative_strategy(game)\n rec_result = minimax_recursive_strategy(game)\n self.assertEqual(ite_result, rec_result)\n except... | <|body_start_0|>
for value in my_results:
try:
with patch('builtins.input', return_value=str(value)):
game = SubtractSquareGame(True)
ite_result = minimax_iterative_strategy(game)
rec_result = minimax_recursive_strategy(game)
... | MinimaxUnitTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinimaxUnitTests:
def test_result_consistency(self):
"""Too lazy to write one."""
<|body_0|>
def test_iterative_subtract_square(self):
"""Too lazy to write one."""
<|body_1|>
def test_recursive_subtract_square(self):
"""Too lazy to write one."""
... | stack_v2_sparse_classes_36k_train_003666 | 6,359 | no_license | [
{
"docstring": "Too lazy to write one.",
"name": "test_result_consistency",
"signature": "def test_result_consistency(self)"
},
{
"docstring": "Too lazy to write one.",
"name": "test_iterative_subtract_square",
"signature": "def test_iterative_subtract_square(self)"
},
{
"docstri... | 5 | stack_v2_sparse_classes_30k_train_000886 | Implement the Python class `MinimaxUnitTests` described below.
Class description:
Implement the MinimaxUnitTests class.
Method signatures and docstrings:
- def test_result_consistency(self): Too lazy to write one.
- def test_iterative_subtract_square(self): Too lazy to write one.
- def test_recursive_subtract_square(... | Implement the Python class `MinimaxUnitTests` described below.
Class description:
Implement the MinimaxUnitTests class.
Method signatures and docstrings:
- def test_result_consistency(self): Too lazy to write one.
- def test_iterative_subtract_square(self): Too lazy to write one.
- def test_recursive_subtract_square(... | e57707b91f5c67a5a9621019134eba99e4daf001 | <|skeleton|>
class MinimaxUnitTests:
def test_result_consistency(self):
"""Too lazy to write one."""
<|body_0|>
def test_iterative_subtract_square(self):
"""Too lazy to write one."""
<|body_1|>
def test_recursive_subtract_square(self):
"""Too lazy to write one."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MinimaxUnitTests:
def test_result_consistency(self):
"""Too lazy to write one."""
for value in my_results:
try:
with patch('builtins.input', return_value=str(value)):
game = SubtractSquareGame(True)
ite_result = minimax_iterative_... | the_stack_v2_python_sparse | assignment/a2/Penguin Test/minimax_penguin_tests_enhanced(not failing).py | TianyuDu/csc148 | train | 1 | |
e5df29c7af9c2c37732937ae4c1d4158f7a6872f | [
"self.id = id\nself.type_id = type_id\nself.name = name\nself.created = to_datetime_utc(created)\nself.modified = to_datetime_utc(modified)",
"if type_id is not None:\n self.type_id = type_id\nif name is not None:\n self.name = name\nif modified is not None:\n self.modified = to_datetime_utc(modified)"
] | <|body_start_0|>
self.id = id
self.type_id = type_id
self.name = name
self.created = to_datetime_utc(created)
self.modified = to_datetime_utc(modified)
<|end_body_0|>
<|body_start_1|>
if type_id is not None:
self.type_id = type_id
if name is not None:... | TelescopeType | [
"MIT",
"BSD-2-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TelescopeType:
def __init__(self, id: int=None, type_id: str=None, name: str=None, created: pendulum.DateTime=None, modified: pendulum.DateTime=None):
"""Construct a TelescopeType object. :param id: unique id. :param type_id: a unique string id for the telescope type. :param name: the na... | stack_v2_sparse_classes_36k_train_003667 | 12,117 | permissive | [
{
"docstring": "Construct a TelescopeType object. :param id: unique id. :param type_id: a unique string id for the telescope type. :param name: the name. :param created: datetime created in UTC. :param modified: datetime modified in UTC.",
"name": "__init__",
"signature": "def __init__(self, id: int=Non... | 2 | null | Implement the Python class `TelescopeType` described below.
Class description:
Implement the TelescopeType class.
Method signatures and docstrings:
- def __init__(self, id: int=None, type_id: str=None, name: str=None, created: pendulum.DateTime=None, modified: pendulum.DateTime=None): Construct a TelescopeType object... | Implement the Python class `TelescopeType` described below.
Class description:
Implement the TelescopeType class.
Method signatures and docstrings:
- def __init__(self, id: int=None, type_id: str=None, name: str=None, created: pendulum.DateTime=None, modified: pendulum.DateTime=None): Construct a TelescopeType object... | 64b62cba83110fea60e91506dff4a83ba9931ba9 | <|skeleton|>
class TelescopeType:
def __init__(self, id: int=None, type_id: str=None, name: str=None, created: pendulum.DateTime=None, modified: pendulum.DateTime=None):
"""Construct a TelescopeType object. :param id: unique id. :param type_id: a unique string id for the telescope type. :param name: the na... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TelescopeType:
def __init__(self, id: int=None, type_id: str=None, name: str=None, created: pendulum.DateTime=None, modified: pendulum.DateTime=None):
"""Construct a TelescopeType object. :param id: unique id. :param type_id: a unique string id for the telescope type. :param name: the name. :param cre... | the_stack_v2_python_sparse | observatory-api/observatory/api/server/orm.py | kieranroberts/observatory-platform | train | 0 | |
b88ebf387658facf0e3b1cedd44c020574e06d65 | [
"queryset = Entity.objects.filter(id__in=ids).filter_for_user(user)\nactual_ids = queryset.values_list('id', flat=True)\nmissing_ids = list(set(ids) - set(actual_ids))\nif missing_ids:\n raise exceptions.ParseError('Entities with the following ids not found: {}'.format(', '.join(map(str, missing_ids))))\nreturn ... | <|body_start_0|>
queryset = Entity.objects.filter(id__in=ids).filter_for_user(user)
actual_ids = queryset.values_list('id', flat=True)
missing_ids = list(set(ids) - set(actual_ids))
if missing_ids:
raise exceptions.ParseError('Entities with the following ids not found: {}'.fo... | API view for entities. | EntityViewSet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityViewSet:
"""API view for entities."""
def _get_entities(self, user, ids):
"""Return entities queryset based on provided entity ids."""
<|body_0|>
def move_to_collection(self, request, *args, **kwargs):
"""Move samples from source to destination collection."... | stack_v2_sparse_classes_36k_train_003668 | 4,290 | permissive | [
{
"docstring": "Return entities queryset based on provided entity ids.",
"name": "_get_entities",
"signature": "def _get_entities(self, user, ids)"
},
{
"docstring": "Move samples from source to destination collection.",
"name": "move_to_collection",
"signature": "def move_to_collection(... | 4 | stack_v2_sparse_classes_30k_train_011090 | Implement the Python class `EntityViewSet` described below.
Class description:
API view for entities.
Method signatures and docstrings:
- def _get_entities(self, user, ids): Return entities queryset based on provided entity ids.
- def move_to_collection(self, request, *args, **kwargs): Move samples from source to des... | Implement the Python class `EntityViewSet` described below.
Class description:
API view for entities.
Method signatures and docstrings:
- def _get_entities(self, user, ids): Return entities queryset based on provided entity ids.
- def move_to_collection(self, request, *args, **kwargs): Move samples from source to des... | ebf0f198bff9e03b248573a8d030822d54151c19 | <|skeleton|>
class EntityViewSet:
"""API view for entities."""
def _get_entities(self, user, ids):
"""Return entities queryset based on provided entity ids."""
<|body_0|>
def move_to_collection(self, request, *args, **kwargs):
"""Move samples from source to destination collection."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntityViewSet:
"""API view for entities."""
def _get_entities(self, user, ids):
"""Return entities queryset based on provided entity ids."""
queryset = Entity.objects.filter(id__in=ids).filter_for_user(user)
actual_ids = queryset.values_list('id', flat=True)
missing_ids = ... | the_stack_v2_python_sparse | resolwe/flow/views/entity.py | gregorjerse/resolwe | train | 0 |
a221aa851847a5a5125f2542b6173ee31971a31c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AttackSimulationRoot()",
"from .entity import Entity\nfrom .simulation import Simulation\nfrom .simulation_automation import SimulationAutomation\nfrom .entity import Entity\nfrom .simulation import Simulation\nfrom .simulation_automat... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AttackSimulationRoot()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .simulation import Simulation
from .simulation_automation import SimulationAutomation
... | AttackSimulationRoot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttackSimulationRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttackSimulationRoot:
"""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_36k_train_003669 | 2,783 | 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: AttackSimulationRoot",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | stack_v2_sparse_classes_30k_train_011476 | Implement the Python class `AttackSimulationRoot` described below.
Class description:
Implement the AttackSimulationRoot class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttackSimulationRoot: Creates a new instance of the appropriate class based o... | Implement the Python class `AttackSimulationRoot` described below.
Class description:
Implement the AttackSimulationRoot class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttackSimulationRoot: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AttackSimulationRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttackSimulationRoot:
"""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_36k | data/stack_v2_sparse_classes_30k | class AttackSimulationRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttackSimulationRoot:
"""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/models/attack_simulation_root.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3106cb9233ae0604f22467633ca8f556cb0207f5 | [
"self._r1 = r1\nself._r2 = r2\nself._direction = direction",
"delev, dazim = direction\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.sin(delev)\nresult_shape = x1.shape\n... | <|body_start_0|>
self._r1 = r1
self._r2 = r2
self._direction = direction
<|end_body_0|>
<|body_start_1|>
delev, dazim = direction
x1 = -r1 * np.cos(elev) * np.cos(azim)
y1 = -r1 * np.cos(elev) * np.sin(azim)
z1 = r1 * np.sin(elev)
dx1 = -np.cos(delev) * n... | Map points from one sphere to another. spheres are cocentered | SphereToSphereMap | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphereToSphereMap:
"""Map points from one sphere to another. spheres are cocentered"""
def __init__(self, r1, r2, direction):
"""r1: initial sphere radius r2: projected sphere radius direction: can be a tuple or a list of 2 elements elevation, azimuth"""
<|body_0|>
def m... | stack_v2_sparse_classes_36k_train_003670 | 16,243 | permissive | [
{
"docstring": "r1: initial sphere radius r2: projected sphere radius direction: can be a tuple or a list of 2 elements elevation, azimuth",
"name": "__init__",
"signature": "def __init__(self, r1, r2, direction)"
},
{
"docstring": "In case of 2 points of intersection picks the closest",
"na... | 4 | stack_v2_sparse_classes_30k_train_007730 | Implement the Python class `SphereToSphereMap` described below.
Class description:
Map points from one sphere to another. spheres are cocentered
Method signatures and docstrings:
- def __init__(self, r1, r2, direction): r1: initial sphere radius r2: projected sphere radius direction: can be a tuple or a list of 2 ele... | Implement the Python class `SphereToSphereMap` described below.
Class description:
Map points from one sphere to another. spheres are cocentered
Method signatures and docstrings:
- def __init__(self, r1, r2, direction): r1: initial sphere radius r2: projected sphere radius direction: can be a tuple or a list of 2 ele... | fdab351e6c5530c8f051193158856ba6ef11d715 | <|skeleton|>
class SphereToSphereMap:
"""Map points from one sphere to another. spheres are cocentered"""
def __init__(self, r1, r2, direction):
"""r1: initial sphere radius r2: projected sphere radius direction: can be a tuple or a list of 2 elements elevation, azimuth"""
<|body_0|>
def m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SphereToSphereMap:
"""Map points from one sphere to another. spheres are cocentered"""
def __init__(self, r1, r2, direction):
"""r1: initial sphere radius r2: projected sphere radius direction: can be a tuple or a list of 2 elements elevation, azimuth"""
self._r1 = r1
self._r2 = r... | the_stack_v2_python_sparse | retina/screen/map/mapimpl.py | neurokernel/retina | train | 5 |
057149a0d2d4bef7af9e7fb73c26d68f122b5bd1 | [
"self.fin = fin\nself.stopd = stopdict\nself.result = []\nif userdict is not None:\n jieba.load_userdict(userdict)",
"stopwords = {}\ntry:\n fstop = open(self.stopd)\nexcept IOError:\n print(self.stopd, '文件读取错误请检查!')\n exit(0)\nfor eachWord in fstop:\n stopwords[eachWord.strip()] = eachWord.strip()... | <|body_start_0|>
self.fin = fin
self.stopd = stopdict
self.result = []
if userdict is not None:
jieba.load_userdict(userdict)
<|end_body_0|>
<|body_start_1|>
stopwords = {}
try:
fstop = open(self.stopd)
except IOError:
print(se... | 切词类,把语料库的文本内容切词 | Cutword | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cutword:
"""切词类,把语料库的文本内容切词"""
def __init__(self, fin, userdict=None, stopdict=stopd):
""":param fin: 语料库文件 :param userdict: 自定义词典 :param stopdict: 停用词典"""
<|body_0|>
def cut(self, fout=None):
""":param fout: :return:"""
<|body_1|>
def save(self, fou... | stack_v2_sparse_classes_36k_train_003671 | 3,192 | no_license | [
{
"docstring": ":param fin: 语料库文件 :param userdict: 自定义词典 :param stopdict: 停用词典",
"name": "__init__",
"signature": "def __init__(self, fin, userdict=None, stopdict=stopd)"
},
{
"docstring": ":param fout: :return:",
"name": "cut",
"signature": "def cut(self, fout=None)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_015285 | Implement the Python class `Cutword` described below.
Class description:
切词类,把语料库的文本内容切词
Method signatures and docstrings:
- def __init__(self, fin, userdict=None, stopdict=stopd): :param fin: 语料库文件 :param userdict: 自定义词典 :param stopdict: 停用词典
- def cut(self, fout=None): :param fout: :return:
- def save(self, fout): ... | Implement the Python class `Cutword` described below.
Class description:
切词类,把语料库的文本内容切词
Method signatures and docstrings:
- def __init__(self, fin, userdict=None, stopdict=stopd): :param fin: 语料库文件 :param userdict: 自定义词典 :param stopdict: 停用词典
- def cut(self, fout=None): :param fout: :return:
- def save(self, fout): ... | 69e72541ca1d2afe03174f89350f7a4d886928dc | <|skeleton|>
class Cutword:
"""切词类,把语料库的文本内容切词"""
def __init__(self, fin, userdict=None, stopdict=stopd):
""":param fin: 语料库文件 :param userdict: 自定义词典 :param stopdict: 停用词典"""
<|body_0|>
def cut(self, fout=None):
""":param fout: :return:"""
<|body_1|>
def save(self, fou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cutword:
"""切词类,把语料库的文本内容切词"""
def __init__(self, fin, userdict=None, stopdict=stopd):
""":param fin: 语料库文件 :param userdict: 自定义词典 :param stopdict: 停用词典"""
self.fin = fin
self.stopd = stopdict
self.result = []
if userdict is not None:
jieba.load_userdic... | the_stack_v2_python_sparse | rec-engine/mining/nlp/cutword.py | worry1613/dongni-recommendation | train | 1 |
aed94d15ef39f31c2bdcf4d6483901516d2a31db | [
"if attrs['password'] != attrs['password2']:\n raise serializers.ValidationError({'password': \"Password fields didn't match.\"})\nreturn attrs",
"user = User.objects.create(username=validated_data['username'], email=validated_data['email'])\nuser.set_password(validated_data['password'])\nuser.save()\nreturn u... | <|body_start_0|>
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError({'password': "Password fields didn't match."})
return attrs
<|end_body_0|>
<|body_start_1|>
user = User.objects.create(username=validated_data['username'], email=validated_data['email'])
... | Serializer for User model | UserSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSerializer:
"""Serializer for User model"""
def validate(self, attrs):
"""Check that received correct data from user"""
<|body_0|>
def create(self, validated_data):
"""Method for creating user instance"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_003672 | 1,902 | no_license | [
{
"docstring": "Check that received correct data from user",
"name": "validate",
"signature": "def validate(self, attrs)"
},
{
"docstring": "Method for creating user instance",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011007 | Implement the Python class `UserSerializer` described below.
Class description:
Serializer for User model
Method signatures and docstrings:
- def validate(self, attrs): Check that received correct data from user
- def create(self, validated_data): Method for creating user instance | Implement the Python class `UserSerializer` described below.
Class description:
Serializer for User model
Method signatures and docstrings:
- def validate(self, attrs): Check that received correct data from user
- def create(self, validated_data): Method for creating user instance
<|skeleton|>
class UserSerializer:
... | 2f3eeaa9d25ea934bab1e8fc98ce00ccb5fed63e | <|skeleton|>
class UserSerializer:
"""Serializer for User model"""
def validate(self, attrs):
"""Check that received correct data from user"""
<|body_0|>
def create(self, validated_data):
"""Method for creating user instance"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSerializer:
"""Serializer for User model"""
def validate(self, attrs):
"""Check that received correct data from user"""
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError({'password': "Password fields didn't match."})
return attrs
de... | the_stack_v2_python_sparse | book_market/apps/registration/serializers.py | Ivan-Soldatenko/SImple-book-market | train | 0 |
83f4a4c55b96f253dd705d3d2ab699359b66705f | [
"length = len(A)\nresult = -sys.maxsize\nfor i in range(length):\n for j in range(i + 1, length):\n total = A[i] + A[j] + i - j\n result = max(total, result)\nreturn result",
"left = A[0]\nresult = -sys.maxsize\nfor j in range(1, len(A)):\n result = max(result, left + A[j] - j)\n left = max... | <|body_start_0|>
length = len(A)
result = -sys.maxsize
for i in range(length):
for j in range(i + 1, length):
total = A[i] + A[j] + i - j
result = max(total, result)
return result
<|end_body_0|>
<|body_start_1|>
left = A[0]
res... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def best_sight_seeing(self, A: List[int]) -> int:
"""获取最佳观光组合 Args: A: 数组A Returns: 最佳观光值"""
<|body_0|>
def best_sight_seeing_2(self, A: List[int]) -> int:
"""获取最佳观光组合 Args: A: 数组A Returns: 最佳观光值"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_003673 | 2,308 | permissive | [
{
"docstring": "获取最佳观光组合 Args: A: 数组A Returns: 最佳观光值",
"name": "best_sight_seeing",
"signature": "def best_sight_seeing(self, A: List[int]) -> int"
},
{
"docstring": "获取最佳观光组合 Args: A: 数组A Returns: 最佳观光值",
"name": "best_sight_seeing_2",
"signature": "def best_sight_seeing_2(self, A: List... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def best_sight_seeing(self, A: List[int]) -> int: 获取最佳观光组合 Args: A: 数组A Returns: 最佳观光值
- def best_sight_seeing_2(self, A: List[int]) -> int: 获取最佳观光组合 Args: A: 数组A Returns: 最佳观光值 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def best_sight_seeing(self, A: List[int]) -> int: 获取最佳观光组合 Args: A: 数组A Returns: 最佳观光值
- def best_sight_seeing_2(self, A: List[int]) -> int: 获取最佳观光组合 Args: A: 数组A Returns: 最佳观光值
... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def best_sight_seeing(self, A: List[int]) -> int:
"""获取最佳观光组合 Args: A: 数组A Returns: 最佳观光值"""
<|body_0|>
def best_sight_seeing_2(self, A: List[int]) -> int:
"""获取最佳观光组合 Args: A: 数组A Returns: 最佳观光值"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def best_sight_seeing(self, A: List[int]) -> int:
"""获取最佳观光组合 Args: A: 数组A Returns: 最佳观光值"""
length = len(A)
result = -sys.maxsize
for i in range(length):
for j in range(i + 1, length):
total = A[i] + A[j] + i - j
result = m... | the_stack_v2_python_sparse | src/leetcodepython/array/best_sight_seeing_1014.py | zhangyu345293721/leetcode | train | 101 | |
bffb5b2ec43fe0dda7a7121250061023acb31905 | [
"probs = torch.sigmoid(logits)\nnumer = 2 * (probs * labels).sum(dim=1) + smooth\ndenor = (probs.pow(p) + labels.pow(p)).sum(dim=1) + smooth\nloss = 1.0 - numer / denor\nctx.vars = (probs, labels, numer, denor, p, smooth)\nreturn loss",
"probs, labels, numer, denor, p, smooth = ctx.vars\nnumer, denor = (numer.vie... | <|body_start_0|>
probs = torch.sigmoid(logits)
numer = 2 * (probs * labels).sum(dim=1) + smooth
denor = (probs.pow(p) + labels.pow(p)).sum(dim=1) + smooth
loss = 1.0 - numer / denor
ctx.vars = (probs, labels, numer, denor, p, smooth)
return loss
<|end_body_0|>
<|body_sta... | compute backward directly for better numeric stability | SoftDiceLossV2Func | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftDiceLossV2Func:
"""compute backward directly for better numeric stability"""
def forward(ctx, logits, labels, p, smooth):
"""inputs: logits: (N, L) labels: (N, L) outpus: loss: (N,)"""
<|body_0|>
def backward(ctx, grad_output):
"""compute gradient of soft-dic... | stack_v2_sparse_classes_36k_train_003674 | 7,172 | permissive | [
{
"docstring": "inputs: logits: (N, L) labels: (N, L) outpus: loss: (N,)",
"name": "forward",
"signature": "def forward(ctx, logits, labels, p, smooth)"
},
{
"docstring": "compute gradient of soft-dice loss",
"name": "backward",
"signature": "def backward(ctx, grad_output)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021342 | Implement the Python class `SoftDiceLossV2Func` described below.
Class description:
compute backward directly for better numeric stability
Method signatures and docstrings:
- def forward(ctx, logits, labels, p, smooth): inputs: logits: (N, L) labels: (N, L) outpus: loss: (N,)
- def backward(ctx, grad_output): compute... | Implement the Python class `SoftDiceLossV2Func` described below.
Class description:
compute backward directly for better numeric stability
Method signatures and docstrings:
- def forward(ctx, logits, labels, p, smooth): inputs: logits: (N, L) labels: (N, L) outpus: loss: (N,)
- def backward(ctx, grad_output): compute... | 99e04f64fb2ce46c2e6906750a716b93984fbe97 | <|skeleton|>
class SoftDiceLossV2Func:
"""compute backward directly for better numeric stability"""
def forward(ctx, logits, labels, p, smooth):
"""inputs: logits: (N, L) labels: (N, L) outpus: loss: (N,)"""
<|body_0|>
def backward(ctx, grad_output):
"""compute gradient of soft-dic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SoftDiceLossV2Func:
"""compute backward directly for better numeric stability"""
def forward(ctx, logits, labels, p, smooth):
"""inputs: logits: (N, L) labels: (N, L) outpus: loss: (N,)"""
probs = torch.sigmoid(logits)
numer = 2 * (probs * labels).sum(dim=1) + smooth
denor... | the_stack_v2_python_sparse | soft_dice_loss.py | CoinCheung/pytorch-loss | train | 2,079 |
a83b960857a3f56ec08535514ff69d9dbe1b11bc | [
"LOGGER.warning('${%s %s}: %s', cls.TYPE_NAME, value, cls.DEPRECATION_MSG)\nregion, value = read_value_from_path(value).split('@', 1)\nreturn (value, {'region': region})",
"if '@' in value:\n query, args = cls.legacy_parse(value)\nelse:\n query, args = cls.parse(value)\nkms = context.get_session(region=args... | <|body_start_0|>
LOGGER.warning('${%s %s}: %s', cls.TYPE_NAME, value, cls.DEPRECATION_MSG)
region, value = read_value_from_path(value).split('@', 1)
return (value, {'region': region})
<|end_body_0|>
<|body_start_1|>
if '@' in value:
query, args = cls.legacy_parse(value)
... | AWS KMS lookup. | KmsLookup | [
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KmsLookup:
"""AWS KMS lookup."""
def legacy_parse(cls, value: str) -> Tuple[str, Dict[str, str]]:
"""Retain support for legacy lookup syntax. Format of value:: <region>@<encrypted-blob>"""
<|body_0|>
def handle(cls, value: str, context: CfnginContext, **_: Any) -> str:
... | stack_v2_sparse_classes_36k_train_003675 | 2,188 | permissive | [
{
"docstring": "Retain support for legacy lookup syntax. Format of value:: <region>@<encrypted-blob>",
"name": "legacy_parse",
"signature": "def legacy_parse(cls, value: str) -> Tuple[str, Dict[str, str]]"
},
{
"docstring": "Decrypt the specified value with a master key in KMS. Args: value: Para... | 2 | null | Implement the Python class `KmsLookup` described below.
Class description:
AWS KMS lookup.
Method signatures and docstrings:
- def legacy_parse(cls, value: str) -> Tuple[str, Dict[str, str]]: Retain support for legacy lookup syntax. Format of value:: <region>@<encrypted-blob>
- def handle(cls, value: str, context: Cf... | Implement the Python class `KmsLookup` described below.
Class description:
AWS KMS lookup.
Method signatures and docstrings:
- def legacy_parse(cls, value: str) -> Tuple[str, Dict[str, str]]: Retain support for legacy lookup syntax. Format of value:: <region>@<encrypted-blob>
- def handle(cls, value: str, context: Cf... | 0763b06aee07d2cf3f037a49ca0cb81a048c5deb | <|skeleton|>
class KmsLookup:
"""AWS KMS lookup."""
def legacy_parse(cls, value: str) -> Tuple[str, Dict[str, str]]:
"""Retain support for legacy lookup syntax. Format of value:: <region>@<encrypted-blob>"""
<|body_0|>
def handle(cls, value: str, context: CfnginContext, **_: Any) -> str:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KmsLookup:
"""AWS KMS lookup."""
def legacy_parse(cls, value: str) -> Tuple[str, Dict[str, str]]:
"""Retain support for legacy lookup syntax. Format of value:: <region>@<encrypted-blob>"""
LOGGER.warning('${%s %s}: %s', cls.TYPE_NAME, value, cls.DEPRECATION_MSG)
region, value = re... | the_stack_v2_python_sparse | runway/cfngin/lookups/handlers/kms.py | onicagroup/runway | train | 156 |
51bf63a5476320866fe9b1a519617e8f602d86e0 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ConditionalAccessUsers()",
"from .conditional_access_guests_or_external_users import ConditionalAccessGuestsOrExternalUsers\nfrom .conditional_access_guests_or_external_users import ConditionalAccessGuestsOrExternalUsers\nfields: Dict[... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ConditionalAccessUsers()
<|end_body_0|>
<|body_start_1|>
from .conditional_access_guests_or_external_users import ConditionalAccessGuestsOrExternalUsers
from .conditional_access_guests_o... | ConditionalAccessUsers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionalAccessUsers:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessUsers:
"""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 ... | stack_v2_sparse_classes_36k_train_003676 | 5,400 | 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: ConditionalAccessUsers",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | null | Implement the Python class `ConditionalAccessUsers` described below.
Class description:
Implement the ConditionalAccessUsers class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessUsers: Creates a new instance of the appropriate class b... | Implement the Python class `ConditionalAccessUsers` described below.
Class description:
Implement the ConditionalAccessUsers class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessUsers: Creates a new instance of the appropriate class b... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ConditionalAccessUsers:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessUsers:
"""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 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionalAccessUsers:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessUsers:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | the_stack_v2_python_sparse | msgraph/generated/models/conditional_access_users.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b97993ad146bdcd399e7f6300f951abdfa953880 | [
"if not matrix:\n return []\nm, n = (len(matrix), len(matrix[0]))\nd = -1\nans = []\nfor s in range(m + n - 1):\n _min = max(0, s - n + 1)\n _max = min(s, m - 1)\n if d == -1:\n for i in range(_max, _min - 1, -1):\n ans.append(matrix[i][s - i])\n else:\n for i in range(_min, ... | <|body_start_0|>
if not matrix:
return []
m, n = (len(matrix), len(matrix[0]))
d = -1
ans = []
for s in range(m + n - 1):
_min = max(0, s - n + 1)
_max = min(s, m - 1)
if d == -1:
for i in range(_max, _min - 1, -1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDiagonalOrder1(self, matrix: List[List[int]]) -> List[int]:
"""for loop"""
<|body_0|>
def findDiagonalOrder2(self, matrix: List[List[int]]) -> List[int]:
"""while loop"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not matrix:
... | stack_v2_sparse_classes_36k_train_003677 | 1,766 | no_license | [
{
"docstring": "for loop",
"name": "findDiagonalOrder1",
"signature": "def findDiagonalOrder1(self, matrix: List[List[int]]) -> List[int]"
},
{
"docstring": "while loop",
"name": "findDiagonalOrder2",
"signature": "def findDiagonalOrder2(self, matrix: List[List[int]]) -> List[int]"
}
] | 2 | stack_v2_sparse_classes_30k_train_015221 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDiagonalOrder1(self, matrix: List[List[int]]) -> List[int]: for loop
- def findDiagonalOrder2(self, matrix: List[List[int]]) -> List[int]: while loop | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDiagonalOrder1(self, matrix: List[List[int]]) -> List[int]: for loop
- def findDiagonalOrder2(self, matrix: List[List[int]]) -> List[int]: while loop
<|skeleton|>
class ... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def findDiagonalOrder1(self, matrix: List[List[int]]) -> List[int]:
"""for loop"""
<|body_0|>
def findDiagonalOrder2(self, matrix: List[List[int]]) -> List[int]:
"""while loop"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDiagonalOrder1(self, matrix: List[List[int]]) -> List[int]:
"""for loop"""
if not matrix:
return []
m, n = (len(matrix), len(matrix[0]))
d = -1
ans = []
for s in range(m + n - 1):
_min = max(0, s - n + 1)
_ma... | the_stack_v2_python_sparse | Leetcode 0498. Diagonal Traversal.py | Chaoran-sjsu/leetcode | train | 0 | |
c7c9a249d55290e3c80faac5db659750fd379b50 | [
"self.aux_weight = aux_weight\nloss_base_cp = loss_base.copy()\nloss_base_name = loss_base_cp.pop('type')\nif ClassFactory.is_exists('trainer.loss', loss_base_name):\n loss_class = ClassFactory.get_cls('trainer.loss', loss_base_name)\nelse:\n loss_class = getattr(importlib.import_module('tensorflow.losses'), ... | <|body_start_0|>
self.aux_weight = aux_weight
loss_base_cp = loss_base.copy()
loss_base_name = loss_base_cp.pop('type')
if ClassFactory.is_exists('trainer.loss', loss_base_name):
loss_class = ClassFactory.get_cls('trainer.loss', loss_base_name)
else:
loss_... | Class of Mix Auxiliary Loss. :param aux_weight: auxiliary loss weight :type aux_weight: float :loss_base: base loss function :loss_base: str | MixAuxiliaryLoss | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixAuxiliaryLoss:
"""Class of Mix Auxiliary Loss. :param aux_weight: auxiliary loss weight :type aux_weight: float :loss_base: base loss function :loss_base: str"""
def __init__(self, aux_weight, loss_base):
"""Init MixAuxiliaryLoss."""
<|body_0|>
def __call__(self, logi... | stack_v2_sparse_classes_36k_train_003678 | 1,827 | permissive | [
{
"docstring": "Init MixAuxiliaryLoss.",
"name": "__init__",
"signature": "def __init__(self, aux_weight, loss_base)"
},
{
"docstring": "Loss forward function.",
"name": "__call__",
"signature": "def __call__(self, logits, labels)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015067 | Implement the Python class `MixAuxiliaryLoss` described below.
Class description:
Class of Mix Auxiliary Loss. :param aux_weight: auxiliary loss weight :type aux_weight: float :loss_base: base loss function :loss_base: str
Method signatures and docstrings:
- def __init__(self, aux_weight, loss_base): Init MixAuxiliar... | Implement the Python class `MixAuxiliaryLoss` described below.
Class description:
Class of Mix Auxiliary Loss. :param aux_weight: auxiliary loss weight :type aux_weight: float :loss_base: base loss function :loss_base: str
Method signatures and docstrings:
- def __init__(self, aux_weight, loss_base): Init MixAuxiliar... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class MixAuxiliaryLoss:
"""Class of Mix Auxiliary Loss. :param aux_weight: auxiliary loss weight :type aux_weight: float :loss_base: base loss function :loss_base: str"""
def __init__(self, aux_weight, loss_base):
"""Init MixAuxiliaryLoss."""
<|body_0|>
def __call__(self, logi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MixAuxiliaryLoss:
"""Class of Mix Auxiliary Loss. :param aux_weight: auxiliary loss weight :type aux_weight: float :loss_base: base loss function :loss_base: str"""
def __init__(self, aux_weight, loss_base):
"""Init MixAuxiliaryLoss."""
self.aux_weight = aux_weight
loss_base_cp = ... | the_stack_v2_python_sparse | vega/networks/tensorflow/losses/mix_auxiliary_loss.py | huawei-noah/vega | train | 850 |
b84426955d0c3729749742c688beacc5e4cd0aa3 | [
"self.logger = PatchLogger(__name__, debug=debug)\nself._COMMAND_PATH = '/etc/securetea/asp/commands.json'\nself.config_data = self.open_json(self._COMMAND_PATH)\nself.os_name = utils.categorize_os()\nif self.os_name:\n try:\n self.os_config_data = self.config_data[self.os_name]\n except KeyError:\n ... | <|body_start_0|>
self.logger = PatchLogger(__name__, debug=debug)
self._COMMAND_PATH = '/etc/securetea/asp/commands.json'
self.config_data = self.open_json(self._COMMAND_PATH)
self.os_name = utils.categorize_os()
if self.os_name:
try:
self.os_config_da... | Installer Class. | Installer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Installer:
"""Installer Class."""
def __init__(self, debug=False):
"""Initialize Installer. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
<|body_0|>
def open_json(path):
"""Read from JSON file. Args: path (str): Path of the JSON file Ra... | stack_v2_sparse_classes_36k_train_003679 | 3,574 | permissive | [
{
"docstring": "Initialize Installer. Args: debug (bool): Log on terminal or not Raises: None Returns: None",
"name": "__init__",
"signature": "def __init__(self, debug=False)"
},
{
"docstring": "Read from JSON file. Args: path (str): Path of the JSON file Raises: None Returns: None",
"name"... | 4 | stack_v2_sparse_classes_30k_train_014937 | Implement the Python class `Installer` described below.
Class description:
Installer Class.
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize Installer. Args: debug (bool): Log on terminal or not Raises: None Returns: None
- def open_json(path): Read from JSON file. Args: path (str): Pat... | Implement the Python class `Installer` described below.
Class description:
Installer Class.
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize Installer. Args: debug (bool): Log on terminal or not Raises: None Returns: None
- def open_json(path): Read from JSON file. Args: path (str): Pat... | 43dec187e5848b9ced8a6b4957b6e9028d4d43cd | <|skeleton|>
class Installer:
"""Installer Class."""
def __init__(self, debug=False):
"""Initialize Installer. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
<|body_0|>
def open_json(path):
"""Read from JSON file. Args: path (str): Path of the JSON file Ra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Installer:
"""Installer Class."""
def __init__(self, debug=False):
"""Initialize Installer. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
self.logger = PatchLogger(__name__, debug=debug)
self._COMMAND_PATH = '/etc/securetea/asp/commands.json'
sel... | the_stack_v2_python_sparse | securetea/lib/auto_server_patcher/installer.py | rejahrehim/SecureTea-Project | train | 1 |
66789a414175d6255b0fc5063ba63d655f5c250e | [
"super(AirflowScheduler, self).__init__(*args, **kwargs)\ncp = configparser.ConfigParser()\ncp.read(self.config.scheduler_config.config)\ntry:\n self.sql_conn = cp['core']['sql_alchemy_conn']\nexcept KeyError:\n self.sql_conn = ''\nif self.sql_conn:\n self.engine = create_engine(self.sql_conn)\nelse:\n ... | <|body_start_0|>
super(AirflowScheduler, self).__init__(*args, **kwargs)
cp = configparser.ConfigParser()
cp.read(self.config.scheduler_config.config)
try:
self.sql_conn = cp['core']['sql_alchemy_conn']
except KeyError:
self.sql_conn = ''
if self.s... | AirflowScheduler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AirflowScheduler:
def __init__(self, *args, **kwargs):
"""Create a new airflow scheduler, connecting to the airflow instances configuration"""
<|body_0|>
def status(self, user, params, session, *args, **kwargs):
"""Get status of job/report DAGs"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_003680 | 5,278 | permissive | [
{
"docstring": "Create a new airflow scheduler, connecting to the airflow instances configuration",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Get status of job/report DAGs",
"name": "status",
"signature": "def status(self, user, params, ses... | 6 | null | Implement the Python class `AirflowScheduler` described below.
Class description:
Implement the AirflowScheduler class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a new airflow scheduler, connecting to the airflow instances configuration
- def status(self, user, params, session, *... | Implement the Python class `AirflowScheduler` described below.
Class description:
Implement the AirflowScheduler class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a new airflow scheduler, connecting to the airflow instances configuration
- def status(self, user, params, session, *... | b27bfdbb4ed27dea597ff1d6346eb831542ae81f | <|skeleton|>
class AirflowScheduler:
def __init__(self, *args, **kwargs):
"""Create a new airflow scheduler, connecting to the airflow instances configuration"""
<|body_0|>
def status(self, user, params, session, *args, **kwargs):
"""Get status of job/report DAGs"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AirflowScheduler:
def __init__(self, *args, **kwargs):
"""Create a new airflow scheduler, connecting to the airflow instances configuration"""
super(AirflowScheduler, self).__init__(*args, **kwargs)
cp = configparser.ConfigParser()
cp.read(self.config.scheduler_config.config)
... | the_stack_v2_python_sparse | paperboy/scheduler/airflow/airflow.py | timkpaine/paperboy | train | 245 | |
2c1ce9b33fc0b7ac96c0e683692982322e64f2ae | [
"q = quantity.Pressure(1.0, 'Pa')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)\nself.assertEqual(q.units, 'Pa')",
"q = quantity.Pressure(1.0, 'bar')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 100000.0, delta=1e-06)\nself.assertEqu... | <|body_start_0|>
q = quantity.Pressure(1.0, 'Pa')
self.assertAlmostEqual(q.value, 1.0, 6)
self.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)
self.assertEqual(q.units, 'Pa')
<|end_body_0|>
<|body_start_1|>
q = quantity.Pressure(1.0, 'bar')
self.assertAlmostEqual(q.value... | Contains unit tests of the Pressure unit type object. | TestPressure | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPressure:
"""Contains unit tests of the Pressure unit type object."""
def test_Pa(self):
"""Test the creation of a pressure quantity with units of Pa."""
<|body_0|>
def test_bar(self):
"""Test the creation of a pressure quantity with units of bar."""
... | stack_v2_sparse_classes_36k_train_003681 | 33,010 | permissive | [
{
"docstring": "Test the creation of a pressure quantity with units of Pa.",
"name": "test_Pa",
"signature": "def test_Pa(self)"
},
{
"docstring": "Test the creation of a pressure quantity with units of bar.",
"name": "test_bar",
"signature": "def test_bar(self)"
},
{
"docstring"... | 5 | stack_v2_sparse_classes_30k_train_001072 | Implement the Python class `TestPressure` described below.
Class description:
Contains unit tests of the Pressure unit type object.
Method signatures and docstrings:
- def test_Pa(self): Test the creation of a pressure quantity with units of Pa.
- def test_bar(self): Test the creation of a pressure quantity with unit... | Implement the Python class `TestPressure` described below.
Class description:
Contains unit tests of the Pressure unit type object.
Method signatures and docstrings:
- def test_Pa(self): Test the creation of a pressure quantity with units of Pa.
- def test_bar(self): Test the creation of a pressure quantity with unit... | 0937b2e0a955dcf21b79674a4e89f43941c0dd85 | <|skeleton|>
class TestPressure:
"""Contains unit tests of the Pressure unit type object."""
def test_Pa(self):
"""Test the creation of a pressure quantity with units of Pa."""
<|body_0|>
def test_bar(self):
"""Test the creation of a pressure quantity with units of bar."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPressure:
"""Contains unit tests of the Pressure unit type object."""
def test_Pa(self):
"""Test the creation of a pressure quantity with units of Pa."""
q = quantity.Pressure(1.0, 'Pa')
self.assertAlmostEqual(q.value, 1.0, 6)
self.assertAlmostEqual(q.value_si, 1.0, de... | the_stack_v2_python_sparse | rmgpy/quantityTest.py | vrlambert/RMG-Py | train | 1 |
7730af6fc733fdf98d564d81dd57ed7cb5d0231b | [
"super(Window, self).__init__(parent)\nself.systemtray_icon = systemtray_icon\nself.statusBar()\nself.widget = MainWidget(self)\nself.setCentralWidget(self.widget)\nself.resize(500, 200)\nself.setWindowTitle(APP_NAME)\nself.setWindowIcon(QIcon(ICON_PATH))\nself.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\nhel... | <|body_start_0|>
super(Window, self).__init__(parent)
self.systemtray_icon = systemtray_icon
self.statusBar()
self.widget = MainWidget(self)
self.setCentralWidget(self.widget)
self.resize(500, 200)
self.setWindowTitle(APP_NAME)
self.setWindowIcon(QIcon(ICO... | Personal mainWindow class. | Window | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Window:
"""Personal mainWindow class."""
def __init__(self, systemtray_icon=None, parent=None):
"""Init window."""
<|body_0|>
def helper(self):
"""Display help."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Window, self).__init__(parent)... | stack_v2_sparse_classes_36k_train_003682 | 11,571 | permissive | [
{
"docstring": "Init window.",
"name": "__init__",
"signature": "def __init__(self, systemtray_icon=None, parent=None)"
},
{
"docstring": "Display help.",
"name": "helper",
"signature": "def helper(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001702 | Implement the Python class `Window` described below.
Class description:
Personal mainWindow class.
Method signatures and docstrings:
- def __init__(self, systemtray_icon=None, parent=None): Init window.
- def helper(self): Display help. | Implement the Python class `Window` described below.
Class description:
Personal mainWindow class.
Method signatures and docstrings:
- def __init__(self, systemtray_icon=None, parent=None): Init window.
- def helper(self): Display help.
<|skeleton|>
class Window:
"""Personal mainWindow class."""
def __init_... | 93dd7abb03d27cf3490d8b2514365260d67ab15b | <|skeleton|>
class Window:
"""Personal mainWindow class."""
def __init__(self, systemtray_icon=None, parent=None):
"""Init window."""
<|body_0|>
def helper(self):
"""Display help."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Window:
"""Personal mainWindow class."""
def __init__(self, systemtray_icon=None, parent=None):
"""Init window."""
super(Window, self).__init__(parent)
self.systemtray_icon = systemtray_icon
self.statusBar()
self.widget = MainWidget(self)
self.setCentralWid... | the_stack_v2_python_sparse | Work_Log_Generator/work_log.py | hastagAB/Awesome-Python-Scripts | train | 1,757 |
72438e4e5abfd1f5585cc497e4e3de10e5f91697 | [
"def helper(l, r):\n if l == r:\n return [l]\n mid = l + (r - l) // 2\n left = helper(l, mid)\n right = helper(mid + 1, r)\n return left[::-1] + right[::-1]\nreturn helper(1, n)",
"res = [1]\nwhile len(res) < n:\n t = []\n for i in res:\n if 2 * i - 1 <= n:\n t.append... | <|body_start_0|>
def helper(l, r):
if l == r:
return [l]
mid = l + (r - l) // 2
left = helper(l, mid)
right = helper(mid + 1, r)
return left[::-1] + right[::-1]
return helper(1, n)
<|end_body_0|>
<|body_start_1|>
res = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def beautifulArrayWrong(self, n):
""":type n: int :rtype: List[int]"""
<|body_0|>
def beautifulArray(self, n):
""":type n: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def helper(l, r):
if l == r:
... | stack_v2_sparse_classes_36k_train_003683 | 1,248 | no_license | [
{
"docstring": ":type n: int :rtype: List[int]",
"name": "beautifulArrayWrong",
"signature": "def beautifulArrayWrong(self, n)"
},
{
"docstring": ":type n: int :rtype: List[int]",
"name": "beautifulArray",
"signature": "def beautifulArray(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def beautifulArrayWrong(self, n): :type n: int :rtype: List[int]
- def beautifulArray(self, n): :type n: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def beautifulArrayWrong(self, n): :type n: int :rtype: List[int]
- def beautifulArray(self, n): :type n: int :rtype: List[int]
<|skeleton|>
class Solution:
def beautifulArr... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def beautifulArrayWrong(self, n):
""":type n: int :rtype: List[int]"""
<|body_0|>
def beautifulArray(self, n):
""":type n: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def beautifulArrayWrong(self, n):
""":type n: int :rtype: List[int]"""
def helper(l, r):
if l == r:
return [l]
mid = l + (r - l) // 2
left = helper(l, mid)
right = helper(mid + 1, r)
return left[::-1] + right... | the_stack_v2_python_sparse | B/BeautifulArray.py | bssrdf/pyleet | train | 2 | |
23ca94c6bf75fb8101f389f905800c4676d8577f | [
"request = Request(request_url)\ntry:\n response = urlopen(request, timeout=30)\nexcept urllib.error.HTTPError as e:\n status: HTTPStatus = HTTPStatus(e.code)\n yield ('Failed to load remote: \"%s\" (%s %s)' % (request_url, e.code, status.phrase))\n sys.exit(1)\nif response.status != 200:\n status: H... | <|body_start_0|>
request = Request(request_url)
try:
response = urlopen(request, timeout=30)
except urllib.error.HTTPError as e:
status: HTTPStatus = HTTPStatus(e.code)
yield ('Failed to load remote: "%s" (%s %s)' % (request_url, e.code, status.phrase))
... | BitbucketRemote | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BitbucketRemote:
def _fetch_payloads(self, request_url: str) -> Generator:
"""Recursively generates payloads from paginated responses"""
<|body_0|>
def fetch_contents(self, url: str, output_path: str) -> Generator:
"""Downloads files from URL to output path"""
... | stack_v2_sparse_classes_36k_train_003684 | 2,843 | permissive | [
{
"docstring": "Recursively generates payloads from paginated responses",
"name": "_fetch_payloads",
"signature": "def _fetch_payloads(self, request_url: str) -> Generator"
},
{
"docstring": "Downloads files from URL to output path",
"name": "fetch_contents",
"signature": "def fetch_cont... | 2 | stack_v2_sparse_classes_30k_train_008836 | Implement the Python class `BitbucketRemote` described below.
Class description:
Implement the BitbucketRemote class.
Method signatures and docstrings:
- def _fetch_payloads(self, request_url: str) -> Generator: Recursively generates payloads from paginated responses
- def fetch_contents(self, url: str, output_path: ... | Implement the Python class `BitbucketRemote` described below.
Class description:
Implement the BitbucketRemote class.
Method signatures and docstrings:
- def _fetch_payloads(self, request_url: str) -> Generator: Recursively generates payloads from paginated responses
- def fetch_contents(self, url: str, output_path: ... | 794be8ee2e61ef69a83ce4ffa2e5fca2212f71b5 | <|skeleton|>
class BitbucketRemote:
def _fetch_payloads(self, request_url: str) -> Generator:
"""Recursively generates payloads from paginated responses"""
<|body_0|>
def fetch_contents(self, url: str, output_path: str) -> Generator:
"""Downloads files from URL to output path"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BitbucketRemote:
def _fetch_payloads(self, request_url: str) -> Generator:
"""Recursively generates payloads from paginated responses"""
request = Request(request_url)
try:
response = urlopen(request, timeout=30)
except urllib.error.HTTPError as e:
statu... | the_stack_v2_python_sparse | pyro/Remotes/BitbucketRemote.py | clayne/pyro | train | 0 | |
c7d98e8e009f90c0df507e623e8f8ff4cc252de9 | [
"integrator = self._simulation.operations.integrator\ntimestep = self._simulation.timestep\nreturn integrator._cpp_obj.computePatchEnergy(timestep)",
"param_array_suffix = {True: '_isotropic', False: ''}[self._is_union]\nconstituent_param_array = {True: 'float *param_array_constituent;', False: ''}[self._is_union... | <|body_start_0|>
integrator = self._simulation.operations.integrator
timestep = self._simulation.timestep
return integrator._cpp_obj.computePatchEnergy(timestep)
<|end_body_0|>
<|body_start_1|>
param_array_suffix = {True: '_isotropic', False: ''}[self._is_union]
constituent_para... | Base class for interaction between pairs of particles given in C++. Pair potential energies define energetic interactions between pairs of particles in `hoomd.hpmc.integrate.HPMCIntegrator`. Particles within a cutoff distance interact with an energy that is a function the type and orientation of the particles and the v... | CPPPotentialBase | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CPPPotentialBase:
"""Base class for interaction between pairs of particles given in C++. Pair potential energies define energetic interactions between pairs of particles in `hoomd.hpmc.integrate.HPMCIntegrator`. Particles within a cutoff distance interact with an energy that is a function the typ... | stack_v2_sparse_classes_36k_train_003685 | 22,491 | permissive | [
{
"docstring": "float: Total interaction energy of the system in the current state. .. math:: U = \\\\sum_{i=0}^\\\\mathrm{N_particles-1} \\\\sum_{j=0}^\\\\mathrm{N_particles-1} U_{\\\\mathrm{pair},ij} Returns `None` when the patch object and integrator are not attached.",
"name": "energy",
"signature":... | 3 | null | Implement the Python class `CPPPotentialBase` described below.
Class description:
Base class for interaction between pairs of particles given in C++. Pair potential energies define energetic interactions between pairs of particles in `hoomd.hpmc.integrate.HPMCIntegrator`. Particles within a cutoff distance interact wi... | Implement the Python class `CPPPotentialBase` described below.
Class description:
Base class for interaction between pairs of particles given in C++. Pair potential energies define energetic interactions between pairs of particles in `hoomd.hpmc.integrate.HPMCIntegrator`. Particles within a cutoff distance interact wi... | abdd76bc854358426e4cf055badd27f80df6ec85 | <|skeleton|>
class CPPPotentialBase:
"""Base class for interaction between pairs of particles given in C++. Pair potential energies define energetic interactions between pairs of particles in `hoomd.hpmc.integrate.HPMCIntegrator`. Particles within a cutoff distance interact with an energy that is a function the typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CPPPotentialBase:
"""Base class for interaction between pairs of particles given in C++. Pair potential energies define energetic interactions between pairs of particles in `hoomd.hpmc.integrate.HPMCIntegrator`. Particles within a cutoff distance interact with an energy that is a function the type and orienta... | the_stack_v2_python_sparse | hoomd/hpmc/pair/user.py | glotzerlab/hoomd-blue | train | 287 |
6d5eca09349aeedbd14692fe35b6e55d8974af17 | [
"if not isinstance(hint_name, str):\n raise _BeartypeDecorBeartypistryException(f'Beartypistry key {repr(hint_name)} not string.')\nelif hint_name in self:\n raise _BeartypeDecorBeartypistryException(f'Beartypistry key \"{hint_name}\" already registered (i.e., key collision between prior registered value {rep... | <|body_start_0|>
if not isinstance(hint_name, str):
raise _BeartypeDecorBeartypistryException(f'Beartypistry key {repr(hint_name)} not string.')
elif hint_name in self:
raise _BeartypeDecorBeartypistryException(f'Beartypistry key "{hint_name}" already registered (i.e., key collis... | **Beartypistry** (i.e., singleton dictionary mapping from strings uniquely identifying PEP-noncompliant type hints annotating callables decorated by the :func:`beartype.beartype` decorator to those hints). This dictionary implements a global registry for **PEP-noncompliant type hints** (i.e., :mod:`beartype`-specific a... | Beartypistry | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Beartypistry:
"""**Beartypistry** (i.e., singleton dictionary mapping from strings uniquely identifying PEP-noncompliant type hints annotating callables decorated by the :func:`beartype.beartype` decorator to those hints). This dictionary implements a global registry for **PEP-noncompliant type h... | stack_v2_sparse_classes_36k_train_003686 | 16,935 | permissive | [
{
"docstring": "Dunder method explicitly called by the superclass on setting the passed key-value pair with ``[``- and ``]``-delimited syntax, mapping the passed string uniquely identifying the passed PEP-noncompliant type hint to that hint. Parameters ---------- hint_name: str String uniquely identifying this ... | 2 | null | Implement the Python class `Beartypistry` described below.
Class description:
**Beartypistry** (i.e., singleton dictionary mapping from strings uniquely identifying PEP-noncompliant type hints annotating callables decorated by the :func:`beartype.beartype` decorator to those hints). This dictionary implements a global... | Implement the Python class `Beartypistry` described below.
Class description:
**Beartypistry** (i.e., singleton dictionary mapping from strings uniquely identifying PEP-noncompliant type hints annotating callables decorated by the :func:`beartype.beartype` decorator to those hints). This dictionary implements a global... | 0cfd53391eb4de2f8297a4632aa5895b8d82a5b7 | <|skeleton|>
class Beartypistry:
"""**Beartypistry** (i.e., singleton dictionary mapping from strings uniquely identifying PEP-noncompliant type hints annotating callables decorated by the :func:`beartype.beartype` decorator to those hints). This dictionary implements a global registry for **PEP-noncompliant type h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Beartypistry:
"""**Beartypistry** (i.e., singleton dictionary mapping from strings uniquely identifying PEP-noncompliant type hints annotating callables decorated by the :func:`beartype.beartype` decorator to those hints). This dictionary implements a global registry for **PEP-noncompliant type hints** (i.e.,... | the_stack_v2_python_sparse | beartype/_decor/cache/cachetype.py | beartype/beartype | train | 1,992 |
ddb7a86a8098de462c41c3530fb5cfeaa376655f | [
"super().__init__(log_level=log_level, _write_kwargs=('result_formatter',))\ntry:\n format_string.format(name='name', result=1)\nexcept KeyError as e:\n raise KeyError(f\"format_string key {e} is not in ('name', 'result')\")\nself.format_string = format_string",
"if result_formatter is not None:\n result... | <|body_start_0|>
super().__init__(log_level=log_level, _write_kwargs=('result_formatter',))
try:
format_string.format(name='name', result=1)
except KeyError as e:
raise KeyError(f"format_string key {e} is not in ('name', 'result')")
self.format_string = format_str... | Logs successful results (designed for task metrics) | ResultsLogWriter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResultsLogWriter:
"""Logs successful results (designed for task metrics)"""
def __init__(self, format_string: str='{name} on benign examples w.r.t. ground truth labels: {result}', log_level: str='METRIC'):
"""format_string - string to format results for output to logging Can contain ... | stack_v2_sparse_classes_36k_train_003687 | 30,084 | permissive | [
{
"docstring": "format_string - string to format results for output to logging Can contain 'name' and 'result' as keys for formatting Other keys will cause an error",
"name": "__init__",
"signature": "def __init__(self, format_string: str='{name} on benign examples w.r.t. ground truth labels: {result}',... | 2 | null | Implement the Python class `ResultsLogWriter` described below.
Class description:
Logs successful results (designed for task metrics)
Method signatures and docstrings:
- def __init__(self, format_string: str='{name} on benign examples w.r.t. ground truth labels: {result}', log_level: str='METRIC'): format_string - st... | Implement the Python class `ResultsLogWriter` described below.
Class description:
Logs successful results (designed for task metrics)
Method signatures and docstrings:
- def __init__(self, format_string: str='{name} on benign examples w.r.t. ground truth labels: {result}', log_level: str='METRIC'): format_string - st... | 3efd21652cfdc8cd192681e9daf58a4b08e82db4 | <|skeleton|>
class ResultsLogWriter:
"""Logs successful results (designed for task metrics)"""
def __init__(self, format_string: str='{name} on benign examples w.r.t. ground truth labels: {result}', log_level: str='METRIC'):
"""format_string - string to format results for output to logging Can contain ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResultsLogWriter:
"""Logs successful results (designed for task metrics)"""
def __init__(self, format_string: str='{name} on benign examples w.r.t. ground truth labels: {result}', log_level: str='METRIC'):
"""format_string - string to format results for output to logging Can contain 'name' and 'r... | the_stack_v2_python_sparse | armory/instrument/instrument.py | twosixlabs/armory | train | 153 |
3209c9523ac332c3718afea9fbced5805202ba82 | [
"metadata = {'targets': ['a', 'c', 'e', 'g', 'i']}\ndata = [[0, 'a'], [2, 'c'], [4, 'e'], [6, 'g'], [8, 'i']]\ncpb = ClassificationProblem(data, metadata)\nmetadata = {'class_subset_length': 20}\ncspb = ClassSubsetProblem(cpb, metadata)\nassert len(cspb) == 20",
"metadata = {'targets': ['a', 'c', 'e', 'g', 'i']}\... | <|body_start_0|>
metadata = {'targets': ['a', 'c', 'e', 'g', 'i']}
data = [[0, 'a'], [2, 'c'], [4, 'e'], [6, 'g'], [8, 'i']]
cpb = ClassificationProblem(data, metadata)
metadata = {'class_subset_length': 20}
cspb = ClassSubsetProblem(cpb, metadata)
assert len(cspb) == 20
... | TestClassSubsetProblem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestClassSubsetProblem:
def test_len_meta(self):
"""Classification subset problem uses 'class_subset_length' as data length"""
<|body_0|>
def test_len(self):
"""Classification subset problem correctly count data in subset"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_003688 | 4,653 | no_license | [
{
"docstring": "Classification subset problem uses 'class_subset_length' as data length",
"name": "test_len_meta",
"signature": "def test_len_meta(self)"
},
{
"docstring": "Classification subset problem correctly count data in subset",
"name": "test_len",
"signature": "def test_len(self)... | 2 | null | Implement the Python class `TestClassSubsetProblem` described below.
Class description:
Implement the TestClassSubsetProblem class.
Method signatures and docstrings:
- def test_len_meta(self): Classification subset problem uses 'class_subset_length' as data length
- def test_len(self): Classification subset problem c... | Implement the Python class `TestClassSubsetProblem` described below.
Class description:
Implement the TestClassSubsetProblem class.
Method signatures and docstrings:
- def test_len_meta(self): Classification subset problem uses 'class_subset_length' as data length
- def test_len(self): Classification subset problem c... | 6c83bf66444a802cec6ad1359683d7a9e1c8c744 | <|skeleton|>
class TestClassSubsetProblem:
def test_len_meta(self):
"""Classification subset problem uses 'class_subset_length' as data length"""
<|body_0|>
def test_len(self):
"""Classification subset problem correctly count data in subset"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestClassSubsetProblem:
def test_len_meta(self):
"""Classification subset problem uses 'class_subset_length' as data length"""
metadata = {'targets': ['a', 'c', 'e', 'g', 'i']}
data = [[0, 'a'], [2, 'c'], [4, 'e'], [6, 'g'], [8, 'i']]
cpb = ClassificationProblem(data, metadata)... | the_stack_v2_python_sparse | mlpython/unit_tests/test_mlproblems/test_classification.py | lkhphuc/HugoLarochelle_NN_Exercises | train | 4 | |
34cf7eaf13e5ddd7a3f842239df3205ec206b19b | [
"p[0] = p[1]\np_list = list(p)\nif isinstance(p_list[-1], dict):\n p[0].update(p_list[-1])\nelse:\n p[0]['database_name'] = p_list[-1]",
"p[0] = p[1]\np_list = list(p)\np[0].update(p_list[-1])"
] | <|body_start_0|>
p[0] = p[1]
p_list = list(p)
if isinstance(p_list[-1], dict):
p[0].update(p_list[-1])
else:
p[0]['database_name'] = p_list[-1]
<|end_body_0|>
<|body_start_1|>
p[0] = p[1]
p_list = list(p)
p[0].update(p_list[-1])
<|end_body... | Database | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Database:
def p_database_base(self, p: List) -> None:
"""database_base : CREATE DATABASE id | database_base clone"""
<|body_0|>
def p_expression_create_database(self, p: List) -> None:
"""expr : expr database_base"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_003689 | 42,571 | permissive | [
{
"docstring": "database_base : CREATE DATABASE id | database_base clone",
"name": "p_database_base",
"signature": "def p_database_base(self, p: List) -> None"
},
{
"docstring": "expr : expr database_base",
"name": "p_expression_create_database",
"signature": "def p_expression_create_dat... | 2 | stack_v2_sparse_classes_30k_train_015124 | Implement the Python class `Database` described below.
Class description:
Implement the Database class.
Method signatures and docstrings:
- def p_database_base(self, p: List) -> None: database_base : CREATE DATABASE id | database_base clone
- def p_expression_create_database(self, p: List) -> None: expr : expr databa... | Implement the Python class `Database` described below.
Class description:
Implement the Database class.
Method signatures and docstrings:
- def p_database_base(self, p: List) -> None: database_base : CREATE DATABASE id | database_base clone
- def p_expression_create_database(self, p: List) -> None: expr : expr databa... | 8f69c9c3b58990f0d47dbe868fe4a572d51e2de7 | <|skeleton|>
class Database:
def p_database_base(self, p: List) -> None:
"""database_base : CREATE DATABASE id | database_base clone"""
<|body_0|>
def p_expression_create_database(self, p: List) -> None:
"""expr : expr database_base"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Database:
def p_database_base(self, p: List) -> None:
"""database_base : CREATE DATABASE id | database_base clone"""
p[0] = p[1]
p_list = list(p)
if isinstance(p_list[-1], dict):
p[0].update(p_list[-1])
else:
p[0]['database_name'] = p_list[-1]
... | the_stack_v2_python_sparse | simple_ddl_parser/dialects/sql.py | bjmc/simple-ddl-parser | train | 0 | |
e7ab2522e27b215aff3c39171c2616d2fdfd1bd6 | [
"logger.debug('Creating new Choice class object...')\nself.choice = 0\nlogger.debug('Completed creation of new Choice class object...')\n\n@property\ndef choice(self):\n \"\"\"\n This function returns the attribute: choice\n\n \"\"\"\n logger.debug('Returning choice attribute data...'... | <|body_start_0|>
logger.debug('Creating new Choice class object...')
self.choice = 0
logger.debug('Completed creation of new Choice class object...')
@property
def choice(self):
"""
This function returns the attribute: choice
... | This class uses object orientation to wrap "data" in a proper class/obj. | Choice | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Choice:
"""This class uses object orientation to wrap "data" in a proper class/obj."""
def __init__(self):
"""This is the constructor function - also known as what happens when this class is created."""
<|body_0|>
def input(self):
"""This function allows user to ... | stack_v2_sparse_classes_36k_train_003690 | 11,246 | permissive | [
{
"docstring": "This is the constructor function - also known as what happens when this class is created.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This function allows user to provide input. Assigns response to the choice attribute.",
"name": "input",
"s... | 2 | stack_v2_sparse_classes_30k_train_012418 | Implement the Python class `Choice` described below.
Class description:
This class uses object orientation to wrap "data" in a proper class/obj.
Method signatures and docstrings:
- def __init__(self): This is the constructor function - also known as what happens when this class is created.
- def input(self): This fun... | Implement the Python class `Choice` described below.
Class description:
This class uses object orientation to wrap "data" in a proper class/obj.
Method signatures and docstrings:
- def __init__(self): This is the constructor function - also known as what happens when this class is created.
- def input(self): This fun... | 71aa6fae8e77f61924619407f34c39b3ace17fe4 | <|skeleton|>
class Choice:
"""This class uses object orientation to wrap "data" in a proper class/obj."""
def __init__(self):
"""This is the constructor function - also known as what happens when this class is created."""
<|body_0|>
def input(self):
"""This function allows user to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Choice:
"""This class uses object orientation to wrap "data" in a proper class/obj."""
def __init__(self):
"""This is the constructor function - also known as what happens when this class is created."""
logger.debug('Creating new Choice class object...')
self.choice = 0
lo... | the_stack_v2_python_sparse | Cisco-Live-2018/semibasic-final.py | GJvignesh/Training-Events | train | 0 |
1171dc0c7c35755e98e2dad0917ddfc227b633d0 | [
"hostname = event.get('hostname')\nutcoffset = event.get('utcoffset')\npid = event.get('pid')\nfreq = event.get('freq')\nsoftware = '{}-{}'.format(event.get('sw_ident'), event.get('sw_ver'))\nos = event.get('sw_sys')\ndetails = event.get('details', {})\nsignature = '{hostname}|{utcoffset}|{pid}|{freq}|{software}|{o... | <|body_start_0|>
hostname = event.get('hostname')
utcoffset = event.get('utcoffset')
pid = event.get('pid')
freq = event.get('freq')
software = '{}-{}'.format(event.get('sw_ident'), event.get('sw_ver'))
os = event.get('sw_sys')
details = event.get('details', {})
... | A worker that runs jobs placed on one or more queues. This model stores information on a worker as captured by the `overseer` service from Celery's worker monitoring events. | Worker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Worker:
"""A worker that runs jobs placed on one or more queues. This model stores information on a worker as captured by the `overseer` service from Celery's worker monitoring events."""
def get_or_create(cls, event: dict, create=False):
"""Get or create a worker from a Celery worke... | stack_v2_sparse_classes_36k_train_003691 | 21,886 | permissive | [
{
"docstring": "Get or create a worker from a Celery worker event. This method extracts the fields of a worker from a Celery worker event and constructs a signature from them. If there is an active worker with the same signature then it is returned. The signature is the only way to uniquely identify a worker.",... | 2 | null | Implement the Python class `Worker` described below.
Class description:
A worker that runs jobs placed on one or more queues. This model stores information on a worker as captured by the `overseer` service from Celery's worker monitoring events.
Method signatures and docstrings:
- def get_or_create(cls, event: dict, ... | Implement the Python class `Worker` described below.
Class description:
A worker that runs jobs placed on one or more queues. This model stores information on a worker as captured by the `overseer` service from Celery's worker monitoring events.
Method signatures and docstrings:
- def get_or_create(cls, event: dict, ... | 47c6377ccbfe8576b35854053d726537e533e78c | <|skeleton|>
class Worker:
"""A worker that runs jobs placed on one or more queues. This model stores information on a worker as captured by the `overseer` service from Celery's worker monitoring events."""
def get_or_create(cls, event: dict, create=False):
"""Get or create a worker from a Celery worke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Worker:
"""A worker that runs jobs placed on one or more queues. This model stores information on a worker as captured by the `overseer` service from Celery's worker monitoring events."""
def get_or_create(cls, event: dict, create=False):
"""Get or create a worker from a Celery worker event. This... | the_stack_v2_python_sparse | director/jobs/models.py | gxf1986/hub | train | 0 |
1081730f6fbe4b849acbe9b1c3b197f8f803f989 | [
"self.clerk = clerk\nself.fID = fID\nself.fclass = fclass",
"if name == 'ID':\n pass\nelse:\n old = stub.private\n new = self.clerk.fetch(self.fclass, self.fID).private\n for slot in self.fclass.__attrs__:\n setattr(old, slot, getattr(new, slot))\n old.isDirty = False\n stub.notifyObserve... | <|body_start_0|>
self.clerk = clerk
self.fID = fID
self.fclass = fclass
<|end_body_0|>
<|body_start_1|>
if name == 'ID':
pass
else:
old = stub.private
new = self.clerk.fetch(self.fclass, self.fID).private
for slot in self.fclass.__... | LinkInjector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkInjector:
def __init__(self, clerk, fclass, fID):
"""Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and injected into box. In other words, this provides lazy loading for strongboxen."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_003692 | 1,550 | no_license | [
{
"docstring": "Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and injected into box. In other words, this provides lazy loading for strongboxen.",
"name": "__init__",
"signature": "def __init__(self, clerk, fclass, fID)"
},... | 2 | stack_v2_sparse_classes_30k_train_016800 | Implement the Python class `LinkInjector` described below.
Class description:
Implement the LinkInjector class.
Method signatures and docstrings:
- def __init__(self, clerk, fclass, fID): Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and i... | Implement the Python class `LinkInjector` described below.
Class description:
Implement the LinkInjector class.
Method signatures and docstrings:
- def __init__(self, clerk, fclass, fID): Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and i... | a7df929147d82d225606c216f69c48d898e19ebe | <|skeleton|>
class LinkInjector:
def __init__(self, clerk, fclass, fID):
"""Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and injected into box. In other words, this provides lazy loading for strongboxen."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkInjector:
def __init__(self, clerk, fclass, fID):
"""Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and injected into box. In other words, this provides lazy loading for strongboxen."""
self.clerk = clerk
... | the_stack_v2_python_sparse | @gone/arlo/LinkInjector.py | mattharkness/sixthdev | train | 0 | |
2dd896ed0cc23e600ac1bfbc6f8a7cb282f0a84b | [
"stack = [root]\nvals = []\nwhile stack:\n node = stack.pop()\n if isinstance(node, TreeNode):\n stack.extend([node.right, node.val, node.left])\n if isinstance(node, int):\n vals.append(node)\nreturn vals == sorted(list(set(vals)))",
"def dfs(node, left_val, right_val):\n if node is Non... | <|body_start_0|>
stack = [root]
vals = []
while stack:
node = stack.pop()
if isinstance(node, TreeNode):
stack.extend([node.right, node.val, node.left])
if isinstance(node, int):
vals.append(node)
return vals == sorted(l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidBST1(self, root) -> bool:
"""满足二叉树搜索树说明该二叉树的中序遍历是单调递增的 使用栈中序遍历该二叉树,然后看是否是有序的"""
<|body_0|>
def isValidBST2(self, root) -> bool:
"""优化:使用递归判断 对root左边的节点,val值都应该满足大于最小值,并且小于上层节点的最小值, 对root右边的节点,val值都应该满足小于最大值,并且大于上层节点的最大值, 最左边的一条线,永远单调递减, 最右边的一条线,永... | stack_v2_sparse_classes_36k_train_003693 | 2,518 | no_license | [
{
"docstring": "满足二叉树搜索树说明该二叉树的中序遍历是单调递增的 使用栈中序遍历该二叉树,然后看是否是有序的",
"name": "isValidBST1",
"signature": "def isValidBST1(self, root) -> bool"
},
{
"docstring": "优化:使用递归判断 对root左边的节点,val值都应该满足大于最小值,并且小于上层节点的最小值, 对root右边的节点,val值都应该满足小于最大值,并且大于上层节点的最大值, 最左边的一条线,永远单调递减, 最右边的一条线,永远单调递增。",
"name": "... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST1(self, root) -> bool: 满足二叉树搜索树说明该二叉树的中序遍历是单调递增的 使用栈中序遍历该二叉树,然后看是否是有序的
- def isValidBST2(self, root) -> bool: 优化:使用递归判断 对root左边的节点,val值都应该满足大于最小值,并且小于上层节点的最小值, 对roo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST1(self, root) -> bool: 满足二叉树搜索树说明该二叉树的中序遍历是单调递增的 使用栈中序遍历该二叉树,然后看是否是有序的
- def isValidBST2(self, root) -> bool: 优化:使用递归判断 对root左边的节点,val值都应该满足大于最小值,并且小于上层节点的最小值, 对roo... | f0f4ba0cb91096e55e21b7a2240afbd347187351 | <|skeleton|>
class Solution:
def isValidBST1(self, root) -> bool:
"""满足二叉树搜索树说明该二叉树的中序遍历是单调递增的 使用栈中序遍历该二叉树,然后看是否是有序的"""
<|body_0|>
def isValidBST2(self, root) -> bool:
"""优化:使用递归判断 对root左边的节点,val值都应该满足大于最小值,并且小于上层节点的最小值, 对root右边的节点,val值都应该满足小于最大值,并且大于上层节点的最大值, 最左边的一条线,永远单调递减, 最右边的一条线,永... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isValidBST1(self, root) -> bool:
"""满足二叉树搜索树说明该二叉树的中序遍历是单调递增的 使用栈中序遍历该二叉树,然后看是否是有序的"""
stack = [root]
vals = []
while stack:
node = stack.pop()
if isinstance(node, TreeNode):
stack.extend([node.right, node.val, node.left])
... | the_stack_v2_python_sparse | coding_test/98_isValidBST.py | zhuheng-mark/myDL | train | 2 | |
143bd3fae438988504d4aab1d38b9a51e099fc15 | [
"self.targets = targets\nself._chooser = target_chooser if callable(target_chooser) else import_name(target_chooser)\nself._kwargs = target_kwargs or {}\nself._source = None\nself._params = kwargs\nself._cat_kwargs = cat_kwargs or {}\nif container:\n self.container = container\nself._validate_params()\nsuper()._... | <|body_start_0|>
self.targets = targets
self._chooser = target_chooser if callable(target_chooser) else import_name(target_chooser)
self._kwargs = target_kwargs or {}
self._source = None
self._params = kwargs
self._cat_kwargs = cat_kwargs or {}
if container:
... | Base source deriving from another source in the same catalog Target picking and parameter validation are performed here, but you probably want to subclass from one of the more specific classes like ``DataFrameTransform``. | DerivedSource | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DerivedSource:
"""Base source deriving from another source in the same catalog Target picking and parameter validation are performed here, but you probably want to subclass from one of the more specific classes like ``DataFrameTransform``."""
def __init__(self, targets, target_chooser=first,... | stack_v2_sparse_classes_36k_train_003694 | 16,158 | permissive | [
{
"docstring": "Parameters ---------- targets: list of string or DataSources If string(s), refer to entries of the same catalog as this Source target_chooser: function to choose between targets function(targets, cat) -> source, or a fully-qualified dotted string pointing to it target_kwargs: dict of dict with k... | 3 | stack_v2_sparse_classes_30k_train_013323 | Implement the Python class `DerivedSource` described below.
Class description:
Base source deriving from another source in the same catalog Target picking and parameter validation are performed here, but you probably want to subclass from one of the more specific classes like ``DataFrameTransform``.
Method signatures... | Implement the Python class `DerivedSource` described below.
Class description:
Base source deriving from another source in the same catalog Target picking and parameter validation are performed here, but you probably want to subclass from one of the more specific classes like ``DataFrameTransform``.
Method signatures... | 81b1567a2030adfb22b856b4f63cefe35de68983 | <|skeleton|>
class DerivedSource:
"""Base source deriving from another source in the same catalog Target picking and parameter validation are performed here, but you probably want to subclass from one of the more specific classes like ``DataFrameTransform``."""
def __init__(self, targets, target_chooser=first,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DerivedSource:
"""Base source deriving from another source in the same catalog Target picking and parameter validation are performed here, but you probably want to subclass from one of the more specific classes like ``DataFrameTransform``."""
def __init__(self, targets, target_chooser=first, target_kwarg... | the_stack_v2_python_sparse | intake/source/derived.py | intake/intake | train | 774 |
1abd30863982dfc622f554848505d41fa359bd65 | [
"result = list()\nn = len(digits)\nnum = 0\nfor a in range(n):\n num += digits[a] * 10 ** (n - 1)\n n -= 1\nnum = num + 1\nresult = result + [int(x) for x in str(num)]\nreturn result",
"for i in range(len(digits) - 1, -1, -1):\n if digits[i] != 9:\n digits[i] += 1\n return digits\n else:... | <|body_start_0|>
result = list()
n = len(digits)
num = 0
for a in range(n):
num += digits[a] * 10 ** (n - 1)
n -= 1
num = num + 1
result = result + [int(x) for x in str(num)]
return result
<|end_body_0|>
<|body_start_1|>
for i in r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne_2(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = list()
n = len... | stack_v2_sparse_classes_36k_train_003695 | 757 | no_license | [
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne",
"signature": "def plusOne(self, digits)"
},
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne_2",
"signature": "def plusOne_2(self, digits)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007272 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne_2(self, digits): :type digits: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne_2(self, digits): :type digits: List[int] :rtype: List[int]
<|skeleton|>
class Solution:
d... | d26c6a18749aa176eba0ef000b8276335979fedb | <|skeleton|>
class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne_2(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
result = list()
n = len(digits)
num = 0
for a in range(n):
num += digits[a] * 10 ** (n - 1)
n -= 1
num = num + 1
result = result + [int(x) for x ... | the_stack_v2_python_sparse | mu_wang/9_13/Plus_One.py | mingming733/LCGroup | train | 0 | |
416fca2abf1e847e6ca897e27dbc298488d629ee | [
"if data is not None:\n if not isinstance(data, list):\n raise TypeError('data must be a list')\n if len(data) <= 2:\n raise ValueError('data must contain multiple values')\n mean = float(sum(data) / len(data))\n summatory = 0\n for elem in data:\n summatory += (elem - mean) ** 2... | <|body_start_0|>
if data is not None:
if not isinstance(data, list):
raise TypeError('data must be a list')
if len(data) <= 2:
raise ValueError('data must contain multiple values')
mean = float(sum(data) / len(data))
summatory = 0
... | Binomial class | Binomial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Binomial:
"""Binomial class"""
def __init__(self, data=None, n=1, p=0.5):
"""Constructor"""
<|body_0|>
def pmf(self, k):
"""Calculates the value of the PMF for a given number of “successes”"""
<|body_1|>
def cdf(self, k):
"""value of the CDF ... | stack_v2_sparse_classes_36k_train_003696 | 1,717 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, data=None, n=1, p=0.5)"
},
{
"docstring": "Calculates the value of the PMF for a given number of “successes”",
"name": "pmf",
"signature": "def pmf(self, k)"
},
{
"docstring": "value of the CDF for... | 3 | null | Implement the Python class `Binomial` described below.
Class description:
Binomial class
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Constructor
- def pmf(self, k): Calculates the value of the PMF for a given number of “successes”
- def cdf(self, k): value of the CDF for a given num... | Implement the Python class `Binomial` described below.
Class description:
Binomial class
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Constructor
- def pmf(self, k): Calculates the value of the PMF for a given number of “successes”
- def cdf(self, k): value of the CDF for a given num... | f83a60babb1d2a510a4a0e0f58aa3880fd9f93a7 | <|skeleton|>
class Binomial:
"""Binomial class"""
def __init__(self, data=None, n=1, p=0.5):
"""Constructor"""
<|body_0|>
def pmf(self, k):
"""Calculates the value of the PMF for a given number of “successes”"""
<|body_1|>
def cdf(self, k):
"""value of the CDF ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Binomial:
"""Binomial class"""
def __init__(self, data=None, n=1, p=0.5):
"""Constructor"""
if data is not None:
if not isinstance(data, list):
raise TypeError('data must be a list')
if len(data) <= 2:
raise ValueError('data must con... | the_stack_v2_python_sparse | math/0x03-probability/binomial.py | jalondono/holbertonschool-machine_learning | train | 2 |
007e5f7d7e13511c443b5dae4709037f6a504a55 | [
"super().__init__(num_features, eps=eps)\nif not 0 < decay < 1:\n raise ValueError('decay must be between 0 and 1')\nself.decay = decay\nself.register_buffer('inv_learning_rate', th.empty(()))\nself.register_buffer('num_batches', th.empty((), dtype=th.int))\nEMANorm.reset_running_stats(self)",
"super().reset_r... | <|body_start_0|>
super().__init__(num_features, eps=eps)
if not 0 < decay < 1:
raise ValueError('decay must be between 0 and 1')
self.decay = decay
self.register_buffer('inv_learning_rate', th.empty(()))
self.register_buffer('num_batches', th.empty((), dtype=th.int))
... | Similar to RunningNorm but uses an exponential weighting. | EMANorm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EMANorm:
"""Similar to RunningNorm but uses an exponential weighting."""
def __init__(self, num_features: int, decay: float=0.99, eps: float=1e-05):
"""Builds EMARunningNorm. Args: num_features: Number of features; the length of the non-batch dim. decay: how quickly the weight on pas... | stack_v2_sparse_classes_36k_train_003697 | 14,535 | no_license | [
{
"docstring": "Builds EMARunningNorm. Args: num_features: Number of features; the length of the non-batch dim. decay: how quickly the weight on past samples decays over time. eps: small constant for numerical stability. Raises: ValueError: if decay is out of range.",
"name": "__init__",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_021147 | Implement the Python class `EMANorm` described below.
Class description:
Similar to RunningNorm but uses an exponential weighting.
Method signatures and docstrings:
- def __init__(self, num_features: int, decay: float=0.99, eps: float=1e-05): Builds EMARunningNorm. Args: num_features: Number of features; the length o... | Implement the Python class `EMANorm` described below.
Class description:
Similar to RunningNorm but uses an exponential weighting.
Method signatures and docstrings:
- def __init__(self, num_features: int, decay: float=0.99, eps: float=1e-05): Builds EMARunningNorm. Args: num_features: Number of features; the length o... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class EMANorm:
"""Similar to RunningNorm but uses an exponential weighting."""
def __init__(self, num_features: int, decay: float=0.99, eps: float=1e-05):
"""Builds EMARunningNorm. Args: num_features: Number of features; the length of the non-batch dim. decay: how quickly the weight on pas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EMANorm:
"""Similar to RunningNorm but uses an exponential weighting."""
def __init__(self, num_features: int, decay: float=0.99, eps: float=1e-05):
"""Builds EMARunningNorm. Args: num_features: Number of features; the length of the non-batch dim. decay: how quickly the weight on past samples dec... | the_stack_v2_python_sparse | generated/test_HumanCompatibleAI_imitation.py | jansel/pytorch-jit-paritybench | train | 35 |
11ff52aedd964ab60cc3b06b5edb5088a6aa9e74 | [
"self._backend = backend\nself._shots = shots\nself._clf = svm.SVC()\nself._num_evaluation = 0\nself._kernel_matrix = None\nself._normalized_training_vectors = None\nself._unnormalized_training_vectors = None\nself._training_labels = None\nif kernel_type == 'qke':\n self._kernel_circuit = KernelEstimationCircuit... | <|body_start_0|>
self._backend = backend
self._shots = shots
self._clf = svm.SVC()
self._num_evaluation = 0
self._kernel_matrix = None
self._normalized_training_vectors = None
self._unnormalized_training_vectors = None
self._training_labels = None
... | Kernel Classifier class | KernelClassifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KernelClassifier:
"""Kernel Classifier class"""
def __init__(self, backend: str, encoding_style: str='IQP', kernel_type: str='qke', shots: int=1024):
"""The constructor of the KernelClassifier class Args: backend (str): Backend to be used in this task. Please refer to https://quantum... | stack_v2_sparse_classes_36k_train_003698 | 5,902 | permissive | [
{
"docstring": "The constructor of the KernelClassifier class Args: backend (str): Backend to be used in this task. Please refer to https://quantum-hub.baidu.com/quickGuide for details encoding_style (str): Encoding scheme to be used, defaults to 'IQP', which uses the default encoding scheme kernel_type (str): ... | 5 | null | Implement the Python class `KernelClassifier` described below.
Class description:
Kernel Classifier class
Method signatures and docstrings:
- def __init__(self, backend: str, encoding_style: str='IQP', kernel_type: str='qke', shots: int=1024): The constructor of the KernelClassifier class Args: backend (str): Backend... | Implement the Python class `KernelClassifier` described below.
Class description:
Kernel Classifier class
Method signatures and docstrings:
- def __init__(self, backend: str, encoding_style: str='IQP', kernel_type: str='qke', shots: int=1024): The constructor of the KernelClassifier class Args: backend (str): Backend... | 8bc3c7238b5b6825eb63ded8d65afb08b389941f | <|skeleton|>
class KernelClassifier:
"""Kernel Classifier class"""
def __init__(self, backend: str, encoding_style: str='IQP', kernel_type: str='qke', shots: int=1024):
"""The constructor of the KernelClassifier class Args: backend (str): Backend to be used in this task. Please refer to https://quantum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KernelClassifier:
"""Kernel Classifier class"""
def __init__(self, backend: str, encoding_style: str='IQP', kernel_type: str='qke', shots: int=1024):
"""The constructor of the KernelClassifier class Args: backend (str): Backend to be used in this task. Please refer to https://quantum-hub.baidu.co... | the_stack_v2_python_sparse | Extensions/QuantumApp/qcompute_qapp/algorithm/kernel_classifier.py | baidu/QCompute | train | 86 |
25ce15be7231d55da089be86209917d1678b4e51 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.documentSetVersion'.casefold():\n from .... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | BaseItemVersion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseItemVersion:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BaseItemVersion:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_36k_train_003699 | 4,284 | 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: BaseItemVersion",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | stack_v2_sparse_classes_30k_train_000713 | Implement the Python class `BaseItemVersion` described below.
Class description:
Implement the BaseItemVersion class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BaseItemVersion: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `BaseItemVersion` described below.
Class description:
Implement the BaseItemVersion class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BaseItemVersion: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BaseItemVersion:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BaseItemVersion:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseItemVersion:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BaseItemVersion:
"""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: BaseItem... | the_stack_v2_python_sparse | msgraph/generated/models/base_item_version.py | microsoftgraph/msgraph-sdk-python | train | 135 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.