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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ee51080ba97daf916cb500d20bdcb2091460acb0 | [
"if not os.path.exists(path):\n raise FileNotFoundError(f'{path!r}')\nself.lon_name = lon_name\nself.lat_name = lat_name\nself.ssh_name = ssh_name\nself.time_name = time_name\nself.regex = re.compile(pattern).search\nself.date_fmt = date_fmt\nself.time_series = self._walk_netcdf(path)\nself.time_delta = self._ca... | <|body_start_0|>
if not os.path.exists(path):
raise FileNotFoundError(f'{path!r}')
self.lon_name = lon_name
self.lat_name = lat_name
self.ssh_name = ssh_name
self.time_name = time_name
self.regex = re.compile(pattern).search
self.date_fmt = date_fmt
... | Plugin that implements a netcdf reader. The netcdf reader works on files whose names have the date in it. A pattern (ex. P(?<date>.*).nc), associated with a date formatter (ex. %Y%m%d) is used to get build the time series. Netcdf files can be expensive to concatenate if there are a lot of files. This loader avoid loadi... | NetcdfLoader | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetcdfLoader:
"""Plugin that implements a netcdf reader. The netcdf reader works on files whose names have the date in it. A pattern (ex. P(?<date>.*).nc), associated with a date formatter (ex. %Y%m%d) is used to get build the time series. Netcdf files can be expensive to concatenate if there are... | stack_v2_sparse_classes_36k_train_031200 | 16,073 | permissive | [
{
"docstring": "Initialization of the netcdf loader. Args: path (str): Folder containing the netcdf files date_fmt (str): date formatter lon_name (str): longitude name in the netcdf files. Defaults to 'lon' lat_name (str): latitude name in the netcdf files. Defaults to 'lat' ssh_name (str): sea surface height n... | 4 | stack_v2_sparse_classes_30k_train_003354 | Implement the Python class `NetcdfLoader` described below.
Class description:
Plugin that implements a netcdf reader. The netcdf reader works on files whose names have the date in it. A pattern (ex. P(?<date>.*).nc), associated with a date formatter (ex. %Y%m%d) is used to get build the time series. Netcdf files can b... | Implement the Python class `NetcdfLoader` described below.
Class description:
Plugin that implements a netcdf reader. The netcdf reader works on files whose names have the date in it. A pattern (ex. P(?<date>.*).nc), associated with a date formatter (ex. %Y%m%d) is used to get build the time series. Netcdf files can b... | 8382703828a236655898d199c8e474b48a57011a | <|skeleton|>
class NetcdfLoader:
"""Plugin that implements a netcdf reader. The netcdf reader works on files whose names have the date in it. A pattern (ex. P(?<date>.*).nc), associated with a date formatter (ex. %Y%m%d) is used to get build the time series. Netcdf files can be expensive to concatenate if there are... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetcdfLoader:
"""Plugin that implements a netcdf reader. The netcdf reader works on files whose names have the date in it. A pattern (ex. P(?<date>.*).nc), associated with a date formatter (ex. %Y%m%d) is used to get build the time series. Netcdf files can be expensive to concatenate if there are a lot of fil... | the_stack_v2_python_sparse | swot_simulator/plugins/data_handler.py | CNES/swot_simulator | train | 25 |
d2c2b13e48775424e9f4192350abbe2bb051f888 | [
"self.auth_url = 'http://' + ip + ':' + port + '/oauth2/token'\nself.rest_prefix = 'http://' + ip + ':' + port + '/rests/'\nself.auth_data = 'grant_type=password&username=' + username\nself.auth_data += '&password=' + password + '&scope=' + scope\nself.auth_header = {'Content-Type': 'application/x-www-form-urlencod... | <|body_start_0|>
self.auth_url = 'http://' + ip + ':' + port + '/oauth2/token'
self.rest_prefix = 'http://' + ip + ':' + port + '/rests/'
self.auth_data = 'grant_type=password&username=' + username
self.auth_data += '&password=' + password + '&scope=' + scope
self.auth_header = {... | Handling of restconf requests using token-based authentication, one session per token. | _TokenReusingSession | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TokenReusingSession:
"""Handling of restconf requests using token-based authentication, one session per token."""
def __init__(self, ip, username, password, scope, port='8181'):
"""Initialize session using hardcoded text data."""
<|body_0|>
def refresh_token(self):
... | stack_v2_sparse_classes_36k_train_031201 | 9,914 | no_license | [
{
"docstring": "Initialize session using hardcoded text data.",
"name": "__init__",
"signature": "def __init__(self, ip, username, password, scope, port='8181')"
},
{
"docstring": "Reset session, invoke call to get token, parse it and remember.",
"name": "refresh_token",
"signature": "de... | 4 | stack_v2_sparse_classes_30k_train_016844 | Implement the Python class `_TokenReusingSession` described below.
Class description:
Handling of restconf requests using token-based authentication, one session per token.
Method signatures and docstrings:
- def __init__(self, ip, username, password, scope, port='8181'): Initialize session using hardcoded text data.... | Implement the Python class `_TokenReusingSession` described below.
Class description:
Handling of restconf requests using token-based authentication, one session per token.
Method signatures and docstrings:
- def __init__(self, ip, username, password, scope, port='8181'): Initialize session using hardcoded text data.... | ff1bb51a8a14f89ceefd91c6fc535a4bce78e0de | <|skeleton|>
class _TokenReusingSession:
"""Handling of restconf requests using token-based authentication, one session per token."""
def __init__(self, ip, username, password, scope, port='8181'):
"""Initialize session using hardcoded text data."""
<|body_0|>
def refresh_token(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _TokenReusingSession:
"""Handling of restconf requests using token-based authentication, one session per token."""
def __init__(self, ip, username, password, scope, port='8181'):
"""Initialize session using hardcoded text data."""
self.auth_url = 'http://' + ip + ':' + port + '/oauth2/tok... | the_stack_v2_python_sparse | csit/libraries/AuthStandalone.py | opendaylight/integration-test | train | 29 |
e6651aaa82c284e68825ed7e24f1ef0f41a4bd60 | [
"subtotal = 0\nfor item in self.items:\n subtotal += item.total_cost\nreturn subtotal",
"if self.shipping_handling:\n return self.subtotal + self.shipping_handling\nreturn self.subtotal"
] | <|body_start_0|>
subtotal = 0
for item in self.items:
subtotal += item.total_cost
return subtotal
<|end_body_0|>
<|body_start_1|>
if self.shipping_handling:
return self.subtotal + self.shipping_handling
return self.subtotal
<|end_body_1|>
| The Manifest object contains manifest properties Attributes: manifest_id: Integer value to uniquely identify a manifest shipping_handling: Float value of the shipping and handling that will be applied to a manifest total: Float value of the subtotal + shipping and handling | Manifest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Manifest:
"""The Manifest object contains manifest properties Attributes: manifest_id: Integer value to uniquely identify a manifest shipping_handling: Float value of the shipping and handling that will be applied to a manifest total: Float value of the subtotal + shipping and handling"""
de... | stack_v2_sparse_classes_36k_train_031202 | 19,591 | no_license | [
{
"docstring": "Calculate the sub total for the item Returns: subtotal (float)",
"name": "subtotal",
"signature": "def subtotal(self)"
},
{
"docstring": "Calculate the actual total of the item. This is done by add shipping and handling to the subtotal. If there is no shipping and handling just r... | 2 | stack_v2_sparse_classes_30k_train_018337 | Implement the Python class `Manifest` described below.
Class description:
The Manifest object contains manifest properties Attributes: manifest_id: Integer value to uniquely identify a manifest shipping_handling: Float value of the shipping and handling that will be applied to a manifest total: Float value of the subt... | Implement the Python class `Manifest` described below.
Class description:
The Manifest object contains manifest properties Attributes: manifest_id: Integer value to uniquely identify a manifest shipping_handling: Float value of the shipping and handling that will be applied to a manifest total: Float value of the subt... | b4774f3e3616ccde6b02086811b82627f6614498 | <|skeleton|>
class Manifest:
"""The Manifest object contains manifest properties Attributes: manifest_id: Integer value to uniquely identify a manifest shipping_handling: Float value of the shipping and handling that will be applied to a manifest total: Float value of the subtotal + shipping and handling"""
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Manifest:
"""The Manifest object contains manifest properties Attributes: manifest_id: Integer value to uniquely identify a manifest shipping_handling: Float value of the shipping and handling that will be applied to a manifest total: Float value of the subtotal + shipping and handling"""
def subtotal(se... | the_stack_v2_python_sparse | models.py | cyberjedi22/TCMS | train | 0 |
695c41c7f778557a88479bfc71625ef260bbb207 | [
"jsonconfig.JsonConfig.__init__(self)\nself.hostname = b'esp%05d' % Hostname.getNumber()\nself.activated = True\nself.fallback = True\nself.default = b''",
"result = '%s:\\n' % self.__class__.__name__\nresult += ' Activated :%s\\n' % useful.tostrings(self.activated)\nresult = ' Hostname :%s\\n' % useful.to... | <|body_start_0|>
jsonconfig.JsonConfig.__init__(self)
self.hostname = b'esp%05d' % Hostname.getNumber()
self.activated = True
self.fallback = True
self.default = b''
<|end_body_0|>
<|body_start_1|>
result = '%s:\n' % self.__class__.__name__
result += ' Activate... | Wifi station configuration class | StationConfig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StationConfig:
"""Wifi station configuration class"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __repr__(self):
"""Display the content of wifi station"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
jsonconfig.JsonConfig.__init__(self... | stack_v2_sparse_classes_36k_train_031203 | 8,871 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Display the content of wifi station",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020412 | Implement the Python class `StationConfig` described below.
Class description:
Wifi station configuration class
Method signatures and docstrings:
- def __init__(self): Constructor
- def __repr__(self): Display the content of wifi station | Implement the Python class `StationConfig` described below.
Class description:
Wifi station configuration class
Method signatures and docstrings:
- def __init__(self): Constructor
- def __repr__(self): Display the content of wifi station
<|skeleton|>
class StationConfig:
"""Wifi station configuration class"""
... | d86814625a7cd2f7e5fa01b8e1652efc811cef3a | <|skeleton|>
class StationConfig:
"""Wifi station configuration class"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __repr__(self):
"""Display the content of wifi station"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StationConfig:
"""Wifi station configuration class"""
def __init__(self):
"""Constructor"""
jsonconfig.JsonConfig.__init__(self)
self.hostname = b'esp%05d' % Hostname.getNumber()
self.activated = True
self.fallback = True
self.default = b''
def __repr_... | the_stack_v2_python_sparse | modules/lib/wifi/station.py | antiquefu/pycameresp | train | 0 |
486119251afaf2bf1b149bb814c9c35059dac0a7 | [
"def help(nums, idx, step):\n if len(nums) - 1 - idx <= step:\n return True\n for i in range(step, 0, -1):\n if nums[idx + i] and help(nums, idx + i, nums[idx + i]):\n return True\n return False\nreturn help(nums, 0, nums[0])",
"if len(nums) == 1:\n return True\nstack = [[0, s... | <|body_start_0|>
def help(nums, idx, step):
if len(nums) - 1 - idx <= step:
return True
for i in range(step, 0, -1):
if nums[idx + i] and help(nums, idx + i, nums[idx + i]):
return True
return False
return help(nums,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump1(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canJump2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body... | stack_v2_sparse_classes_36k_train_031204 | 1,254 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump1",
"signature": "def canJump1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump2",
"signature": "def canJump2(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bo... | 3 | stack_v2_sparse_classes_30k_train_000499 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump1(self, nums): :type nums: List[int] :rtype: bool
- def canJump2(self, nums): :type nums: List[int] :rtype: bool
- def canJump(self, nums): :type nums: List[int] :rtyp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump1(self, nums): :type nums: List[int] :rtype: bool
- def canJump2(self, nums): :type nums: List[int] :rtype: bool
- def canJump(self, nums): :type nums: List[int] :rtyp... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def canJump1(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canJump2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump1(self, nums):
""":type nums: List[int] :rtype: bool"""
def help(nums, idx, step):
if len(nums) - 1 - idx <= step:
return True
for i in range(step, 0, -1):
if nums[idx + i] and help(nums, idx + i, nums[idx + i]):
... | the_stack_v2_python_sparse | py/leetcode/55.py | wfeng1991/learnpy | train | 0 | |
2ce78c7158dc1cc9446cc4ca6345778382c57f50 | [
"super().__init__(name=name)\nself.fragments_storage = CloudFiles(fragments_path)\nself.output_storage = CloudFiles(output_path)",
"print(f'aggregate skeletons with prefix of {prefix}')\nid2filenames = defaultdict(list)\nfor filename in self.fragments_storage.list_files(prefix=prefix):\n filename = os.path.bas... | <|body_start_0|>
super().__init__(name=name)
self.fragments_storage = CloudFiles(fragments_path)
self.output_storage = CloudFiles(output_path)
<|end_body_0|>
<|body_start_1|>
print(f'aggregate skeletons with prefix of {prefix}')
id2filenames = defaultdict(list)
for filen... | Merge skeleton fragments for Neuroglancer visualization. | AggregateSkeletonFragmentsOperator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AggregateSkeletonFragmentsOperator:
"""Merge skeleton fragments for Neuroglancer visualization."""
def __init__(self, fragments_path: str, output_path: str, name: str='aggregate-skeleton-fragments'):
"""Parameters ------------ fragments_path: path to store fragment files output_path:... | stack_v2_sparse_classes_36k_train_031205 | 2,270 | permissive | [
{
"docstring": "Parameters ------------ fragments_path: path to store fragment files output_path: save the merged skeleton file here.",
"name": "__init__",
"signature": "def __init__(self, fragments_path: str, output_path: str, name: str='aggregate-skeleton-fragments')"
},
{
"docstring": "To-do:... | 2 | stack_v2_sparse_classes_30k_train_003750 | Implement the Python class `AggregateSkeletonFragmentsOperator` described below.
Class description:
Merge skeleton fragments for Neuroglancer visualization.
Method signatures and docstrings:
- def __init__(self, fragments_path: str, output_path: str, name: str='aggregate-skeleton-fragments'): Parameters ------------ ... | Implement the Python class `AggregateSkeletonFragmentsOperator` described below.
Class description:
Merge skeleton fragments for Neuroglancer visualization.
Method signatures and docstrings:
- def __init__(self, fragments_path: str, output_path: str, name: str='aggregate-skeleton-fragments'): Parameters ------------ ... | 4b1b6cc7844f8bf453ae0ba3b618106163fa9bcf | <|skeleton|>
class AggregateSkeletonFragmentsOperator:
"""Merge skeleton fragments for Neuroglancer visualization."""
def __init__(self, fragments_path: str, output_path: str, name: str='aggregate-skeleton-fragments'):
"""Parameters ------------ fragments_path: path to store fragment files output_path:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AggregateSkeletonFragmentsOperator:
"""Merge skeleton fragments for Neuroglancer visualization."""
def __init__(self, fragments_path: str, output_path: str, name: str='aggregate-skeleton-fragments'):
"""Parameters ------------ fragments_path: path to store fragment files output_path: save the mer... | the_stack_v2_python_sparse | chunkflow/plugins/aggregate_skeleton_fragments.py | seung-lab/chunkflow | train | 47 |
4211e47e5d84f2f86018686a325dc62e4fb52e08 | [
"self.rule_id = rule_id\nself.match = match_obj\nself.spans = tuple([match_obj.span(i) for i in xrange(1, groups_cnt)])\nself.captured_chars = self.__count_chars()\nself.captured_groups = len(self.spans)\nself.start = self.match.start()\nself.end = self.match.end()\nself.gstart = self.spans[0][0]\nself.gend = self.... | <|body_start_0|>
self.rule_id = rule_id
self.match = match_obj
self.spans = tuple([match_obj.span(i) for i in xrange(1, groups_cnt)])
self.captured_chars = self.__count_chars()
self.captured_groups = len(self.spans)
self.start = self.match.start()
self.end = self.... | Class for holding relevant information about condition matches. | MatchTuple | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchTuple:
"""Class for holding relevant information about condition matches."""
def __init__(self, rule_id, match_obj, groups_cnt):
"""Create an instance of MatchTuple."""
<|body_0|>
def __repr__(self):
"""String representation of object."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_031206 | 17,033 | permissive | [
{
"docstring": "Create an instance of MatchTuple.",
"name": "__init__",
"signature": "def __init__(self, rule_id, match_obj, groups_cnt)"
},
{
"docstring": "String representation of object.",
"name": "__repr__",
"signature": "def __repr__(self)"
},
{
"docstring": "Count total num... | 3 | stack_v2_sparse_classes_30k_train_008966 | Implement the Python class `MatchTuple` described below.
Class description:
Class for holding relevant information about condition matches.
Method signatures and docstrings:
- def __init__(self, rule_id, match_obj, groups_cnt): Create an instance of MatchTuple.
- def __repr__(self): String representation of object.
-... | Implement the Python class `MatchTuple` described below.
Class description:
Class for holding relevant information about condition matches.
Method signatures and docstrings:
- def __init__(self, rule_id, match_obj, groups_cnt): Create an instance of MatchTuple.
- def __repr__(self): String representation of object.
-... | ac645fb41260b86491b17fbc50e5ea3300dc28b7 | <|skeleton|>
class MatchTuple:
"""Class for holding relevant information about condition matches."""
def __init__(self, rule_id, match_obj, groups_cnt):
"""Create an instance of MatchTuple."""
<|body_0|>
def __repr__(self):
"""String representation of object."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MatchTuple:
"""Class for holding relevant information about condition matches."""
def __init__(self, rule_id, match_obj, groups_cnt):
"""Create an instance of MatchTuple."""
self.rule_id = rule_id
self.match = match_obj
self.spans = tuple([match_obj.span(i) for i in xrange... | the_stack_v2_python_sparse | scripts/lib/python/ld/p2p.py | WladimirSidorenko/TextNormalization | train | 1 |
19f81d8a82bd75d236396d35b82d82fd0fb2831f | [
"cur_root_val, path = (-2147483648, [])\nfor n in preorder:\n if n < cur_root_val:\n return False\n while len(path) > 0 and n > path[-1]:\n cur_root_val = path[-1]\n path.pop()\n path.append(n)\nreturn True",
"cur_root_val, stack_top = (-2147483648, -1)\nfor n in preorder:\n if n ... | <|body_start_0|>
cur_root_val, path = (-2147483648, [])
for n in preorder:
if n < cur_root_val:
return False
while len(path) > 0 and n > path[-1]:
cur_root_val = path[-1]
path.pop()
path.append(n)
return True
<|e... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def verifyPreorder(self, preorder):
""":type preorder: List[int] :rtype: bool"""
<|body_0|>
def verifyPreorder_constant_storage(self, preorder):
""":type preorder: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cur_... | stack_v2_sparse_classes_36k_train_031207 | 1,139 | no_license | [
{
"docstring": ":type preorder: List[int] :rtype: bool",
"name": "verifyPreorder",
"signature": "def verifyPreorder(self, preorder)"
},
{
"docstring": ":type preorder: List[int] :rtype: bool",
"name": "verifyPreorder_constant_storage",
"signature": "def verifyPreorder_constant_storage(se... | 2 | stack_v2_sparse_classes_30k_train_005160 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def verifyPreorder(self, preorder): :type preorder: List[int] :rtype: bool
- def verifyPreorder_constant_storage(self, preorder): :type preorder: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def verifyPreorder(self, preorder): :type preorder: List[int] :rtype: bool
- def verifyPreorder_constant_storage(self, preorder): :type preorder: List[int] :rtype: bool
<|skelet... | 3873502679a5def6af4be03028542f07d059d1a9 | <|skeleton|>
class Solution:
def verifyPreorder(self, preorder):
""":type preorder: List[int] :rtype: bool"""
<|body_0|>
def verifyPreorder_constant_storage(self, preorder):
""":type preorder: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def verifyPreorder(self, preorder):
""":type preorder: List[int] :rtype: bool"""
cur_root_val, path = (-2147483648, [])
for n in preorder:
if n < cur_root_val:
return False
while len(path) > 0 and n > path[-1]:
cur_root_... | the_stack_v2_python_sparse | Python-Algorithms-DataStructure/src/leet/255_VerifyPreorderSequenceinBinarySearchTree.py | coremedy/Python-Algorithms-DataStructure | train | 0 | |
bb1aa61f197e545dac1a4ff767ffb7480eb28b33 | [
"for page in range(1, 6):\n page_url = self.url.format(page)\n yield scrapy.Request(url=page_url, callback=self.parse)",
"li_list = response.xpath('//ul[@class=\"carlist clearfix js-top\"]/li')\nfor li in li_list:\n item = GuaziItem()\n item['title'] = li.xpath('./a/@title').get()\n item['price'] =... | <|body_start_0|>
for page in range(1, 6):
page_url = self.url.format(page)
yield scrapy.Request(url=page_url, callback=self.parse)
<|end_body_0|>
<|body_start_1|>
li_list = response.xpath('//ul[@class="carlist clearfix js-top"]/li')
for li in li_list:
item = ... | GuaziSpider | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GuaziSpider:
def start_requests(self):
"""生成所有要抓取的URL地址,一次性交给调度器如队列"""
<|body_0|>
def parse(self, response):
"""一级页面解析函数: 名称、价格、链接"""
<|body_1|>
def parse_second_page(self, response):
"""二级页面解析函数:里程、排量、变速箱"""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_031208 | 2,329 | permissive | [
{
"docstring": "生成所有要抓取的URL地址,一次性交给调度器如队列",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "一级页面解析函数: 名称、价格、链接",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "二级页面解析函数:里程、排量、变速箱",
"name": "parse_second_page",... | 3 | null | Implement the Python class `GuaziSpider` described below.
Class description:
Implement the GuaziSpider class.
Method signatures and docstrings:
- def start_requests(self): 生成所有要抓取的URL地址,一次性交给调度器如队列
- def parse(self, response): 一级页面解析函数: 名称、价格、链接
- def parse_second_page(self, response): 二级页面解析函数:里程、排量、变速箱 | Implement the Python class `GuaziSpider` described below.
Class description:
Implement the GuaziSpider class.
Method signatures and docstrings:
- def start_requests(self): 生成所有要抓取的URL地址,一次性交给调度器如队列
- def parse(self, response): 一级页面解析函数: 名称、价格、链接
- def parse_second_page(self, response): 二级页面解析函数:里程、排量、变速箱
<|skeleton|... | abe983ddc52690f4726cf42cc6390cba815026d8 | <|skeleton|>
class GuaziSpider:
def start_requests(self):
"""生成所有要抓取的URL地址,一次性交给调度器如队列"""
<|body_0|>
def parse(self, response):
"""一级页面解析函数: 名称、价格、链接"""
<|body_1|>
def parse_second_page(self, response):
"""二级页面解析函数:里程、排量、变速箱"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GuaziSpider:
def start_requests(self):
"""生成所有要抓取的URL地址,一次性交给调度器如队列"""
for page in range(1, 6):
page_url = self.url.format(page)
yield scrapy.Request(url=page_url, callback=self.parse)
def parse(self, response):
"""一级页面解析函数: 名称、价格、链接"""
li_list = re... | the_stack_v2_python_sparse | month05/spider/day07_course/day07_code/Guazi/Guazi/spiders/guazi.py | chaofan-zheng/tedu-python-demo | train | 4 | |
f06c073330ee853587217d023a191b8e2de1ab7d | [
"self.prefixes = collections.defaultdict(set)\nself.suffixes = collections.defaultdict(set)\nself.weights = {}\nfor i, word in enumerate(words):\n prefix, suffix = ('', '')\n for char in [''] + list(word):\n prefix += char\n self.prefixes[prefix].add(word)\n for char in [''] + list(word[::-1]... | <|body_start_0|>
self.prefixes = collections.defaultdict(set)
self.suffixes = collections.defaultdict(set)
self.weights = {}
for i, word in enumerate(words):
prefix, suffix = ('', '')
for char in [''] + list(word):
prefix += char
se... | WordFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def f(self, prefix, suffix):
""":type prefix: str :type suffix: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.prefixes = collections.defaultdict(se... | stack_v2_sparse_classes_36k_train_031209 | 1,094 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type prefix: str :type suffix: str :rtype: int",
"name": "f",
"signature": "def f(self, prefix, suffix)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008934 | Implement the Python class `WordFilter` described below.
Class description:
Implement the WordFilter class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int | Implement the Python class `WordFilter` described below.
Class description:
Implement the WordFilter class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int
<|skeleton|>
class WordFilter:
def __in... | 26c6ee936cdc1914dc3598c5dc74df64fa7960a1 | <|skeleton|>
class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def f(self, prefix, suffix):
""":type prefix: str :type suffix: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
self.prefixes = collections.defaultdict(set)
self.suffixes = collections.defaultdict(set)
self.weights = {}
for i, word in enumerate(words):
prefix, suffix = ('', '')
for char in... | the_stack_v2_python_sparse | 745-Prefix and Suffix Search.py | JinnieJJ/leetcode | train | 3 | |
e0fe56975cc73becdc5b8364b51699dd7c60ce9c | [
"if self.request.user.is_superuser:\n return models.Workflow.objects.all()\nreturn models.Workflow.objects.filter(Q(user=self.request.user) | Q(shared=self.request.user)).distinct()",
"if self.request.user.is_superuser:\n serializer.save()\nelse:\n serializer.save(Q(user=self.request.user) | Q(shared=sel... | <|body_start_0|>
if self.request.user.is_superuser:
return models.Workflow.objects.all()
return models.Workflow.objects.filter(Q(user=self.request.user) | Q(shared=self.request.user)).distinct()
<|end_body_0|>
<|body_start_1|>
if self.request.user.is_superuser:
serialize... | API to manage workflow operations. get: Returns the information stored for the workflow put: Modifies the workflow with the information included in the request (all fields are overwritten) patch: Update only the given fields in the workshop (the rest remain unchanged) delete: Delete the workflow | WorkflowAPIRetrieveUpdateDestroy | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowAPIRetrieveUpdateDestroy:
"""API to manage workflow operations. get: Returns the information stored for the workflow put: Modifies the workflow with the information included in the request (all fields are overwritten) patch: Update only the given fields in the workshop (the rest remain un... | stack_v2_sparse_classes_36k_train_031210 | 4,435 | permissive | [
{
"docstring": "Access the relevant workflow.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Create the workflow element.",
"name": "perform_create",
"signature": "def perform_create(self, serializer)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003855 | Implement the Python class `WorkflowAPIRetrieveUpdateDestroy` described below.
Class description:
API to manage workflow operations. get: Returns the information stored for the workflow put: Modifies the workflow with the information included in the request (all fields are overwritten) patch: Update only the given fie... | Implement the Python class `WorkflowAPIRetrieveUpdateDestroy` described below.
Class description:
API to manage workflow operations. get: Returns the information stored for the workflow put: Modifies the workflow with the information included in the request (all fields are overwritten) patch: Update only the given fie... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class WorkflowAPIRetrieveUpdateDestroy:
"""API to manage workflow operations. get: Returns the information stored for the workflow put: Modifies the workflow with the information included in the request (all fields are overwritten) patch: Update only the given fields in the workshop (the rest remain un... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkflowAPIRetrieveUpdateDestroy:
"""API to manage workflow operations. get: Returns the information stored for the workflow put: Modifies the workflow with the information included in the request (all fields are overwritten) patch: Update only the given fields in the workshop (the rest remain unchanged) dele... | the_stack_v2_python_sparse | ontask/workflow/api.py | abelardopardo/ontask_b | train | 43 |
a393bf71ef60f5cec5577944e7b7debde696ad99 | [
"try:\n params = request._serialize()\n headers = request.headers\n body = self.call('CancelTask', params, headers=headers)\n response = json.loads(body)\n model = models.CancelTaskResponse()\n model._deserialize(response['Response'])\n return model\nexcept Exception as e:\n if isinstance(e,... | <|body_start_0|>
try:
params = request._serialize()
headers = request.headers
body = self.call('CancelTask', params, headers=headers)
response = json.loads(body)
model = models.CancelTaskResponse()
model._deserialize(response['Response'])
... | VmClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VmClient:
def CancelTask(self, request):
"""可使用该接口取消审核任务,成功取消后,该接口返回已取消任务的TaskId。<br> 默认接口请求频率限制:**20次/秒**。 :param request: Request instance for CancelTask. :type request: :class:`tencentcloud.vm.v20201229.models.CancelTaskRequest` :rtype: :class:`tencentcloud.vm.v20201229.models.CancelT... | stack_v2_sparse_classes_36k_train_031211 | 9,114 | permissive | [
{
"docstring": "可使用该接口取消审核任务,成功取消后,该接口返回已取消任务的TaskId。<br> 默认接口请求频率限制:**20次/秒**。 :param request: Request instance for CancelTask. :type request: :class:`tencentcloud.vm.v20201229.models.CancelTaskRequest` :rtype: :class:`tencentcloud.vm.v20201229.models.CancelTaskResponse`",
"name": "CancelTask",
"signat... | 4 | stack_v2_sparse_classes_30k_val_000302 | Implement the Python class `VmClient` described below.
Class description:
Implement the VmClient class.
Method signatures and docstrings:
- def CancelTask(self, request): 可使用该接口取消审核任务,成功取消后,该接口返回已取消任务的TaskId。<br> 默认接口请求频率限制:**20次/秒**。 :param request: Request instance for CancelTask. :type request: :class:`tencentclou... | Implement the Python class `VmClient` described below.
Class description:
Implement the VmClient class.
Method signatures and docstrings:
- def CancelTask(self, request): 可使用该接口取消审核任务,成功取消后,该接口返回已取消任务的TaskId。<br> 默认接口请求频率限制:**20次/秒**。 :param request: Request instance for CancelTask. :type request: :class:`tencentclou... | 6baf00a5a56ba58b6a1123423e0a1422d17a0201 | <|skeleton|>
class VmClient:
def CancelTask(self, request):
"""可使用该接口取消审核任务,成功取消后,该接口返回已取消任务的TaskId。<br> 默认接口请求频率限制:**20次/秒**。 :param request: Request instance for CancelTask. :type request: :class:`tencentcloud.vm.v20201229.models.CancelTaskRequest` :rtype: :class:`tencentcloud.vm.v20201229.models.CancelT... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VmClient:
def CancelTask(self, request):
"""可使用该接口取消审核任务,成功取消后,该接口返回已取消任务的TaskId。<br> 默认接口请求频率限制:**20次/秒**。 :param request: Request instance for CancelTask. :type request: :class:`tencentcloud.vm.v20201229.models.CancelTaskRequest` :rtype: :class:`tencentcloud.vm.v20201229.models.CancelTaskResponse`""... | the_stack_v2_python_sparse | tencentcloud/vm/v20201229/vm_client.py | TencentCloud/tencentcloud-sdk-python | train | 594 | |
4d9c5447d5c09557490f1a6f16236ecb19bf0b34 | [
"self.expert = MagicMock(spec=Expert, userbase=MagicMock(id=1))\nself.expert.profiles.all.return_value = []\nself.content = MagicMock(spec=Content, id=1)\nself.push_admin_feeds = PushSuperAdminFeeds(self.expert.userbase)\nself.expert_profile_ids = [2]\nself.tag_ids = [1, 2, 3, 4]",
"result = self.push_admin_feeds... | <|body_start_0|>
self.expert = MagicMock(spec=Expert, userbase=MagicMock(id=1))
self.expert.profiles.all.return_value = []
self.content = MagicMock(spec=Content, id=1)
self.push_admin_feeds = PushSuperAdminFeeds(self.expert.userbase)
self.expert_profile_ids = [2]
self.tag... | Test case for PushFeeds | TestPushSuperAdminFeeds | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPushSuperAdminFeeds:
"""Test case for PushFeeds"""
def setUp(self):
"""SetUp method for test case"""
<|body_0|>
def test_push_super_admin_feeds(self, mock_expert_publish_content):
"""test case for testing the mocked method is getting called with exact argumen... | stack_v2_sparse_classes_36k_train_031212 | 20,391 | no_license | [
{
"docstring": "SetUp method for test case",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test case for testing the mocked method is getting called with exact arguments",
"name": "test_push_super_admin_feeds",
"signature": "def test_push_super_admin_feeds(self, mock... | 2 | stack_v2_sparse_classes_30k_train_014454 | Implement the Python class `TestPushSuperAdminFeeds` described below.
Class description:
Test case for PushFeeds
Method signatures and docstrings:
- def setUp(self): SetUp method for test case
- def test_push_super_admin_feeds(self, mock_expert_publish_content): test case for testing the mocked method is getting call... | Implement the Python class `TestPushSuperAdminFeeds` described below.
Class description:
Test case for PushFeeds
Method signatures and docstrings:
- def setUp(self): SetUp method for test case
- def test_push_super_admin_feeds(self, mock_expert_publish_content): test case for testing the mocked method is getting call... | 248a7b406686c0c98e944319a6eca08485104f5d | <|skeleton|>
class TestPushSuperAdminFeeds:
"""Test case for PushFeeds"""
def setUp(self):
"""SetUp method for test case"""
<|body_0|>
def test_push_super_admin_feeds(self, mock_expert_publish_content):
"""test case for testing the mocked method is getting called with exact argumen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPushSuperAdminFeeds:
"""Test case for PushFeeds"""
def setUp(self):
"""SetUp method for test case"""
self.expert = MagicMock(spec=Expert, userbase=MagicMock(id=1))
self.expert.profiles.all.return_value = []
self.content = MagicMock(spec=Content, id=1)
self.push... | the_stack_v2_python_sparse | common/feeds/tests.py | skshivammahajan/DRFChat | train | 0 |
dbf79be09c93d7f22a0a2299eb5ce389477894d9 | [
"self.owner = owner\nself.timeout = 0.0\nself.handle = KOKORO.call_after(timeout, type(self)._step, self)",
"timeout = self.timeout\nif timeout > 0.0:\n self.handle = KOKORO.call_after(timeout, type(self)._step, self)\n self.timeout = 0.0\n return\nself.handle = None\nowner = self.owner\nif owner is None... | <|body_start_0|>
self.owner = owner
self.timeout = 0.0
self.handle = KOKORO.call_after(timeout, type(self)._step, self)
<|end_body_0|>
<|body_start_1|>
timeout = self.timeout
if timeout > 0.0:
self.handle = KOKORO.call_after(timeout, type(self)._step, self)
... | Executes timing out feature on ``Pagination`` and on other familiar types. Attributes ---------- handle : `None`, ``TimerHandle`` Handle to wake_up the timeouter with it's `._step` function. Set to `None`, when the respective timeout is over or if the timeout is cancelled. owner : `Any` The object what uses the timeout... | Timeouter | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Timeouter:
"""Executes timing out feature on ``Pagination`` and on other familiar types. Attributes ---------- handle : `None`, ``TimerHandle`` Handle to wake_up the timeouter with it's `._step` function. Set to `None`, when the respective timeout is over or if the timeout is cancelled. owner : `... | stack_v2_sparse_classes_36k_train_031213 | 4,721 | permissive | [
{
"docstring": "Creates a new ``Timeouter`` with the given `owner` and `timeout`. Parameters ---------- owner : `Any` The object what uses the timeouter. timeout : `float` The time with what the timeout will be expired when it's current waiting cycle is over.",
"name": "__init__",
"signature": "def __in... | 5 | null | Implement the Python class `Timeouter` described below.
Class description:
Executes timing out feature on ``Pagination`` and on other familiar types. Attributes ---------- handle : `None`, ``TimerHandle`` Handle to wake_up the timeouter with it's `._step` function. Set to `None`, when the respective timeout is over or... | Implement the Python class `Timeouter` described below.
Class description:
Executes timing out feature on ``Pagination`` and on other familiar types. Attributes ---------- handle : `None`, ``TimerHandle`` Handle to wake_up the timeouter with it's `._step` function. Set to `None`, when the respective timeout is over or... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class Timeouter:
"""Executes timing out feature on ``Pagination`` and on other familiar types. Attributes ---------- handle : `None`, ``TimerHandle`` Handle to wake_up the timeouter with it's `._step` function. Set to `None`, when the respective timeout is over or if the timeout is cancelled. owner : `... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Timeouter:
"""Executes timing out feature on ``Pagination`` and on other familiar types. Attributes ---------- handle : `None`, ``TimerHandle`` Handle to wake_up the timeouter with it's `._step` function. Set to `None`, when the respective timeout is over or if the timeout is cancelled. owner : `Any` The obje... | the_stack_v2_python_sparse | hata/ext/command_utils/utils.py | HuyaneMatsu/hata | train | 3 |
b911e40a3f5d80d4cfcbace42b8d3795e1f7bdcf | [
"params['n_clusters'] = n_clusters\nself.km = Kmeans(**params)\nself.metric = self.km.metric",
"self.covmeans_ = []\nself.classes_ = numpy.unique(y)\nfor c in self.classes_:\n self.km.fit(X[y == c])\n self.covmeans_.extend(self.km.centroids())\nreturn self",
"mdm = MDM(metric=self.metric)\nmdm.covmeans_ =... | <|body_start_0|>
params['n_clusters'] = n_clusters
self.km = Kmeans(**params)
self.metric = self.km.metric
<|end_body_0|>
<|body_start_1|>
self.covmeans_ = []
self.classes_ = numpy.unique(y)
for c in self.classes_:
self.km.fit(X[y == c])
self.covm... | Run kmeans for each class. | KmeansPerClassTransform | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KmeansPerClassTransform:
"""Run kmeans for each class."""
def __init__(self, n_clusters=2, **params):
"""Init."""
<|body_0|>
def fit(self, X, y):
"""fit."""
<|body_1|>
def transform(self, X):
"""transform."""
<|body_2|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_031214 | 12,224 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, n_clusters=2, **params)"
},
{
"docstring": "fit.",
"name": "fit",
"signature": "def fit(self, X, y)"
},
{
"docstring": "transform.",
"name": "transform",
"signature": "def transform(self, X)"
}... | 3 | stack_v2_sparse_classes_30k_train_010457 | Implement the Python class `KmeansPerClassTransform` described below.
Class description:
Run kmeans for each class.
Method signatures and docstrings:
- def __init__(self, n_clusters=2, **params): Init.
- def fit(self, X, y): fit.
- def transform(self, X): transform. | Implement the Python class `KmeansPerClassTransform` described below.
Class description:
Run kmeans for each class.
Method signatures and docstrings:
- def __init__(self, n_clusters=2, **params): Init.
- def fit(self, X, y): fit.
- def transform(self, X): transform.
<|skeleton|>
class KmeansPerClassTransform:
""... | 26c2ebf5200b5a5cd268fa73ac3928d7257d08d3 | <|skeleton|>
class KmeansPerClassTransform:
"""Run kmeans for each class."""
def __init__(self, n_clusters=2, **params):
"""Init."""
<|body_0|>
def fit(self, X, y):
"""fit."""
<|body_1|>
def transform(self, X):
"""transform."""
<|body_2|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KmeansPerClassTransform:
"""Run kmeans for each class."""
def __init__(self, n_clusters=2, **params):
"""Init."""
params['n_clusters'] = n_clusters
self.km = Kmeans(**params)
self.metric = self.km.metric
def fit(self, X, y):
"""fit."""
self.covmeans_ =... | the_stack_v2_python_sparse | externals/pyriemann/clustering.py | kingjr/decoding_challenge_cortana_2016_3rd | train | 10 |
667426322e8b20be95be8415c8b544312fa8f4f5 | [
"role = db.Role.get(id)\nif not role:\n return ({'msg': f'Role id={id} not found!'}, HTTPStatus.NOT_FOUND)\nauth_org = self.obtain_auth_organization()\nif not self.r.v_glo.can():\n if not (self.r.v_org.can() and auth_org == role.organization):\n return ({'msg': 'You lack permissions to do that'}, HTTPS... | <|body_start_0|>
role = db.Role.get(id)
if not role:
return ({'msg': f'Role id={id} not found!'}, HTTPStatus.NOT_FOUND)
auth_org = self.obtain_auth_organization()
if not self.r.v_glo.can():
if not (self.r.v_org.can() and auth_org == role.organization):
... | RoleRules | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleRules:
def get(self, id):
"""Returns the rules for a specific role --- description: >- View the rules that belong to a specific role. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|--|--|--|--| |Role|Global|View|❌|❌|View a ... | stack_v2_sparse_classes_36k_train_031215 | 26,260 | permissive | [
{
"docstring": "Returns the rules for a specific role --- description: >- View the rules that belong to a specific role. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|--|--|--|--| |Role|Global|View|❌|❌|View a role's rules| |Role|Organization|View|❌|❌... | 3 | stack_v2_sparse_classes_30k_train_017441 | Implement the Python class `RoleRules` described below.
Class description:
Implement the RoleRules class.
Method signatures and docstrings:
- def get(self, id): Returns the rules for a specific role --- description: >- View the rules that belong to a specific role. ### Permission Table |Rule name|Scope|Operation|Assi... | Implement the Python class `RoleRules` described below.
Class description:
Implement the RoleRules class.
Method signatures and docstrings:
- def get(self, id): Returns the rules for a specific role --- description: >- View the rules that belong to a specific role. ### Permission Table |Rule name|Scope|Operation|Assi... | b3ff6e91ac4caeaf31c12c20f73dfc61cfd9baca | <|skeleton|>
class RoleRules:
def get(self, id):
"""Returns the rules for a specific role --- description: >- View the rules that belong to a specific role. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|--|--|--|--| |Role|Global|View|❌|❌|View a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleRules:
def get(self, id):
"""Returns the rules for a specific role --- description: >- View the rules that belong to a specific role. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|--|--|--|--| |Role|Global|View|❌|❌|View a role's rules| ... | the_stack_v2_python_sparse | vantage6-server/vantage6/server/resource/role.py | vantage6/vantage6 | train | 15 | |
0fb98998ddaeef5c4bbfdb856d3133c142f8a643 | [
"assert isinstance(request, HttpRequest)\nqapp_id = request.GET.get('qapp_id', None)\nqapp = Qapp.objects.get(id=qapp_id)\nedit_message = ''\nif not check_can_edit(qapp, request.user):\n edit_message = 'You cannot edit this QAPP.'\nexisting_section_d = SectionD.objects.filter(qapp=qapp).first()\nif existing_sect... | <|body_start_0|>
assert isinstance(request, HttpRequest)
qapp_id = request.GET.get('qapp_id', None)
qapp = Qapp.objects.get(id=qapp_id)
edit_message = ''
if not check_can_edit(qapp, request.user):
edit_message = 'You cannot edit this QAPP.'
existing_section_d ... | Class for processing QAPP Section D information. | SectionDView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SectionDView:
"""Class for processing QAPP Section D information."""
def get(self, request, *args, **kwargs):
"""Return the index page for QAPP Section D."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Process the post request with a SectionD form fil... | stack_v2_sparse_classes_36k_train_031216 | 36,787 | no_license | [
{
"docstring": "Return the index page for QAPP Section D.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Process the post request with a SectionD form filled out.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `SectionDView` described below.
Class description:
Class for processing QAPP Section D information.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return the index page for QAPP Section D.
- def post(self, request, *args, **kwargs): Process the post request wit... | Implement the Python class `SectionDView` described below.
Class description:
Class for processing QAPP Section D information.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return the index page for QAPP Section D.
- def post(self, request, *args, **kwargs): Process the post request wit... | ee419afa3c9f4b9ef3b30b62b693cfac956ce5b4 | <|skeleton|>
class SectionDView:
"""Class for processing QAPP Section D information."""
def get(self, request, *args, **kwargs):
"""Return the index page for QAPP Section D."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Process the post request with a SectionD form fil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SectionDView:
"""Class for processing QAPP Section D information."""
def get(self, request, *args, **kwargs):
"""Return the index page for QAPP Section D."""
assert isinstance(request, HttpRequest)
qapp_id = request.GET.get('qapp_id', None)
qapp = Qapp.objects.get(id=qapp_... | the_stack_v2_python_sparse | DataSearch/qar5/views.py | USEPA/FoodWaste | train | 1 |
2165f2b1d85c1b654466a49e1a333e98e4241e3e | [
"super(W, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)\nself.options = options\nself.ret_required = False\nself._is_overwritten = False\nself.current_ret['GENERAL_INFO'] = dict()\nself.current_ret['RESULT'] = list()\nself.headers = list()",
"if self._regex_helpe... | <|body_start_0|>
super(W, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)
self.options = options
self.ret_required = False
self._is_overwritten = False
self.current_ret['GENERAL_INFO'] = dict()
self.current_ret['RESULT'] = ... | W command class. | W | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class W:
"""W command class."""
def __init__(self, connection, options='', prompt=None, newline_chars=None, runner=None):
"""W command. :param connection: Moler connection to device, terminal when command is executed. :param options: Options of w command. :param prompt: Expected prompt tha... | stack_v2_sparse_classes_36k_train_031217 | 9,989 | permissive | [
{
"docstring": "W command. :param connection: Moler connection to device, terminal when command is executed. :param options: Options of w command. :param prompt: Expected prompt that has been sent by device after command execution. :param newline_chars: Characters to split lines - list. :param runner: Runner to... | 6 | stack_v2_sparse_classes_30k_train_009390 | Implement the Python class `W` described below.
Class description:
W command class.
Method signatures and docstrings:
- def __init__(self, connection, options='', prompt=None, newline_chars=None, runner=None): W command. :param connection: Moler connection to device, terminal when command is executed. :param options:... | Implement the Python class `W` described below.
Class description:
W command class.
Method signatures and docstrings:
- def __init__(self, connection, options='', prompt=None, newline_chars=None, runner=None): W command. :param connection: Moler connection to device, terminal when command is executed. :param options:... | 5a7bb06807b6e0124c77040367d0c20f42849a4c | <|skeleton|>
class W:
"""W command class."""
def __init__(self, connection, options='', prompt=None, newline_chars=None, runner=None):
"""W command. :param connection: Moler connection to device, terminal when command is executed. :param options: Options of w command. :param prompt: Expected prompt tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class W:
"""W command class."""
def __init__(self, connection, options='', prompt=None, newline_chars=None, runner=None):
"""W command. :param connection: Moler connection to device, terminal when command is executed. :param options: Options of w command. :param prompt: Expected prompt that has been se... | the_stack_v2_python_sparse | moler/cmd/unix/w.py | nokia/moler | train | 60 |
ee774693af6da70f02410cb5857f1b0da6f27c4c | [
"self.vec = vec2d\nself.cur_ind = 0\nself.lst_ind = 0",
"ret = self.vec[self.cur_ind][self.lst_ind]\nif len(self.vec[self.cur_ind]) - 1 == self.lst_ind:\n self.cur_ind += 1\n self.lst_ind = 0\nelse:\n self.lst_ind += 1\nreturn ret",
"while self.cur_ind < len(self.vec):\n if self.vec[self.cur_ind]:\n... | <|body_start_0|>
self.vec = vec2d
self.cur_ind = 0
self.lst_ind = 0
<|end_body_0|>
<|body_start_1|>
ret = self.vec[self.cur_ind][self.lst_ind]
if len(self.vec[self.cur_ind]) - 1 == self.lst_ind:
self.cur_ind += 1
self.lst_ind = 0
else:
... | Vector2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_031218 | 1,177 | no_license | [
{
"docstring": "Initialize your data structure here. :type vec2d: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, vec2d)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",... | 3 | stack_v2_sparse_classes_30k_train_006309 | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool
<|skeleton|>
class V... | b619498d2b8b5e53b629b664fabcff0b68c10897 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
self.vec = vec2d
self.cur_ind = 0
self.lst_ind = 0
def next(self):
""":rtype: int"""
ret = self.vec[self.cur_ind][self.lst_ind]
if len(self.... | the_stack_v2_python_sparse | flatten_2d.py | MatthewC221/Algorithms | train | 1 | |
bb7d46c8e1b0e0c2e1e2d4aa161d9d232b08af90 | [
"import matplotlib.pyplot as plt\nfigure, axes = plt.subplots()\ngood = self.mask & self.flags.get(*ignoreFlags) == 0 if ignoreFlags is not None else np.ones_like(self.mask, dtype=bool)\naxes.plot(self.wavelength[good], self.flux[good], 'k-', label='Flux')\naxes.set_xlabel('Wavelength (nm)')\naxes.set_ylabel('Flux ... | <|body_start_0|>
import matplotlib.pyplot as plt
figure, axes = plt.subplots()
good = self.mask & self.flags.get(*ignoreFlags) == 0 if ignoreFlags is not None else np.ones_like(self.mask, dtype=bool)
axes.plot(self.wavelength[good], self.flux[good], 'k-', label='Flux')
axes.set_x... | FluxTable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FluxTable:
def plot(self, ignoreFlags=None, show=True):
"""Plot the object spectrum Parameters ---------- ignorePixelMask : `int` Mask to apply to flux pixels. show : `bool`, optional Show the plot and block on the window? Returns ------- figure : `matplotlib.Figure` Figure containing th... | stack_v2_sparse_classes_36k_train_031219 | 1,990 | no_license | [
{
"docstring": "Plot the object spectrum Parameters ---------- ignorePixelMask : `int` Mask to apply to flux pixels. show : `bool`, optional Show the plot and block on the window? Returns ------- figure : `matplotlib.Figure` Figure containing the plot. axes : `matplotlib.Axes` Axes containing the plot.",
"n... | 2 | null | Implement the Python class `FluxTable` described below.
Class description:
Implement the FluxTable class.
Method signatures and docstrings:
- def plot(self, ignoreFlags=None, show=True): Plot the object spectrum Parameters ---------- ignorePixelMask : `int` Mask to apply to flux pixels. show : `bool`, optional Show t... | Implement the Python class `FluxTable` described below.
Class description:
Implement the FluxTable class.
Method signatures and docstrings:
- def plot(self, ignoreFlags=None, show=True): Plot the object spectrum Parameters ---------- ignorePixelMask : `int` Mask to apply to flux pixels. show : `bool`, optional Show t... | 85602eea2485ac24e0831046dc74f1b2d1a3d89f | <|skeleton|>
class FluxTable:
def plot(self, ignoreFlags=None, show=True):
"""Plot the object spectrum Parameters ---------- ignorePixelMask : `int` Mask to apply to flux pixels. show : `bool`, optional Show the plot and block on the window? Returns ------- figure : `matplotlib.Figure` Figure containing th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FluxTable:
def plot(self, ignoreFlags=None, show=True):
"""Plot the object spectrum Parameters ---------- ignorePixelMask : `int` Mask to apply to flux pixels. show : `bool`, optional Show the plot and block on the window? Returns ------- figure : `matplotlib.Figure` Figure containing the plot. axes :... | the_stack_v2_python_sparse | python/pfs/drp/stella/datamodel/fluxTable.py | Subaru-PFS/drp_stella | train | 3 | |
74ba213d4fab33b0a7cfabe35671d93818512ca4 | [
"self.mu_g = mu_g\nself.s_g = s_g\nself.s_s = s_s\nself.h = h",
"assert len(f1.shape) == 1, 'input must be 1d ndarray'\nassert len(f2.shape) == 1, 'input must be 1d ndarray'\nassert f1.shape == f2.shape\nn_trial = len(f1)\nf1_ = np.tile(f1, (n_samp, 1)) + self.s_s * np.random.randn(n_samp, n_trial)\ns = (1.0 / se... | <|body_start_0|>
self.mu_g = mu_g
self.s_g = s_g
self.s_s = s_s
self.h = h
<|end_body_0|>
<|body_start_1|>
assert len(f1.shape) == 1, 'input must be 1d ndarray'
assert len(f2.shape) == 1, 'input must be 1d ndarray'
assert f1.shape == f2.shape
n_trial = le... | A model of tone discrimination where - the value of the first tone is inferred from noisy observation - the value of the second tone is noiseless - prior is unigauss | Model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
"""A model of tone discrimination where - the value of the first tone is inferred from noisy observation - the value of the second tone is noiseless - prior is unigauss"""
def __init__(self, mu_g, s_g, h, s_s):
"""Constructor :param mu_g: mean of gaussian part of unigauss :par... | stack_v2_sparse_classes_36k_train_031220 | 11,426 | no_license | [
{
"docstring": "Constructor :param mu_g: mean of gaussian part of unigauss :param s_g: std of gaussian part of unigauss :param h: weight of flat prior in unigauss mixture assuming unnormalized gaussian p(x) 1/Z*( h + exp((x-mu)/2/s^2) ) :param s_s: std of likelihood",
"name": "__init__",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_010514 | Implement the Python class `Model` described below.
Class description:
A model of tone discrimination where - the value of the first tone is inferred from noisy observation - the value of the second tone is noiseless - prior is unigauss
Method signatures and docstrings:
- def __init__(self, mu_g, s_g, h, s_s): Constr... | Implement the Python class `Model` described below.
Class description:
A model of tone discrimination where - the value of the first tone is inferred from noisy observation - the value of the second tone is noiseless - prior is unigauss
Method signatures and docstrings:
- def __init__(self, mu_g, s_g, h, s_s): Constr... | 2a05aa98b501c8633e1fe2baf611d137740709de | <|skeleton|>
class Model:
"""A model of tone discrimination where - the value of the first tone is inferred from noisy observation - the value of the second tone is noiseless - prior is unigauss"""
def __init__(self, mu_g, s_g, h, s_s):
"""Constructor :param mu_g: mean of gaussian part of unigauss :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Model:
"""A model of tone discrimination where - the value of the first tone is inferred from noisy observation - the value of the second tone is noiseless - prior is unigauss"""
def __init__(self, mu_g, s_g, h, s_s):
"""Constructor :param mu_g: mean of gaussian part of unigauss :param s_g: std o... | the_stack_v2_python_sparse | model/simple_model.py | ItayLieder/GMM_simulations | train | 0 |
ed7fc820896454fe2235f13851fa43c9d072bb88 | [
"super().__init__(strategy=strategy, kwargs=kwargs)\nself.create_time = None\nself.save_time = None",
"j = OrderedDict()\nj['create_time'] = self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time is not None else ''\nj['save_time'] = self.save_time.strftime('%Y-%m-%d %H:%M:%S') if self.save_time is no... | <|body_start_0|>
super().__init__(strategy=strategy, kwargs=kwargs)
self.create_time = None
self.save_time = None
<|end_body_0|>
<|body_start_1|>
j = OrderedDict()
j['create_time'] = self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time is not None else ''
j... | 策略的持久化Policy组件 | CtaPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CtaPolicy:
"""策略的持久化Policy组件"""
def __init__(self, strategy=None, **kwargs):
"""构造 :param strategy:"""
<|body_0|>
def to_json(self):
"""将数据转换成dict datetime =》 string object =》 string :return:"""
<|body_1|>
def from_json(self, json_data):
"""将... | stack_v2_sparse_classes_36k_train_031221 | 3,572 | permissive | [
{
"docstring": "构造 :param strategy:",
"name": "__init__",
"signature": "def __init__(self, strategy=None, **kwargs)"
},
{
"docstring": "将数据转换成dict datetime =》 string object =》 string :return:",
"name": "to_json",
"signature": "def to_json(self)"
},
{
"docstring": "将数据从json_data中恢... | 5 | null | Implement the Python class `CtaPolicy` described below.
Class description:
策略的持久化Policy组件
Method signatures and docstrings:
- def __init__(self, strategy=None, **kwargs): 构造 :param strategy:
- def to_json(self): 将数据转换成dict datetime =》 string object =》 string :return:
- def from_json(self, json_data): 将数据从json_data中恢复... | Implement the Python class `CtaPolicy` described below.
Class description:
策略的持久化Policy组件
Method signatures and docstrings:
- def __init__(self, strategy=None, **kwargs): 构造 :param strategy:
- def to_json(self): 将数据转换成dict datetime =》 string object =》 string :return:
- def from_json(self, json_data): 将数据从json_data中恢复... | 7f4fd3cd202712b083ed7dc2f346ba4bb1bda6d7 | <|skeleton|>
class CtaPolicy:
"""策略的持久化Policy组件"""
def __init__(self, strategy=None, **kwargs):
"""构造 :param strategy:"""
<|body_0|>
def to_json(self):
"""将数据转换成dict datetime =》 string object =》 string :return:"""
<|body_1|>
def from_json(self, json_data):
"""将... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CtaPolicy:
"""策略的持久化Policy组件"""
def __init__(self, strategy=None, **kwargs):
"""构造 :param strategy:"""
super().__init__(strategy=strategy, kwargs=kwargs)
self.create_time = None
self.save_time = None
def to_json(self):
"""将数据转换成dict datetime =》 string object =... | the_stack_v2_python_sparse | vnpy/component/cta_policy.py | msincenselee/vnpy | train | 359 |
01814021144befbb15bf864d5231f5713b704a34 | [
"self.left = []\nself.right = []\nself.median = None",
"left = self.left\nright = self.right\nif self.median is None:\n self.median = num\n return\nif num <= self.median:\n heapq.heappush(left, -num)\nelse:\n heapq.heappush(right, num)\nif len(left) > len(right) + 1:\n top = -heapq.heappop(left)\n ... | <|body_start_0|>
self.left = []
self.right = []
self.median = None
<|end_body_0|>
<|body_start_1|>
left = self.left
right = self.right
if self.median is None:
self.median = num
return
if num <= self.median:
heapq.heappush(left,... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_36k_train_031222 | 1,251 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds a num into the data structure. :type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": "Returns the ... | 3 | null | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
self.left = []
self.right = []
self.median = None
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
left = self.left
right = self... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/lc-all-solutions/295.find-median-from-data-stream/find-median-from-data-stream.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
3d7e2b462da93f154c994a3fa4ef3ebe2f4a3ae8 | [
"self.stored = None\nself.indexed = None\nself.description = None\nself.data_type = None\nself.name = None\nreplace_names = {'stored': 'stored', 'indexed': 'indexed', 'description': 'description', 'dataType': 'data_type', 'name': 'name'}\nif kwargs is not None:\n for key in kwargs:\n if key in replace_nam... | <|body_start_0|>
self.stored = None
self.indexed = None
self.description = None
self.data_type = None
self.name = None
replace_names = {'stored': 'stored', 'indexed': 'indexed', 'description': 'description', 'dataType': 'data_type', 'name': 'name'}
if kwargs is no... | Implementation of the 'Occurrence_indexed_fields_Response' model. Occurrence_indexed_fields_Response Attributes: stored (bool): stored indexed (bool): indexed description (string): description data_type (string): dataType name (string): name | OccurrenceIndexedFieldsResponse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OccurrenceIndexedFieldsResponse:
"""Implementation of the 'Occurrence_indexed_fields_Response' model. Occurrence_indexed_fields_Response Attributes: stored (bool): stored indexed (bool): indexed description (string): description data_type (string): dataType name (string): name"""
def __init_... | stack_v2_sparse_classes_36k_train_031223 | 3,103 | no_license | [
{
"docstring": "Constructor for the OccurrenceIndexedFieldsResponse class Args: **kwargs: Keyword Arguments in order to initialise the object. Any of the attributes in this object are able to be set through the **kwargs of the constructor. The values that can be supplied and their types are as follows:: stored ... | 2 | stack_v2_sparse_classes_30k_train_020933 | Implement the Python class `OccurrenceIndexedFieldsResponse` described below.
Class description:
Implementation of the 'Occurrence_indexed_fields_Response' model. Occurrence_indexed_fields_Response Attributes: stored (bool): stored indexed (bool): indexed description (string): description data_type (string): dataType ... | Implement the Python class `OccurrenceIndexedFieldsResponse` described below.
Class description:
Implementation of the 'Occurrence_indexed_fields_Response' model. Occurrence_indexed_fields_Response Attributes: stored (bool): stored indexed (bool): indexed description (string): description data_type (string): dataType ... | a9f803ea42bef4eb3720d5dd92a53dc98e8f2678 | <|skeleton|>
class OccurrenceIndexedFieldsResponse:
"""Implementation of the 'Occurrence_indexed_fields_Response' model. Occurrence_indexed_fields_Response Attributes: stored (bool): stored indexed (bool): indexed description (string): description data_type (string): dataType name (string): name"""
def __init_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OccurrenceIndexedFieldsResponse:
"""Implementation of the 'Occurrence_indexed_fields_Response' model. Occurrence_indexed_fields_Response Attributes: stored (bool): stored indexed (bool): indexed description (string): description data_type (string): dataType name (string): name"""
def __init__(self, **kwa... | the_stack_v2_python_sparse | AtlasOfLivingAustraliaOccurrencesLib/Models/OccurrenceIndexedFieldsResponse.py | chm052/naturehack | train | 2 |
f00fc9b4082a43d85cab5a599307a9f5c5ad5579 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(username=username, email=self.normalize_email(email), phone=phone)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(username=username, email=email, phone=phone, password=passw... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(username=username, email=self.normalize_email(email), phone=phone)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
... | This class handles the creation of our users. We need to create this class and extend BaseUserManager because our model (CustomUser) has additional fields to Django's default User class. | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
"""This class handles the creation of our users. We need to create this class and extend BaseUserManager because our model (CustomUser) has additional fields to Django's default User class."""
def create_user(self, username, email, phone, password=None):
"""Create a Cu... | stack_v2_sparse_classes_36k_train_031224 | 22,769 | no_license | [
{
"docstring": "Create a CustomUser, which are the users on our site.",
"name": "create_user",
"signature": "def create_user(self, username, email, phone, password=None)"
},
{
"docstring": "Create a superuser, which is just a user object with special attributes.",
"name": "create_superuser",... | 2 | stack_v2_sparse_classes_30k_train_010228 | Implement the Python class `MyUserManager` described below.
Class description:
This class handles the creation of our users. We need to create this class and extend BaseUserManager because our model (CustomUser) has additional fields to Django's default User class.
Method signatures and docstrings:
- def create_user(... | Implement the Python class `MyUserManager` described below.
Class description:
This class handles the creation of our users. We need to create this class and extend BaseUserManager because our model (CustomUser) has additional fields to Django's default User class.
Method signatures and docstrings:
- def create_user(... | 31ef33b573b991f9425e4b1edc09dbbd044a69b0 | <|skeleton|>
class MyUserManager:
"""This class handles the creation of our users. We need to create this class and extend BaseUserManager because our model (CustomUser) has additional fields to Django's default User class."""
def create_user(self, username, email, phone, password=None):
"""Create a Cu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyUserManager:
"""This class handles the creation of our users. We need to create this class and extend BaseUserManager because our model (CustomUser) has additional fields to Django's default User class."""
def create_user(self, username, email, phone, password=None):
"""Create a CustomUser, whi... | the_stack_v2_python_sparse | ibet_apps/users/models.py | senclaymoreusa/ibet-django-backup | train | 0 |
c4ac7364d338b7ec22760f43d2c3b6c299f80c60 | [
"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.security.ediscoveryReviewTag'.casefold():\n... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | Tag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tag:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Tag:
"""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: Tag"""
<|b... | stack_v2_sparse_classes_36k_train_031225 | 3,413 | 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: Tag",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(parse_nod... | 3 | null | Implement the Python class `Tag` described below.
Class description:
Implement the Tag class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Tag: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse n... | Implement the Python class `Tag` described below.
Class description:
Implement the Tag class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Tag: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse n... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Tag:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Tag:
"""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: Tag"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tag:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Tag:
"""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: Tag"""
if not parse_node... | the_stack_v2_python_sparse | msgraph/generated/models/security/tag.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
6d8964c999013cf9977488687b806acf9a02c107 | [
"shots = 100\ncircuits = ref_unitary_gate.unitary_gate_circuits_deterministic(final_measure=True)\ntargets = ref_unitary_gate.unitary_gate_counts_deterministic(shots)\nresult = execute(circuits, self.SIMULATOR, shots=shots).result()\nself.assertTrue(getattr(result, 'success', False))\nself.compare_counts(result, ci... | <|body_start_0|>
shots = 100
circuits = ref_unitary_gate.unitary_gate_circuits_deterministic(final_measure=True)
targets = ref_unitary_gate.unitary_gate_counts_deterministic(shots)
result = execute(circuits, self.SIMULATOR, shots=shots).result()
self.assertTrue(getattr(result, 's... | QasmSimulator additional tests. | QasmUnitaryGateTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QasmUnitaryGateTests:
"""QasmSimulator additional tests."""
def test_unitary_gate(self):
"""Test simulation with unitary gate circuit instructions."""
<|body_0|>
def test_random_unitary_gate(self):
"""Test simulation with random unitary gate circuit instructions.... | stack_v2_sparse_classes_36k_train_031226 | 3,511 | permissive | [
{
"docstring": "Test simulation with unitary gate circuit instructions.",
"name": "test_unitary_gate",
"signature": "def test_unitary_gate(self)"
},
{
"docstring": "Test simulation with random unitary gate circuit instructions.",
"name": "test_random_unitary_gate",
"signature": "def test... | 2 | stack_v2_sparse_classes_30k_train_018925 | Implement the Python class `QasmUnitaryGateTests` described below.
Class description:
QasmSimulator additional tests.
Method signatures and docstrings:
- def test_unitary_gate(self): Test simulation with unitary gate circuit instructions.
- def test_random_unitary_gate(self): Test simulation with random unitary gate ... | Implement the Python class `QasmUnitaryGateTests` described below.
Class description:
QasmSimulator additional tests.
Method signatures and docstrings:
- def test_unitary_gate(self): Test simulation with unitary gate circuit instructions.
- def test_random_unitary_gate(self): Test simulation with random unitary gate ... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class QasmUnitaryGateTests:
"""QasmSimulator additional tests."""
def test_unitary_gate(self):
"""Test simulation with unitary gate circuit instructions."""
<|body_0|>
def test_random_unitary_gate(self):
"""Test simulation with random unitary gate circuit instructions.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QasmUnitaryGateTests:
"""QasmSimulator additional tests."""
def test_unitary_gate(self):
"""Test simulation with unitary gate circuit instructions."""
shots = 100
circuits = ref_unitary_gate.unitary_gate_circuits_deterministic(final_measure=True)
targets = ref_unitary_gate... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits/qiskit-aer/qiskit-aer#707/before/qasm_unitary_gate.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
f49958df4e894b6174bc048589695948bde0c3d5 | [
"result = self.function(*args, **kwargs)\nself.validate(result)\nreturn result",
"result = await self.function(*args, **kwargs)\nself.validate(result)\nreturn result",
"for result in self.function(*args, **kwargs):\n self.validate(result)\n yield result"
] | <|body_start_0|>
result = self.function(*args, **kwargs)
self.validate(result)
return result
<|end_body_0|>
<|body_start_1|>
result = await self.function(*args, **kwargs)
self.validate(result)
return result
<|end_body_1|>
<|body_start_2|>
for result in self.func... | Check contract (validator) after function processing. Validate output result. | Post | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Post:
"""Check contract (validator) after function processing. Validate output result."""
def patched_function(self, *args, **kwargs):
"""Step 3. Wrapped function calling."""
<|body_0|>
async def async_patched_function(self, *args, **kwargs):
"""Step 3. Wrapped f... | stack_v2_sparse_classes_36k_train_031227 | 1,082 | permissive | [
{
"docstring": "Step 3. Wrapped function calling.",
"name": "patched_function",
"signature": "def patched_function(self, *args, **kwargs)"
},
{
"docstring": "Step 3. Wrapped function calling.",
"name": "async_patched_function",
"signature": "async def async_patched_function(self, *args, ... | 3 | stack_v2_sparse_classes_30k_train_000736 | Implement the Python class `Post` described below.
Class description:
Check contract (validator) after function processing. Validate output result.
Method signatures and docstrings:
- def patched_function(self, *args, **kwargs): Step 3. Wrapped function calling.
- async def async_patched_function(self, *args, **kwarg... | Implement the Python class `Post` described below.
Class description:
Check contract (validator) after function processing. Validate output result.
Method signatures and docstrings:
- def patched_function(self, *args, **kwargs): Step 3. Wrapped function calling.
- async def async_patched_function(self, *args, **kwarg... | 9dff86e1dc5c8607f02ded34b6d64e770f1959fa | <|skeleton|>
class Post:
"""Check contract (validator) after function processing. Validate output result."""
def patched_function(self, *args, **kwargs):
"""Step 3. Wrapped function calling."""
<|body_0|>
async def async_patched_function(self, *args, **kwargs):
"""Step 3. Wrapped f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Post:
"""Check contract (validator) after function processing. Validate output result."""
def patched_function(self, *args, **kwargs):
"""Step 3. Wrapped function calling."""
result = self.function(*args, **kwargs)
self.validate(result)
return result
async def async_p... | the_stack_v2_python_sparse | deal/_decorators/post.py | toonarmycaptain/deal | train | 0 |
5ead8ee283fd6ed0ccbd0adaaf4504ef0b306a7a | [
"im = Image.open(cls.infile)\nout = im.resize((width, height), Image.ANTIALIAS)\nout.save(cls.outfile)",
"im = Image.open(cls.infile)\nx, y = im.size\nx_s = x\ny_s = x / w_divide_h\nout = im.resize((x_s, y_s), Image.ANTIALIAS)\nout.save(cls.outfile)",
"im = Image.open(cls.infile)\nx, y = im.size\nx_s = y * w_di... | <|body_start_0|>
im = Image.open(cls.infile)
out = im.resize((width, height), Image.ANTIALIAS)
out.save(cls.outfile)
<|end_body_0|>
<|body_start_1|>
im = Image.open(cls.infile)
x, y = im.size
x_s = x
y_s = x / w_divide_h
out = im.resize((x_s, y_s), Image.... | Graphics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graphics:
def fixed_size(cls, width, height):
"""按照固定尺寸处理图片"""
<|body_0|>
def resize_by_width(cls, w_divide_h):
"""按照宽度进行所需比例缩放"""
<|body_1|>
def resize_by_height(cls, w_divide_h):
"""按照高度进行所需比例缩放"""
<|body_2|>
def resize_by_size(cls... | stack_v2_sparse_classes_36k_train_031228 | 2,331 | no_license | [
{
"docstring": "按照固定尺寸处理图片",
"name": "fixed_size",
"signature": "def fixed_size(cls, width, height)"
},
{
"docstring": "按照宽度进行所需比例缩放",
"name": "resize_by_width",
"signature": "def resize_by_width(cls, w_divide_h)"
},
{
"docstring": "按照高度进行所需比例缩放",
"name": "resize_by_height",
... | 5 | stack_v2_sparse_classes_30k_train_010239 | Implement the Python class `Graphics` described below.
Class description:
Implement the Graphics class.
Method signatures and docstrings:
- def fixed_size(cls, width, height): 按照固定尺寸处理图片
- def resize_by_width(cls, w_divide_h): 按照宽度进行所需比例缩放
- def resize_by_height(cls, w_divide_h): 按照高度进行所需比例缩放
- def resize_by_size(cls... | Implement the Python class `Graphics` described below.
Class description:
Implement the Graphics class.
Method signatures and docstrings:
- def fixed_size(cls, width, height): 按照固定尺寸处理图片
- def resize_by_width(cls, w_divide_h): 按照宽度进行所需比例缩放
- def resize_by_height(cls, w_divide_h): 按照高度进行所需比例缩放
- def resize_by_size(cls... | 53a4d00752eb7134397b230d1d3eaeb056de32ef | <|skeleton|>
class Graphics:
def fixed_size(cls, width, height):
"""按照固定尺寸处理图片"""
<|body_0|>
def resize_by_width(cls, w_divide_h):
"""按照宽度进行所需比例缩放"""
<|body_1|>
def resize_by_height(cls, w_divide_h):
"""按照高度进行所需比例缩放"""
<|body_2|>
def resize_by_size(cls... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Graphics:
def fixed_size(cls, width, height):
"""按照固定尺寸处理图片"""
im = Image.open(cls.infile)
out = im.resize((width, height), Image.ANTIALIAS)
out.save(cls.outfile)
def resize_by_width(cls, w_divide_h):
"""按照宽度进行所需比例缩放"""
im = Image.open(cls.infile)
x... | the_stack_v2_python_sparse | src/reXXXX/Graphics.py | happyxuwork/data-preprocess | train | 1 | |
e13a5dba785546764b30fd6639ff865c0b48838f | [
"parser.add_argument('VIEW_ID', help='Id of the view to update.')\nparser.add_argument('--description', help='New description for the view.')\nparser.add_argument('--log-filter', help='New filter for the view.')\nutil.AddParentArgs(parser, 'view to update')\nutil.AddBucketLocationArg(parser, True, 'Location of the ... | <|body_start_0|>
parser.add_argument('VIEW_ID', help='Id of the view to update.')
parser.add_argument('--description', help='New description for the view.')
parser.add_argument('--log-filter', help='New filter for the view.')
util.AddParentArgs(parser, 'view to update')
util.AddB... | Update a view. Changes one or more properties associated with a view. | Update | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Update:
"""Update a view. Changes one or more properties associated with a view."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse names... | stack_v2_sparse_classes_36k_train_031229 | 3,426 | permissive | [
{
"docstring": "Register flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: The updated... | 2 | null | Implement the Python class `Update` described below.
Class description:
Update a view. Changes one or more properties associated with a view.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: ar... | Implement the Python class `Update` described below.
Class description:
Update a view. Changes one or more properties associated with a view.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: ar... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Update:
"""Update a view. Changes one or more properties associated with a view."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse names... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Update:
"""Update a view. Changes one or more properties associated with a view."""
def Args(parser):
"""Register flags for this command."""
parser.add_argument('VIEW_ID', help='Id of the view to update.')
parser.add_argument('--description', help='New description for the view.')
... | the_stack_v2_python_sparse | lib/surface/logging/views/update.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
c814413a89f1a2ba365ccf859a397170ddd11655 | [
"if not dgl.base.is_all(eids):\n gidx = gidx.edge_subgraph([eids], True).graph\nscore_sums = _gspmm(gidx, 'copy_rhs', 'sum', None, score)[0]\nscore_counts = _gspmm(gidx, 'copy_rhs', 'sum', None, th.ones_like(score))[0]\nmeans = score_sums / score_counts.clamp_min(1)\nresidual = _gsddmm(gidx, 'sub', score, means,... | <|body_start_0|>
if not dgl.base.is_all(eids):
gidx = gidx.edge_subgraph([eids], True).graph
score_sums = _gspmm(gidx, 'copy_rhs', 'sum', None, score)[0]
score_counts = _gspmm(gidx, 'copy_rhs', 'sum', None, th.ones_like(score))[0]
means = score_sums / score_counts.clamp_min(1... | Apply normalization over signals of incoming edges. For a node :math:`i` of :math:`N`, head :math:`m`, EdgeNorm is an operation computing .. math:: \\textbf{\\textit{a}}^i_m = \\text{normalize}([l^{i,1}_m, ... , l^{i,N}_m]) \\text{normalize}(\\textbf{\\textit{x}})^j = g \\cdot \\frac{x^j - \\mu_{x}}{\\sigma_x} + b Adap... | EdgeNorm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeNorm:
"""Apply normalization over signals of incoming edges. For a node :math:`i` of :math:`N`, head :math:`m`, EdgeNorm is an operation computing .. math:: \\textbf{\\textit{a}}^i_m = \\text{normalize}([l^{i,1}_m, ... , l^{i,N}_m]) \\text{normalize}(\\textbf{\\textit{x}})^j = g \\cdot \\frac... | stack_v2_sparse_classes_36k_train_031230 | 25,239 | no_license | [
{
"docstring": "Args: ctx: context to save cache intermediate values to gidx: graph index object score: edata shaped scores to normalize, first dimension should match length of eids eids: ids of edges to normalize Returns: edge score values normalized by destination node grouping.",
"name": "forward",
"... | 2 | stack_v2_sparse_classes_30k_train_021593 | Implement the Python class `EdgeNorm` described below.
Class description:
Apply normalization over signals of incoming edges. For a node :math:`i` of :math:`N`, head :math:`m`, EdgeNorm is an operation computing .. math:: \\textbf{\\textit{a}}^i_m = \\text{normalize}([l^{i,1}_m, ... , l^{i,N}_m]) \\text{normalize}(\\t... | Implement the Python class `EdgeNorm` described below.
Class description:
Apply normalization over signals of incoming edges. For a node :math:`i` of :math:`N`, head :math:`m`, EdgeNorm is an operation computing .. math:: \\textbf{\\textit{a}}^i_m = \\text{normalize}([l^{i,1}_m, ... , l^{i,N}_m]) \\text{normalize}(\\t... | e88840528fa963066f85940ffeb31687773be2ba | <|skeleton|>
class EdgeNorm:
"""Apply normalization over signals of incoming edges. For a node :math:`i` of :math:`N`, head :math:`m`, EdgeNorm is an operation computing .. math:: \\textbf{\\textit{a}}^i_m = \\text{normalize}([l^{i,1}_m, ... , l^{i,N}_m]) \\text{normalize}(\\textbf{\\textit{x}})^j = g \\cdot \\frac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdgeNorm:
"""Apply normalization over signals of incoming edges. For a node :math:`i` of :math:`N`, head :math:`m`, EdgeNorm is an operation computing .. math:: \\textbf{\\textit{a}}^i_m = \\text{normalize}([l^{i,1}_m, ... , l^{i,N}_m]) \\text{normalize}(\\textbf{\\textit{x}})^j = g \\cdot \\frac{x^j - \\mu_{... | the_stack_v2_python_sparse | Utility/layers.py | kaicd/KAICD_pipeline | train | 0 |
045bcb3d28e0dc5cd7cbb2b6e3e97838511baaf5 | [
"courses = sorted(courses, key=lambda x: x[1])\ntaken = []\ntotal = 0\nfor d, e in courses:\n if total + d <= e:\n total += d\n heapq.heappush(taken, -d)\n elif taken and d < -taken[0] and (total + taken[0] <= e):\n total += heapq.heapreplace(taken, -d)\nreturn len(taken)",
"courses = s... | <|body_start_0|>
courses = sorted(courses, key=lambda x: x[1])
taken = []
total = 0
for d, e in courses:
if total + d <= e:
total += d
heapq.heappush(taken, -d)
elif taken and d < -taken[0] and (total + taken[0] <= e):
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
"""Runtime: 727 ms, faster than 95.65% Memory Usage: 19.9 MB, less than 79.40% 1 <= courses.length <= 10^4 1 <= durationi, lastDayi <= 10^4"""
<|body_0|>
def scheduleCourse2(self, courses: List[List[int]]) ... | stack_v2_sparse_classes_36k_train_031231 | 1,807 | permissive | [
{
"docstring": "Runtime: 727 ms, faster than 95.65% Memory Usage: 19.9 MB, less than 79.40% 1 <= courses.length <= 10^4 1 <= durationi, lastDayi <= 10^4",
"name": "scheduleCourse",
"signature": "def scheduleCourse(self, courses: List[List[int]]) -> int"
},
{
"docstring": "LTE 1 <= courses.length... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def scheduleCourse(self, courses: List[List[int]]) -> int: Runtime: 727 ms, faster than 95.65% Memory Usage: 19.9 MB, less than 79.40% 1 <= courses.length <= 10^4 1 <= durationi,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def scheduleCourse(self, courses: List[List[int]]) -> int: Runtime: 727 ms, faster than 95.65% Memory Usage: 19.9 MB, less than 79.40% 1 <= courses.length <= 10^4 1 <= durationi,... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
"""Runtime: 727 ms, faster than 95.65% Memory Usage: 19.9 MB, less than 79.40% 1 <= courses.length <= 10^4 1 <= durationi, lastDayi <= 10^4"""
<|body_0|>
def scheduleCourse2(self, courses: List[List[int]]) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
"""Runtime: 727 ms, faster than 95.65% Memory Usage: 19.9 MB, less than 79.40% 1 <= courses.length <= 10^4 1 <= durationi, lastDayi <= 10^4"""
courses = sorted(courses, key=lambda x: x[1])
taken = []
total = 0... | the_stack_v2_python_sparse | src/630-CourseScheduleIII.py | Jiezhi/myleetcode | train | 1 | |
2bf04db19fecc2095c8aa673bcc50c72d604ed49 | [
"self.__dp = copy.deepcopy(matrix)\nself.__r = len(self.__dp)\nif self.__r < 1:\n return\nself.__c = len(self.__dp[0])\nfor i in range(1, self.__r):\n self.__dp[i][0] = self.__dp[i - 1][0] + self.__dp[i][0]\nfor i in range(1, self.__c):\n self.__dp[0][i] = self.__dp[0][i - 1] + self.__dp[0][i]\nfor i in ra... | <|body_start_0|>
self.__dp = copy.deepcopy(matrix)
self.__r = len(self.__dp)
if self.__r < 1:
return
self.__c = len(self.__dp[0])
for i in range(1, self.__r):
self.__dp[i][0] = self.__dp[i - 1][0] + self.__dp[i][0]
for i in range(1, self.__c):
... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_031232 | 1,474 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 3bf3209791b902ec9086e230a3e3316aaced4a5f | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.__dp = copy.deepcopy(matrix)
self.__r = len(self.__dp)
if self.__r < 1:
return
self.__c = len(self.__dp[0])
for i in range(1, self.__r):
self.__dp[i][0] = sel... | the_stack_v2_python_sparse | LeetCode/304.py | yaoMYZ/LeetCode | train | 0 | |
6d1fa7f50802de1a432993bcbb5eb82ed8122d4d | [
"self.length = length\nself.partition_number = partition_number\nself.partition_type_uuid = partition_type_uuid\nself.partition_uuid = partition_uuid\nself.start_offset = start_offset",
"if dictionary is None:\n return None\nlength = dictionary.get('length')\npartition_number = dictionary.get('partitionNumber'... | <|body_start_0|>
self.length = length
self.partition_number = partition_number
self.partition_type_uuid = partition_type_uuid
self.partition_uuid = partition_uuid
self.start_offset = start_offset
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return N... | Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: length (long|int): Length of partition in bytes. partition_number (long|int): Partition number. partitio... | VolumeInfo_DiskInfo_PartitionInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumeInfo_DiskInfo_PartitionInfo:
"""Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: length (long|int): Length of partition in b... | stack_v2_sparse_classes_36k_train_031233 | 3,327 | permissive | [
{
"docstring": "Constructor for the VolumeInfo_DiskInfo_PartitionInfo class",
"name": "__init__",
"signature": "def __init__(self, length=None, partition_number=None, partition_type_uuid=None, partition_uuid=None, start_offset=None)"
},
{
"docstring": "Creates an instance of this model from a di... | 2 | stack_v2_sparse_classes_30k_train_003378 | Implement the Python class `VolumeInfo_DiskInfo_PartitionInfo` described below.
Class description:
Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: leng... | Implement the Python class `VolumeInfo_DiskInfo_PartitionInfo` described below.
Class description:
Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: leng... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VolumeInfo_DiskInfo_PartitionInfo:
"""Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: length (long|int): Length of partition in b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VolumeInfo_DiskInfo_PartitionInfo:
"""Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: length (long|int): Length of partition in bytes. partiti... | the_stack_v2_python_sparse | cohesity_management_sdk/models/volume_info_disk_info_partition_info.py | cohesity/management-sdk-python | train | 24 |
275c3e554f07a727d948fdc54bb0fdcfa7103c66 | [
"super().__init__()\nassert cell_type in {'LSTM', 'GRU'}, 'Unknown cell type for BiRNN: {}'.format(cell_type)\nrnn_cell = nn.LSTM if cell_type == 'LSTM' else nn.GRU\nself.rnn = rnn_cell(embed_dim, hidden_dim, num_layers, batch_first=True, dropout=dropout, bidirectional=True)\nif embed_dropout is not None:\n if e... | <|body_start_0|>
super().__init__()
assert cell_type in {'LSTM', 'GRU'}, 'Unknown cell type for BiRNN: {}'.format(cell_type)
rnn_cell = nn.LSTM if cell_type == 'LSTM' else nn.GRU
self.rnn = rnn_cell(embed_dim, hidden_dim, num_layers, batch_first=True, dropout=dropout, bidirectional=True)... | Bi-directional LSTM or GRU | BiRNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiRNN:
"""Bi-directional LSTM or GRU"""
def __init__(self, embed_dim: int, hidden_dim: int, num_layers: int, dropout: float, cell_type: str, embed_dropout: float=None, word_dropout: float=None, locked_dropout: float=None):
"""Args: embed_dim: dimension of input token embeddings hidde... | stack_v2_sparse_classes_36k_train_031234 | 3,213 | permissive | [
{
"docstring": "Args: embed_dim: dimension of input token embeddings hidden_dim: dimensions of hidden states of RNN in each direction. num_layers: number of layers of BiRNN. dropout: the dropout rate. The input is assumed to be before any dropout. cell_type: \"LSTM\" or \"GRU\" embed_dropout: when None, follow ... | 2 | stack_v2_sparse_classes_30k_train_001511 | Implement the Python class `BiRNN` described below.
Class description:
Bi-directional LSTM or GRU
Method signatures and docstrings:
- def __init__(self, embed_dim: int, hidden_dim: int, num_layers: int, dropout: float, cell_type: str, embed_dropout: float=None, word_dropout: float=None, locked_dropout: float=None): A... | Implement the Python class `BiRNN` described below.
Class description:
Bi-directional LSTM or GRU
Method signatures and docstrings:
- def __init__(self, embed_dim: int, hidden_dim: int, num_layers: int, dropout: float, cell_type: str, embed_dropout: float=None, word_dropout: float=None, locked_dropout: float=None): A... | 8b4a7a40cc34bff608f19d3f7eb64bda76669c5b | <|skeleton|>
class BiRNN:
"""Bi-directional LSTM or GRU"""
def __init__(self, embed_dim: int, hidden_dim: int, num_layers: int, dropout: float, cell_type: str, embed_dropout: float=None, word_dropout: float=None, locked_dropout: float=None):
"""Args: embed_dim: dimension of input token embeddings hidde... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BiRNN:
"""Bi-directional LSTM or GRU"""
def __init__(self, embed_dim: int, hidden_dim: int, num_layers: int, dropout: float, cell_type: str, embed_dropout: float=None, word_dropout: float=None, locked_dropout: float=None):
"""Args: embed_dim: dimension of input token embeddings hidden_dim: dimens... | the_stack_v2_python_sparse | nsr/model/sentence_encoder.py | GaoSida/Neural-SampleRank | train | 3 |
bd3c0f21b242358df7a7b062eff96c729417f720 | [
"self.entity_description = description\nself.startcadata = startcadata\nself._attr_name = f'{name} {description.name}'",
"await self.startcadata.async_update()\nsensor_type = self.entity_description.key\nif sensor_type in self.startcadata.data:\n self._attr_native_value = round(self.startcadata.data[sensor_typ... | <|body_start_0|>
self.entity_description = description
self.startcadata = startcadata
self._attr_name = f'{name} {description.name}'
<|end_body_0|>
<|body_start_1|>
await self.startcadata.async_update()
sensor_type = self.entity_description.key
if sensor_type in self.sta... | Representation of Start.ca Bandwidth sensor. | StartcaSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StartcaSensor:
"""Representation of Start.ca Bandwidth sensor."""
def __init__(self, startcadata, name, description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
async def async_update(self) -> None:
"""Get the latest data from Start.... | stack_v2_sparse_classes_36k_train_031235 | 8,472 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, startcadata, name, description: SensorEntityDescription) -> None"
},
{
"docstring": "Get the latest data from Start.ca and update the state.",
"name": "async_update",
"signature": "async def asy... | 2 | null | Implement the Python class `StartcaSensor` described below.
Class description:
Representation of Start.ca Bandwidth sensor.
Method signatures and docstrings:
- def __init__(self, startcadata, name, description: SensorEntityDescription) -> None: Initialize the sensor.
- async def async_update(self) -> None: Get the la... | Implement the Python class `StartcaSensor` described below.
Class description:
Representation of Start.ca Bandwidth sensor.
Method signatures and docstrings:
- def __init__(self, startcadata, name, description: SensorEntityDescription) -> None: Initialize the sensor.
- async def async_update(self) -> None: Get the la... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class StartcaSensor:
"""Representation of Start.ca Bandwidth sensor."""
def __init__(self, startcadata, name, description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
async def async_update(self) -> None:
"""Get the latest data from Start.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StartcaSensor:
"""Representation of Start.ca Bandwidth sensor."""
def __init__(self, startcadata, name, description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
self.entity_description = description
self.startcadata = startcadata
self._attr_name = f'{nam... | the_stack_v2_python_sparse | homeassistant/components/startca/sensor.py | home-assistant/core | train | 35,501 |
2454c516e0403bbb8b9583b6fc8dd32c3b7c4e34 | [
"super().__init__(hass=hass, logger=LOGGER, name=DOMAIN, update_interval=timedelta(seconds=30))\nself.game_icons: dict[int, str] = {}\nself.player_interface: INTMethod = None\nself.user_interface: INTMethod = None\nsteam.api.key.set(self.config_entry.data[CONF_API_KEY])",
"accounts = self.config_entry.options[CON... | <|body_start_0|>
super().__init__(hass=hass, logger=LOGGER, name=DOMAIN, update_interval=timedelta(seconds=30))
self.game_icons: dict[int, str] = {}
self.player_interface: INTMethod = None
self.user_interface: INTMethod = None
steam.api.key.set(self.config_entry.data[CONF_API_KEY... | Data update coordinator for the Steam integration. | SteamDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SteamDataUpdateCoordinator:
"""Data update coordinator for the Steam integration."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the coordinator."""
<|body_0|>
def _update(self) -> dict[str, dict[str, str | int]]:
"""Fetch data from API endpoin... | stack_v2_sparse_classes_36k_train_031236 | 2,808 | permissive | [
{
"docstring": "Initialize the coordinator.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant) -> None"
},
{
"docstring": "Fetch data from API endpoint.",
"name": "_update",
"signature": "def _update(self) -> dict[str, dict[str, str | int]]"
},
{
"docstri... | 3 | stack_v2_sparse_classes_30k_train_015298 | Implement the Python class `SteamDataUpdateCoordinator` described below.
Class description:
Data update coordinator for the Steam integration.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize the coordinator.
- def _update(self) -> dict[str, dict[str, str | int]]: Fetch ... | Implement the Python class `SteamDataUpdateCoordinator` described below.
Class description:
Data update coordinator for the Steam integration.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize the coordinator.
- def _update(self) -> dict[str, dict[str, str | int]]: Fetch ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SteamDataUpdateCoordinator:
"""Data update coordinator for the Steam integration."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the coordinator."""
<|body_0|>
def _update(self) -> dict[str, dict[str, str | int]]:
"""Fetch data from API endpoin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SteamDataUpdateCoordinator:
"""Data update coordinator for the Steam integration."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the coordinator."""
super().__init__(hass=hass, logger=LOGGER, name=DOMAIN, update_interval=timedelta(seconds=30))
self.game_icons: d... | the_stack_v2_python_sparse | homeassistant/components/steam_online/coordinator.py | home-assistant/core | train | 35,501 |
c1924c508526bc1ad59661667524d6f30cd546fc | [
"if level == len(self.out_channels) - 1:\n return nn.Conv2d(out_channels, boxes_per_location * self.num_categories, kernel_size=1)\nreturn SeparableConv2d(out_channels, boxes_per_location * self.num_categories, kernel_size=3, stride=1, padding=1)",
"if level == len(self.out_channels) - 1:\n return nn.Conv2d... | <|body_start_0|>
if level == len(self.out_channels) - 1:
return nn.Conv2d(out_channels, boxes_per_location * self.num_categories, kernel_size=1)
return SeparableConv2d(out_channels, boxes_per_location * self.num_categories, kernel_size=3, stride=1, padding=1)
<|end_body_0|>
<|body_start_1|>... | description | SSDLiteBoxPredictor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSDLiteBoxPredictor:
"""description"""
def category_block(self, level: int, out_channels: int, boxes_per_location: int) -> nn.Module:
""":param level: :type level: :param out_channels: :type out_channels: :param boxes_per_location: :type boxes_per_location: :return: :rtype:"""
... | stack_v2_sparse_classes_36k_train_031237 | 1,739 | permissive | [
{
"docstring": ":param level: :type level: :param out_channels: :type out_channels: :param boxes_per_location: :type boxes_per_location: :return: :rtype:",
"name": "category_block",
"signature": "def category_block(self, level: int, out_channels: int, boxes_per_location: int) -> nn.Module"
},
{
... | 2 | null | Implement the Python class `SSDLiteBoxPredictor` described below.
Class description:
description
Method signatures and docstrings:
- def category_block(self, level: int, out_channels: int, boxes_per_location: int) -> nn.Module: :param level: :type level: :param out_channels: :type out_channels: :param boxes_per_locat... | Implement the Python class `SSDLiteBoxPredictor` described below.
Class description:
description
Method signatures and docstrings:
- def category_block(self, level: int, out_channels: int, boxes_per_location: int) -> nn.Module: :param level: :type level: :param out_channels: :type out_channels: :param boxes_per_locat... | 06839b08d8e8f274c02a6bcd31bf1b32d3dc04e4 | <|skeleton|>
class SSDLiteBoxPredictor:
"""description"""
def category_block(self, level: int, out_channels: int, boxes_per_location: int) -> nn.Module:
""":param level: :type level: :param out_channels: :type out_channels: :param boxes_per_location: :type boxes_per_location: :return: :rtype:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSDLiteBoxPredictor:
"""description"""
def category_block(self, level: int, out_channels: int, boxes_per_location: int) -> nn.Module:
""":param level: :type level: :param out_channels: :type out_channels: :param boxes_per_location: :type boxes_per_location: :return: :rtype:"""
if level ==... | the_stack_v2_python_sparse | neodroidvision/detection/single_stage/ssd/architecture/nms_box_heads/ssd_lite_box_predictor.py | aivclab/vision | train | 1 |
7c7c0d7aed0e289cbfaa21ed83ee072225a21b68 | [
"super().__init__(**kwargs)\nself.fc1 = keras.layers.Dense(hidden_dim)\nself.ln1 = keras.layers.LayerNormalization()\nself.fc2 = keras.layers.Dense(hidden_dim)\nself.ln2 = keras.layers.LayerNormalization()\nself.fc3 = keras.layers.Dense(output_dim)",
"x = tf.nn.relu(self.ln1(self.fc1(x)))\nx = tf.nn.relu(self.ln2... | <|body_start_0|>
super().__init__(**kwargs)
self.fc1 = keras.layers.Dense(hidden_dim)
self.ln1 = keras.layers.LayerNormalization()
self.fc2 = keras.layers.Dense(hidden_dim)
self.ln2 = keras.layers.LayerNormalization()
self.fc3 = keras.layers.Dense(output_dim)
<|end_body_0... | Actor network. The network follows the standard actor-critic architecture used in Deep Reinforcement Learning. The model is used in Counterfactual with Reinforcement Learning (CFRL) for both data modalities (images and tabular). The hidden dimension used for the all experiments is 256, which is a common choice in most ... | Actor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Actor:
"""Actor network. The network follows the standard actor-critic architecture used in Deep Reinforcement Learning. The model is used in Counterfactual with Reinforcement Learning (CFRL) for both data modalities (images and tabular). The hidden dimension used for the all experiments is 256, ... | stack_v2_sparse_classes_36k_train_031238 | 2,913 | permissive | [
{
"docstring": "Constructor. Parameters ---------- hidden_dim Hidden dimension output_dim Output dimension",
"name": "__init__",
"signature": "def __init__(self, hidden_dim: int, output_dim: int, **kwargs)"
},
{
"docstring": "Forward pass. Parameters ---------- x Input tensor. **kwargs Other arg... | 2 | null | Implement the Python class `Actor` described below.
Class description:
Actor network. The network follows the standard actor-critic architecture used in Deep Reinforcement Learning. The model is used in Counterfactual with Reinforcement Learning (CFRL) for both data modalities (images and tabular). The hidden dimensio... | Implement the Python class `Actor` described below.
Class description:
Actor network. The network follows the standard actor-critic architecture used in Deep Reinforcement Learning. The model is used in Counterfactual with Reinforcement Learning (CFRL) for both data modalities (images and tabular). The hidden dimensio... | 54d0c957fb01c7ebba4e2a0d28fcbde52d9c6718 | <|skeleton|>
class Actor:
"""Actor network. The network follows the standard actor-critic architecture used in Deep Reinforcement Learning. The model is used in Counterfactual with Reinforcement Learning (CFRL) for both data modalities (images and tabular). The hidden dimension used for the all experiments is 256, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Actor:
"""Actor network. The network follows the standard actor-critic architecture used in Deep Reinforcement Learning. The model is used in Counterfactual with Reinforcement Learning (CFRL) for both data modalities (images and tabular). The hidden dimension used for the all experiments is 256, which is a co... | the_stack_v2_python_sparse | alibi/models/tensorflow/actor_critic.py | SeldonIO/alibi | train | 2,143 |
cd4cb59b16da23cacf3715739163122aa80e8e19 | [
"result: Dict[str, Union[str, List[str], Dict]] = {}\nif self.query_type != QueryType.Simple:\n result['query_type'] = self.query_type.name\nif self.selectables:\n result['selectables'] = [s.as_str() for s in self.selectables]\nif self.ctes:\n result['ctes'] = {k: v.as_json() for k, v in self.ctes.items()}... | <|body_start_0|>
result: Dict[str, Union[str, List[str], Dict]] = {}
if self.query_type != QueryType.Simple:
result['query_type'] = self.query_type.name
if self.selectables:
result['selectables'] = [s.as_str() for s in self.selectables]
if self.ctes:
r... | A main SELECT query plus possible CTEs. | Query | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Query:
"""A main SELECT query plus possible CTEs."""
def as_json(self) -> Dict:
"""JSON representation for logging/testing."""
<|body_0|>
def lookup_cte(self, name: str, pop: bool=True) -> Optional['Query']:
"""Look up a CTE by name, in the current or any parent ... | stack_v2_sparse_classes_36k_train_031239 | 19,401 | permissive | [
{
"docstring": "JSON representation for logging/testing.",
"name": "as_json",
"signature": "def as_json(self) -> Dict"
},
{
"docstring": "Look up a CTE by name, in the current or any parent scope.",
"name": "lookup_cte",
"signature": "def lookup_cte(self, name: str, pop: bool=True) -> Op... | 3 | null | Implement the Python class `Query` described below.
Class description:
A main SELECT query plus possible CTEs.
Method signatures and docstrings:
- def as_json(self) -> Dict: JSON representation for logging/testing.
- def lookup_cte(self, name: str, pop: bool=True) -> Optional['Query']: Look up a CTE by name, in the c... | Implement the Python class `Query` described below.
Class description:
A main SELECT query plus possible CTEs.
Method signatures and docstrings:
- def as_json(self) -> Dict: JSON representation for logging/testing.
- def lookup_cte(self, name: str, pop: bool=True) -> Optional['Query']: Look up a CTE by name, in the c... | a66da908907ee1eaf09d88a731025da29e7fca07 | <|skeleton|>
class Query:
"""A main SELECT query plus possible CTEs."""
def as_json(self) -> Dict:
"""JSON representation for logging/testing."""
<|body_0|>
def lookup_cte(self, name: str, pop: bool=True) -> Optional['Query']:
"""Look up a CTE by name, in the current or any parent ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Query:
"""A main SELECT query plus possible CTEs."""
def as_json(self) -> Dict:
"""JSON representation for logging/testing."""
result: Dict[str, Union[str, List[str], Dict]] = {}
if self.query_type != QueryType.Simple:
result['query_type'] = self.query_type.name
... | the_stack_v2_python_sparse | src/sqlfluff/utils/analysis/select_crawler.py | sqlfluff/sqlfluff | train | 5,931 |
105f6731214c1ead9c3e9769503445d4c1a7c9b4 | [
"if debug:\n print('parse' + lineno())\niam_user = resource\nfor policy in iam_user.policies:\n if debug:\n print('policy: ' + str(policy) + lineno())\n new_policy = Policy(debug=debug)\n new_policy.policy_name = policy['PolicyName']\n policy_document_parser = PolicyDocumentParser()\n new_p... | <|body_start_0|>
if debug:
print('parse' + lineno())
iam_user = resource
for policy in iam_user.policies:
if debug:
print('policy: ' + str(policy) + lineno())
new_policy = Policy(debug=debug)
new_policy.policy_name = policy['PolicyN... | IAM User Parser | IamUserParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IamUserParser:
"""IAM User Parser"""
def parse(cfn_model, resource, debug=False):
"""Parse iam user :param resource: :param debug: :return:"""
<|body_0|>
def user_to_group_addition_has_username(addition_user_names, user_to_find, debug=False):
"""??? :param user_t... | stack_v2_sparse_classes_36k_train_031240 | 3,072 | permissive | [
{
"docstring": "Parse iam user :param resource: :param debug: :return:",
"name": "parse",
"signature": "def parse(cfn_model, resource, debug=False)"
},
{
"docstring": "??? :param user_to_find: :param debug: :return:",
"name": "user_to_group_addition_has_username",
"signature": "def user_... | 2 | stack_v2_sparse_classes_30k_train_019473 | Implement the Python class `IamUserParser` described below.
Class description:
IAM User Parser
Method signatures and docstrings:
- def parse(cfn_model, resource, debug=False): Parse iam user :param resource: :param debug: :return:
- def user_to_group_addition_has_username(addition_user_names, user_to_find, debug=Fals... | Implement the Python class `IamUserParser` described below.
Class description:
IAM User Parser
Method signatures and docstrings:
- def parse(cfn_model, resource, debug=False): Parse iam user :param resource: :param debug: :return:
- def user_to_group_addition_has_username(addition_user_names, user_to_find, debug=Fals... | a9d0335a532acdb4070e5537155b03b34915b73e | <|skeleton|>
class IamUserParser:
"""IAM User Parser"""
def parse(cfn_model, resource, debug=False):
"""Parse iam user :param resource: :param debug: :return:"""
<|body_0|>
def user_to_group_addition_has_username(addition_user_names, user_to_find, debug=False):
"""??? :param user_t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IamUserParser:
"""IAM User Parser"""
def parse(cfn_model, resource, debug=False):
"""Parse iam user :param resource: :param debug: :return:"""
if debug:
print('parse' + lineno())
iam_user = resource
for policy in iam_user.policies:
if debug:
... | the_stack_v2_python_sparse | terraform_model/parser/IamUserParser.py | rubelw/terraform-validator | train | 7 |
ca2a47c5f172e955b0f074053e6e252a9765fa0a | [
"n = len(prices)\nif n == 0:\n return 0\ndp = [0] * n\nmin_price = prices[0]\nfor i in range(1, n):\n min_price = min(min_price, prices[i])\n dp[i] = max(dp[i - 1], prices[i] - min_price)\nreturn dp[-1]",
"min_price, max_price = (float('inf'), 0)\nfor price in prices:\n min_price = min(min_price, pric... | <|body_start_0|>
n = len(prices)
if n == 0:
return 0
dp = [0] * n
min_price = prices[0]
for i in range(1, n):
min_price = min(min_price, prices[i])
dp[i] = max(dp[i - 1], prices[i] - min_price)
return dp[-1]
<|end_body_0|>
<|body_start... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def max_profit(self, prices: List[int]) -> int:
"""动态规划。"""
<|body_0|>
def max_profit_2(self, prices: List[int]) -> int:
"""动态规划(一次遍历,优化空间)。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(prices)
if n == 0:
ret... | stack_v2_sparse_classes_36k_train_031241 | 1,942 | no_license | [
{
"docstring": "动态规划。",
"name": "max_profit",
"signature": "def max_profit(self, prices: List[int]) -> int"
},
{
"docstring": "动态规划(一次遍历,优化空间)。",
"name": "max_profit_2",
"signature": "def max_profit_2(self, prices: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_profit(self, prices: List[int]) -> int: 动态规划。
- def max_profit_2(self, prices: List[int]) -> int: 动态规划(一次遍历,优化空间)。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_profit(self, prices: List[int]) -> int: 动态规划。
- def max_profit_2(self, prices: List[int]) -> int: 动态规划(一次遍历,优化空间)。
<|skeleton|>
class Solution:
def max_profit(self,... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class Solution:
def max_profit(self, prices: List[int]) -> int:
"""动态规划。"""
<|body_0|>
def max_profit_2(self, prices: List[int]) -> int:
"""动态规划(一次遍历,优化空间)。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def max_profit(self, prices: List[int]) -> int:
"""动态规划。"""
n = len(prices)
if n == 0:
return 0
dp = [0] * n
min_price = prices[0]
for i in range(1, n):
min_price = min(min_price, prices[i])
dp[i] = max(dp[i - 1], pr... | the_stack_v2_python_sparse | 0121_best-time-to-buy-and-sell-stock.py | Nigirimeshi/leetcode | train | 0 | |
fe418098dead5b83336d00fe93e645aca3e7ee34 | [
"super().__init__()\nself.base = base\nassert isinstance(self.base, ValueFunctionBase)\nself.outputs = namedtuple('Outputs', ['value', 'state_out'])",
"outs = self.base(ob) if state_in is None else self.base(ob, state_in)\nif isinstance(outs, tuple):\n value, state_out = outs\nelse:\n value, state_out = (ou... | <|body_start_0|>
super().__init__()
self.base = base
assert isinstance(self.base, ValueFunctionBase)
self.outputs = namedtuple('Outputs', ['value', 'state_out'])
<|end_body_0|>
<|body_start_1|>
outs = self.base(ob) if state_in is None else self.base(ob, state_in)
if isin... | Value function module. | ValueFunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueFunction:
"""Value function module."""
def __init__(self, base):
"""Init."""
<|body_0|>
def forward(self, ob, state_in=None):
"""Forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.base = base
as... | stack_v2_sparse_classes_36k_train_031242 | 1,416 | no_license | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, base)"
},
{
"docstring": "Forward.",
"name": "forward",
"signature": "def forward(self, ob, state_in=None)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000824 | Implement the Python class `ValueFunction` described below.
Class description:
Value function module.
Method signatures and docstrings:
- def __init__(self, base): Init.
- def forward(self, ob, state_in=None): Forward. | Implement the Python class `ValueFunction` described below.
Class description:
Value function module.
Method signatures and docstrings:
- def __init__(self, base): Init.
- def forward(self, ob, state_in=None): Forward.
<|skeleton|>
class ValueFunction:
"""Value function module."""
def __init__(self, base):
... | e71c4b12955b01bfb907aa31c91ded6bcd8aaec8 | <|skeleton|>
class ValueFunction:
"""Value function module."""
def __init__(self, base):
"""Init."""
<|body_0|>
def forward(self, ob, state_in=None):
"""Forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValueFunction:
"""Value function module."""
def __init__(self, base):
"""Init."""
super().__init__()
self.base = base
assert isinstance(self.base, ValueFunctionBase)
self.outputs = namedtuple('Outputs', ['value', 'state_out'])
def forward(self, ob, state_in=No... | the_stack_v2_python_sparse | dl/rl/modules/value_function.py | cbschaff/dl | train | 1 |
450cb6a00055706bf8a1619a74c026c217cea815 | [
"self.command = command\nif '{' and '}' not in command:\n print('GM命令格式错误,缺少大括号,请重新检查')\n return False\nif ',' not in command:\n print('GM命令格式错误,缺少逗号,请重新检查')\n return False\nreturn True",
"self.command = command\nif self.check_command_is_legal(self.command):\n split = self.command.index(',')\n s... | <|body_start_0|>
self.command = command
if '{' and '}' not in command:
print('GM命令格式错误,缺少大括号,请重新检查')
return False
if ',' not in command:
print('GM命令格式错误,缺少逗号,请重新检查')
return False
return True
<|end_body_0|>
<|body_start_1|>
self.com... | Gmhelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gmhelper:
def check_command_is_legal(self, command: str):
"""检查字符串是否符合规定格式 :param command: :return: True表示合法 False表示不合法"""
<|body_0|>
def add_item_normal(self, command: str):
"""把指定字符串转换成GM命令 :param command: add_item {{1001 to 1003}},10 这种字符串 :return:"""
<|bo... | stack_v2_sparse_classes_36k_train_031243 | 2,781 | permissive | [
{
"docstring": "检查字符串是否符合规定格式 :param command: :return: True表示合法 False表示不合法",
"name": "check_command_is_legal",
"signature": "def check_command_is_legal(self, command: str)"
},
{
"docstring": "把指定字符串转换成GM命令 :param command: add_item {{1001 to 1003}},10 这种字符串 :return:",
"name": "add_item_normal... | 4 | stack_v2_sparse_classes_30k_train_001442 | Implement the Python class `Gmhelper` described below.
Class description:
Implement the Gmhelper class.
Method signatures and docstrings:
- def check_command_is_legal(self, command: str): 检查字符串是否符合规定格式 :param command: :return: True表示合法 False表示不合法
- def add_item_normal(self, command: str): 把指定字符串转换成GM命令 :param command... | Implement the Python class `Gmhelper` described below.
Class description:
Implement the Gmhelper class.
Method signatures and docstrings:
- def check_command_is_legal(self, command: str): 检查字符串是否符合规定格式 :param command: :return: True表示合法 False表示不合法
- def add_item_normal(self, command: str): 把指定字符串转换成GM命令 :param command... | 9d9ff9fb0dc4f1b63cdd31d6bbc12f9cd467eb81 | <|skeleton|>
class Gmhelper:
def check_command_is_legal(self, command: str):
"""检查字符串是否符合规定格式 :param command: :return: True表示合法 False表示不合法"""
<|body_0|>
def add_item_normal(self, command: str):
"""把指定字符串转换成GM命令 :param command: add_item {{1001 to 1003}},10 这种字符串 :return:"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Gmhelper:
def check_command_is_legal(self, command: str):
"""检查字符串是否符合规定格式 :param command: :return: True表示合法 False表示不合法"""
self.command = command
if '{' and '}' not in command:
print('GM命令格式错误,缺少大括号,请重新检查')
return False
if ',' not in command:
... | the_stack_v2_python_sparse | code/kagamimoe/001/gmhelper.py | jianbing/python-practice-for-game-tester | train | 42 | |
0b9cd0d01da410a04ebc31793f743600d9781df4 | [
"is_batched = True if isinstance(text, (list, tuple)) else False\nif not is_batched:\n text = [text]\nresult = []\nfor t in text:\n if isinstance(t, str):\n bstr = t.encode()\n else:\n bstr = t\n result.append(self._tokenize(bstr, add_bos))\nif not is_batched:\n result = result[0]\nretu... | <|body_start_0|>
is_batched = True if isinstance(text, (list, tuple)) else False
if not is_batched:
text = [text]
result = []
for t in text:
if isinstance(t, str):
bstr = t.encode()
else:
bstr = t
result.appe... | A class containing all functions for auto-regressive text generation Pass custom parameter values to 'generate' . | GenerationMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenerationMixin:
"""A class containing all functions for auto-regressive text generation Pass custom parameter values to 'generate' ."""
def tokenize(self, text: Union[str, List[str]], add_bos: bool=True) -> List[int]:
"""Decode the id to words :param text: The text or batch of text ... | stack_v2_sparse_classes_36k_train_031244 | 6,354 | permissive | [
{
"docstring": "Decode the id to words :param text: The text or batch of text to be tokenized :param add_bos: :return: list of ids that indicates the tokens",
"name": "tokenize",
"signature": "def tokenize(self, text: Union[str, List[str]], add_bos: bool=True) -> List[int]"
},
{
"docstring": "De... | 4 | null | Implement the Python class `GenerationMixin` described below.
Class description:
A class containing all functions for auto-regressive text generation Pass custom parameter values to 'generate' .
Method signatures and docstrings:
- def tokenize(self, text: Union[str, List[str]], add_bos: bool=True) -> List[int]: Decod... | Implement the Python class `GenerationMixin` described below.
Class description:
A class containing all functions for auto-regressive text generation Pass custom parameter values to 'generate' .
Method signatures and docstrings:
- def tokenize(self, text: Union[str, List[str]], add_bos: bool=True) -> List[int]: Decod... | 4ffa012a426e0d16ed13b707b03d8787ddca6aa4 | <|skeleton|>
class GenerationMixin:
"""A class containing all functions for auto-regressive text generation Pass custom parameter values to 'generate' ."""
def tokenize(self, text: Union[str, List[str]], add_bos: bool=True) -> List[int]:
"""Decode the id to words :param text: The text or batch of text ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenerationMixin:
"""A class containing all functions for auto-regressive text generation Pass custom parameter values to 'generate' ."""
def tokenize(self, text: Union[str, List[str]], add_bos: bool=True) -> List[int]:
"""Decode the id to words :param text: The text or batch of text to be tokeniz... | the_stack_v2_python_sparse | python/llm/src/bigdl/llm/ggml/model/generation/utils.py | intel-analytics/BigDL | train | 4,913 |
b54f21a78a77347bb51bd99ca33454d928d67af0 | [
"self.cfg_path = cfg_key.split('.')\nself.field = field\nself.translator = translator",
"for key in self.cfg_path[:-1]:\n cfg = cast(ReadOnlyOrderedDict, cfg.get(key))\ndata = cfg.get(self.cfg_path[-1])\nfield.data = self.translator.load(data)",
"for key in self.cfg_path[:-1]:\n cfg = cast(AttrOrderedDict... | <|body_start_0|>
self.cfg_path = cfg_key.split('.')
self.field = field
self.translator = translator
<|end_body_0|>
<|body_start_1|>
for key in self.cfg_path[:-1]:
cfg = cast(ReadOnlyOrderedDict, cfg.get(key))
data = cfg.get(self.cfg_path[-1])
field.data = sel... | Represents a relation between a node in a lexicon config and a field in a public-facing form that exposes it to the editor for modification. | Setting | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Setting:
"""Represents a relation between a node in a lexicon config and a field in a public-facing form that exposes it to the editor for modification."""
def __init__(self, cfg_key: str, field: Field, translator: SettingTranslator=SettingTranslator()):
"""Creates a setting. Optiona... | stack_v2_sparse_classes_36k_train_031245 | 8,067 | no_license | [
{
"docstring": "Creates a setting. Optionally, defines a nontrivial translation between internal and public values.",
"name": "__init__",
"signature": "def __init__(self, cfg_key: str, field: Field, translator: SettingTranslator=SettingTranslator())"
},
{
"docstring": "Sets the field's value to ... | 3 | stack_v2_sparse_classes_30k_train_010190 | Implement the Python class `Setting` described below.
Class description:
Represents a relation between a node in a lexicon config and a field in a public-facing form that exposes it to the editor for modification.
Method signatures and docstrings:
- def __init__(self, cfg_key: str, field: Field, translator: SettingTr... | Implement the Python class `Setting` described below.
Class description:
Represents a relation between a node in a lexicon config and a field in a public-facing form that exposes it to the editor for modification.
Method signatures and docstrings:
- def __init__(self, cfg_key: str, field: Field, translator: SettingTr... | 875482355693c0787716c9b4930942e3e2e712f4 | <|skeleton|>
class Setting:
"""Represents a relation between a node in a lexicon config and a field in a public-facing form that exposes it to the editor for modification."""
def __init__(self, cfg_key: str, field: Field, translator: SettingTranslator=SettingTranslator()):
"""Creates a setting. Optiona... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Setting:
"""Represents a relation between a node in a lexicon config and a field in a public-facing form that exposes it to the editor for modification."""
def __init__(self, cfg_key: str, field: Field, translator: SettingTranslator=SettingTranslator()):
"""Creates a setting. Optionally, defines ... | the_stack_v2_python_sparse | amanuensis/server/session/settings.py | Jaculabilis/Amanuensis | train | 0 |
680b01a3e0721ccc7f62880ce22e7157a99ef1c8 | [
"if isinstance(users, list):\n self.users = users\n self.users_lookup = {}\n for user in users:\n self.users_lookup[user['login']] = user\nelse:\n self.users = []\n self.users_lookup = {}\n for login, data in users.items():\n user_rec = dict(data)\n user_rec['login'] = login\n... | <|body_start_0|>
if isinstance(users, list):
self.users = users
self.users_lookup = {}
for user in users:
self.users_lookup[user['login']] = user
else:
self.users = []
self.users_lookup = {}
for login, data in users.... | SimpleTicketAuthenticator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleTicketAuthenticator:
def __init__(self, users):
"""This takes a list of users in the format: users = [ { login: 'USERNAME1', password: 'PASSWORD1', role: 'ROLENAME1' }, ... { login: 'USERNAMEn', password: 'PASSWORDn', role: 'ROLENAMEn' }, ] This can also handle hash entries as well... | stack_v2_sparse_classes_36k_train_031246 | 9,197 | permissive | [
{
"docstring": "This takes a list of users in the format: users = [ { login: 'USERNAME1', password: 'PASSWORD1', role: 'ROLENAME1' }, ... { login: 'USERNAMEn', password: 'PASSWORDn', role: 'ROLENAMEn' }, ] This can also handle hash entries as well of the form: users = { 'USERNAME1': { 'password': 'PASSWORD1', '... | 2 | stack_v2_sparse_classes_30k_train_000134 | Implement the Python class `SimpleTicketAuthenticator` described below.
Class description:
Implement the SimpleTicketAuthenticator class.
Method signatures and docstrings:
- def __init__(self, users): This takes a list of users in the format: users = [ { login: 'USERNAME1', password: 'PASSWORD1', role: 'ROLENAME1' },... | Implement the Python class `SimpleTicketAuthenticator` described below.
Class description:
Implement the SimpleTicketAuthenticator class.
Method signatures and docstrings:
- def __init__(self, users): This takes a list of users in the format: users = [ { login: 'USERNAME1', password: 'PASSWORD1', role: 'ROLENAME1' },... | 8f6c33b583b54f7deb32fc06070db568bf88065d | <|skeleton|>
class SimpleTicketAuthenticator:
def __init__(self, users):
"""This takes a list of users in the format: users = [ { login: 'USERNAME1', password: 'PASSWORD1', role: 'ROLENAME1' }, ... { login: 'USERNAMEn', password: 'PASSWORDn', role: 'ROLENAMEn' }, ] This can also handle hash entries as well... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleTicketAuthenticator:
def __init__(self, users):
"""This takes a list of users in the format: users = [ { login: 'USERNAME1', password: 'PASSWORD1', role: 'ROLENAME1' }, ... { login: 'USERNAMEn', password: 'PASSWORDn', role: 'ROLENAMEn' }, ] This can also handle hash entries as well of the form: ... | the_stack_v2_python_sparse | izaber_flask_wamp/authenticators.py | zabertech/python-izaber-flask-wamp | train | 0 | |
02a141871c1f43935f88d54d3e34822a16561f17 | [
"repeat = False\nfor attr in list(target.attrs):\n if attr.is_group:\n repeat = True\n self.process_attribute(target, attr)\nif repeat:\n self.process(target)",
"qname = attr.types[0].qname\nsource = self.container.find(qname, condition=lambda x: x.tag == attr.tag)\nif not source:\n raise A... | <|body_start_0|>
repeat = False
for attr in list(target.attrs):
if attr.is_group:
repeat = True
self.process_attribute(target, attr)
if repeat:
self.process(target)
<|end_body_0|>
<|body_start_1|>
qname = attr.types[0].qname
... | Replace groups and attGroups with the source class attributes. | FlattenAttributeGroups | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlattenAttributeGroups:
"""Replace groups and attGroups with the source class attributes."""
def process(self, target: Class):
"""Iterate over all group attributes and apply handler logic. Group attributes can refer to attributes or other group attributes, repeat until there is no gr... | stack_v2_sparse_classes_36k_train_031247 | 1,558 | permissive | [
{
"docstring": "Iterate over all group attributes and apply handler logic. Group attributes can refer to attributes or other group attributes, repeat until there is no group attribute left.",
"name": "process",
"signature": "def process(self, target: Class)"
},
{
"docstring": "Find the source cl... | 2 | stack_v2_sparse_classes_30k_train_003795 | Implement the Python class `FlattenAttributeGroups` described below.
Class description:
Replace groups and attGroups with the source class attributes.
Method signatures and docstrings:
- def process(self, target: Class): Iterate over all group attributes and apply handler logic. Group attributes can refer to attribut... | Implement the Python class `FlattenAttributeGroups` described below.
Class description:
Replace groups and attGroups with the source class attributes.
Method signatures and docstrings:
- def process(self, target: Class): Iterate over all group attributes and apply handler logic. Group attributes can refer to attribut... | 31f672af84fd040a97996871916a41b1046fe46b | <|skeleton|>
class FlattenAttributeGroups:
"""Replace groups and attGroups with the source class attributes."""
def process(self, target: Class):
"""Iterate over all group attributes and apply handler logic. Group attributes can refer to attributes or other group attributes, repeat until there is no gr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlattenAttributeGroups:
"""Replace groups and attGroups with the source class attributes."""
def process(self, target: Class):
"""Iterate over all group attributes and apply handler logic. Group attributes can refer to attributes or other group attributes, repeat until there is no group attribute... | the_stack_v2_python_sparse | xsdata/codegen/handlers/flatten_attribute_groups.py | tefra/xsdata | train | 243 |
15470ff195ba368570c85d6f308b628cc3725e19 | [
"super(Meme_classifier, self).__init__()\nself.backbone = backbone\nself.fc1 = nn.Linear(2048, 50, bias=True)\nself.relu1 = nn.ReLU()\nself.bn1 = nn.BatchNorm1d(100)\nself.input_size = weight_matrix.shape[1]\nself.embedding = nn.Embedding.from_pretrained(weight_matrix)\nself.embedding.weight.requires_grad = True\ns... | <|body_start_0|>
super(Meme_classifier, self).__init__()
self.backbone = backbone
self.fc1 = nn.Linear(2048, 50, bias=True)
self.relu1 = nn.ReLU()
self.bn1 = nn.BatchNorm1d(100)
self.input_size = weight_matrix.shape[1]
self.embedding = nn.Embedding.from_pretrained... | MemeClassifier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemeClassifier:
def __init__(self, backbone, weight_matrix):
"""Input: backbone: This the image feature extractor, we used pretrained model for this. weight_matrix: (Tensor) This is matrix for initilize the word embedding layer hidden_size2: size for first image fc output hidden_size: th... | stack_v2_sparse_classes_36k_train_031248 | 4,920 | no_license | [
{
"docstring": "Input: backbone: This the image feature extractor, we used pretrained model for this. weight_matrix: (Tensor) This is matrix for initilize the word embedding layer hidden_size2: size for first image fc output hidden_size: this is size for LSTM hidden layer and this is the feature size for superi... | 2 | stack_v2_sparse_classes_30k_train_017116 | Implement the Python class `MemeClassifier` described below.
Class description:
Implement the MemeClassifier class.
Method signatures and docstrings:
- def __init__(self, backbone, weight_matrix): Input: backbone: This the image feature extractor, we used pretrained model for this. weight_matrix: (Tensor) This is mat... | Implement the Python class `MemeClassifier` described below.
Class description:
Implement the MemeClassifier class.
Method signatures and docstrings:
- def __init__(self, backbone, weight_matrix): Input: backbone: This the image feature extractor, we used pretrained model for this. weight_matrix: (Tensor) This is mat... | a3ae712f54d9a32d0272dd5636874aef4550bbff | <|skeleton|>
class MemeClassifier:
def __init__(self, backbone, weight_matrix):
"""Input: backbone: This the image feature extractor, we used pretrained model for this. weight_matrix: (Tensor) This is matrix for initilize the word embedding layer hidden_size2: size for first image fc output hidden_size: th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MemeClassifier:
def __init__(self, backbone, weight_matrix):
"""Input: backbone: This the image feature extractor, we used pretrained model for this. weight_matrix: (Tensor) This is matrix for initilize the word embedding layer hidden_size2: size for first image fc output hidden_size: this is size for... | the_stack_v2_python_sparse | step2_MemeClassifier/MemeModel.py | yuhaodu/TwitterMeme | train | 5 | |
56fe6f477b29d29123fe1b035d23768eb77ad8d0 | [
"if not is_bytes(data):\n raise TypeError('The `data` value must be of bytes type. Got {0}'.format(type(data)))\ndecoder = self._registry.get_decoder(typ)\nstream = ContextFramesBytesIO(data)\nreturn decoder(stream)",
"if not is_bytes(data):\n raise TypeError('The `data` value must be of bytes type. Got {... | <|body_start_0|>
if not is_bytes(data):
raise TypeError('The `data` value must be of bytes type. Got {0}'.format(type(data)))
decoder = self._registry.get_decoder(typ)
stream = ContextFramesBytesIO(data)
return decoder(stream)
<|end_body_0|>
<|body_start_1|>
if not ... | Wraps a registry to provide last-mile decoding functionality. | ABIDecoder | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ABIDecoder:
"""Wraps a registry to provide last-mile decoding functionality."""
def decode_single(self, typ: TypeStr, data: Decodable) -> Any:
"""Decodes the binary value ``data`` of the ABI type ``typ`` into its equivalent python value. :param typ: The string representation of the A... | stack_v2_sparse_classes_36k_train_031249 | 5,761 | permissive | [
{
"docstring": "Decodes the binary value ``data`` of the ABI type ``typ`` into its equivalent python value. :param typ: The string representation of the ABI type that will be used for decoding e.g. ``'uint256'``, ``'bytes[]'``, ``'(int,int)'``, etc. :param data: The binary value to be decoded. :returns: The equ... | 2 | null | Implement the Python class `ABIDecoder` described below.
Class description:
Wraps a registry to provide last-mile decoding functionality.
Method signatures and docstrings:
- def decode_single(self, typ: TypeStr, data: Decodable) -> Any: Decodes the binary value ``data`` of the ABI type ``typ`` into its equivalent pyt... | Implement the Python class `ABIDecoder` described below.
Class description:
Wraps a registry to provide last-mile decoding functionality.
Method signatures and docstrings:
- def decode_single(self, typ: TypeStr, data: Decodable) -> Any: Decodes the binary value ``data`` of the ABI type ``typ`` into its equivalent pyt... | 5fa6cc416b604de4bbd0d2407f36ed286d67a792 | <|skeleton|>
class ABIDecoder:
"""Wraps a registry to provide last-mile decoding functionality."""
def decode_single(self, typ: TypeStr, data: Decodable) -> Any:
"""Decodes the binary value ``data`` of the ABI type ``typ`` into its equivalent python value. :param typ: The string representation of the A... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ABIDecoder:
"""Wraps a registry to provide last-mile decoding functionality."""
def decode_single(self, typ: TypeStr, data: Decodable) -> Any:
"""Decodes the binary value ``data`` of the ABI type ``typ`` into its equivalent python value. :param typ: The string representation of the ABI type that ... | the_stack_v2_python_sparse | eth_abi/codec.py | FISCO-BCOS/python-sdk | train | 68 |
88000392ff7ed945a764d5d379e590379727bad8 | [
"super().__init__()\nself.unified_encoder = unified_encoder\nself.decoder = decoder\nself.output_layer = output_layer",
"enc_src, src_mask, src_inp = self.unified_encoder(*args)\nbatch_size, _, hid_dim = src_inp.shape\ndevice = src_inp.device\ntrg_inp = torch.cat((torch.zeros((batch_size, 1, hid_dim), device=devi... | <|body_start_0|>
super().__init__()
self.unified_encoder = unified_encoder
self.decoder = decoder
self.output_layer = output_layer
<|end_body_0|>
<|body_start_1|>
enc_src, src_mask, src_inp = self.unified_encoder(*args)
batch_size, _, hid_dim = src_inp.shape
devi... | TransformerAutoEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerAutoEncoder:
def __init__(self, unified_encoder, decoder, output_layer):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1|>
def run(self, y, seq_cat_data, seq_co... | stack_v2_sparse_classes_36k_train_031250 | 15,906 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, unified_encoder, decoder, output_layer)"
},
{
"docstring": "Run a forward pass of model over the data.",
"name": "forward",
"signature": "def forward(self, *args)"
},
{
"docstring... | 3 | stack_v2_sparse_classes_30k_test_000491 | Implement the Python class `TransformerAutoEncoder` described below.
Class description:
Implement the TransformerAutoEncoder class.
Method signatures and docstrings:
- def __init__(self, unified_encoder, decoder, output_layer): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over... | Implement the Python class `TransformerAutoEncoder` described below.
Class description:
Implement the TransformerAutoEncoder class.
Method signatures and docstrings:
- def __init__(self, unified_encoder, decoder, output_layer): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class TransformerAutoEncoder:
def __init__(self, unified_encoder, decoder, output_layer):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1|>
def run(self, y, seq_cat_data, seq_co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerAutoEncoder:
def __init__(self, unified_encoder, decoder, output_layer):
"""Initialize model with params."""
super().__init__()
self.unified_encoder = unified_encoder
self.decoder = decoder
self.output_layer = output_layer
def forward(self, *args):
... | the_stack_v2_python_sparse | caspr/models/model_wrapper.py | microsoft/CASPR | train | 29 | |
3a170742570a1bdd95daf55499a98b63a475e575 | [
"if self._attrMap is not None:\n for key in self.__dict__.keys():\n if key[0] != '_':\n msg = 'Unexpected attribute %s found in %s' % (key, self)\n assert key in self._attrMap, msg\n for attr, metavalue in self._attrMap.items():\n msg = 'Missing attribute %s from %s' % (att... | <|body_start_0|>
if self._attrMap is not None:
for key in self.__dict__.keys():
if key[0] != '_':
msg = 'Unexpected attribute %s found in %s' % (key, self)
assert key in self._attrMap, msg
for attr, metavalue in self._attrMap.items(... | Base for property holders | PropHolder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PropHolder:
"""Base for property holders"""
def verify(self):
"""If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) checks each attribute has a valid value. Either succeeds ... | stack_v2_sparse_classes_36k_train_031251 | 18,700 | permissive | [
{
"docstring": "If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) checks each attribute has a valid value. Either succeeds or raises an informative exception.",
"name": "verify",
"signature": ... | 4 | stack_v2_sparse_classes_30k_train_012700 | Implement the Python class `PropHolder` described below.
Class description:
Base for property holders
Method signatures and docstrings:
- def verify(self): If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) ... | Implement the Python class `PropHolder` described below.
Class description:
Base for property holders
Method signatures and docstrings:
- def verify(self): If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) ... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class PropHolder:
"""Base for property holders"""
def verify(self):
"""If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) checks each attribute has a valid value. Either succeeds ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PropHolder:
"""Base for property holders"""
def verify(self):
"""If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) checks each attribute has a valid value. Either succeeds or raises an ... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/reportlab/graphics/widgetbase.py | ryfeus/lambda-packs | train | 1,283 |
2288c7e93069d369f7693626a7994bf25ef0a459 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn HostCookie()",
"from .artifact import Artifact\nfrom .host import Host\nfrom .artifact import Artifact\nfrom .host import Host\nfields: Dict[str, Callable[[Any], None]] = {'domain': lambda n: setattr(self, 'domain', n.get_str_value()),... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return HostCookie()
<|end_body_0|>
<|body_start_1|>
from .artifact import Artifact
from .host import Host
from .artifact import Artifact
from .host import Host
fields: D... | HostCookie | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostCookie:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostCookie:
"""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: Host... | stack_v2_sparse_classes_36k_train_031252 | 3,561 | 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: HostCookie",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(pa... | 3 | stack_v2_sparse_classes_30k_train_015052 | Implement the Python class `HostCookie` described below.
Class description:
Implement the HostCookie class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostCookie: Creates a new instance of the appropriate class based on discriminator value Args: pa... | Implement the Python class `HostCookie` described below.
Class description:
Implement the HostCookie class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostCookie: Creates a new instance of the appropriate class based on discriminator value Args: pa... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class HostCookie:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostCookie:
"""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: Host... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HostCookie:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostCookie:
"""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: HostCookie"""
... | the_stack_v2_python_sparse | msgraph/generated/models/security/host_cookie.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
048e6500651bb7b7bcd37a991421be697a63a2ca | [
"args = parser.parse_args()\nsentence = args.get('sentence')\nreturn jsonify(rst)",
"form = ChargeForm().validate_for_api()\nsentence = form.sentence.data\nreturn jsonify(rst)"
] | <|body_start_0|>
args = parser.parse_args()
sentence = args.get('sentence')
return jsonify(rst)
<|end_body_0|>
<|body_start_1|>
form = ChargeForm().validate_for_api()
sentence = form.sentence.data
return jsonify(rst)
<|end_body_1|>
| (刑事)罪名预测引擎 | Charge | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Charge:
"""(刑事)罪名预测引擎"""
def get(self):
"""罪名预测 根据用户的输入预测罪名"""
<|body_0|>
def post(self):
"""罪名预测 根据用户的输入预测罪名"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = parser.parse_args()
sentence = args.get('sentence')
return jsoni... | stack_v2_sparse_classes_36k_train_031253 | 1,388 | no_license | [
{
"docstring": "罪名预测 根据用户的输入预测罪名",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "罪名预测 根据用户的输入预测罪名",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001197 | Implement the Python class `Charge` described below.
Class description:
(刑事)罪名预测引擎
Method signatures and docstrings:
- def get(self): 罪名预测 根据用户的输入预测罪名
- def post(self): 罪名预测 根据用户的输入预测罪名 | Implement the Python class `Charge` described below.
Class description:
(刑事)罪名预测引擎
Method signatures and docstrings:
- def get(self): 罪名预测 根据用户的输入预测罪名
- def post(self): 罪名预测 根据用户的输入预测罪名
<|skeleton|>
class Charge:
"""(刑事)罪名预测引擎"""
def get(self):
"""罪名预测 根据用户的输入预测罪名"""
<|body_0|>
def post... | d373f6bcd461a55d6a6662ccf3a9edd66f0b91ab | <|skeleton|>
class Charge:
"""(刑事)罪名预测引擎"""
def get(self):
"""罪名预测 根据用户的输入预测罪名"""
<|body_0|>
def post(self):
"""罪名预测 根据用户的输入预测罪名"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Charge:
"""(刑事)罪名预测引擎"""
def get(self):
"""罪名预测 根据用户的输入预测罪名"""
args = parser.parse_args()
sentence = args.get('sentence')
return jsonify(rst)
def post(self):
"""罪名预测 根据用户的输入预测罪名"""
form = ChargeForm().validate_for_api()
sentence = form.sentence... | the_stack_v2_python_sparse | charges_kg/charges_kg/src/web/apps/v1/charge.py | yaolinxia/practice | train | 0 |
e6944af20e5287975a20fc9a02e1a181db8373e0 | [
"super().save_model(request, obj, form, change)\nfrom celery_tasks.tasks import generate_static_index_html\ngenerate_static_index_html.delay()\ncache.delete('index_page_data')",
"super().delete_model(request, obj)\nfrom celery_tasks.tasks import generate_static_index_html\ngenerate_static_index_html.delay()\ncach... | <|body_start_0|>
super().save_model(request, obj, form, change)
from celery_tasks.tasks import generate_static_index_html
generate_static_index_html.delay()
cache.delete('index_page_data')
<|end_body_0|>
<|body_start_1|>
super().delete_model(request, obj)
from celery_tas... | BaseModelAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseModelAdmin:
def save_model(self, request, obj, form, change):
"""新增或更新表中数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""删除表中数据时调用"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().save_model(request, obj, form, change)
... | stack_v2_sparse_classes_36k_train_031254 | 1,816 | no_license | [
{
"docstring": "新增或更新表中数据时调用",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "删除表中数据时调用",
"name": "delete_model",
"signature": "def delete_model(self, request, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000848 | Implement the Python class `BaseModelAdmin` described below.
Class description:
Implement the BaseModelAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 新增或更新表中数据时调用
- def delete_model(self, request, obj): 删除表中数据时调用 | Implement the Python class `BaseModelAdmin` described below.
Class description:
Implement the BaseModelAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 新增或更新表中数据时调用
- def delete_model(self, request, obj): 删除表中数据时调用
<|skeleton|>
class BaseModelAdmin:
def save_mod... | 304f50a8ad056a2e9290af23dfc8de32fbbb0888 | <|skeleton|>
class BaseModelAdmin:
def save_model(self, request, obj, form, change):
"""新增或更新表中数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""删除表中数据时调用"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseModelAdmin:
def save_model(self, request, obj, form, change):
"""新增或更新表中数据时调用"""
super().save_model(request, obj, form, change)
from celery_tasks.tasks import generate_static_index_html
generate_static_index_html.delay()
cache.delete('index_page_data')
def dele... | the_stack_v2_python_sparse | ttsx/apps/goods/admin.py | yhhuang1996/Django-B2C-Project | train | 0 | |
3e47ffbfd35b25a57607c954d644d3b1b7f65851 | [
"expressions = ['a&b', 'a&b&c', 'a|b', 'a|b|c', '(a&b)|c', '(a|b)&c', 'a|(b&c)', 'a&(b|c)', '(a&b)|(b&c)', '(a|b)&(c|d)', '\"test&|\"&b', '((a&b)|c)&(d|e)']\nparser = VisParser()\nfor e in expressions:\n tree = parser.parse(e)\n parsed_expr = tree.__str__()\n self.assertEqual(parsed_expr, e, 'Parser did no... | <|body_start_0|>
expressions = ['a&b', 'a&b&c', 'a|b', 'a|b|c', '(a&b)|c', '(a|b)&c', 'a|(b&c)', 'a&(b|c)', '(a&b)|(b&c)', '(a|b)&(c|d)', '"test&|"&b', '((a&b)|c)&(d|e)']
parser = VisParser()
for e in expressions:
tree = parser.parse(e)
parsed_expr = tree.__str__()
... | VisParserTest | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisParserTest:
def test_correct_expressions(self):
"""Tests the parser on correct expressions"""
<|body_0|>
def test_incorrect_expressions(self):
"""Test the parser on incorrect expressions"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
expressions... | stack_v2_sparse_classes_36k_train_031255 | 2,397 | permissive | [
{
"docstring": "Tests the parser on correct expressions",
"name": "test_correct_expressions",
"signature": "def test_correct_expressions(self)"
},
{
"docstring": "Test the parser on incorrect expressions",
"name": "test_incorrect_expressions",
"signature": "def test_incorrect_expressions... | 2 | null | Implement the Python class `VisParserTest` described below.
Class description:
Implement the VisParserTest class.
Method signatures and docstrings:
- def test_correct_expressions(self): Tests the parser on correct expressions
- def test_incorrect_expressions(self): Test the parser on incorrect expressions | Implement the Python class `VisParserTest` described below.
Class description:
Implement the VisParserTest class.
Method signatures and docstrings:
- def test_correct_expressions(self): Tests the parser on correct expressions
- def test_incorrect_expressions(self): Test the parser on incorrect expressions
<|skeleton... | eb61250886e51647bd1edb6d8f4fa7f83eb0bc81 | <|skeleton|>
class VisParserTest:
def test_correct_expressions(self):
"""Tests the parser on correct expressions"""
<|body_0|>
def test_incorrect_expressions(self):
"""Test the parser on incorrect expressions"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VisParserTest:
def test_correct_expressions(self):
"""Tests the parser on correct expressions"""
expressions = ['a&b', 'a&b&c', 'a|b', 'a|b|c', '(a&b)|c', '(a|b)&c', 'a|(b&c)', 'a&(b|c)', '(a&b)|(b&c)', '(a|b)&(c|d)', '"test&|"&b', '((a&b)|c)&(d|e)']
parser = VisParser()
for e ... | the_stack_v2_python_sparse | pace/encryption/visibility/vis_parser_test.py | Global-localhost/PACE-python | train | 0 | |
bb9a92fb19344cdd66ace0c11684016e67668eef | [
"def dfs(root: TreeNode, curNum: int) -> int:\n if not root:\n return 0\n curNum = (curNum << 1) + root.val\n if not root.left and (not root.right):\n return curNum\n return dfs(root.left, curNum) + dfs(root.right, curNum)\nreturn dfs(root, 0)",
"if not root:\n return 0\nret = 0\nstac... | <|body_start_0|>
def dfs(root: TreeNode, curNum: int) -> int:
if not root:
return 0
curNum = (curNum << 1) + root.val
if not root.left and (not root.right):
return curNum
return dfs(root.left, curNum) + dfs(root.right, curNum)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumRootToLeaf_MK1(self, root: TreeNode) -> int:
"""Recursive Preorder Traversal. Time complexity: O(N). N is a number of nodes. Space complexity: O(H). H is a tree height."""
<|body_0|>
def sumRootToLeaf_MK2(self, root: TreeNode) -> int:
"""Iterative Pr... | stack_v2_sparse_classes_36k_train_031256 | 2,503 | no_license | [
{
"docstring": "Recursive Preorder Traversal. Time complexity: O(N). N is a number of nodes. Space complexity: O(H). H is a tree height.",
"name": "sumRootToLeaf_MK1",
"signature": "def sumRootToLeaf_MK1(self, root: TreeNode) -> int"
},
{
"docstring": "Iterative Preorder Traversal. Time complexi... | 3 | stack_v2_sparse_classes_30k_train_004348 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumRootToLeaf_MK1(self, root: TreeNode) -> int: Recursive Preorder Traversal. Time complexity: O(N). N is a number of nodes. Space complexity: O(H). H is a tree height.
- def... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumRootToLeaf_MK1(self, root: TreeNode) -> int: Recursive Preorder Traversal. Time complexity: O(N). N is a number of nodes. Space complexity: O(H). H is a tree height.
- def... | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | <|skeleton|>
class Solution:
def sumRootToLeaf_MK1(self, root: TreeNode) -> int:
"""Recursive Preorder Traversal. Time complexity: O(N). N is a number of nodes. Space complexity: O(H). H is a tree height."""
<|body_0|>
def sumRootToLeaf_MK2(self, root: TreeNode) -> int:
"""Iterative Pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumRootToLeaf_MK1(self, root: TreeNode) -> int:
"""Recursive Preorder Traversal. Time complexity: O(N). N is a number of nodes. Space complexity: O(H). H is a tree height."""
def dfs(root: TreeNode, curNum: int) -> int:
if not root:
return 0
... | the_stack_v2_python_sparse | 1022. Sum of Root To Leaf Binary Numbers/Solution.py | faterazer/LeetCode | train | 4 | |
7e5885d431d00796af7654dfe435ed846ca7411f | [
"super().__init__(**kwarg)\nself._recorder = Recorder('temp.wav')\nself._recording = False",
"if not self._recording:\n try:\n self._recorder.start()\n self._recording = True\n except OSError as e:\n message = 'Invalid input device (no default output device)' if e.errno == -9996 else 'A... | <|body_start_0|>
super().__init__(**kwarg)
self._recorder = Recorder('temp.wav')
self._recording = False
<|end_body_0|>
<|body_start_1|>
if not self._recording:
try:
self._recorder.start()
self._recording = True
except OSError as e... | Starts and stops a recording and saves the wave file. | RecordButton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecordButton:
"""Starts and stops a recording and saves the wave file."""
def __init__(self, **kwarg):
"""Creates the recorder and sets the _recording flag to false"""
<|body_0|>
def toggle(self):
"""Starts or stops the recording depending of the value of the _re... | stack_v2_sparse_classes_36k_train_031257 | 2,770 | no_license | [
{
"docstring": "Creates the recorder and sets the _recording flag to false",
"name": "__init__",
"signature": "def __init__(self, **kwarg)"
},
{
"docstring": "Starts or stops the recording depending of the value of the _recording attributes. When the recording is stopped, the analysis is launche... | 2 | stack_v2_sparse_classes_30k_val_000485 | Implement the Python class `RecordButton` described below.
Class description:
Starts and stops a recording and saves the wave file.
Method signatures and docstrings:
- def __init__(self, **kwarg): Creates the recorder and sets the _recording flag to false
- def toggle(self): Starts or stops the recording depending of... | Implement the Python class `RecordButton` described below.
Class description:
Starts and stops a recording and saves the wave file.
Method signatures and docstrings:
- def __init__(self, **kwarg): Creates the recorder and sets the _recording flag to false
- def toggle(self): Starts or stops the recording depending of... | 473a63578f069cd466d37a22aa4abc2700d17f54 | <|skeleton|>
class RecordButton:
"""Starts and stops a recording and saves the wave file."""
def __init__(self, **kwarg):
"""Creates the recorder and sets the _recording flag to false"""
<|body_0|>
def toggle(self):
"""Starts or stops the recording depending of the value of the _re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecordButton:
"""Starts and stops a recording and saves the wave file."""
def __init__(self, **kwarg):
"""Creates the recorder and sets the _recording flag to false"""
super().__init__(**kwarg)
self._recorder = Recorder('temp.wav')
self._recording = False
def toggle(s... | the_stack_v2_python_sparse | gui/button.py | pfmonville/Perfect-Melody | train | 0 |
e5c30d3d3267b12d93f05eca73199e4c4f578492 | [
"import pycbf\nself.cbf_handle = pycbf.cbf_handle_struct()\nself.cbf_handle.read_file(filename, pycbf.MSG_DIGEST)\nself.cbf_handle.rewind_datablock()",
"from scitbx.array_family import flex\nself.cbf_handle.select_datablock(0)\nself.cbf_handle.select_category(0)\nself.cbf_handle.select_column(2)\nself.cbf_handle.... | <|body_start_0|>
import pycbf
self.cbf_handle = pycbf.cbf_handle_struct()
self.cbf_handle.read_file(filename, pycbf.MSG_DIGEST)
self.cbf_handle.rewind_datablock()
<|end_body_0|>
<|body_start_1|>
from scitbx.array_family import flex
self.cbf_handle.select_datablock(0)
... | A class to read the CBF files used in DIALS | reader | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class reader:
"""A class to read the CBF files used in DIALS"""
def read_file(self, filename):
"""Read the CBF file"""
<|body_0|>
def get_data(self):
"""Get the gain array from the file"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import pycbf
... | stack_v2_sparse_classes_36k_train_031258 | 1,568 | permissive | [
{
"docstring": "Read the CBF file",
"name": "read_file",
"signature": "def read_file(self, filename)"
},
{
"docstring": "Get the gain array from the file",
"name": "get_data",
"signature": "def get_data(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016913 | Implement the Python class `reader` described below.
Class description:
A class to read the CBF files used in DIALS
Method signatures and docstrings:
- def read_file(self, filename): Read the CBF file
- def get_data(self): Get the gain array from the file | Implement the Python class `reader` described below.
Class description:
A class to read the CBF files used in DIALS
Method signatures and docstrings:
- def read_file(self, filename): Read the CBF file
- def get_data(self): Get the gain array from the file
<|skeleton|>
class reader:
"""A class to read the CBF fil... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class reader:
"""A class to read the CBF files used in DIALS"""
def read_file(self, filename):
"""Read the CBF file"""
<|body_0|>
def get_data(self):
"""Get the gain array from the file"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class reader:
"""A class to read the CBF files used in DIALS"""
def read_file(self, filename):
"""Read the CBF file"""
import pycbf
self.cbf_handle = pycbf.cbf_handle_struct()
self.cbf_handle.read_file(filename, pycbf.MSG_DIGEST)
self.cbf_handle.rewind_datablock()
d... | the_stack_v2_python_sparse | src/dials/util/image.py | dials/dials | train | 71 |
2b25b68905da913bf8ca1696a312b4c893948d34 | [
"res = dict()\nres[KeyPair.DICT_PUBLIC_KEY] = key_pair.public\nres[KeyPair.DICT_SECRET_KEY] = key_pair.secret\nreturn res",
"if KeyPair.DICT_PUBLIC_KEY not in data:\n raise ParseError(\"required key '\" + KeyPair.DICT_PUBLIC_KEY + \"' is missing\")\nif KeyPair.DICT_SECRET_KEY not in data:\n raise ParseError... | <|body_start_0|>
res = dict()
res[KeyPair.DICT_PUBLIC_KEY] = key_pair.public
res[KeyPair.DICT_SECRET_KEY] = key_pair.secret
return res
<|end_body_0|>
<|body_start_1|>
if KeyPair.DICT_PUBLIC_KEY not in data:
raise ParseError("required key '" + KeyPair.DICT_PUBLIC_KEY ... | Can be used to serialize and deserialize a KeyPair derived alias such as an AccountSecret instance or an AddressSecret. | KeyPairSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyPairSerializer:
"""Can be used to serialize and deserialize a KeyPair derived alias such as an AccountSecret instance or an AddressSecret."""
def as_dict(self, key_pair: KeyPair) -> dict:
"""Transforms a KeyPair into a dictionary that contains all attributes of the KeyPair. After ... | stack_v2_sparse_classes_36k_train_031259 | 1,532 | permissive | [
{
"docstring": "Transforms a KeyPair into a dictionary that contains all attributes of the KeyPair. After that, the dict may be persisted and deserialized later. For example, the dict representation may be converted into JSON using the standard json library.",
"name": "as_dict",
"signature": "def as_dic... | 2 | null | Implement the Python class `KeyPairSerializer` described below.
Class description:
Can be used to serialize and deserialize a KeyPair derived alias such as an AccountSecret instance or an AddressSecret.
Method signatures and docstrings:
- def as_dict(self, key_pair: KeyPair) -> dict: Transforms a KeyPair into a dicti... | Implement the Python class `KeyPairSerializer` described below.
Class description:
Can be used to serialize and deserialize a KeyPair derived alias such as an AccountSecret instance or an AddressSecret.
Method signatures and docstrings:
- def as_dict(self, key_pair: KeyPair) -> dict: Transforms a KeyPair into a dicti... | b5e7489eff3e65d2e7d802802afd0dd38ddd2e96 | <|skeleton|>
class KeyPairSerializer:
"""Can be used to serialize and deserialize a KeyPair derived alias such as an AccountSecret instance or an AddressSecret."""
def as_dict(self, key_pair: KeyPair) -> dict:
"""Transforms a KeyPair into a dictionary that contains all attributes of the KeyPair. After ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeyPairSerializer:
"""Can be used to serialize and deserialize a KeyPair derived alias such as an AccountSecret instance or an AddressSecret."""
def as_dict(self, key_pair: KeyPair) -> dict:
"""Transforms a KeyPair into a dictionary that contains all attributes of the KeyPair. After that, the dic... | the_stack_v2_python_sparse | waves_gateway/serializer/key_pair_serializer.py | jansenmarc/WavesGatewayFramework | train | 26 |
054a9fb01603e6f6fe59f389c127f453b8912a11 | [
"if not root:\n return ''\nres = []\n\ndef helper(root):\n if not root:\n res.append('N,')\n return\n res.append(str(root.val) + ',')\n helper(root.left)\n helper(root.right)\nhelper(root)\nreturn ''.join(res)",
"if not data:\n return None\n\ndef helper():\n if not data:\n ... | <|body_start_0|>
if not root:
return ''
res = []
def helper(root):
if not root:
res.append('N,')
return
res.append(str(root.val) + ',')
helper(root.left)
helper(root.right)
helper(root)
r... | 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_031260 | 3,717 | 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:... | 0ef3ef71d75ea20cd3079ad6aa3211f61efb7b7a | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
res = []
def helper(root):
if not root:
res.append('N,')
return
res.append(str... | the_stack_v2_python_sparse | common-problems-leetcode/hard/serialize-and-deserialize-binary-tree.py | JackMGrundy/coding-challenges | train | 3 | |
bb602474d0647a3a18c239c87672bfa308f4d1ac | [
"self.consumer_id = consumer_id\nself.consumer_ssn = consumer_ssn\nself.event_name = event_name\nself.id = id\nself.status = status\nself.mtype = mtype\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nconsumer_id = dictionary.get('consumerId')\nconsumer_ssn = diction... | <|body_start_0|>
self.consumer_id = consumer_id
self.consumer_ssn = consumer_ssn
self.event_name = event_name
self.id = id
self.status = status
self.mtype = mtype
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictio... | Implementation of the 'ReportNotification' model. TODO: type model description here. Attributes: consumer_id (string): Finicity’s consumer ID. This field is optional and may not always return. consumer_ssn (string): The last four of the consumer’s social security number. This field is optional and may not always return... | ReportNotification | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportNotification:
"""Implementation of the 'ReportNotification' model. TODO: type model description here. Attributes: consumer_id (string): Finicity’s consumer ID. This field is optional and may not always return. consumer_ssn (string): The last four of the consumer’s social security number. Th... | stack_v2_sparse_classes_36k_train_031261 | 3,117 | permissive | [
{
"docstring": "Constructor for the ReportNotification class",
"name": "__init__",
"signature": "def __init__(self, consumer_id=None, consumer_ssn=None, event_name=None, id=None, status=None, mtype=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dicti... | 2 | stack_v2_sparse_classes_30k_train_003219 | Implement the Python class `ReportNotification` described below.
Class description:
Implementation of the 'ReportNotification' model. TODO: type model description here. Attributes: consumer_id (string): Finicity’s consumer ID. This field is optional and may not always return. consumer_ssn (string): The last four of th... | Implement the Python class `ReportNotification` described below.
Class description:
Implementation of the 'ReportNotification' model. TODO: type model description here. Attributes: consumer_id (string): Finicity’s consumer ID. This field is optional and may not always return. consumer_ssn (string): The last four of th... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class ReportNotification:
"""Implementation of the 'ReportNotification' model. TODO: type model description here. Attributes: consumer_id (string): Finicity’s consumer ID. This field is optional and may not always return. consumer_ssn (string): The last four of the consumer’s social security number. Th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReportNotification:
"""Implementation of the 'ReportNotification' model. TODO: type model description here. Attributes: consumer_id (string): Finicity’s consumer ID. This field is optional and may not always return. consumer_ssn (string): The last four of the consumer’s social security number. This field is o... | the_stack_v2_python_sparse | finicityapi/models/report_notification.py | monarchmoney/finicity-python | train | 0 |
30736015f61a40d134307025e29b2cf2de88be2c | [
"ref_input = ['10', '11', '12.1']\nexpected_output = (float(ref_input[0]) + float(ref_input[1]) / 60 + float(ref_input[2]) / 3600) * (math.pi / 180)\nactual_output = UnitConverter().dms_to_rad(ref_input)\nassert actual_output == expected_output",
"ref_input = 0.1866052706727415\nref_input_dd = ref_input * (180 / ... | <|body_start_0|>
ref_input = ['10', '11', '12.1']
expected_output = (float(ref_input[0]) + float(ref_input[1]) / 60 + float(ref_input[2]) / 3600) * (math.pi / 180)
actual_output = UnitConverter().dms_to_rad(ref_input)
assert actual_output == expected_output
<|end_body_0|>
<|body_start_1... | Class to test UnitConverter's methods. | TestUnitConverter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUnitConverter:
"""Class to test UnitConverter's methods."""
def test_dms_to_rad(self):
"""This function tests whether dms_to_rad() converts dig:min:sec to radians correctly."""
<|body_0|>
def test_rad_to_dms(self):
"""This function tests whether rad_to_dms() ... | stack_v2_sparse_classes_36k_train_031262 | 1,962 | permissive | [
{
"docstring": "This function tests whether dms_to_rad() converts dig:min:sec to radians correctly.",
"name": "test_dms_to_rad",
"signature": "def test_dms_to_rad(self)"
},
{
"docstring": "This function tests whether rad_to_dms() converts radians to dig:min:sec correctly.",
"name": "test_rad... | 3 | null | Implement the Python class `TestUnitConverter` described below.
Class description:
Class to test UnitConverter's methods.
Method signatures and docstrings:
- def test_dms_to_rad(self): This function tests whether dms_to_rad() converts dig:min:sec to radians correctly.
- def test_rad_to_dms(self): This function tests ... | Implement the Python class `TestUnitConverter` described below.
Class description:
Class to test UnitConverter's methods.
Method signatures and docstrings:
- def test_dms_to_rad(self): This function tests whether dms_to_rad() converts dig:min:sec to radians correctly.
- def test_rad_to_dms(self): This function tests ... | 7ee65a9c8dada9b28893144b372a398bd0646195 | <|skeleton|>
class TestUnitConverter:
"""Class to test UnitConverter's methods."""
def test_dms_to_rad(self):
"""This function tests whether dms_to_rad() converts dig:min:sec to radians correctly."""
<|body_0|>
def test_rad_to_dms(self):
"""This function tests whether rad_to_dms() ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestUnitConverter:
"""Class to test UnitConverter's methods."""
def test_dms_to_rad(self):
"""This function tests whether dms_to_rad() converts dig:min:sec to radians correctly."""
ref_input = ['10', '11', '12.1']
expected_output = (float(ref_input[0]) + float(ref_input[1]) / 60 +... | the_stack_v2_python_sparse | temp_tests/ska-tmc-disleafnode-mid/unit/utils_test.py | ska-telescope/tmc-prototype | train | 4 |
2d69ce70673b8e5fd64a3d066ce07c20d23d3d08 | [
"if not s:\n res.append(path)\n return\nfor word in wordDict:\n k = len(word)\n if s[:k] == word:\n self.dfs(s[k:], wordDict, path + [word], res)",
"if not self.check(s, wordDict):\n return []\nres = []\nself.dfs(s, wordDict, [], res)\nreturn [' '.join(x) for x in res]",
"if not self.check... | <|body_start_0|>
if not s:
res.append(path)
return
for word in wordDict:
k = len(word)
if s[:k] == word:
self.dfs(s[k:], wordDict, path + [word], res)
<|end_body_0|>
<|body_start_1|>
if not self.check(s, wordDict):
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dfs(self, s, wordDict, path, res):
"""超时 :param s: :param wordDict: :param path: :param res: :return:"""
<|body_0|>
def wordBreak(self, s, wordDict):
"""dfs 超时 加个139题的判断就不会超时了。。。mdzz :type s: str :type wordDict: List[str] :rtype: List[str]"""
<|... | stack_v2_sparse_classes_36k_train_031263 | 3,438 | no_license | [
{
"docstring": "超时 :param s: :param wordDict: :param path: :param res: :return:",
"name": "dfs",
"signature": "def dfs(self, s, wordDict, path, res)"
},
{
"docstring": "dfs 超时 加个139题的判断就不会超时了。。。mdzz :type s: str :type wordDict: List[str] :rtype: List[str]",
"name": "wordBreak",
"signatur... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, s, wordDict, path, res): 超时 :param s: :param wordDict: :param path: :param res: :return:
- def wordBreak(self, s, wordDict): dfs 超时 加个139题的判断就不会超时了。。。mdzz :type s: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, s, wordDict, path, res): 超时 :param s: :param wordDict: :param path: :param res: :return:
- def wordBreak(self, s, wordDict): dfs 超时 加个139题的判断就不会超时了。。。mdzz :type s: ... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def dfs(self, s, wordDict, path, res):
"""超时 :param s: :param wordDict: :param path: :param res: :return:"""
<|body_0|>
def wordBreak(self, s, wordDict):
"""dfs 超时 加个139题的判断就不会超时了。。。mdzz :type s: str :type wordDict: List[str] :rtype: List[str]"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def dfs(self, s, wordDict, path, res):
"""超时 :param s: :param wordDict: :param path: :param res: :return:"""
if not s:
res.append(path)
return
for word in wordDict:
k = len(word)
if s[:k] == word:
self.dfs(s[k:],... | the_stack_v2_python_sparse | 140_单词拆分 II.py | lovehhf/LeetCode | train | 0 | |
1a899aa5912589a9ab1edd407989fb8e5dde0d5e | [
"self.api_type = api_type\nself.IOLoop = tornado.ioloop\nself.mc = memcache.Client(MEMCACHE_HOST, debug=1)\nself.timer = TOKEN_TIMER * 1000\nself.default_rate = 0\nself.app_rates = {}\nself.scheduler = None\nif not self._token_init():\n raise Exception('TokenBucket token init fail')",
"try:\n self.app_rates... | <|body_start_0|>
self.api_type = api_type
self.IOLoop = tornado.ioloop
self.mc = memcache.Client(MEMCACHE_HOST, debug=1)
self.timer = TOKEN_TIMER * 1000
self.default_rate = 0
self.app_rates = {}
self.scheduler = None
if not self._token_init():
... | TokenBucket | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenBucket:
def __init__(self, api_type):
"""初始化 :param api_type: (string)需要控制流量的接口类型 sms/mms/... :return:"""
<|body_0|>
def _token_init(self):
"""初始化各应用令牌数量 :return:"""
<|body_1|>
def _update_app_rate(self):
"""更新各应用速率 :return:"""
<|bod... | stack_v2_sparse_classes_36k_train_031264 | 5,361 | no_license | [
{
"docstring": "初始化 :param api_type: (string)需要控制流量的接口类型 sms/mms/... :return:",
"name": "__init__",
"signature": "def __init__(self, api_type)"
},
{
"docstring": "初始化各应用令牌数量 :return:",
"name": "_token_init",
"signature": "def _token_init(self)"
},
{
"docstring": "更新各应用速率 :return:... | 5 | stack_v2_sparse_classes_30k_train_004695 | Implement the Python class `TokenBucket` described below.
Class description:
Implement the TokenBucket class.
Method signatures and docstrings:
- def __init__(self, api_type): 初始化 :param api_type: (string)需要控制流量的接口类型 sms/mms/... :return:
- def _token_init(self): 初始化各应用令牌数量 :return:
- def _update_app_rate(self): 更新各应用... | Implement the Python class `TokenBucket` described below.
Class description:
Implement the TokenBucket class.
Method signatures and docstrings:
- def __init__(self, api_type): 初始化 :param api_type: (string)需要控制流量的接口类型 sms/mms/... :return:
- def _token_init(self): 初始化各应用令牌数量 :return:
- def _update_app_rate(self): 更新各应用... | 75f83797885a05df038bc7aab29138ecef27fa06 | <|skeleton|>
class TokenBucket:
def __init__(self, api_type):
"""初始化 :param api_type: (string)需要控制流量的接口类型 sms/mms/... :return:"""
<|body_0|>
def _token_init(self):
"""初始化各应用令牌数量 :return:"""
<|body_1|>
def _update_app_rate(self):
"""更新各应用速率 :return:"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenBucket:
def __init__(self, api_type):
"""初始化 :param api_type: (string)需要控制流量的接口类型 sms/mms/... :return:"""
self.api_type = api_type
self.IOLoop = tornado.ioloop
self.mc = memcache.Client(MEMCACHE_HOST, debug=1)
self.timer = TOKEN_TIMER * 1000
self.default_ra... | the_stack_v2_python_sparse | OpenAPI/api_qos/api_token_bucket.py | ennismar/python | train | 0 | |
996abf27245527f67c27f7fa8b0ed2a826771b79 | [
"for section in ['parameters', 'variables', 'extensions']:\n DictUtils.ensure_exists(config, section, {})\nfor extension in config['extensions']:\n for section in ['condition', 'parameters', 'cases']:\n DictUtils.ensure_exists(extension, section, {})\nfor var_name in variables:\n config['variables']... | <|body_start_0|>
for section in ['parameters', 'variables', 'extensions']:
DictUtils.ensure_exists(config, section, {})
for extension in config['extensions']:
for section in ['condition', 'parameters', 'cases']:
DictUtils.ensure_exists(extension, section, {})
... | Builds experiments' plans but does not compute their variables. | Builder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Builder:
"""Builds experiments' plans but does not compute their variables."""
def build(config, params, variables):
"""Given input configuration and command line parameters/variables build experiments Args: config (dict): Dictionary of parameters/variables/extensions params (dict): ... | stack_v2_sparse_classes_36k_train_031265 | 10,549 | permissive | [
{
"docstring": "Given input configuration and command line parameters/variables build experiments Args: config (dict): Dictionary of parameters/variables/extensions params (dict): Dictionary of command line parameters variables (dict): Dictionary of command line variables Returns: list: Array of experiments. Ea... | 4 | stack_v2_sparse_classes_30k_train_010726 | Implement the Python class `Builder` described below.
Class description:
Builds experiments' plans but does not compute their variables.
Method signatures and docstrings:
- def build(config, params, variables): Given input configuration and command line parameters/variables build experiments Args: config (dict): Dict... | Implement the Python class `Builder` described below.
Class description:
Builds experiments' plans but does not compute their variables.
Method signatures and docstrings:
- def build(config, params, variables): Given input configuration and command line parameters/variables build experiments Args: config (dict): Dict... | 834350c81154e48af132b7d27874e30a7b80a78c | <|skeleton|>
class Builder:
"""Builds experiments' plans but does not compute their variables."""
def build(config, params, variables):
"""Given input configuration and command line parameters/variables build experiments Args: config (dict): Dictionary of parameters/variables/extensions params (dict): ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Builder:
"""Builds experiments' plans but does not compute their variables."""
def build(config, params, variables):
"""Given input configuration and command line parameters/variables build experiments Args: config (dict): Dictionary of parameters/variables/extensions params (dict): Dictionary of... | the_stack_v2_python_sparse | python/dlbs/builder.py | HewlettPackard/dlcookbook-dlbs | train | 132 |
604302862d9d71679915f730cb6233360bbd34a0 | [
"super(skip_connect, self).__init__()\ndesc.channel_in = desc.C\ndesc.channel_out = desc.C\nself.desc = desc",
"if self.desc.stride == 1:\n return Identity()(x)\nelse:\n return FactorizedReduce(self.desc)(x, training=training)"
] | <|body_start_0|>
super(skip_connect, self).__init__()
desc.channel_in = desc.C
desc.channel_out = desc.C
self.desc = desc
<|end_body_0|>
<|body_start_1|>
if self.desc.stride == 1:
return Identity()(x)
else:
return FactorizedReduce(self.desc)(x, tr... | Class of skip connect. :param desc: description of skip_connect :type desc: Config | skip_connect | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class skip_connect:
"""Class of skip connect. :param desc: description of skip_connect :type desc: Config"""
def __init__(self, desc):
"""Init skip_connect."""
<|body_0|>
def __call__(self, x, training):
"""Forward function of skip_connect."""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_031266 | 9,137 | permissive | [
{
"docstring": "Init skip_connect.",
"name": "__init__",
"signature": "def __init__(self, desc)"
},
{
"docstring": "Forward function of skip_connect.",
"name": "__call__",
"signature": "def __call__(self, x, training)"
}
] | 2 | null | Implement the Python class `skip_connect` described below.
Class description:
Class of skip connect. :param desc: description of skip_connect :type desc: Config
Method signatures and docstrings:
- def __init__(self, desc): Init skip_connect.
- def __call__(self, x, training): Forward function of skip_connect. | Implement the Python class `skip_connect` described below.
Class description:
Class of skip connect. :param desc: description of skip_connect :type desc: Config
Method signatures and docstrings:
- def __init__(self, desc): Init skip_connect.
- def __call__(self, x, training): Forward function of skip_connect.
<|skel... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class skip_connect:
"""Class of skip connect. :param desc: description of skip_connect :type desc: Config"""
def __init__(self, desc):
"""Init skip_connect."""
<|body_0|>
def __call__(self, x, training):
"""Forward function of skip_connect."""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class skip_connect:
"""Class of skip connect. :param desc: description of skip_connect :type desc: Config"""
def __init__(self, desc):
"""Init skip_connect."""
super(skip_connect, self).__init__()
desc.channel_in = desc.C
desc.channel_out = desc.C
self.desc = desc
d... | the_stack_v2_python_sparse | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/search_space/networks/tensorflow/blocks/darts_ops.py | Huawei-Ascend/modelzoo | train | 1 |
ae8d8edf697aafed9bb5dbb4c318b53b0bf4417d | [
"tiling_options = {'verbose': 0, 'mode': 'LARS', 'print_summary': True}\nself.problem = dict(problem.items() + {'tiling_options': tiling_options}.items())\nnp.random.seed(problem['random_seed'])\nrandom_state = np.random.get_state()\nself.problem['random_state'] = random_state\nA, y, u_real, v_real = create_specifi... | <|body_start_0|>
tiling_options = {'verbose': 0, 'mode': 'LARS', 'print_summary': True}
self.problem = dict(problem.items() + {'tiling_options': tiling_options}.items())
np.random.seed(problem['random_seed'])
random_state = np.random.get_state()
self.problem['random_state'] = ran... | Test class implementing a test that compares the tiling results with the scipy implementation of the lars algorithm. Concretely, we use the problem setup defined in the beginning of this file, and we create the support tiling for this problem. Afterwards, we run the scipy-lars algorithm for each single beta in the list... | CompareToScipyLARSTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompareToScipyLARSTestCase:
"""Test class implementing a test that compares the tiling results with the scipy implementation of the lars algorithm. Concretely, we use the problem setup defined in the beginning of this file, and we create the support tiling for this problem. Afterwards, we run the... | stack_v2_sparse_classes_36k_train_031267 | 9,738 | no_license | [
{
"docstring": "Set up for the tests by calculating the tiling and the lars-path for some distinct beta's given in problem['betas_to_test'].",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests the support and sign pattern equality of the scipy implementation and our tiling... | 2 | stack_v2_sparse_classes_30k_train_010169 | Implement the Python class `CompareToScipyLARSTestCase` described below.
Class description:
Test class implementing a test that compares the tiling results with the scipy implementation of the lars algorithm. Concretely, we use the problem setup defined in the beginning of this file, and we create the support tiling f... | Implement the Python class `CompareToScipyLARSTestCase` described below.
Class description:
Test class implementing a test that compares the tiling results with the scipy implementation of the lars algorithm. Concretely, we use the problem setup defined in the beginning of this file, and we create the support tiling f... | 2238f0a2bdd4c5acb01564977eada2be8450f413 | <|skeleton|>
class CompareToScipyLARSTestCase:
"""Test class implementing a test that compares the tiling results with the scipy implementation of the lars algorithm. Concretely, we use the problem setup defined in the beginning of this file, and we create the support tiling for this problem. Afterwards, we run the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompareToScipyLARSTestCase:
"""Test class implementing a test that compares the tiling results with the scipy implementation of the lars algorithm. Concretely, we use the problem setup defined in the beginning of this file, and we create the support tiling for this problem. Afterwards, we run the scipy-lars a... | the_stack_v2_python_sparse | test_utils/test_scipy_comparison.py | soply/mpgraph | train | 0 |
ccee0d533b8ff28049f232b8de54df919b3f2c2c | [
"BaseIO.__init__(self)\nself._filename = filename\nself._path, file = os.path.split(filename)\nself._kwik = h5py.File(filename, 'r')\nself._dataset = dataset\ntry:\n rawfile = self._kwik['recordings'][str(self._dataset)]['raw'].attrs['hdf5_path']\n rawfile = rawfile.split('/')[0]\nexcept:\n rawfile = file.... | <|body_start_0|>
BaseIO.__init__(self)
self._filename = filename
self._path, file = os.path.split(filename)
self._kwik = h5py.File(filename, 'r')
self._dataset = dataset
try:
rawfile = self._kwik['recordings'][str(self._dataset)]['raw'].attrs['hdf5_path']
... | Class for "reading" experimental data from a .kwik file. Generates a :class:`Segment` with a :class:`AnalogSignal` | KwikIO | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KwikIO:
"""Class for "reading" experimental data from a .kwik file. Generates a :class:`Segment` with a :class:`AnalogSignal`"""
def __init__(self, filename, dataset=0):
"""Arguments: filename : the filename dataset: points to a specific dataset in the .kwik and .raw.kwd file, howeve... | stack_v2_sparse_classes_36k_train_031268 | 6,675 | permissive | [
{
"docstring": "Arguments: filename : the filename dataset: points to a specific dataset in the .kwik and .raw.kwd file, however this can be an issue to change in e.g. OpenElectrophy or Spykeviewer",
"name": "__init__",
"signature": "def __init__(self, filename, dataset=0)"
},
{
"docstring": "Ar... | 3 | stack_v2_sparse_classes_30k_train_017158 | Implement the Python class `KwikIO` described below.
Class description:
Class for "reading" experimental data from a .kwik file. Generates a :class:`Segment` with a :class:`AnalogSignal`
Method signatures and docstrings:
- def __init__(self, filename, dataset=0): Arguments: filename : the filename dataset: points to ... | Implement the Python class `KwikIO` described below.
Class description:
Class for "reading" experimental data from a .kwik file. Generates a :class:`Segment` with a :class:`AnalogSignal`
Method signatures and docstrings:
- def __init__(self, filename, dataset=0): Arguments: filename : the filename dataset: points to ... | e06cda2bd4ec849655de76bea563c597fbdb41e3 | <|skeleton|>
class KwikIO:
"""Class for "reading" experimental data from a .kwik file. Generates a :class:`Segment` with a :class:`AnalogSignal`"""
def __init__(self, filename, dataset=0):
"""Arguments: filename : the filename dataset: points to a specific dataset in the .kwik and .raw.kwd file, howeve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KwikIO:
"""Class for "reading" experimental data from a .kwik file. Generates a :class:`Segment` with a :class:`AnalogSignal`"""
def __init__(self, filename, dataset=0):
"""Arguments: filename : the filename dataset: points to a specific dataset in the .kwik and .raw.kwd file, however this can be... | the_stack_v2_python_sparse | pore_stats/rp/python-neo-master/neo/io/kwikio.py | codycombs/pore_stats | train | 0 |
3f7b4585e9401281aa943f9ca27943bf5da85d90 | [
"if not arr:\n return 0\nif len(arr) == 1:\n return len(arr[0])\nresult = [0]\nself.max_unique(arr, 0, '', result)\nreturn result[0]",
"if index == len(arr) and self.unique_chars(current) > result[0]:\n result[0] = self.unique_chars(current)\n return\nif index == len(arr):\n return\nself.max_unique... | <|body_start_0|>
if not arr:
return 0
if len(arr) == 1:
return len(arr[0])
result = [0]
self.max_unique(arr, 0, '', result)
return result[0]
<|end_body_0|>
<|body_start_1|>
if index == len(arr) and self.unique_chars(current) > result[0]:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxLength(self, arr):
""":type arr: List[str] :rtype: int"""
<|body_0|>
def max_unique(self, arr, index, current, result):
"""Finds the max possible length of s"""
<|body_1|>
def unique_chars(self, word):
"""Returns the length of th... | stack_v2_sparse_classes_36k_train_031269 | 1,214 | permissive | [
{
"docstring": ":type arr: List[str] :rtype: int",
"name": "maxLength",
"signature": "def maxLength(self, arr)"
},
{
"docstring": "Finds the max possible length of s",
"name": "max_unique",
"signature": "def max_unique(self, arr, index, current, result)"
},
{
"docstring": "Return... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxLength(self, arr): :type arr: List[str] :rtype: int
- def max_unique(self, arr, index, current, result): Finds the max possible length of s
- def unique_chars(self, word):... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxLength(self, arr): :type arr: List[str] :rtype: int
- def max_unique(self, arr, index, current, result): Finds the max possible length of s
- def unique_chars(self, word):... | 547c200b627c774535bc22880b16d5390183aeba | <|skeleton|>
class Solution:
def maxLength(self, arr):
""":type arr: List[str] :rtype: int"""
<|body_0|>
def max_unique(self, arr, index, current, result):
"""Finds the max possible length of s"""
<|body_1|>
def unique_chars(self, word):
"""Returns the length of th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxLength(self, arr):
""":type arr: List[str] :rtype: int"""
if not arr:
return 0
if len(arr) == 1:
return len(arr[0])
result = [0]
self.max_unique(arr, 0, '', result)
return result[0]
def max_unique(self, arr, index, c... | the_stack_v2_python_sparse | medium/1239_maximum_length_of_a_concatenated_string_with_unique_characters.py | Sukhrobjon/leetcode | train | 0 | |
b440031b04c5b4903fe6ceaa3758f2c070590a9f | [
"legal_moves = game.get_legal_moves()\nif not legal_moves:\n return (-1, -1)\nif game.move_count == 0:\n return (int(game.height / 2), int(game.width / 2))\nbest_move = (-1, -1)\nself.time_left = time_left\ntry:\n _, greedy_move = max([(self.score(game.forecast_move(m), self), m) for m in legal_moves])\n ... | <|body_start_0|>
legal_moves = game.get_legal_moves()
if not legal_moves:
return (-1, -1)
if game.move_count == 0:
return (int(game.height / 2), int(game.width / 2))
best_move = (-1, -1)
self.time_left = time_left
try:
_, greedy_move = ... | Game-playing agent that chooses a move using depth-limited minimax search. You must finish and test this player to make sure it properly uses minimax to return a good move before the search time limit expires. | MinimaxPlayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinimaxPlayer:
"""Game-playing agent that chooses a move using depth-limited minimax search. You must finish and test this player to make sure it properly uses minimax to return a good move before the search time limit expires."""
def get_move(self, game, time_left):
"""Search for th... | stack_v2_sparse_classes_36k_train_031270 | 26,094 | no_license | [
{
"docstring": "Search for the best move from the available legal moves and return a result before the time limit expires. NOTE: This function has been modified from the original version in the following ways: 1. Implements iterative deepening, using the same approach as AlphaBeta. Not clear whether this was ac... | 2 | stack_v2_sparse_classes_30k_test_001106 | Implement the Python class `MinimaxPlayer` described below.
Class description:
Game-playing agent that chooses a move using depth-limited minimax search. You must finish and test this player to make sure it properly uses minimax to return a good move before the search time limit expires.
Method signatures and docstri... | Implement the Python class `MinimaxPlayer` described below.
Class description:
Game-playing agent that chooses a move using depth-limited minimax search. You must finish and test this player to make sure it properly uses minimax to return a good move before the search time limit expires.
Method signatures and docstri... | a641d875e7bc321e5a892b95a764ae61bf127aff | <|skeleton|>
class MinimaxPlayer:
"""Game-playing agent that chooses a move using depth-limited minimax search. You must finish and test this player to make sure it properly uses minimax to return a good move before the search time limit expires."""
def get_move(self, game, time_left):
"""Search for th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MinimaxPlayer:
"""Game-playing agent that chooses a move using depth-limited minimax search. You must finish and test this player to make sure it properly uses minimax to return a good move before the search time limit expires."""
def get_move(self, game, time_left):
"""Search for the best move f... | the_stack_v2_python_sparse | Isolation/game_agent.py | bobradov/AI | train | 0 |
d036b6e2af8f8406331834288d38908bf32e2362 | [
"if v is None:\n return default\nelif v == '':\n return default\nelif column.illegal_value and str(v) == str(column.illegal_value):\n return default\nelif isinstance(v, basestring) and v.startswith('!'):\n return -2\nelif isinstance(v, basestring) and v.startswith('#'):\n return -3\nelse:\n return... | <|body_start_0|>
if v is None:
return default
elif v == '':
return default
elif column.illegal_value and str(v) == str(column.illegal_value):
return default
elif isinstance(v, basestring) and v.startswith('!'):
return -2
elif isinst... | Transformation that condsiders the special codes that the Census data may have in integer fields. | CensusTransform | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CensusTransform:
"""Transformation that condsiders the special codes that the Census data may have in integer fields."""
def census_defaults(v, column, default, f):
"""Basic defaults method, using only the column default and illegal_value parameters. WIll also convert blanks and None... | stack_v2_sparse_classes_36k_train_031271 | 17,438 | permissive | [
{
"docstring": "Basic defaults method, using only the column default and illegal_value parameters. WIll also convert blanks and None to the default",
"name": "census_defaults",
"signature": "def census_defaults(v, column, default, f)"
},
{
"docstring": "A Transform that is designed for the US Ce... | 2 | null | Implement the Python class `CensusTransform` described below.
Class description:
Transformation that condsiders the special codes that the Census data may have in integer fields.
Method signatures and docstrings:
- def census_defaults(v, column, default, f): Basic defaults method, using only the column default and il... | Implement the Python class `CensusTransform` described below.
Class description:
Transformation that condsiders the special codes that the Census data may have in integer fields.
Method signatures and docstrings:
- def census_defaults(v, column, default, f): Basic defaults method, using only the column default and il... | ae865245128b92693d654fbdbb3efc9ef29e9745 | <|skeleton|>
class CensusTransform:
"""Transformation that condsiders the special codes that the Census data may have in integer fields."""
def census_defaults(v, column, default, f):
"""Basic defaults method, using only the column default and illegal_value parameters. WIll also convert blanks and None... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CensusTransform:
"""Transformation that condsiders the special codes that the Census data may have in integer fields."""
def census_defaults(v, column, default, f):
"""Basic defaults method, using only the column default and illegal_value parameters. WIll also convert blanks and None to the defau... | the_stack_v2_python_sparse | ambry/transform.py | kball/ambry | train | 1 |
52fd70b5ec0c2c41447eef1deebb67fdbd9c3d23 | [
"if len(s) < 1:\n return ''\nmin_word, max_word = (s[0], s[0])\nfor word in s:\n if min_word > word:\n min_word = word\n if max_word < word:\n max_word = word\nlength = min(len(min_word), len(max_word))\nindex = 0\nfor i in range(length):\n if min_word[i] == max_word[i]:\n index += ... | <|body_start_0|>
if len(s) < 1:
return ''
min_word, max_word = (s[0], s[0])
for word in s:
if min_word > word:
min_word = word
if max_word < word:
max_word = word
length = min(len(min_word), len(max_word))
index ... | String | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class String:
def longest_common_prefix_(self, s: str) -> str:
"""Approach: Linear Time Complexity: O(N + M) Space Complexity: O(1) :param s: :return:"""
<|body_0|>
def longest_common_prefix(self, s: str) -> str:
"""Approach: Binary Search Time Complexity: O(S log m) S - s... | stack_v2_sparse_classes_36k_train_031272 | 1,641 | no_license | [
{
"docstring": "Approach: Linear Time Complexity: O(N + M) Space Complexity: O(1) :param s: :return:",
"name": "longest_common_prefix_",
"signature": "def longest_common_prefix_(self, s: str) -> str"
},
{
"docstring": "Approach: Binary Search Time Complexity: O(S log m) S - sum of all characters... | 2 | null | Implement the Python class `String` described below.
Class description:
Implement the String class.
Method signatures and docstrings:
- def longest_common_prefix_(self, s: str) -> str: Approach: Linear Time Complexity: O(N + M) Space Complexity: O(1) :param s: :return:
- def longest_common_prefix(self, s: str) -> str... | Implement the Python class `String` described below.
Class description:
Implement the String class.
Method signatures and docstrings:
- def longest_common_prefix_(self, s: str) -> str: Approach: Linear Time Complexity: O(N + M) Space Complexity: O(1) :param s: :return:
- def longest_common_prefix(self, s: str) -> str... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class String:
def longest_common_prefix_(self, s: str) -> str:
"""Approach: Linear Time Complexity: O(N + M) Space Complexity: O(1) :param s: :return:"""
<|body_0|>
def longest_common_prefix(self, s: str) -> str:
"""Approach: Binary Search Time Complexity: O(S log m) S - s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class String:
def longest_common_prefix_(self, s: str) -> str:
"""Approach: Linear Time Complexity: O(N + M) Space Complexity: O(1) :param s: :return:"""
if len(s) < 1:
return ''
min_word, max_word = (s[0], s[0])
for word in s:
if min_word > word:
... | the_stack_v2_python_sparse | revisited__2021/math_and_string/longest_common_prefix.py | Shiv2157k/leet_code | train | 1 | |
627c0d0d965037e8314d86819636404c5400c66a | [
"employees = pd.read_excel('data/Employees.xlsx', index_col='ID')\ndf = employees['Full Name'].str.split(expand=True)\nemployees['First Name'] = df[0]\nemployees['Last Name'] = df[1]\nprint(employees)",
"videos = pd.read_excel('data/Videos.xlsx', index_col='Month')\ntable = videos.T\nprint(table)"
] | <|body_start_0|>
employees = pd.read_excel('data/Employees.xlsx', index_col='ID')
df = employees['Full Name'].str.split(expand=True)
employees['First Name'] = df[0]
employees['Last Name'] = df[1]
print(employees)
<|end_body_0|>
<|body_start_1|>
videos = pd.read_excel('da... | UnitTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitTest:
def test_splitting_col_into_cols(self):
"""将一列数据分割成多列"""
<|body_0|>
def test_rotation(self):
"""行变列,列变行"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
employees = pd.read_excel('data/Employees.xlsx', index_col='ID')
df = employees... | stack_v2_sparse_classes_36k_train_031273 | 868 | no_license | [
{
"docstring": "将一列数据分割成多列",
"name": "test_splitting_col_into_cols",
"signature": "def test_splitting_col_into_cols(self)"
},
{
"docstring": "行变列,列变行",
"name": "test_rotation",
"signature": "def test_rotation(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011144 | Implement the Python class `UnitTest` described below.
Class description:
Implement the UnitTest class.
Method signatures and docstrings:
- def test_splitting_col_into_cols(self): 将一列数据分割成多列
- def test_rotation(self): 行变列,列变行 | Implement the Python class `UnitTest` described below.
Class description:
Implement the UnitTest class.
Method signatures and docstrings:
- def test_splitting_col_into_cols(self): 将一列数据分割成多列
- def test_rotation(self): 行变列,列变行
<|skeleton|>
class UnitTest:
def test_splitting_col_into_cols(self):
"""将一列数据分... | c0cc9a2050b9b564e71aab571a6025522bf7b0b0 | <|skeleton|>
class UnitTest:
def test_splitting_col_into_cols(self):
"""将一列数据分割成多列"""
<|body_0|>
def test_rotation(self):
"""行变列,列变行"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnitTest:
def test_splitting_col_into_cols(self):
"""将一列数据分割成多列"""
employees = pd.read_excel('data/Employees.xlsx', index_col='ID')
df = employees['Full Name'].str.split(expand=True)
employees['First Name'] = df[0]
employees['Last Name'] = df[1]
print(employees)... | the_stack_v2_python_sparse | pandas/transformation.py | ruanhao/python-for-fun | train | 0 | |
24975956c40bd648db2d4635df1a3329c7feff59 | [
"self.file = TFile(fnam)\nif self.file.IsZombie():\n raise ValueError(fnam + ' cannot be opened')\nself.hist = self.file.Get(histnam)\nif self.hist == None:\n raise ValueError('{h} cannot be found in {f}'.format(h=histnam, f=fnam))",
"eta = p4.eta()\npt = p4.pt()\nreturn pt * self.correction_factor(pt, eta)... | <|body_start_0|>
self.file = TFile(fnam)
if self.file.IsZombie():
raise ValueError(fnam + ' cannot be opened')
self.hist = self.file.Get(histnam)
if self.hist == None:
raise ValueError('{h} cannot be found in {f}'.format(h=histnam, f=fnam))
<|end_body_0|>
<|body_... | Generic energy corrector | EnergyCorrector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnergyCorrector:
"""Generic energy corrector"""
def __init__(self, fnam, histnam='h_cor'):
"""fnam is a root file containing a 1D histogram giving the correction factor as a function of eta."""
<|body_0|>
def correct_p4(self, p4):
"""returns the corrected 4-momen... | stack_v2_sparse_classes_36k_train_031274 | 1,532 | permissive | [
{
"docstring": "fnam is a root file containing a 1D histogram giving the correction factor as a function of eta.",
"name": "__init__",
"signature": "def __init__(self, fnam, histnam='h_cor')"
},
{
"docstring": "returns the corrected 4-momentum. The 4 momentum is expected to behave as the one of ... | 3 | stack_v2_sparse_classes_30k_train_006232 | Implement the Python class `EnergyCorrector` described below.
Class description:
Generic energy corrector
Method signatures and docstrings:
- def __init__(self, fnam, histnam='h_cor'): fnam is a root file containing a 1D histogram giving the correction factor as a function of eta.
- def correct_p4(self, p4): returns ... | Implement the Python class `EnergyCorrector` described below.
Class description:
Generic energy corrector
Method signatures and docstrings:
- def __init__(self, fnam, histnam='h_cor'): fnam is a root file containing a 1D histogram giving the correction factor as a function of eta.
- def correct_p4(self, p4): returns ... | 19c178740257eb48367778593da55dcad08b7a4f | <|skeleton|>
class EnergyCorrector:
"""Generic energy corrector"""
def __init__(self, fnam, histnam='h_cor'):
"""fnam is a root file containing a 1D histogram giving the correction factor as a function of eta."""
<|body_0|>
def correct_p4(self, p4):
"""returns the corrected 4-momen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnergyCorrector:
"""Generic energy corrector"""
def __init__(self, fnam, histnam='h_cor'):
"""fnam is a root file containing a 1D histogram giving the correction factor as a function of eta."""
self.file = TFile(fnam)
if self.file.IsZombie():
raise ValueError(fnam + ' ... | the_stack_v2_python_sparse | PhysicsTools/Heppy/python/physicsutils/EnergyCorrector.py | cms-sw/cmssw | train | 1,006 |
9a1f2fb214ff2a3c00f4efb85d24daebcd30eac4 | [
"url = self.l + read_yaml()[9]['url1']\nresult = get_shares_contacts(url=url, contacts_id=self.contacts_id, header=self.header)\nself.assertEqual(0, result['code'])",
"url = self.l + read_yaml()[9]['url2']\nmember_id = readconfig('member_id')\nresult = contactShare(url=url, contacts_id=self.contacts_id, header=se... | <|body_start_0|>
url = self.l + read_yaml()[9]['url1']
result = get_shares_contacts(url=url, contacts_id=self.contacts_id, header=self.header)
self.assertEqual(0, result['code'])
<|end_body_0|>
<|body_start_1|>
url = self.l + read_yaml()[9]['url2']
member_id = readconfig('member... | TestContactShare | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestContactShare:
def test_getcontactshare(self):
"""共享联系,接口地址:/api/scrm/getSharesContacts"""
<|body_0|>
def test_contactshare(self):
"""共享联系,接口地址:/api/scrm/contactShare"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
url = self.l + read_yaml()[9]['... | stack_v2_sparse_classes_36k_train_031275 | 880 | no_license | [
{
"docstring": "共享联系,接口地址:/api/scrm/getSharesContacts",
"name": "test_getcontactshare",
"signature": "def test_getcontactshare(self)"
},
{
"docstring": "共享联系,接口地址:/api/scrm/contactShare",
"name": "test_contactshare",
"signature": "def test_contactshare(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005048 | Implement the Python class `TestContactShare` described below.
Class description:
Implement the TestContactShare class.
Method signatures and docstrings:
- def test_getcontactshare(self): 共享联系,接口地址:/api/scrm/getSharesContacts
- def test_contactshare(self): 共享联系,接口地址:/api/scrm/contactShare | Implement the Python class `TestContactShare` described below.
Class description:
Implement the TestContactShare class.
Method signatures and docstrings:
- def test_getcontactshare(self): 共享联系,接口地址:/api/scrm/getSharesContacts
- def test_contactshare(self): 共享联系,接口地址:/api/scrm/contactShare
<|skeleton|>
class TestCont... | 75f18afa6d74cb1916a2496d1a1f267bf8ddb93c | <|skeleton|>
class TestContactShare:
def test_getcontactshare(self):
"""共享联系,接口地址:/api/scrm/getSharesContacts"""
<|body_0|>
def test_contactshare(self):
"""共享联系,接口地址:/api/scrm/contactShare"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestContactShare:
def test_getcontactshare(self):
"""共享联系,接口地址:/api/scrm/getSharesContacts"""
url = self.l + read_yaml()[9]['url1']
result = get_shares_contacts(url=url, contacts_id=self.contacts_id, header=self.header)
self.assertEqual(0, result['code'])
def test_contacts... | the_stack_v2_python_sparse | Test_case/test_7contactShare.py | jiangna123000/api_test_case | train | 0 | |
69d9d58a9ba83a6337092f15bad56672e3365243 | [
"size = len(nums)\ndp = [0] * (size + 1)\nif size:\n dp[1] = nums[0]\nfor i in range(2, size + 1):\n dp[i] = max(dp[i - 1], dp[i - 2] + nums[i - 1])\nreturn dp[size]",
"last, now = (0, 0)\nfor num in nums:\n last, now = (now, max(last + num, now))\nreturn now"
] | <|body_start_0|>
size = len(nums)
dp = [0] * (size + 1)
if size:
dp[1] = nums[0]
for i in range(2, size + 1):
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i - 1])
return dp[size]
<|end_body_0|>
<|body_start_1|>
last, now = (0, 0)
for num in num... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def houseRobber(self, nums):
"""动态转移方程:dp[i] = max(dp[i-1], dp[i-2]+nums[i]) dp[i]表示打劫到第i家的时候,累计取得的金钱最大值 :param nums: :return:"""
<|body_0|>
def house_robber(self, nums):
""":param nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_031276 | 928 | no_license | [
{
"docstring": "动态转移方程:dp[i] = max(dp[i-1], dp[i-2]+nums[i]) dp[i]表示打劫到第i家的时候,累计取得的金钱最大值 :param nums: :return:",
"name": "houseRobber",
"signature": "def houseRobber(self, nums)"
},
{
"docstring": ":param nums: :return:",
"name": "house_robber",
"signature": "def house_robber(self, nums)... | 2 | stack_v2_sparse_classes_30k_train_016385 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def houseRobber(self, nums): 动态转移方程:dp[i] = max(dp[i-1], dp[i-2]+nums[i]) dp[i]表示打劫到第i家的时候,累计取得的金钱最大值 :param nums: :return:
- def house_robber(self, nums): :param nums: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def houseRobber(self, nums): 动态转移方程:dp[i] = max(dp[i-1], dp[i-2]+nums[i]) dp[i]表示打劫到第i家的时候,累计取得的金钱最大值 :param nums: :return:
- def house_robber(self, nums): :param nums: :return:
... | 215d513b3564a7a76db3d2b29e4acc341a68e8ee | <|skeleton|>
class Solution:
def houseRobber(self, nums):
"""动态转移方程:dp[i] = max(dp[i-1], dp[i-2]+nums[i]) dp[i]表示打劫到第i家的时候,累计取得的金钱最大值 :param nums: :return:"""
<|body_0|>
def house_robber(self, nums):
""":param nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def houseRobber(self, nums):
"""动态转移方程:dp[i] = max(dp[i-1], dp[i-2]+nums[i]) dp[i]表示打劫到第i家的时候,累计取得的金钱最大值 :param nums: :return:"""
size = len(nums)
dp = [0] * (size + 1)
if size:
dp[1] = nums[0]
for i in range(2, size + 1):
dp[i] = max(d... | the_stack_v2_python_sparse | python/dp/house-robber.py | euxuoh/leetcode | train | 0 | |
59fbd7ac47e2c78c1d0774a7ccff2ef292d66330 | [
"custom_module_count = termite_models.TemplateCustomModule.objects.filter(owner=request.manager, is_deleted=False).count()\nif custom_module_count > 0:\n has_custom_module = True\nelse:\n has_custom_module = False\nc = RequestContext(request, {'first_nav_name': FIRST_NAV, 'second_navs': export.get_wepage_seco... | <|body_start_0|>
custom_module_count = termite_models.TemplateCustomModule.objects.filter(owner=request.manager, is_deleted=False).count()
if custom_module_count > 0:
has_custom_module = True
else:
has_custom_module = False
c = RequestContext(request, {'first_nav_... | 自定义模块列表 | CustomModules | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomModules:
"""自定义模块列表"""
def get(request):
"""获取自定义模块"""
<|body_0|>
def api_get(request):
"""获取自定义模块的json表示"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
custom_module_count = termite_models.TemplateCustomModule.objects.filter(owner=reques... | stack_v2_sparse_classes_36k_train_031277 | 2,585 | no_license | [
{
"docstring": "获取自定义模块",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "获取自定义模块的json表示",
"name": "api_get",
"signature": "def api_get(request)"
}
] | 2 | null | Implement the Python class `CustomModules` described below.
Class description:
自定义模块列表
Method signatures and docstrings:
- def get(request): 获取自定义模块
- def api_get(request): 获取自定义模块的json表示 | Implement the Python class `CustomModules` described below.
Class description:
自定义模块列表
Method signatures and docstrings:
- def get(request): 获取自定义模块
- def api_get(request): 获取自定义模块的json表示
<|skeleton|>
class CustomModules:
"""自定义模块列表"""
def get(request):
"""获取自定义模块"""
<|body_0|>
def api_... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class CustomModules:
"""自定义模块列表"""
def get(request):
"""获取自定义模块"""
<|body_0|>
def api_get(request):
"""获取自定义模块的json表示"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomModules:
"""自定义模块列表"""
def get(request):
"""获取自定义模块"""
custom_module_count = termite_models.TemplateCustomModule.objects.filter(owner=request.manager, is_deleted=False).count()
if custom_module_count > 0:
has_custom_module = True
else:
has_cus... | the_stack_v2_python_sparse | weapp/termite2/custom_module/custom_modules.py | chengdg/weizoom | train | 1 |
40bab044a5a1c1841d074f3a8e787b40207b71ce | [
"if search('^GET.*\\\\?.*' + self.httpIDRE, packet.payload, I) != None:\n return True\nelse:\n return False",
"if search('^GET.*\\\\?.*(;.*)*--.*' + self.httpIDRE, packet.payload, I) != None:\n return True\nelse:\n return False",
"sqlKeyWords = ['ADD', 'EXCEPT', 'PERCENT', 'ALL', 'EXEC', 'PLAN', 'AL... | <|body_start_0|>
if search('^GET.*\\?.*' + self.httpIDRE, packet.payload, I) != None:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
if search('^GET.*\\?.*(;.*)*--.*' + self.httpIDRE, packet.payload, I) != None:
return True
else:
... | SQLInjectionAnalyzer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLInjectionAnalyzer:
def isQuery(self, packet):
"""Returns True if the packet is an HTTP GET that looks like it has a query in it. @param packet - The packet to search in"""
<|body_0|>
def hasSQLComment(self, packet):
"""Returns True if the packet is an HTTP GET tha... | stack_v2_sparse_classes_36k_train_031278 | 7,144 | no_license | [
{
"docstring": "Returns True if the packet is an HTTP GET that looks like it has a query in it. @param packet - The packet to search in",
"name": "isQuery",
"signature": "def isQuery(self, packet)"
},
{
"docstring": "Returns True if the packet is an HTTP GET that looks like it has an sql comment... | 4 | stack_v2_sparse_classes_30k_train_015815 | Implement the Python class `SQLInjectionAnalyzer` described below.
Class description:
Implement the SQLInjectionAnalyzer class.
Method signatures and docstrings:
- def isQuery(self, packet): Returns True if the packet is an HTTP GET that looks like it has a query in it. @param packet - The packet to search in
- def h... | Implement the Python class `SQLInjectionAnalyzer` described below.
Class description:
Implement the SQLInjectionAnalyzer class.
Method signatures and docstrings:
- def isQuery(self, packet): Returns True if the packet is an HTTP GET that looks like it has a query in it. @param packet - The packet to search in
- def h... | 418abe9a105bfd1f54d420466a7ddb5318695a79 | <|skeleton|>
class SQLInjectionAnalyzer:
def isQuery(self, packet):
"""Returns True if the packet is an HTTP GET that looks like it has a query in it. @param packet - The packet to search in"""
<|body_0|>
def hasSQLComment(self, packet):
"""Returns True if the packet is an HTTP GET tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SQLInjectionAnalyzer:
def isQuery(self, packet):
"""Returns True if the packet is an HTTP GET that looks like it has a query in it. @param packet - The packet to search in"""
if search('^GET.*\\?.*' + self.httpIDRE, packet.payload, I) != None:
return True
else:
... | the_stack_v2_python_sparse | src/honeynet_web/packetAnalysis/analyzers/sqlinj.py | finitem/pig | train | 0 | |
08a37ffc8486237c81deda35bbb7eb1d9a87ef24 | [
"dict = defaultdict(list)\nfor i in range(len(nums)):\n dict[nums[i]].append(i)\ndegree = 0\nsubarray = dict.values()[0]\nfor value in dict.values():\n if len(value) > degree:\n degree = len(value)\n subarray = value\n elif len(value) == degree:\n if value[-1] - value[0] < subarray[-1]... | <|body_start_0|>
dict = defaultdict(list)
for i in range(len(nums)):
dict[nums[i]].append(i)
degree = 0
subarray = dict.values()[0]
for value in dict.values():
if len(value) > degree:
degree = len(value)
subarray = value
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dict = defaultdict(list)
... | stack_v2_sparse_classes_36k_train_031279 | 1,173 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findShortestSubArray",
"signature": "def findShortestSubArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findShortestSubArray",
"signature": "def findShortestSubArray(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findShortestSubArray(self, nums): :type nums: List[int] :rtype: int
- def findShortestSubArray(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findShortestSubArray(self, nums): :type nums: List[int] :rtype: int
- def findShortestSubArray(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
dict = defaultdict(list)
for i in range(len(nums)):
dict[nums[i]].append(i)
degree = 0
subarray = dict.values()[0]
for value in dict.values():
if len(... | the_stack_v2_python_sparse | 0697_Degree_of_an_Array.py | bingli8802/leetcode | train | 0 | |
96b316984e58f7aeac9c9ece573eb3387602c0c4 | [
"user = None\nif auth.is_client_role():\n user = g.user\nprojects = Project.find_all_or_by_user(user)\nreturn (jsonify({'projects': projects}), HTTPStatus.OK)",
"project_json = request.get_json()\ntry:\n user = g.user\n project_schema = ProjectSchema()\n dict_data = project_schema.load(project_json)\n... | <|body_start_0|>
user = None
if auth.is_client_role():
user = g.user
projects = Project.find_all_or_by_user(user)
return (jsonify({'projects': projects}), HTTPStatus.OK)
<|end_body_0|>
<|body_start_1|>
project_json = request.get_json()
try:
user =... | Resource for managing create project. | ProjectResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectResource:
"""Resource for managing create project."""
def get():
"""Get all project."""
<|body_0|>
def post():
"""Post a new project using the request body."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = None
if auth.is_cl... | stack_v2_sparse_classes_36k_train_031280 | 6,357 | permissive | [
{
"docstring": "Get all project.",
"name": "get",
"signature": "def get()"
},
{
"docstring": "Post a new project using the request body.",
"name": "post",
"signature": "def post()"
}
] | 2 | stack_v2_sparse_classes_30k_train_000817 | Implement the Python class `ProjectResource` described below.
Class description:
Resource for managing create project.
Method signatures and docstrings:
- def get(): Get all project.
- def post(): Post a new project using the request body. | Implement the Python class `ProjectResource` described below.
Class description:
Resource for managing create project.
Method signatures and docstrings:
- def get(): Get all project.
- def post(): Post a new project using the request body.
<|skeleton|>
class ProjectResource:
"""Resource for managing create proje... | 3bfe09c100a0f5b98d61228324336d5f45ad93ad | <|skeleton|>
class ProjectResource:
"""Resource for managing create project."""
def get():
"""Get all project."""
<|body_0|>
def post():
"""Post a new project using the request body."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectResource:
"""Resource for managing create project."""
def get():
"""Get all project."""
user = None
if auth.is_client_role():
user = g.user
projects = Project.find_all_or_by_user(user)
return (jsonify({'projects': projects}), HTTPStatus.OK)
... | the_stack_v2_python_sparse | selfservice-api/src/selfservice_api/resources/project.py | bcgov/BCSC-SS | train | 2 |
eb91aaefae2b9f54370dbe8db4d03cea4a8158e0 | [
"if k == 1:\n return 1\nli = [1, 1]\nSUM = li[-1] + li[-2]\nwhile SUM < k:\n SUM = li[-1] + li[-2]\n if SUM <= k:\n li.append(SUM)\ncnt = 0\nrem = k\ni = len(li) - 1\nwhile rem != 0:\n rem -= li[i]\n if rem == 0:\n cnt += 1\n return cnt\n elif rem > 0:\n cnt += 1\n ... | <|body_start_0|>
if k == 1:
return 1
li = [1, 1]
SUM = li[-1] + li[-2]
while SUM < k:
SUM = li[-1] + li[-2]
if SUM <= k:
li.append(SUM)
cnt = 0
rem = k
i = len(li) - 1
while rem != 0:
rem -= l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
<|body_0|>
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
<|body_1|>
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
... | stack_v2_sparse_classes_36k_train_031281 | 1,677 | no_license | [
{
"docstring": ":type k: int :rtype: int",
"name": "findMinFibonacciNumbers",
"signature": "def findMinFibonacciNumbers(self, k)"
},
{
"docstring": ":type k: int :rtype: int",
"name": "findMinFibonacciNumbers",
"signature": "def findMinFibonacciNumbers(self, k)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_016580 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinFibonacciNumbers(self, k): :type k: int :rtype: int
- def findMinFibonacciNumbers(self, k): :type k: int :rtype: int
- def findMinFibonacciNumbers(self, k): :type k: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinFibonacciNumbers(self, k): :type k: int :rtype: int
- def findMinFibonacciNumbers(self, k): :type k: int :rtype: int
- def findMinFibonacciNumbers(self, k): :type k: i... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
<|body_0|>
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
<|body_1|>
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMinFibonacciNumbers(self, k):
""":type k: int :rtype: int"""
if k == 1:
return 1
li = [1, 1]
SUM = li[-1] + li[-2]
while SUM < k:
SUM = li[-1] + li[-2]
if SUM <= k:
li.append(SUM)
cnt = 0
... | the_stack_v2_python_sparse | 1414_Find_the_Minimum_Number_of_Fibonacci_Numbers_Whose_Sum_Is_K.py | bingli8802/leetcode | train | 0 | |
9e59841cede13dfea67bb1b925f9d1112ff7335d | [
"field_string = ''\nif is_string(field_value):\n field_string = field_value.strip()\nelif isinstance(field_value, collections.abc.Mapping):\n field_string = field_value['@value']\n if '@language' in field_value and field_value['@language']:\n field_string += ' (' + field_value['@language'] + ')'\nre... | <|body_start_0|>
field_string = ''
if is_string(field_value):
field_string = field_value.strip()
elif isinstance(field_value, collections.abc.Mapping):
field_string = field_value['@value']
if '@language' in field_value and field_value['@language']:
... | Value mapper class for language-tagged text | TextLanguageValueMapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextLanguageValueMapper:
"""Value mapper class for language-tagged text"""
def encode(cls, field_value):
"""Encodes language-tagged string for display >>> TextLanguageValueMapper.encode("text") == "text" True >>> TextLanguageValueMapper.encode({ "@value": "text" }) == "text" True >>>... | stack_v2_sparse_classes_36k_train_031282 | 4,842 | permissive | [
{
"docstring": "Encodes language-tagged string for display >>> TextLanguageValueMapper.encode(\"text\") == \"text\" True >>> TextLanguageValueMapper.encode({ \"@value\": \"text\" }) == \"text\" True >>> TextLanguageValueMapper.encode({ \"@value\": \"text\", \"@language\": \"en\" }) == \"text (en)\" True >>> Tex... | 2 | stack_v2_sparse_classes_30k_train_014541 | Implement the Python class `TextLanguageValueMapper` described below.
Class description:
Value mapper class for language-tagged text
Method signatures and docstrings:
- def encode(cls, field_value): Encodes language-tagged string for display >>> TextLanguageValueMapper.encode("text") == "text" True >>> TextLanguageVa... | Implement the Python class `TextLanguageValueMapper` described below.
Class description:
Value mapper class for language-tagged text
Method signatures and docstrings:
- def encode(cls, field_value): Encodes language-tagged string for display >>> TextLanguageValueMapper.encode("text") == "text" True >>> TextLanguageVa... | 4e17e51fb0a1fdc40873b233641aac4e11576396 | <|skeleton|>
class TextLanguageValueMapper:
"""Value mapper class for language-tagged text"""
def encode(cls, field_value):
"""Encodes language-tagged string for display >>> TextLanguageValueMapper.encode("text") == "text" True >>> TextLanguageValueMapper.encode({ "@value": "text" }) == "text" True >>>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextLanguageValueMapper:
"""Value mapper class for language-tagged text"""
def encode(cls, field_value):
"""Encodes language-tagged string for display >>> TextLanguageValueMapper.encode("text") == "text" True >>> TextLanguageValueMapper.encode({ "@value": "text" }) == "text" True >>> TextLanguage... | the_stack_v2_python_sparse | src/annalist_root/annalist/views/fields/render_text_language.py | gklyne/annalist | train | 20 |
d1742ec12dc4bb8a2f78e3cb02a4f54815bdfcbc | [
"enum_descriptor = descriptor.EnumDescriptor()\nenum_descriptor.name = 'Empty'\nenum_class = definition.define_enum(enum_descriptor, 'whatever')\nself.assertEquals('Empty', enum_class.__name__)\nself.assertEquals('whatever', enum_class.__module__)\nself.assertEquals(enum_descriptor, descriptor.describe_enum(enum_cl... | <|body_start_0|>
enum_descriptor = descriptor.EnumDescriptor()
enum_descriptor.name = 'Empty'
enum_class = definition.define_enum(enum_descriptor, 'whatever')
self.assertEquals('Empty', enum_class.__name__)
self.assertEquals('whatever', enum_class.__module__)
self.assertE... | Test for define_enum. | DefineEnumTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefineEnumTest:
"""Test for define_enum."""
def testDefineEnum_Empty(self):
"""Test defining an empty enum."""
<|body_0|>
def testDefineEnum(self):
"""Test defining an enum."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
enum_descriptor = descr... | stack_v2_sparse_classes_36k_train_031283 | 23,499 | permissive | [
{
"docstring": "Test defining an empty enum.",
"name": "testDefineEnum_Empty",
"signature": "def testDefineEnum_Empty(self)"
},
{
"docstring": "Test defining an enum.",
"name": "testDefineEnum",
"signature": "def testDefineEnum(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003034 | Implement the Python class `DefineEnumTest` described below.
Class description:
Test for define_enum.
Method signatures and docstrings:
- def testDefineEnum_Empty(self): Test defining an empty enum.
- def testDefineEnum(self): Test defining an enum. | Implement the Python class `DefineEnumTest` described below.
Class description:
Test for define_enum.
Method signatures and docstrings:
- def testDefineEnum_Empty(self): Test defining an empty enum.
- def testDefineEnum(self): Test defining an enum.
<|skeleton|>
class DefineEnumTest:
"""Test for define_enum."""
... | 2cb4493d796746cb46c8519a100ef3ef128a761a | <|skeleton|>
class DefineEnumTest:
"""Test for define_enum."""
def testDefineEnum_Empty(self):
"""Test defining an empty enum."""
<|body_0|>
def testDefineEnum(self):
"""Test defining an enum."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefineEnumTest:
"""Test for define_enum."""
def testDefineEnum_Empty(self):
"""Test defining an empty enum."""
enum_descriptor = descriptor.EnumDescriptor()
enum_descriptor.name = 'Empty'
enum_class = definition.define_enum(enum_descriptor, 'whatever')
self.assertE... | the_stack_v2_python_sparse | src/lib/protorpc/definition_test.py | thonkify/thonkify | train | 17 |
37b1593fc0331627081f8e4d7f21800fc9a33983 | [
"pre = [1] * 5\ncur = pre\nfor i in range(1, n):\n for j in range(1, 5):\n cur[j] = cur[j - 1] + pre[j]\n pre = cur\nreturn sum(cur)",
"ret = 0\nvowels = 'aeiou'\ndq = collections.deque(list(vowels))\nwhile dq:\n node = dq.popleft()\n if len(node) == n:\n ret += 1\n continue\n ... | <|body_start_0|>
pre = [1] * 5
cur = pre
for i in range(1, n):
for j in range(1, 5):
cur[j] = cur[j - 1] + pre[j]
pre = cur
return sum(cur)
<|end_body_0|>
<|body_start_1|>
ret = 0
vowels = 'aeiou'
dq = collections.deque(lis... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countVowelStrings(self, n: int) -> int:
"""Runtime: 61 ms, faster than 26.05% Memory Usage: 13.9 MB, less than 65.31% 1 <= n <= 50 :param n: :return:"""
<|body_0|>
def countVowelStrings2(self, n: int) -> int:
"""1 <= n <= 50 LTE"""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_031284 | 1,363 | permissive | [
{
"docstring": "Runtime: 61 ms, faster than 26.05% Memory Usage: 13.9 MB, less than 65.31% 1 <= n <= 50 :param n: :return:",
"name": "countVowelStrings",
"signature": "def countVowelStrings(self, n: int) -> int"
},
{
"docstring": "1 <= n <= 50 LTE",
"name": "countVowelStrings2",
"signatu... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countVowelStrings(self, n: int) -> int: Runtime: 61 ms, faster than 26.05% Memory Usage: 13.9 MB, less than 65.31% 1 <= n <= 50 :param n: :return:
- def countVowelStrings2(se... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countVowelStrings(self, n: int) -> int: Runtime: 61 ms, faster than 26.05% Memory Usage: 13.9 MB, less than 65.31% 1 <= n <= 50 :param n: :return:
- def countVowelStrings2(se... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def countVowelStrings(self, n: int) -> int:
"""Runtime: 61 ms, faster than 26.05% Memory Usage: 13.9 MB, less than 65.31% 1 <= n <= 50 :param n: :return:"""
<|body_0|>
def countVowelStrings2(self, n: int) -> int:
"""1 <= n <= 50 LTE"""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countVowelStrings(self, n: int) -> int:
"""Runtime: 61 ms, faster than 26.05% Memory Usage: 13.9 MB, less than 65.31% 1 <= n <= 50 :param n: :return:"""
pre = [1] * 5
cur = pre
for i in range(1, n):
for j in range(1, 5):
cur[j] = cur[j ... | the_stack_v2_python_sparse | src/1641-CountSortedVowelStrings.py | Jiezhi/myleetcode | train | 1 | |
6c0da7cc92518ad56850358757ac147348052b6a | [
"self.pause_backup = pause_backup\nself.protected_source_uid = protected_source_uid\nself.rpo_policy_id = rpo_policy_id\nself.source_parameters = source_parameters",
"if dictionary is None:\n return None\npause_backup = dictionary.get('pauseBackup')\nprotected_source_uid = cohesity_management_sdk.models.univer... | <|body_start_0|>
self.pause_backup = pause_backup
self.protected_source_uid = protected_source_uid
self.rpo_policy_id = rpo_policy_id
self.source_parameters = source_parameters
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
pause_backup = ... | Implementation of the 'UpdateProtectionObjectParameters' model. Specifies the parameters to update a Protection Object. Attributes: pause_backup (bool): Specifies if the protection for the Protection Object is to be paused. protected_source_uid (UniversalId, required): Specifies the unique id of the Protected Source to... | UpdateProtectionObjectParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateProtectionObjectParameters:
"""Implementation of the 'UpdateProtectionObjectParameters' model. Specifies the parameters to update a Protection Object. Attributes: pause_backup (bool): Specifies if the protection for the Protection Object is to be paused. protected_source_uid (UniversalId, r... | stack_v2_sparse_classes_36k_train_031285 | 3,048 | permissive | [
{
"docstring": "Constructor for the UpdateProtectionObjectParameters class",
"name": "__init__",
"signature": "def __init__(self, pause_backup=None, protected_source_uid=None, rpo_policy_id=None, source_parameters=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args... | 2 | stack_v2_sparse_classes_30k_train_006622 | Implement the Python class `UpdateProtectionObjectParameters` described below.
Class description:
Implementation of the 'UpdateProtectionObjectParameters' model. Specifies the parameters to update a Protection Object. Attributes: pause_backup (bool): Specifies if the protection for the Protection Object is to be pause... | Implement the Python class `UpdateProtectionObjectParameters` described below.
Class description:
Implementation of the 'UpdateProtectionObjectParameters' model. Specifies the parameters to update a Protection Object. Attributes: pause_backup (bool): Specifies if the protection for the Protection Object is to be pause... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class UpdateProtectionObjectParameters:
"""Implementation of the 'UpdateProtectionObjectParameters' model. Specifies the parameters to update a Protection Object. Attributes: pause_backup (bool): Specifies if the protection for the Protection Object is to be paused. protected_source_uid (UniversalId, r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateProtectionObjectParameters:
"""Implementation of the 'UpdateProtectionObjectParameters' model. Specifies the parameters to update a Protection Object. Attributes: pause_backup (bool): Specifies if the protection for the Protection Object is to be paused. protected_source_uid (UniversalId, required): Spe... | the_stack_v2_python_sparse | cohesity_management_sdk/models/update_protection_object_parameters.py | cohesity/management-sdk-python | train | 24 |
6665c0325a9ca0af580e978b3b71c1c1ec3619e8 | [
"self.xcol = int(kwds.get('x', kwds.get('logx', 0)))\nself.ycol = int(kwds.get('y', kwds.get('logy', 1)))\nself.logx = 'logx' in kwds\nself.logy = 'logy' in kwds\nself.xdata, self.ydata = ([], [])",
"row = line.split()\ntry:\n self.xdata.append(float(row[self.xcol]))\n self.ydata.append(float(row[self.ycol]... | <|body_start_0|>
self.xcol = int(kwds.get('x', kwds.get('logx', 0)))
self.ycol = int(kwds.get('y', kwds.get('logy', 1)))
self.logx = 'logx' in kwds
self.logy = 'logy' in kwds
self.xdata, self.ydata = ([], [])
<|end_body_0|>
<|body_start_1|>
row = line.split()
try... | parser used for reading columns | StdParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StdParser:
"""parser used for reading columns"""
def __init__(self, **kwds):
"""keys may be other 'x' or 'logx' and either 'y' or 'logy' default is x=0, y=1"""
<|body_0|>
def parse(self, line):
"""get numbers from a line and put them to self.xdata / self.ydata"""... | stack_v2_sparse_classes_36k_train_031286 | 8,043 | no_license | [
{
"docstring": "keys may be other 'x' or 'logx' and either 'y' or 'logy' default is x=0, y=1",
"name": "__init__",
"signature": "def __init__(self, **kwds)"
},
{
"docstring": "get numbers from a line and put them to self.xdata / self.ydata",
"name": "parse",
"signature": "def parse(self,... | 2 | null | Implement the Python class `StdParser` described below.
Class description:
parser used for reading columns
Method signatures and docstrings:
- def __init__(self, **kwds): keys may be other 'x' or 'logx' and either 'y' or 'logy' default is x=0, y=1
- def parse(self, line): get numbers from a line and put them to self.... | Implement the Python class `StdParser` described below.
Class description:
parser used for reading columns
Method signatures and docstrings:
- def __init__(self, **kwds): keys may be other 'x' or 'logx' and either 'y' or 'logy' default is x=0, y=1
- def parse(self, line): get numbers from a line and put them to self.... | 2e741728693b0fab40204d429000a5a4f827d841 | <|skeleton|>
class StdParser:
"""parser used for reading columns"""
def __init__(self, **kwds):
"""keys may be other 'x' or 'logx' and either 'y' or 'logy' default is x=0, y=1"""
<|body_0|>
def parse(self, line):
"""get numbers from a line and put them to self.xdata / self.ydata"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StdParser:
"""parser used for reading columns"""
def __init__(self, **kwds):
"""keys may be other 'x' or 'logx' and either 'y' or 'logy' default is x=0, y=1"""
self.xcol = int(kwds.get('x', kwds.get('logx', 0)))
self.ycol = int(kwds.get('y', kwds.get('logy', 1)))
self.logx... | the_stack_v2_python_sparse | frappy_psi/softcal.py | SampleEnvironment/frappy | train | 3 |
48915b02fde39b705ceae53fb5e7533d051eb798 | [
"nodeValuePairs = self.fetch('nodeValuePairs', None)\nfor nodeValuePair in nodeValuePairs:\n node = nodeValuePair[0]\n value = nodeValuePair[1]\n self.setNodeDatum(node, value)\nself.puts(success=True)\nreturn",
"if not cmds.attributeQuery('datum', node=node, exists=True):\n cmds.addAttr(node, longNam... | <|body_start_0|>
nodeValuePairs = self.fetch('nodeValuePairs', None)
for nodeValuePair in nodeValuePairs:
node = nodeValuePair[0]
value = nodeValuePair[1]
self.setNodeDatum(node, value)
self.puts(success=True)
return
<|end_body_0|>
<|body_start_1|>
... | A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed else False | SetNodeDatum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetNodeDatum:
"""A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed else False"""
def run(self, *args, **... | stack_v2_sparse_classes_36k_train_031287 | 1,869 | no_license | [
{
"docstring": "Sets the prev and next links for a list of node-value pairs that provide information about the prev and next to each specified node.",
"name": "run",
"signature": "def run(self, *args, **kwargs)"
},
{
"docstring": "Sets the node's datum value, creating the attribute if not alread... | 2 | stack_v2_sparse_classes_30k_train_001225 | Implement the Python class `SetNodeDatum` described below.
Class description:
A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed els... | Implement the Python class `SetNodeDatum` described below.
Class description:
A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed els... | c795ed7cfab512ad340ff88c8c0e67237ac2dfc5 | <|skeleton|>
class SetNodeDatum:
"""A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed else False"""
def run(self, *args, **... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SetNodeDatum:
"""A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed else False"""
def run(self, *args, **kwargs):
... | the_stack_v2_python_sparse | src/cadence/mayan/trackway/SetNodeDatum.py | satello/Cadence | train | 0 |
522a4455ada482203860efcbeca6344870543810 | [
"i = j = k = 0\nn = len(digits)\nret = set()\nfor i in range(n):\n if digits[i] == 0:\n continue\n for j in range(n):\n if j == i:\n continue\n for k in range(n):\n if k == i or k == j:\n continue\n num = 100 * digits[i] + 10 * digits[j] + d... | <|body_start_0|>
i = j = k = 0
n = len(digits)
ret = set()
for i in range(n):
if digits[i] == 0:
continue
for j in range(n):
if j == i:
continue
for k in range(n):
if k == i or... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findEvenNumbers(self, digits):
""":type digits: List[int] :rtype: List[int] easy: 10 min, o(n^3) loops, used set and list. thought: o(n^3) solution? 3 loops to test all possible combinations, store result in set or list(make sure it's unique) 01/29/2022 14:20 Accepted 7329 ... | stack_v2_sparse_classes_36k_train_031288 | 2,991 | no_license | [
{
"docstring": ":type digits: List[int] :rtype: List[int] easy: 10 min, o(n^3) loops, used set and list. thought: o(n^3) solution? 3 loops to test all possible combinations, store result in set or list(make sure it's unique) 01/29/2022 14:20 Accepted 7329 ms 13.5 MB python",
"name": "findEvenNumbers",
"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findEvenNumbers(self, digits): :type digits: List[int] :rtype: List[int] easy: 10 min, o(n^3) loops, used set and list. thought: o(n^3) solution? 3 loops to test all possible... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findEvenNumbers(self, digits): :type digits: List[int] :rtype: List[int] easy: 10 min, o(n^3) loops, used set and list. thought: o(n^3) solution? 3 loops to test all possible... | 02726da394971ef02616a038dadc126c6ff260de | <|skeleton|>
class Solution:
def findEvenNumbers(self, digits):
""":type digits: List[int] :rtype: List[int] easy: 10 min, o(n^3) loops, used set and list. thought: o(n^3) solution? 3 loops to test all possible combinations, store result in set or list(make sure it's unique) 01/29/2022 14:20 Accepted 7329 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findEvenNumbers(self, digits):
""":type digits: List[int] :rtype: List[int] easy: 10 min, o(n^3) loops, used set and list. thought: o(n^3) solution? 3 loops to test all possible combinations, store result in set or list(make sure it's unique) 01/29/2022 14:20 Accepted 7329 ms 13.5 MB pyt... | the_stack_v2_python_sparse | N2094_Finding3-DigitEvenNumbers.py | zerghua/leetcode-python | train | 2 | |
d20a2d818796ff592f18993d822b0b2e4f379736 | [
"self.assertEqual(Number(20) + Number(10), Number(30))\nself.assertEqual(Number(20) + 10, Number(30))\nself.assertEqual(Number(20) - Number(10), Number(10))\nself.assertEqual(Number(20) - 10, Number(10))\nself.assertEqual(Number(20) / Number(10), Number(2))\nself.assertEqual(Number(20) / 10, Number(2))\nself.assert... | <|body_start_0|>
self.assertEqual(Number(20) + Number(10), Number(30))
self.assertEqual(Number(20) + 10, Number(30))
self.assertEqual(Number(20) - Number(10), Number(10))
self.assertEqual(Number(20) - 10, Number(10))
self.assertEqual(Number(20) / Number(10), Number(2))
se... | Cpp1OperatorsTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cpp1OperatorsTestCase:
def test1MathOperators(self):
"""Test overloading of math operators"""
<|body_0|>
def test2UnaryMathOperators(self):
"""Test overloading of unary math operators"""
<|body_1|>
def test3ComparisonOperators(self):
"""Test over... | stack_v2_sparse_classes_36k_train_031289 | 5,582 | no_license | [
{
"docstring": "Test overloading of math operators",
"name": "test1MathOperators",
"signature": "def test1MathOperators(self)"
},
{
"docstring": "Test overloading of unary math operators",
"name": "test2UnaryMathOperators",
"signature": "def test2UnaryMathOperators(self)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_012262 | Implement the Python class `Cpp1OperatorsTestCase` described below.
Class description:
Implement the Cpp1OperatorsTestCase class.
Method signatures and docstrings:
- def test1MathOperators(self): Test overloading of math operators
- def test2UnaryMathOperators(self): Test overloading of unary math operators
- def tes... | Implement the Python class `Cpp1OperatorsTestCase` described below.
Class description:
Implement the Cpp1OperatorsTestCase class.
Method signatures and docstrings:
- def test1MathOperators(self): Test overloading of math operators
- def test2UnaryMathOperators(self): Test overloading of unary math operators
- def tes... | 134508460915282a5d82d6cbbb6e6afa14653413 | <|skeleton|>
class Cpp1OperatorsTestCase:
def test1MathOperators(self):
"""Test overloading of math operators"""
<|body_0|>
def test2UnaryMathOperators(self):
"""Test overloading of unary math operators"""
<|body_1|>
def test3ComparisonOperators(self):
"""Test over... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cpp1OperatorsTestCase:
def test1MathOperators(self):
"""Test overloading of math operators"""
self.assertEqual(Number(20) + Number(10), Number(30))
self.assertEqual(Number(20) + 10, Number(30))
self.assertEqual(Number(20) - Number(10), Number(10))
self.assertEqual(Numbe... | the_stack_v2_python_sparse | python/basic/PyROOT_operatortests.py | root-project/roottest | train | 41 | |
3587501ef4fd035b28994fcc0aeccb41be251ed7 | [
"retention_partner = partner_id.retention_partner_rule_ids.filtered(lambda x: x.retention_id == self)\nif not retention_partner:\n raise ValidationError('El partner no tiene configurada la actividad para retener ganancias')\nretention_rule = self.retention_rule_ids.filtered(lambda x: x.activity_id == retention_p... | <|body_start_0|>
retention_partner = partner_id.retention_partner_rule_ids.filtered(lambda x: x.retention_id == self)
if not retention_partner:
raise ValidationError('El partner no tiene configurada la actividad para retener ganancias')
retention_rule = self.retention_rule_ids.filter... | RetentionRetention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetentionRetention:
def get_profit_retention_rule(self, partner_id):
"""Busca la regla de retencion de ganancia para la actividad del partner :param partner_id: res.partner del cual se usará la actividad configurada :return: retention.retention.rule de la retencion para esa actividad"""
... | stack_v2_sparse_classes_36k_train_031290 | 5,090 | no_license | [
{
"docstring": "Busca la regla de retencion de ganancia para la actividad del partner :param partner_id: res.partner del cual se usará la actividad configurada :return: retention.retention.rule de la retencion para esa actividad",
"name": "get_profit_retention_rule",
"signature": "def get_profit_retenti... | 4 | null | Implement the Python class `RetentionRetention` described below.
Class description:
Implement the RetentionRetention class.
Method signatures and docstrings:
- def get_profit_retention_rule(self, partner_id): Busca la regla de retencion de ganancia para la actividad del partner :param partner_id: res.partner del cual... | Implement the Python class `RetentionRetention` described below.
Class description:
Implement the RetentionRetention class.
Method signatures and docstrings:
- def get_profit_retention_rule(self, partner_id): Busca la regla de retencion de ganancia para la actividad del partner :param partner_id: res.partner del cual... | 77921b4d965f2e4c081d523b373eb306a450a873 | <|skeleton|>
class RetentionRetention:
def get_profit_retention_rule(self, partner_id):
"""Busca la regla de retencion de ganancia para la actividad del partner :param partner_id: res.partner del cual se usará la actividad configurada :return: retention.retention.rule de la retencion para esa actividad"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RetentionRetention:
def get_profit_retention_rule(self, partner_id):
"""Busca la regla de retencion de ganancia para la actividad del partner :param partner_id: res.partner del cual se usará la actividad configurada :return: retention.retention.rule de la retencion para esa actividad"""
retent... | the_stack_v2_python_sparse | odoo_addons_others/l10n_ar_automatic_retentions/models/retention_retention.py | test-odoorosario/opt | train | 0 | |
3d63362695c87fda4ab81ffcd38900c1babe1005 | [
"user = User(username=username)\ncol = Client().get_collection(guild_id, 'users')\ncol.insert_one(user.to_dict)",
"col = Client().get_collection(guild_id, 'users')\nuser = col.find_one({'username': username}, {'_id': False})\nreturn User(**user)",
"if is_decrement:\n amount *= -1\ncol = Client().get_collecti... | <|body_start_0|>
user = User(username=username)
col = Client().get_collection(guild_id, 'users')
col.insert_one(user.to_dict)
<|end_body_0|>
<|body_start_1|>
col = Client().get_collection(guild_id, 'users')
user = col.find_one({'username': username}, {'_id': False})
retu... | A class that deals with the user's collection of a db. | UserService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserService:
"""A class that deals with the user's collection of a db."""
def add_user(guild_id: int, username: str):
"""Adds a user given guild_id to identify a db. :param guild_id: the id to identify the db. :param username: the username to add to the users collection. :return: Non... | stack_v2_sparse_classes_36k_train_031291 | 2,305 | no_license | [
{
"docstring": "Adds a user given guild_id to identify a db. :param guild_id: the id to identify the db. :param username: the username to add to the users collection. :return: None.",
"name": "add_user",
"signature": "def add_user(guild_id: int, username: str)"
},
{
"docstring": "Gets the user i... | 4 | stack_v2_sparse_classes_30k_train_005734 | Implement the Python class `UserService` described below.
Class description:
A class that deals with the user's collection of a db.
Method signatures and docstrings:
- def add_user(guild_id: int, username: str): Adds a user given guild_id to identify a db. :param guild_id: the id to identify the db. :param username: ... | Implement the Python class `UserService` described below.
Class description:
A class that deals with the user's collection of a db.
Method signatures and docstrings:
- def add_user(guild_id: int, username: str): Adds a user given guild_id to identify a db. :param guild_id: the id to identify the db. :param username: ... | 60f8c572b0bfce64909f38d91f08ddfda1b40377 | <|skeleton|>
class UserService:
"""A class that deals with the user's collection of a db."""
def add_user(guild_id: int, username: str):
"""Adds a user given guild_id to identify a db. :param guild_id: the id to identify the db. :param username: the username to add to the users collection. :return: Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserService:
"""A class that deals with the user's collection of a db."""
def add_user(guild_id: int, username: str):
"""Adds a user given guild_id to identify a db. :param guild_id: the id to identify the db. :param username: the username to add to the users collection. :return: None."""
... | the_stack_v2_python_sparse | src/modules/services/user.py | ksyeo1010/poynt | train | 0 |
4ba225b07a6d3d0528ffcecb49153fd9ba34d658 | [
"self.description = self.brief = self.author = self.license = self.license_url = self.url = self.status = self.version = self.notes = ''\nself.depends = []\nself.rosdeps = []\nself.exports = []\nself.platforms = []\nself.is_catkin = is_catkin\nself.type = type_\nself.filename = filename\nself.unknown_tags = []",
... | <|body_start_0|>
self.description = self.brief = self.author = self.license = self.license_url = self.url = self.status = self.version = self.notes = ''
self.depends = []
self.rosdeps = []
self.exports = []
self.platforms = []
self.is_catkin = is_catkin
self.type ... | Object representation of a ROS manifest file (``manifest.xml`` and ``stack.xml``) | Manifest | [
"BSD-3-Clause",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Manifest:
"""Object representation of a ROS manifest file (``manifest.xml`` and ``stack.xml``)"""
def __init__(self, type_='package', filename=None, is_catkin=False):
""":param type: `'package'` or `'stack'` :param filename: location of manifest file. Necessary if converting ``${pref... | stack_v2_sparse_classes_36k_train_031292 | 17,667 | permissive | [
{
"docstring": ":param type: `'package'` or `'stack'` :param filename: location of manifest file. Necessary if converting ``${prefix}`` in ``<export>`` values, ``str``.",
"name": "__init__",
"signature": "def __init__(self, type_='package', filename=None, is_catkin=False)"
},
{
"docstring": ":pa... | 2 | null | Implement the Python class `Manifest` described below.
Class description:
Object representation of a ROS manifest file (``manifest.xml`` and ``stack.xml``)
Method signatures and docstrings:
- def __init__(self, type_='package', filename=None, is_catkin=False): :param type: `'package'` or `'stack'` :param filename: lo... | Implement the Python class `Manifest` described below.
Class description:
Object representation of a ROS manifest file (``manifest.xml`` and ``stack.xml``)
Method signatures and docstrings:
- def __init__(self, type_='package', filename=None, is_catkin=False): :param type: `'package'` or `'stack'` :param filename: lo... | 1f3039edd24c059459563cb81d194326fe824905 | <|skeleton|>
class Manifest:
"""Object representation of a ROS manifest file (``manifest.xml`` and ``stack.xml``)"""
def __init__(self, type_='package', filename=None, is_catkin=False):
""":param type: `'package'` or `'stack'` :param filename: location of manifest file. Necessary if converting ``${pref... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Manifest:
"""Object representation of a ROS manifest file (``manifest.xml`` and ``stack.xml``)"""
def __init__(self, type_='package', filename=None, is_catkin=False):
""":param type: `'package'` or `'stack'` :param filename: location of manifest file. Necessary if converting ``${prefix}`` in ``<e... | the_stack_v2_python_sparse | arm/usr/lib/python2.7/dist-packages/rospkg/manifest.py | Roboy/roboy_plexus | train | 2 |
20e7991f4068a4b7c31b61b3a22a35b4a3a510be | [
"self.skips = skip_connections\nsuper().__init__()\nnn.Module.__init__(self)\nif isinstance(activation, str):\n activation = activations[activation]\nnominal_width = width\nif self.skips:\n nominal_width = (nominal_width - n_inputs) // 2\nn_in = n_inputs\nn_out = nominal_width\nmodules = []\nfor i in range(n_... | <|body_start_0|>
self.skips = skip_connections
super().__init__()
nn.Module.__init__(self)
if isinstance(activation, str):
activation = activations[activation]
nominal_width = width
if self.skips:
nominal_width = (nominal_width - n_inputs) // 2
... | A fully-connected neural network model. | FullyConnected | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullyConnected:
"""A fully-connected neural network model."""
def __init__(self, n_inputs, n_outputs, n_layers, width, activation=nn.ReLU, batch_norm=False, skip_connections=False):
"""Create a fully-connect neural network model. Args: n_inputs: The number of input features to the ne... | stack_v2_sparse_classes_36k_train_031293 | 9,125 | permissive | [
{
"docstring": "Create a fully-connect neural network model. Args: n_inputs: The number of input features to the network. n_outputs: The number of outputs of the model. layers: The number of hidden layers in the model. width: The number of neurons in the hidden layers. activation: The activation function to use... | 2 | stack_v2_sparse_classes_30k_train_017206 | Implement the Python class `FullyConnected` described below.
Class description:
A fully-connected neural network model.
Method signatures and docstrings:
- def __init__(self, n_inputs, n_outputs, n_layers, width, activation=nn.ReLU, batch_norm=False, skip_connections=False): Create a fully-connect neural network mode... | Implement the Python class `FullyConnected` described below.
Class description:
A fully-connected neural network model.
Method signatures and docstrings:
- def __init__(self, n_inputs, n_outputs, n_layers, width, activation=nn.ReLU, batch_norm=False, skip_connections=False): Create a fully-connect neural network mode... | a27e329cd30337995c359160a0d878bf331c13fb | <|skeleton|>
class FullyConnected:
"""A fully-connected neural network model."""
def __init__(self, n_inputs, n_outputs, n_layers, width, activation=nn.ReLU, batch_norm=False, skip_connections=False):
"""Create a fully-connect neural network model. Args: n_inputs: The number of input features to the ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullyConnected:
"""A fully-connected neural network model."""
def __init__(self, n_inputs, n_outputs, n_layers, width, activation=nn.ReLU, batch_norm=False, skip_connections=False):
"""Create a fully-connect neural network model. Args: n_inputs: The number of input features to the network. n_outp... | the_stack_v2_python_sparse | quantnn/models/pytorch/fully_connected.py | simonpf/quantnn | train | 7 |
89b80a1bc0fcaa3c2f1efd5a9ecafd5963d9428e | [
"if not o1 or not o2:\n return ListNode(0)\nn = self.convert(o1) + self.convert(o2)\nreturn self.revert(n)",
"f = 1\nn = 0\np = o\nwhile p:\n n += p.v * f\n f *= 10\n p = p.c\nreturn n",
"if n == 0:\n return ListNode(0)\no = ListNode(None)\np = o\nwhile n > 0:\n n, x = divmod(n, 10)\n p.c =... | <|body_start_0|>
if not o1 or not o2:
return ListNode(0)
n = self.convert(o1) + self.convert(o2)
return self.revert(n)
<|end_body_0|>
<|body_start_1|>
f = 1
n = 0
p = o
while p:
n += p.v * f
f *= 10
p = p.c
... | Time complexity: O(len(o1) + len(o2)) - Amortized sum of lengths for both integers as linked list Space complexity: O(max(len(o1), len(o2))) - Amortized length of sum as linked list | Solution3 | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution3:
"""Time complexity: O(len(o1) + len(o2)) - Amortized sum of lengths for both integers as linked list Space complexity: O(max(len(o1), len(o2))) - Amortized length of sum as linked list"""
def add_two_numbers(self, o1, o2):
"""Calculates sum of two numbers as linked list. :... | stack_v2_sparse_classes_36k_train_031294 | 4,006 | permissive | [
{
"docstring": "Calculates sum of two numbers as linked list. :param ListNode o1: head node of first number :param ListNode o2: head node of second number :return: head node of sum :rtype: ListNode",
"name": "add_two_numbers",
"signature": "def add_two_numbers(self, o1, o2)"
},
{
"docstring": "T... | 3 | stack_v2_sparse_classes_30k_train_007082 | Implement the Python class `Solution3` described below.
Class description:
Time complexity: O(len(o1) + len(o2)) - Amortized sum of lengths for both integers as linked list Space complexity: O(max(len(o1), len(o2))) - Amortized length of sum as linked list
Method signatures and docstrings:
- def add_two_numbers(self,... | Implement the Python class `Solution3` described below.
Class description:
Time complexity: O(len(o1) + len(o2)) - Amortized sum of lengths for both integers as linked list Space complexity: O(max(len(o1), len(o2))) - Amortized length of sum as linked list
Method signatures and docstrings:
- def add_two_numbers(self,... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution3:
"""Time complexity: O(len(o1) + len(o2)) - Amortized sum of lengths for both integers as linked list Space complexity: O(max(len(o1), len(o2))) - Amortized length of sum as linked list"""
def add_two_numbers(self, o1, o2):
"""Calculates sum of two numbers as linked list. :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution3:
"""Time complexity: O(len(o1) + len(o2)) - Amortized sum of lengths for both integers as linked list Space complexity: O(max(len(o1), len(o2))) - Amortized length of sum as linked list"""
def add_two_numbers(self, o1, o2):
"""Calculates sum of two numbers as linked list. :param ListNod... | the_stack_v2_python_sparse | 0002_add_two_numbers/python_source.py | arthurdysart/LeetCode | train | 0 |
ea1446e829194f3f6abfca6a085dd1b9c67c1137 | [
"super().__init__(**kwargs)\nself.login_page_selectors = kwargs.get('login_page_selectors', None)\nself.selectors = kwargs.get('selectors', None)\nself.login_button_selector = kwargs.get('login_button_selector', None)\nkwargs['selector'] = self.login_button_selector\nself.login_button_action = ScraperAction(**kwarg... | <|body_start_0|>
super().__init__(**kwargs)
self.login_page_selectors = kwargs.get('login_page_selectors', None)
self.selectors = kwargs.get('selectors', None)
self.login_button_selector = kwargs.get('login_button_selector', None)
kwargs['selector'] = self.login_button_selector
... | Python class that will log into an interface | ScraperLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScraperLogin:
"""Python class that will log into an interface"""
def __init__(self, **kwargs):
"""Constructor for all ScraperComponents :param **kwargs dict using the following data. driver: WebScraper driver default None web_driver: WebScraper default None scraper_url: str url to op... | stack_v2_sparse_classes_36k_train_031295 | 4,501 | no_license | [
{
"docstring": "Constructor for all ScraperComponents :param **kwargs dict using the following data. driver: WebScraper driver default None web_driver: WebScraper default None scraper_url: str url to open default None open_url: bool True to open upon startup and False it waits. command: str command this compone... | 4 | stack_v2_sparse_classes_30k_train_009916 | Implement the Python class `ScraperLogin` described below.
Class description:
Python class that will log into an interface
Method signatures and docstrings:
- def __init__(self, **kwargs): Constructor for all ScraperComponents :param **kwargs dict using the following data. driver: WebScraper driver default None web_d... | Implement the Python class `ScraperLogin` described below.
Class description:
Python class that will log into an interface
Method signatures and docstrings:
- def __init__(self, **kwargs): Constructor for all ScraperComponents :param **kwargs dict using the following data. driver: WebScraper driver default None web_d... | c2577d8626e09a2f388b774fe0c78dda6a4464db | <|skeleton|>
class ScraperLogin:
"""Python class that will log into an interface"""
def __init__(self, **kwargs):
"""Constructor for all ScraperComponents :param **kwargs dict using the following data. driver: WebScraper driver default None web_driver: WebScraper default None scraper_url: str url to op... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScraperLogin:
"""Python class that will log into an interface"""
def __init__(self, **kwargs):
"""Constructor for all ScraperComponents :param **kwargs dict using the following data. driver: WebScraper driver default None web_driver: WebScraper default None scraper_url: str url to open default No... | the_stack_v2_python_sparse | events_hitparade_co/components/login.py | richardathitparade/hitparade_bots | train | 0 |
2a722b884d8c600f292c6061008c45b917386149 | [
"extra_data = self.clean_keys_of_slashes(data.json)\ndata_value = MetaData.textit(data.xform)\nif data_value:\n token, flow, contacts = data_value.split(METADATA_SEPARATOR)\n post_data = {'extra': extra_data, 'flow': flow, 'contacts': contacts.split(',')}\n headers = {'Content-Type': 'application/json', 'A... | <|body_start_0|>
extra_data = self.clean_keys_of_slashes(data.json)
data_value = MetaData.textit(data.xform)
if data_value:
token, flow, contacts = data_value.split(METADATA_SEPARATOR)
post_data = {'extra': extra_data, 'flow': flow, 'contacts': contacts.split(',')}
... | Post submission data to a textit/rapidpro server. | ServiceDefinition | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceDefinition:
"""Post submission data to a textit/rapidpro server."""
def send(self, url, data=None):
"""Sends the submission to the configured rest service :param url: :param data: :return:"""
<|body_0|>
def clean_keys_of_slashes(self, record):
"""Replaces ... | stack_v2_sparse_classes_36k_train_031296 | 2,305 | permissive | [
{
"docstring": "Sends the submission to the configured rest service :param url: :param data: :return:",
"name": "send",
"signature": "def send(self, url, data=None)"
},
{
"docstring": "Replaces the slashes found in a dataset keys with underscores :param record: list containing a couple of dictio... | 2 | null | Implement the Python class `ServiceDefinition` described below.
Class description:
Post submission data to a textit/rapidpro server.
Method signatures and docstrings:
- def send(self, url, data=None): Sends the submission to the configured rest service :param url: :param data: :return:
- def clean_keys_of_slashes(sel... | Implement the Python class `ServiceDefinition` described below.
Class description:
Post submission data to a textit/rapidpro server.
Method signatures and docstrings:
- def send(self, url, data=None): Sends the submission to the configured rest service :param url: :param data: :return:
- def clean_keys_of_slashes(sel... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class ServiceDefinition:
"""Post submission data to a textit/rapidpro server."""
def send(self, url, data=None):
"""Sends the submission to the configured rest service :param url: :param data: :return:"""
<|body_0|>
def clean_keys_of_slashes(self, record):
"""Replaces ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServiceDefinition:
"""Post submission data to a textit/rapidpro server."""
def send(self, url, data=None):
"""Sends the submission to the configured rest service :param url: :param data: :return:"""
extra_data = self.clean_keys_of_slashes(data.json)
data_value = MetaData.textit(da... | the_stack_v2_python_sparse | onadata/apps/restservice/services/textit.py | onaio/onadata | train | 177 |
d4531cccbe4f50bb97e452dcbbd82d66bd3c893c | [
"n = len(nums)\nans = 0\nfor i in range(n):\n total = 0\n for j in range(i, n):\n total += nums[j]\n if total == k:\n ans += 1\nreturn ans",
"\"\"\"Very tricky please see: https://www.youtube.com/watch?v=HbbYPQc-Oo4\"\"\"\nfrom collections import Counter\nprefixsum_counter = Counter... | <|body_start_0|>
n = len(nums)
ans = 0
for i in range(n):
total = 0
for j in range(i, n):
total += nums[j]
if total == k:
ans += 1
return ans
<|end_body_0|>
<|body_start_1|>
"""Very tricky please see: ht... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""Brute Force, Time: O(n^2), Space: O(1), TLE"""
<|body_0|>
def subarraySum(self, nums: List[int], k: int) -> int:
"""Prefix Sum + HashMap, Time: O(n), Space: O(n)"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_031297 | 1,413 | no_license | [
{
"docstring": "Brute Force, Time: O(n^2), Space: O(1), TLE",
"name": "subarraySum",
"signature": "def subarraySum(self, nums: List[int], k: int) -> int"
},
{
"docstring": "Prefix Sum + HashMap, Time: O(n), Space: O(n)",
"name": "subarraySum",
"signature": "def subarraySum(self, nums: Li... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum(self, nums: List[int], k: int) -> int: Brute Force, Time: O(n^2), Space: O(1), TLE
- def subarraySum(self, nums: List[int], k: int) -> int: Prefix Sum + HashMap, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum(self, nums: List[int], k: int) -> int: Brute Force, Time: O(n^2), Space: O(1), TLE
- def subarraySum(self, nums: List[int], k: int) -> int: Prefix Sum + HashMap, ... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""Brute Force, Time: O(n^2), Space: O(1), TLE"""
<|body_0|>
def subarraySum(self, nums: List[int], k: int) -> int:
"""Prefix Sum + HashMap, Time: O(n), Space: O(n)"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""Brute Force, Time: O(n^2), Space: O(1), TLE"""
n = len(nums)
ans = 0
for i in range(n):
total = 0
for j in range(i, n):
total += nums[j]
if total == k:
... | the_stack_v2_python_sparse | python/560-subarray sum equals k.py | cwza/leetcode | train | 0 | |
394b10ed158286c957616e271e7903476e876a31 | [
"Block.__init__(self, scenario, args)\nif self.language is None:\n raise LoadingException('Language must be defined!')",
"tantum_match = re.search('_(s[ei])$', tnode.t_lemma)\nif tantum_match:\n refl_form = tantum_match.group(1)\n afun = 'AuxT'\nelif tnode.voice == 'reflexive_diathesis' or tnode.gram_dia... | <|body_start_0|>
Block.__init__(self, scenario, args)
if self.language is None:
raise LoadingException('Language must be defined!')
<|end_body_0|>
<|body_start_1|>
tantum_match = re.search('_(s[ei])$', tnode.t_lemma)
if tantum_match:
refl_form = tantum_match.grou... | Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree | AddReflexiveParticles | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddReflexiveParticles:
"""Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values""... | stack_v2_sparse_classes_36k_train_031298 | 1,857 | permissive | [
{
"docstring": "Constructor, just checking the argument values",
"name": "__init__",
"signature": "def __init__(self, scenario, args)"
},
{
"docstring": "Add reflexive particle to a node, if applicable.",
"name": "process_tnode",
"signature": "def process_tnode(self, tnode)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014808 | Implement the Python class `AddReflexiveParticles` described below.
Class description:
Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario... | Implement the Python class `AddReflexiveParticles` described below.
Class description:
Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario... | 73af644ec35c8a1cd0c37cd478c2afc1db717e0b | <|skeleton|>
class AddReflexiveParticles:
"""Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddReflexiveParticles:
"""Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
Blo... | the_stack_v2_python_sparse | alex/components/nlg/tectotpl/block/t2a/cs/addreflexiveparticles.py | oplatek/alex | train | 0 |
00bc4d8f7226100738131c6b2696c0838e227e72 | [
"self.__hazard_func = hazard_func\nself.__likelihood_func = likelihood_func\nself.__threshold = threshold",
"likelihood_func = deepcopy(self.__likelihood_func)\ndetector = Prospective(hazard_func=self.__hazard_func, likelihood_func=likelihood_func)\nscores = []\nfor i in X:\n score = detector.update(i)\n sc... | <|body_start_0|>
self.__hazard_func = hazard_func
self.__likelihood_func = likelihood_func
self.__threshold = threshold
<|end_body_0|>
<|body_start_1|>
likelihood_func = deepcopy(self.__likelihood_func)
detector = Prospective(hazard_func=self.__hazard_func, likelihood_func=likel... | BOCPD (Retrospective) | Retrospective | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Retrospective:
"""BOCPD (Retrospective)"""
def __init__(self, hazard_func, likelihood_func, threshold=0.5):
"""Args: hazard_func: hazard function likelihood_func: likelihood function threshold: threshold for alarms."""
<|body_0|>
def calc_scores(self, X):
"""calc... | stack_v2_sparse_classes_36k_train_031299 | 5,419 | permissive | [
{
"docstring": "Args: hazard_func: hazard function likelihood_func: likelihood function threshold: threshold for alarms.",
"name": "__init__",
"signature": "def __init__(self, hazard_func, likelihood_func, threshold=0.5)"
},
{
"docstring": "calculate scores Args: X: input data Returns: ndarray: ... | 3 | stack_v2_sparse_classes_30k_train_012176 | Implement the Python class `Retrospective` described below.
Class description:
BOCPD (Retrospective)
Method signatures and docstrings:
- def __init__(self, hazard_func, likelihood_func, threshold=0.5): Args: hazard_func: hazard function likelihood_func: likelihood function threshold: threshold for alarms.
- def calc_... | Implement the Python class `Retrospective` described below.
Class description:
BOCPD (Retrospective)
Method signatures and docstrings:
- def __init__(self, hazard_func, likelihood_func, threshold=0.5): Args: hazard_func: hazard function likelihood_func: likelihood function threshold: threshold for alarms.
- def calc_... | 7faf99f36ac012799602f32b359dcda089bcd119 | <|skeleton|>
class Retrospective:
"""BOCPD (Retrospective)"""
def __init__(self, hazard_func, likelihood_func, threshold=0.5):
"""Args: hazard_func: hazard function likelihood_func: likelihood function threshold: threshold for alarms."""
<|body_0|>
def calc_scores(self, X):
"""calc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Retrospective:
"""BOCPD (Retrospective)"""
def __init__(self, hazard_func, likelihood_func, threshold=0.5):
"""Args: hazard_func: hazard function likelihood_func: likelihood function threshold: threshold for alarms."""
self.__hazard_func = hazard_func
self.__likelihood_func = like... | the_stack_v2_python_sparse | bocpd/bocpd.py | IbarakikenYukishi/two-stage-MDL | train | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.