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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aecace3adc72bcd266a4952eba01315e108abc4c | [
"transformed_structures = []\nlines = cif_string.split('\\n')\nstructure_data = []\nread_data = False\nfor line in lines:\n if re.match('^\\\\s*data', line):\n structure_data.append([])\n read_data = True\n if read_data:\n structure_data[-1].append(line)\nfor data in structure_data:\n ... | <|body_start_0|>
transformed_structures = []
lines = cif_string.split('\n')
structure_data = []
read_data = False
for line in lines:
if re.match('^\\s*data', line):
structure_data.append([])
read_data = True
if read_data:
... | Generates a Transmuter from a cif string, possibly containing multiple structures. | CifTransmuter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CifTransmuter:
"""Generates a Transmuter from a cif string, possibly containing multiple structures."""
def __init__(self, cif_string, transformations=None, primitive=True, extend_collection=False):
"""Generates a Transmuter from a cif string, possibly containing multiple structures.... | stack_v2_sparse_classes_36k_train_018000 | 15,693 | permissive | [
{
"docstring": "Generates a Transmuter from a cif string, possibly containing multiple structures. Args: cif_string: A string containing a cif or a series of cifs transformations: New transformations to be applied to all structures primitive: Whether to generate the primitive cell from the cif. extend_collectio... | 2 | null | Implement the Python class `CifTransmuter` described below.
Class description:
Generates a Transmuter from a cif string, possibly containing multiple structures.
Method signatures and docstrings:
- def __init__(self, cif_string, transformations=None, primitive=True, extend_collection=False): Generates a Transmuter fr... | Implement the Python class `CifTransmuter` described below.
Class description:
Generates a Transmuter from a cif string, possibly containing multiple structures.
Method signatures and docstrings:
- def __init__(self, cif_string, transformations=None, primitive=True, extend_collection=False): Generates a Transmuter fr... | 62ecae1c7382a41861e3a5d9b9c8dd1207472409 | <|skeleton|>
class CifTransmuter:
"""Generates a Transmuter from a cif string, possibly containing multiple structures."""
def __init__(self, cif_string, transformations=None, primitive=True, extend_collection=False):
"""Generates a Transmuter from a cif string, possibly containing multiple structures.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CifTransmuter:
"""Generates a Transmuter from a cif string, possibly containing multiple structures."""
def __init__(self, cif_string, transformations=None, primitive=True, extend_collection=False):
"""Generates a Transmuter from a cif string, possibly containing multiple structures. Args: cif_st... | the_stack_v2_python_sparse | pymatgen/alchemy/transmuters.py | montoyjh/pymatgen | train | 2 |
5b82728ecdb8af261742df9cdf47c4237b1d2a6e | [
"osh = ObjectStateHolder('mscsresource')\nosh.setAttribute('data_name', resource.name)\nif resource.details:\n details = resource.details\n if details.description:\n osh.setStringAttribute('data_description', details.description)\n if details.type is not None:\n osh.setStringAttribute('type',... | <|body_start_0|>
osh = ObjectStateHolder('mscsresource')
osh.setAttribute('data_name', resource.name)
if resource.details:
details = resource.details
if details.description:
osh.setStringAttribute('data_description', details.description)
if det... | ResourceBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceBuilder:
def buildResource(self, resource):
"""@types: Resource -> ObjectStateHolder"""
<|body_0|>
def buildResourcePdo(self, pdo):
"""@types: Builder.Pdo -> ObjectStateHolder"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
osh = ObjectState... | stack_v2_sparse_classes_36k_train_018001 | 15,554 | no_license | [
{
"docstring": "@types: Resource -> ObjectStateHolder",
"name": "buildResource",
"signature": "def buildResource(self, resource)"
},
{
"docstring": "@types: Builder.Pdo -> ObjectStateHolder",
"name": "buildResourcePdo",
"signature": "def buildResourcePdo(self, pdo)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000547 | Implement the Python class `ResourceBuilder` described below.
Class description:
Implement the ResourceBuilder class.
Method signatures and docstrings:
- def buildResource(self, resource): @types: Resource -> ObjectStateHolder
- def buildResourcePdo(self, pdo): @types: Builder.Pdo -> ObjectStateHolder | Implement the Python class `ResourceBuilder` described below.
Class description:
Implement the ResourceBuilder class.
Method signatures and docstrings:
- def buildResource(self, resource): @types: Resource -> ObjectStateHolder
- def buildResourcePdo(self, pdo): @types: Builder.Pdo -> ObjectStateHolder
<|skeleton|>
c... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class ResourceBuilder:
def buildResource(self, resource):
"""@types: Resource -> ObjectStateHolder"""
<|body_0|>
def buildResourcePdo(self, pdo):
"""@types: Builder.Pdo -> ObjectStateHolder"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourceBuilder:
def buildResource(self, resource):
"""@types: Resource -> ObjectStateHolder"""
osh = ObjectStateHolder('mscsresource')
osh.setAttribute('data_name', resource.name)
if resource.details:
details = resource.details
if details.description:
... | the_stack_v2_python_sparse | reference/ucmdb/discovery/ms_cluster.py | madmonkyang/cda-record | train | 0 | |
ed1f954d2f09dceae5d423ec77b803a0fbc7959a | [
"first_name = 'John'\nlast_name = 'Doe'\nsalary = 100000\nself.employee = Employee(first_name, last_name, salary)",
"oldsalary = self.employee.salary\nself.employee.give_raise()\nself.assertEqual(self.employee.salary, oldsalary + 5000)",
"oldsalary = self.employee.salary\nself.employee.give_raise(10000)\nself.a... | <|body_start_0|>
first_name = 'John'
last_name = 'Doe'
salary = 100000
self.employee = Employee(first_name, last_name, salary)
<|end_body_0|>
<|body_start_1|>
oldsalary = self.employee.salary
self.employee.give_raise()
self.assertEqual(self.employee.salary, oldsa... | Tests for the Employee class | TestEmployee | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestEmployee:
"""Tests for the Employee class"""
def setUp(self):
"""Defines test case"""
<|body_0|>
def test_give_default_raise(self):
"""Tests giving default raise"""
<|body_1|>
def test_give_custom_raise(self):
"""Tests giving custom raise... | stack_v2_sparse_classes_36k_train_018002 | 787 | no_license | [
{
"docstring": "Defines test case",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests giving default raise",
"name": "test_give_default_raise",
"signature": "def test_give_default_raise(self)"
},
{
"docstring": "Tests giving custom raise",
"name": "test... | 3 | stack_v2_sparse_classes_30k_train_005097 | Implement the Python class `TestEmployee` described below.
Class description:
Tests for the Employee class
Method signatures and docstrings:
- def setUp(self): Defines test case
- def test_give_default_raise(self): Tests giving default raise
- def test_give_custom_raise(self): Tests giving custom raise | Implement the Python class `TestEmployee` described below.
Class description:
Tests for the Employee class
Method signatures and docstrings:
- def setUp(self): Defines test case
- def test_give_default_raise(self): Tests giving default raise
- def test_give_custom_raise(self): Tests giving custom raise
<|skeleton|>
... | cdc3ff2be11eb2f26027fc968efa2876d2dc12cb | <|skeleton|>
class TestEmployee:
"""Tests for the Employee class"""
def setUp(self):
"""Defines test case"""
<|body_0|>
def test_give_default_raise(self):
"""Tests giving default raise"""
<|body_1|>
def test_give_custom_raise(self):
"""Tests giving custom raise... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestEmployee:
"""Tests for the Employee class"""
def setUp(self):
"""Defines test case"""
first_name = 'John'
last_name = 'Doe'
salary = 100000
self.employee = Employee(first_name, last_name, salary)
def test_give_default_raise(self):
"""Tests giving d... | the_stack_v2_python_sparse | chap11/test_employee.py | xatlasm/python-crash-course | train | 0 |
f3395b1643969e4bd7a6237e093857a0c589b6f1 | [
"self.conf = self.getConf(namespace)\nself.mapping = self.getMapping(self.conf)\nself.priority = self.getPriority(self.mapping)\nlogger.info('_getRenderers - loaded custom event renderers: self.mapping=%s self.priority=%s' % (self.mapping, self.priority))",
"bundleConf = splunk.bundle.getConf(CONF_NAME, namespace... | <|body_start_0|>
self.conf = self.getConf(namespace)
self.mapping = self.getMapping(self.conf)
self.priority = self.getPriority(self.mapping)
logger.info('_getRenderers - loaded custom event renderers: self.mapping=%s self.priority=%s' % (self.mapping, self.priority))
<|end_body_0|>
<|b... | Custom | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Custom:
def __init__(self, namespace=None):
"""Config wrapper for event renderers. Normlizes pathing and selection of appropriate renderer based on priority and matching eventtype."""
<|body_0|>
def getConf(self, namespace):
"""Pre-process a Conf object into a a more... | stack_v2_sparse_classes_36k_train_018003 | 7,389 | no_license | [
{
"docstring": "Config wrapper for event renderers. Normlizes pathing and selection of appropriate renderer based on priority and matching eventtype.",
"name": "__init__",
"signature": "def __init__(self, namespace=None)"
},
{
"docstring": "Pre-process a Conf object into a a more primitive dict ... | 6 | stack_v2_sparse_classes_30k_train_002497 | Implement the Python class `Custom` described below.
Class description:
Implement the Custom class.
Method signatures and docstrings:
- def __init__(self, namespace=None): Config wrapper for event renderers. Normlizes pathing and selection of appropriate renderer based on priority and matching eventtype.
- def getCon... | Implement the Python class `Custom` described below.
Class description:
Implement the Custom class.
Method signatures and docstrings:
- def __init__(self, namespace=None): Config wrapper for event renderers. Normlizes pathing and selection of appropriate renderer based on priority and matching eventtype.
- def getCon... | 7cf8a158bc8e1cecef374dad9165d44ccb00c6e0 | <|skeleton|>
class Custom:
def __init__(self, namespace=None):
"""Config wrapper for event renderers. Normlizes pathing and selection of appropriate renderer based on priority and matching eventtype."""
<|body_0|>
def getConf(self, namespace):
"""Pre-process a Conf object into a a more... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Custom:
def __init__(self, namespace=None):
"""Config wrapper for event renderers. Normlizes pathing and selection of appropriate renderer based on priority and matching eventtype."""
self.conf = self.getConf(namespace)
self.mapping = self.getMapping(self.conf)
self.priority = ... | the_stack_v2_python_sparse | appserver/mrsparkle/lib/eventrenderer.py | bullll/splunk | train | 2 | |
1f2f968a0a62f1cda6f947114cc5d6512544c8e4 | [
"self.rect = rect\nself.function = function\nself.overlay = overlay if not isinstance(overlay, str) else ButtonFont.render(overlay, True, KDS.Colors.White)\nself.button_default_color = button_default_color\nself.button_highlighted_color = button_highlighted_color\nself.button_pressed_color = button_pressed_color\ns... | <|body_start_0|>
self.rect = rect
self.function = function
self.overlay = overlay if not isinstance(overlay, str) else ButtonFont.render(overlay, True, KDS.Colors.White)
self.button_default_color = button_default_color
self.button_highlighted_color = button_highlighted_color
... | Button | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Button:
def __init__(self, rect: pygame.Rect, function: Callable, overlay: Union[pygame.Surface, str]=None, button_default_color: Tuple[int, int, int]=(100, 100, 100), button_highlighted_color: Tuple[int, int, int]=(115, 115, 115), button_pressed_color: Tuple[int, int, int]=(90, 90, 90), button_... | stack_v2_sparse_classes_36k_train_018004 | 18,129 | no_license | [
{
"docstring": "Instantiates a new Button Args: rect (Rect): The rect where the button will be drawn. function (Callable): A function to be called when the button is pressed. overlay (Surface, optional): Any surface you want to write on top of the button. Defaults to None. button_default_color (Tuple[int, int, ... | 2 | stack_v2_sparse_classes_30k_train_002247 | Implement the Python class `Button` described below.
Class description:
Implement the Button class.
Method signatures and docstrings:
- def __init__(self, rect: pygame.Rect, function: Callable, overlay: Union[pygame.Surface, str]=None, button_default_color: Tuple[int, int, int]=(100, 100, 100), button_highlighted_col... | Implement the Python class `Button` described below.
Class description:
Implement the Button class.
Method signatures and docstrings:
- def __init__(self, rect: pygame.Rect, function: Callable, overlay: Union[pygame.Surface, str]=None, button_default_color: Tuple[int, int, int]=(100, 100, 100), button_highlighted_col... | 641695c56ea2d2a02cca1077b6289988ec9eeb3d | <|skeleton|>
class Button:
def __init__(self, rect: pygame.Rect, function: Callable, overlay: Union[pygame.Surface, str]=None, button_default_color: Tuple[int, int, int]=(100, 100, 100), button_highlighted_color: Tuple[int, int, int]=(115, 115, 115), button_pressed_color: Tuple[int, int, int]=(90, 90, 90), button_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Button:
def __init__(self, rect: pygame.Rect, function: Callable, overlay: Union[pygame.Surface, str]=None, button_default_color: Tuple[int, int, int]=(100, 100, 100), button_highlighted_color: Tuple[int, int, int]=(115, 115, 115), button_pressed_color: Tuple[int, int, int]=(90, 90, 90), button_disabled_color... | the_stack_v2_python_sparse | KDS/UI.py | KL-Corporation/Koponen-Dating-Simulator | train | 0 | |
ad14551af5a156ae4c87b25bdcb75383ea771922 | [
"digits_len = len(digits)\nif not self.increment_digit(digits, digits_len - 1, 1):\n return digits\nfor i in range(digits_len - 2, -1, -1):\n if not self.increment_digit(digits, i, 1):\n break\nreturn digits",
"new_digit = digits[i] + carry\ndigits[i] = new_digit % 10\ncarry = new_digit // 10\nif i =... | <|body_start_0|>
digits_len = len(digits)
if not self.increment_digit(digits, digits_len - 1, 1):
return digits
for i in range(digits_len - 2, -1, -1):
if not self.increment_digit(digits, i, 1):
break
return digits
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
"""(Solution, list of int) -> list of int Return a list of digits representing a number that is one higher than the number represented by digits. >>> soln = Solution() >>> soln.plusOne([1, 2, 3]) [1, 2, 4] >>> soln.plusOne([4, ... | stack_v2_sparse_classes_36k_train_018005 | 2,409 | no_license | [
{
"docstring": "(Solution, list of int) -> list of int Return a list of digits representing a number that is one higher than the number represented by digits. >>> soln = Solution() >>> soln.plusOne([1, 2, 3]) [1, 2, 4] >>> soln.plusOne([4, 3, 2, 1]) [4, 3, 2, 2] >>> soln.plusOne([9]) [1, 0]",
"name": "plusO... | 2 | stack_v2_sparse_classes_30k_train_017979 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits: List[int]) -> List[int]: (Solution, list of int) -> list of int Return a list of digits representing a number that is one higher than the number represe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits: List[int]) -> List[int]: (Solution, list of int) -> list of int Return a list of digits representing a number that is one higher than the number represe... | 6812253b90bdd5a35c6bfba8eac54da9be26d56c | <|skeleton|>
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
"""(Solution, list of int) -> list of int Return a list of digits representing a number that is one higher than the number represented by digits. >>> soln = Solution() >>> soln.plusOne([1, 2, 3]) [1, 2, 4] >>> soln.plusOne([4, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
"""(Solution, list of int) -> list of int Return a list of digits representing a number that is one higher than the number represented by digits. >>> soln = Solution() >>> soln.plusOne([1, 2, 3]) [1, 2, 4] >>> soln.plusOne([4, 3, 2, 1]) [4, ... | the_stack_v2_python_sparse | python3/plusOne.py | yichuanma95/leetcode-solns | train | 2 | |
125ee024fb9d112d43625ea9ff1bc742e36ed1ef | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Manages long-running operations with an API service. When an API method normally takes long time to complete, it can be designed to return [Operation][google.longrunning.Operation] to the client, and the client can use this interface to receive the real response asynchronously by polling the operation resource, or usin... | OperationsServicer | [
"LicenseRef-scancode-python-cwi",
"GPL-1.0-or-later",
"Python-2.0",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-free-unknown",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OperationsServicer:
"""Manages long-running operations with an API service. When an API method normally takes long time to complete, it can be designed to return [Operation][google.longrunning.Operation] to the client, and the client can use this interface to receive the real response asynchronou... | stack_v2_sparse_classes_36k_train_018006 | 13,771 | permissive | [
{
"docstring": "Gets the latest state of a long-running operation. Clients may use this method to poll the operation result at intervals as recommended by the API service.",
"name": "GetOperation",
"signature": "def GetOperation(self, request, context)"
},
{
"docstring": "Lists operations that m... | 4 | stack_v2_sparse_classes_30k_train_017770 | Implement the Python class `OperationsServicer` described below.
Class description:
Manages long-running operations with an API service. When an API method normally takes long time to complete, it can be designed to return [Operation][google.longrunning.Operation] to the client, and the client can use this interface t... | Implement the Python class `OperationsServicer` described below.
Class description:
Manages long-running operations with an API service. When an API method normally takes long time to complete, it can be designed to return [Operation][google.longrunning.Operation] to the client, and the client can use this interface t... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class OperationsServicer:
"""Manages long-running operations with an API service. When an API method normally takes long time to complete, it can be designed to return [Operation][google.longrunning.Operation] to the client, and the client can use this interface to receive the real response asynchronou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OperationsServicer:
"""Manages long-running operations with an API service. When an API method normally takes long time to complete, it can be designed to return [Operation][google.longrunning.Operation] to the client, and the client can use this interface to receive the real response asynchronously by pollin... | the_stack_v2_python_sparse | third_party/chromite/third_party/gcloud/bigtable/_generated/operations_grpc_pb2.py | metux/chromium-suckless | train | 5 |
3f5a36348a63c253f7eb7da6926877042ff64412 | [
"rr_interval_data = get_datastream(self.CC, stream_identifier, day, user_id, False)\nprint('-' * 20, ' rr interval data ', len(rr_interval_data), '-' * 20)\nif not rr_interval_data:\n return\nfinal_data = []\nfor dp in rr_interval_data:\n if math.isnan(dp.sample[1]):\n continue\n if not list(dp.samp... | <|body_start_0|>
rr_interval_data = get_datastream(self.CC, stream_identifier, day, user_id, False)
print('-' * 20, ' rr interval data ', len(rr_interval_data), '-' * 20)
if not rr_interval_data:
return
final_data = []
for dp in rr_interval_data:
if math.i... | This class extracts the pre computed rr interval timeseries and computes a continuous heart rate timeseries with a resolution of two seconds | heart_rate | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class heart_rate:
"""This class extracts the pre computed rr interval timeseries and computes a continuous heart rate timeseries with a resolution of two seconds"""
def get_and_save_data(self, streams: dict, day: str, stream_identifier: str, user_id: str, json_path: str):
"""This function ... | stack_v2_sparse_classes_36k_train_018007 | 4,499 | permissive | [
{
"docstring": "This function takes all the streams of a user on a specific day alongwith the rr interval datastream name and extracts the rr interval data for the day. It then unpacks the minute based list of heart rate present in the RR interval data to compute a heart rate timeseries of two second resolution... | 2 | stack_v2_sparse_classes_30k_train_010141 | Implement the Python class `heart_rate` described below.
Class description:
This class extracts the pre computed rr interval timeseries and computes a continuous heart rate timeseries with a resolution of two seconds
Method signatures and docstrings:
- def get_and_save_data(self, streams: dict, day: str, stream_ident... | Implement the Python class `heart_rate` described below.
Class description:
This class extracts the pre computed rr interval timeseries and computes a continuous heart rate timeseries with a resolution of two seconds
Method signatures and docstrings:
- def get_and_save_data(self, streams: dict, day: str, stream_ident... | 73f5ea2430bc7c23de422dccb7b65ef9f8917595 | <|skeleton|>
class heart_rate:
"""This class extracts the pre computed rr interval timeseries and computes a continuous heart rate timeseries with a resolution of two seconds"""
def get_and_save_data(self, streams: dict, day: str, stream_identifier: str, user_id: str, json_path: str):
"""This function ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class heart_rate:
"""This class extracts the pre computed rr interval timeseries and computes a continuous heart rate timeseries with a resolution of two seconds"""
def get_and_save_data(self, streams: dict, day: str, stream_identifier: str, user_id: str, json_path: str):
"""This function takes all the... | the_stack_v2_python_sparse | core/feature/heart_rate/heart_rate.py | MD2Korg/CerebralCortex-DataAnalysis | train | 1 |
c084529666d514a0d67d8ef8824a2d83b332a32e | [
"self.r = radius\nself.x = x_center\nself.y = y_center",
"r = random.triangular(0, self.r, self.r)\ntheta = random.uniform(-math.pi, math.pi)\nreturn [self.x + r * math.cos(theta), self.y + r * math.sin(theta)]"
] | <|body_start_0|>
self.r = radius
self.x = x_center
self.y = y_center
<|end_body_0|>
<|body_start_1|>
r = random.triangular(0, self.r, self.r)
theta = random.uniform(-math.pi, math.pi)
return [self.x + r * math.cos(theta), self.y + r * math.sin(theta)]
<|end_body_1|>
| Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.r = radius
... | stack_v2_sparse_classes_36k_train_018008 | 889 | permissive | [
{
"docstring": ":type radius: float :type x_center: float :type y_center: float",
"name": "__init__",
"signature": "def __init__(self, radius, x_center, y_center)"
},
{
"docstring": ":rtype: List[float]",
"name": "randPoint",
"signature": "def randPoint(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float]
<|skeleton|>
class Sol... | fc5b1744af7be93f4dd01d6ad58d2bd12f7ed33f | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
self.r = radius
self.x = x_center
self.y = y_center
def randPoint(self):
""":rtype: List[float]"""
r = random.triangular(0, self.... | the_stack_v2_python_sparse | 478.Generate_Random_Point_in_a_Circle.py | mickey0524/leetcode | train | 27 | |
620d3176dc92fcc9c95323c4a6a2069b136f9749 | [
"self.name = name\nself.output_format = output_format\nself.parameters = parameters\nself.subject_line = subject_line\nself.mtype = mtype",
"if dictionary is None:\n return None\nname = dictionary.get('name')\noutput_format = dictionary.get('outputFormat')\nparameters = cohesity_management_sdk.models.scheduler... | <|body_start_0|>
self.name = name
self.output_format = output_format
self.parameters = parameters
self.subject_line = subject_line
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
name = dictionary.get('name')
... | Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report' model. Specifies the type and parameters of a report. Attributes: name (string): Specifies the report name. output_format (string): Specifies the output format of the report. parameters ( SchedulerProto_SchedulerJob_Sche... | SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report:
"""Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report' model. Specifies the type and parameters of a report. Attributes: name (string): Specifies the report name. output_fo... | stack_v2_sparse_classes_36k_train_018009 | 2,862 | permissive | [
{
"docstring": "Constructor for the SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report class",
"name": "__init__",
"signature": "def __init__(self, name=None, output_format=None, parameters=None, subject_line=None, mtype=None)"
},
{
"docstring": "Creates an instance of t... | 2 | stack_v2_sparse_classes_30k_train_003198 | Implement the Python class `SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report` described below.
Class description:
Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report' model. Specifies the type and parameters of a report. Attributes: name (string... | Implement the Python class `SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report` described below.
Class description:
Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report' model. Specifies the type and parameters of a report. Attributes: name (string... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report:
"""Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report' model. Specifies the type and parameters of a report. Attributes: name (string): Specifies the report name. output_fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report:
"""Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report' model. Specifies the type and parameters of a report. Attributes: name (string): Specifies the report name. output_format (string)... | the_stack_v2_python_sparse | cohesity_management_sdk/models/scheduler_proto_scheduler_job_schedule__report.py | cohesity/management-sdk-python | train | 24 |
6f9dd6ae83fb1d9351ae6be5c514fd797afc573e | [
"appName: str = 'Correlator'\ndevicePath: str = deviceName\nleft: str = appName\nmid: str = ' '\nright: str = devicePath\nmidBegin: int = self.nChars // 2 - len(mid) // 2\nrightBegin: int = self.charRight - len(right) + 1\nself.drawStr(' ' * self.charsWidth)\nself.drawStr(left)\nself.drawStr(mid, midBegin)\nself.dr... | <|body_start_0|>
appName: str = 'Correlator'
devicePath: str = deviceName
left: str = appName
mid: str = ' '
right: str = devicePath
midBegin: int = self.nChars // 2 - len(mid) // 2
rightBegin: int = self.charRight - len(right) + 1
self.drawStr(' ' * self.... | The "full" window is a rectangle in the middle of the screen. +----------- ... -------------+ |Title... | | | | inputs/parameters | | | ... ... | | | outputs/results | | | |Status... | +----------- ... -------------+ | FullWindow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullWindow:
"""The "full" window is a rectangle in the middle of the screen. +----------- ... -------------+ |Title... | | | | inputs/parameters | | | ... ... | | | outputs/results | | | |Status... | +----------- ... -------------+"""
def drawTitle(self, deviceName, hwRegs) -> None:
... | stack_v2_sparse_classes_36k_train_018010 | 28,296 | permissive | [
{
"docstring": "Draw the static title section. Intended to be called only once. <appName> ... ... <devicePath>",
"name": "drawTitle",
"signature": "def drawTitle(self, deviceName, hwRegs) -> None"
},
{
"docstring": "Draw/redraw the status section. Up/Down: Move ... Left/Right: Change ... Enter: ... | 2 | stack_v2_sparse_classes_30k_train_011843 | Implement the Python class `FullWindow` described below.
Class description:
The "full" window is a rectangle in the middle of the screen. +----------- ... -------------+ |Title... | | | | inputs/parameters | | | ... ... | | | outputs/results | | | |Status... | +----------- ... -------------+
Method signatures and doc... | Implement the Python class `FullWindow` described below.
Class description:
The "full" window is a rectangle in the middle of the screen. +----------- ... -------------+ |Title... | | | | inputs/parameters | | | ... ... | | | outputs/results | | | |Status... | +----------- ... -------------+
Method signatures and doc... | 68e8a121d4591360080cd40121add1796ae48a1b | <|skeleton|>
class FullWindow:
"""The "full" window is a rectangle in the middle of the screen. +----------- ... -------------+ |Title... | | | | inputs/parameters | | | ... ... | | | outputs/results | | | |Status... | +----------- ... -------------+"""
def drawTitle(self, deviceName, hwRegs) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullWindow:
"""The "full" window is a rectangle in the middle of the screen. +----------- ... -------------+ |Title... | | | | inputs/parameters | | | ... ... | | | outputs/results | | | |Status... | +----------- ... -------------+"""
def drawTitle(self, deviceName, hwRegs) -> None:
"""Draw the s... | the_stack_v2_python_sparse | dmppl/experiments/correlator/correlator_tui.py | DaveMcEwan/dmppl | train | 1 |
d953f3efe6f392b5e513e38617f88f57835d2c79 | [
"self.sequence = A\nself.cursor = 0\nself.length = len(A)",
"while self.cursor < self.length and self.sequence[self.cursor] < n:\n n -= self.sequence[self.cursor]\n self.cursor += 2\nif self.cursor < self.length:\n self.sequence[self.cursor] -= n\n return self.sequence[self.cursor + 1]\nelse:\n ret... | <|body_start_0|>
self.sequence = A
self.cursor = 0
self.length = len(A)
<|end_body_0|>
<|body_start_1|>
while self.cursor < self.length and self.sequence[self.cursor] < n:
n -= self.sequence[self.cursor]
self.cursor += 2
if self.cursor < self.length:
... | RLEIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sequence = A
self.cursor = 0
self.length = len(A)
<|end_body_... | stack_v2_sparse_classes_36k_train_018011 | 699 | no_license | [
{
"docstring": ":type A: List[int]",
"name": "__init__",
"signature": "def __init__(self, A)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "next",
"signature": "def next(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019791 | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int
<|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: Lis... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
self.sequence = A
self.cursor = 0
self.length = len(A)
def next(self, n):
""":type n: int :rtype: int"""
while self.cursor < self.length and self.sequence[self.cursor] < n:
n -= self.s... | the_stack_v2_python_sparse | python/leetcode/900_RLE_Iterator.py | bobcaoge/my-code | train | 0 | |
3d9a4fa16551d9863e59c4f1b1e980c4b2943ae9 | [
"def recur(root, k, hashset):\n if not root:\n return False\n target = k - root.val\n if target in hashset:\n return True\n else:\n hashset.add(root.val)\n return recur(root.left, k, hashset) or recur(root.right, k, hashset)\nhashset = set()\nreturn recur(root, k, hashset)",
"i... | <|body_start_0|>
def recur(root, k, hashset):
if not root:
return False
target = k - root.val
if target in hashset:
return True
else:
hashset.add(root.val)
return recur(root.left, k, hashset) or recur(roo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTarget1(self, root: TreeNode, k: int) -> bool:
"""思路:回溯+剪枝"""
<|body_0|>
def findTarget2(self, root: TreeNode, k: int) -> bool:
"""思路:通过flag来标记是否已找到"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def recur(root, k, hashset):
... | stack_v2_sparse_classes_36k_train_018012 | 1,757 | no_license | [
{
"docstring": "思路:回溯+剪枝",
"name": "findTarget1",
"signature": "def findTarget1(self, root: TreeNode, k: int) -> bool"
},
{
"docstring": "思路:通过flag来标记是否已找到",
"name": "findTarget2",
"signature": "def findTarget2(self, root: TreeNode, k: int) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_test_001118 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTarget1(self, root: TreeNode, k: int) -> bool: 思路:回溯+剪枝
- def findTarget2(self, root: TreeNode, k: int) -> bool: 思路:通过flag来标记是否已找到 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTarget1(self, root: TreeNode, k: int) -> bool: 思路:回溯+剪枝
- def findTarget2(self, root: TreeNode, k: int) -> bool: 思路:通过flag来标记是否已找到
<|skeleton|>
class Solution:
def ... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def findTarget1(self, root: TreeNode, k: int) -> bool:
"""思路:回溯+剪枝"""
<|body_0|>
def findTarget2(self, root: TreeNode, k: int) -> bool:
"""思路:通过flag来标记是否已找到"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findTarget1(self, root: TreeNode, k: int) -> bool:
"""思路:回溯+剪枝"""
def recur(root, k, hashset):
if not root:
return False
target = k - root.val
if target in hashset:
return True
else:
h... | the_stack_v2_python_sparse | LeetCode/树(Binary Tree)/653. 两数之和 IV - 输入 BST.py | yiming1012/MyLeetCode | train | 2 | |
9ddad8253d4a8379d70c9546a6f891b702c50c29 | [
"if self == RewardType.EVERY_STEP_ZERO_SUM:\n return (0.0, 1.0)\nelif self == RewardType.EVERY_STEP_LENGTH:\n return (0.0, 1.0)\nelif self == RewardType.ON_EAT_AND_ON_DEATH:\n return (-1.0, 1.0)\nelif self == RewardType.RANK_ON_DEATH:\n return (-1.0, 1.0)\nelse:\n raise ValueError(f'RewardType not ye... | <|body_start_0|>
if self == RewardType.EVERY_STEP_ZERO_SUM:
return (0.0, 1.0)
elif self == RewardType.EVERY_STEP_LENGTH:
return (0.0, 1.0)
elif self == RewardType.ON_EAT_AND_ON_DEATH:
return (-1.0, 1.0)
elif self == RewardType.RANK_ON_DEATH:
... | RewardType | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RewardType:
def get_cumulative_reward_spec(self) -> Tuple[Optional[float], Optional[float]]:
"""The minimum/maximum cumulative available reward"""
<|body_0|>
def get_recommended_value_activation_scale_shift_dict(self) -> Dict:
"""The recommended value activation func... | stack_v2_sparse_classes_36k_train_018013 | 49,153 | permissive | [
{
"docstring": "The minimum/maximum cumulative available reward",
"name": "get_cumulative_reward_spec",
"signature": "def get_cumulative_reward_spec(self) -> Tuple[Optional[float], Optional[float]]"
},
{
"docstring": "The recommended value activation function, value_scale, and value_shift for th... | 2 | stack_v2_sparse_classes_30k_train_013973 | Implement the Python class `RewardType` described below.
Class description:
Implement the RewardType class.
Method signatures and docstrings:
- def get_cumulative_reward_spec(self) -> Tuple[Optional[float], Optional[float]]: The minimum/maximum cumulative available reward
- def get_recommended_value_activation_scale_... | Implement the Python class `RewardType` described below.
Class description:
Implement the RewardType class.
Method signatures and docstrings:
- def get_cumulative_reward_spec(self) -> Tuple[Optional[float], Optional[float]]: The minimum/maximum cumulative available reward
- def get_recommended_value_activation_scale_... | f4d9fcb0811704bd339ad5c7ff937dd0d9e25763 | <|skeleton|>
class RewardType:
def get_cumulative_reward_spec(self) -> Tuple[Optional[float], Optional[float]]:
"""The minimum/maximum cumulative available reward"""
<|body_0|>
def get_recommended_value_activation_scale_shift_dict(self) -> Dict:
"""The recommended value activation func... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RewardType:
def get_cumulative_reward_spec(self) -> Tuple[Optional[float], Optional[float]]:
"""The minimum/maximum cumulative available reward"""
if self == RewardType.EVERY_STEP_ZERO_SUM:
return (0.0, 1.0)
elif self == RewardType.EVERY_STEP_LENGTH:
return (0.0... | the_stack_v2_python_sparse | hungry_geese/env/goose_env.py | IsaiahPressman/Kaggle_Hungry_Geese | train | 0 | |
8ff325dc3009217ed64db1b38ad29baf3c8b7044 | [
"err_msg = {'status': 0, 'message': '错误'}\nif check_request_method(request) == RequestMethod.GET:\n token = get_request_args(request, 'token')\n token = conversion_args_type({token: str})\n if token != 'bGlhbnpvbmdzaGVuZw==':\n response = err_msg\n else:\n brandshare = BrandShare.objects.f... | <|body_start_0|>
err_msg = {'status': 0, 'message': '错误'}
if check_request_method(request) == RequestMethod.GET:
token = get_request_args(request, 'token')
token = conversion_args_type({token: str})
if token != 'bGlhbnpvbmdzaGVuZw==':
response = err_ms... | MobileDataDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MobileDataDetail:
def get_public_brand_share_queryset(request):
"""获取固定的品牌公开数据 http://127.0.0.1:8000/interface/api/getBrandShare?token=bGlhbnpvbmdzaGVuZw== :param request: :return:"""
<|body_0|>
def get_mobile_system_rate_queryset(request):
"""http://127.0.0.1:8000/i... | stack_v2_sparse_classes_36k_train_018014 | 4,309 | no_license | [
{
"docstring": "获取固定的品牌公开数据 http://127.0.0.1:8000/interface/api/getBrandShare?token=bGlhbnpvbmdzaGVuZw== :param request: :return:",
"name": "get_public_brand_share_queryset",
"signature": "def get_public_brand_share_queryset(request)"
},
{
"docstring": "http://127.0.0.1:8000/interface/api/getMob... | 4 | stack_v2_sparse_classes_30k_train_005303 | Implement the Python class `MobileDataDetail` described below.
Class description:
Implement the MobileDataDetail class.
Method signatures and docstrings:
- def get_public_brand_share_queryset(request): 获取固定的品牌公开数据 http://127.0.0.1:8000/interface/api/getBrandShare?token=bGlhbnpvbmdzaGVuZw== :param request: :return:
- ... | Implement the Python class `MobileDataDetail` described below.
Class description:
Implement the MobileDataDetail class.
Method signatures and docstrings:
- def get_public_brand_share_queryset(request): 获取固定的品牌公开数据 http://127.0.0.1:8000/interface/api/getBrandShare?token=bGlhbnpvbmdzaGVuZw== :param request: :return:
- ... | 200fbbdb016f592618e0a9fcd64f981dbf46cd3f | <|skeleton|>
class MobileDataDetail:
def get_public_brand_share_queryset(request):
"""获取固定的品牌公开数据 http://127.0.0.1:8000/interface/api/getBrandShare?token=bGlhbnpvbmdzaGVuZw== :param request: :return:"""
<|body_0|>
def get_mobile_system_rate_queryset(request):
"""http://127.0.0.1:8000/i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MobileDataDetail:
def get_public_brand_share_queryset(request):
"""获取固定的品牌公开数据 http://127.0.0.1:8000/interface/api/getBrandShare?token=bGlhbnpvbmdzaGVuZw== :param request: :return:"""
err_msg = {'status': 0, 'message': '错误'}
if check_request_method(request) == RequestMethod.GET:
... | the_stack_v2_python_sparse | digitalsmart/datainterface/mobile_data_view.py | LianZS/digitalsmart | train | 1 | |
62de74fa68a27ded1c590edd14cfd56759fbf803 | [
"if self.action == 'list':\n return Areas.objects.filter(parent=None)\nelse:\n return Areas.objects.all()",
"if self.action == 'list':\n return serializers.AreaSerializer\nelse:\n return serializers.SubsSerializer"
] | <|body_start_0|>
if self.action == 'list':
return Areas.objects.filter(parent=None)
else:
return Areas.objects.all()
<|end_body_0|>
<|body_start_1|>
if self.action == 'list':
return serializers.AreaSerializer
else:
return serializers.SubsS... | 省份视图 | AreasViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AreasViewSet:
"""省份视图"""
def get_queryset(self):
"""提供数据"""
<|body_0|>
def get_serializer_class(self):
"""提供序列化器"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.action == 'list':
return Areas.objects.filter(parent=None)
... | stack_v2_sparse_classes_36k_train_018015 | 713 | no_license | [
{
"docstring": "提供数据",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "提供序列化器",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
}
] | 2 | null | Implement the Python class `AreasViewSet` described below.
Class description:
省份视图
Method signatures and docstrings:
- def get_queryset(self): 提供数据
- def get_serializer_class(self): 提供序列化器 | Implement the Python class `AreasViewSet` described below.
Class description:
省份视图
Method signatures and docstrings:
- def get_queryset(self): 提供数据
- def get_serializer_class(self): 提供序列化器
<|skeleton|>
class AreasViewSet:
"""省份视图"""
def get_queryset(self):
"""提供数据"""
<|body_0|>
def get_... | 61798f2c3624bfde540cfb7469d42564ffe674a6 | <|skeleton|>
class AreasViewSet:
"""省份视图"""
def get_queryset(self):
"""提供数据"""
<|body_0|>
def get_serializer_class(self):
"""提供序列化器"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AreasViewSet:
"""省份视图"""
def get_queryset(self):
"""提供数据"""
if self.action == 'list':
return Areas.objects.filter(parent=None)
else:
return Areas.objects.all()
def get_serializer_class(self):
"""提供序列化器"""
if self.action == 'list':
... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/areas/views.py | MEGALO-JOE/meiduo | train | 0 |
1eb95a009f4d506cbd75b37128a125311eba62c1 | [
"opt_logfile_name = self.DEFAULT_LOGFILE\nopt_interval = self.DEFAULT_INTERVAL\nopt_functions = self.DEFAULT_FUNCTIONS\nif 'logfile' in opt:\n opt_logfile_name = opt['logfile']\nif 'interval' in opt:\n opt_interval = opt['interval']\nif 'functions' in opt:\n opt_functions = opt['functions']\nself.functions... | <|body_start_0|>
opt_logfile_name = self.DEFAULT_LOGFILE
opt_interval = self.DEFAULT_INTERVAL
opt_functions = self.DEFAULT_FUNCTIONS
if 'logfile' in opt:
opt_logfile_name = opt['logfile']
if 'interval' in opt:
opt_interval = opt['interval']
if 'fun... | Check some function's statistics in the DPM logfile | check_dpns_perf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class check_dpns_perf:
"""Check some function's statistics in the DPM logfile"""
def __init__(self, opt={}, args=[]):
"""Constructor @param opt Contains a dictionary with the long option name as the key, and the argument as value @param args Contains the arguments not associated with any o... | stack_v2_sparse_classes_36k_train_018016 | 4,886 | no_license | [
{
"docstring": "Constructor @param opt Contains a dictionary with the long option name as the key, and the argument as value @param args Contains the arguments not associated with any option",
"name": "__init__",
"signature": "def __init__(self, opt={}, args=[])"
},
{
"docstring": "Test code its... | 2 | stack_v2_sparse_classes_30k_train_008424 | Implement the Python class `check_dpns_perf` described below.
Class description:
Check some function's statistics in the DPM logfile
Method signatures and docstrings:
- def __init__(self, opt={}, args=[]): Constructor @param opt Contains a dictionary with the long option name as the key, and the argument as value @pa... | Implement the Python class `check_dpns_perf` described below.
Class description:
Check some function's statistics in the DPM logfile
Method signatures and docstrings:
- def __init__(self, opt={}, args=[]): Constructor @param opt Contains a dictionary with the long option name as the key, and the argument as value @pa... | 270b7d2fff4ae56735d53fa99bb1613c07f1f9a3 | <|skeleton|>
class check_dpns_perf:
"""Check some function's statistics in the DPM logfile"""
def __init__(self, opt={}, args=[]):
"""Constructor @param opt Contains a dictionary with the long option name as the key, and the argument as value @param args Contains the arguments not associated with any o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class check_dpns_perf:
"""Check some function's statistics in the DPM logfile"""
def __init__(self, opt={}, args=[]):
"""Constructor @param opt Contains a dictionary with the long option name as the key, and the argument as value @param args Contains the arguments not associated with any option"""
... | the_stack_v2_python_sparse | cambox-package/plugins/lcgdm/check_dpm_perf | usuporte/install.issabel | train | 1 |
22b2a3a7f0f89443e2626988a950824a1c476ace | [
"agentId = request.GET.get('agentId', None)\nagentName = request.GET.get('agentName', None)\nif None not in [agentId, agentName]:\n con_mysql_connect = con_mysql.connection()\n cursor = con_mysql_connect.cursor()\n cursor.execute(\"delete from agent_list where agentName = '%s' and agentId = '%s'\", agentNa... | <|body_start_0|>
agentId = request.GET.get('agentId', None)
agentName = request.GET.get('agentName', None)
if None not in [agentId, agentName]:
con_mysql_connect = con_mysql.connection()
cursor = con_mysql_connect.cursor()
cursor.execute("delete from agent_lis... | 新增/删除 代理商 | AddDelAgent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddDelAgent:
"""新增/删除 代理商"""
def get(self, request):
"""删除代理商 :param request: :return:"""
<|body_0|>
def post(self, request):
"""新增代理商 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
agentId = request.GET.get('agentId', ... | stack_v2_sparse_classes_36k_train_018017 | 5,449 | no_license | [
{
"docstring": "删除代理商 :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "新增代理商 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009578 | Implement the Python class `AddDelAgent` described below.
Class description:
新增/删除 代理商
Method signatures and docstrings:
- def get(self, request): 删除代理商 :param request: :return:
- def post(self, request): 新增代理商 :param request: :return: | Implement the Python class `AddDelAgent` described below.
Class description:
新增/删除 代理商
Method signatures and docstrings:
- def get(self, request): 删除代理商 :param request: :return:
- def post(self, request): 新增代理商 :param request: :return:
<|skeleton|>
class AddDelAgent:
"""新增/删除 代理商"""
def get(self, request):
... | 37b0bbff8818e73fd4897871956cfef446589e2f | <|skeleton|>
class AddDelAgent:
"""新增/删除 代理商"""
def get(self, request):
"""删除代理商 :param request: :return:"""
<|body_0|>
def post(self, request):
"""新增代理商 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddDelAgent:
"""新增/删除 代理商"""
def get(self, request):
"""删除代理商 :param request: :return:"""
agentId = request.GET.get('agentId', None)
agentName = request.GET.get('agentName', None)
if None not in [agentId, agentName]:
con_mysql_connect = con_mysql.connection()
... | the_stack_v2_python_sparse | applet_background/participate_hospital_management/agent_participate_views.py | xieboxiebo/escortbed | train | 0 |
cedc972b0656600a70e7c021cb81bbd44f991220 | [
"hang = len(M)\nlie = len(M[0])\nfor i in range(hang):\n for j in range(lie):\n pass",
"dirs = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]\nheight = len(M)\nwidth = len(M[0])\nres = []\nfor i in range(height):\n cache = []\n for j in range(width):\n sum = M[i][j]\... | <|body_start_0|>
hang = len(M)
lie = len(M[0])
for i in range(hang):
for j in range(lie):
pass
<|end_body_0|>
<|body_start_1|>
dirs = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
height = len(M)
width = len(M[0])
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def imageSmoother(self, M):
"""暴力法看起来可以求解的样子 但比较麻烦。。 :param M: :return:"""
<|body_0|>
def imageSmoother2(self, M):
"""卷积神经网络里的平均池 :param M: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hang = len(M)
lie = len(M[0])
... | stack_v2_sparse_classes_36k_train_018018 | 2,234 | permissive | [
{
"docstring": "暴力法看起来可以求解的样子 但比较麻烦。。 :param M: :return:",
"name": "imageSmoother",
"signature": "def imageSmoother(self, M)"
},
{
"docstring": "卷积神经网络里的平均池 :param M: :return:",
"name": "imageSmoother2",
"signature": "def imageSmoother2(self, M)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005538 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def imageSmoother(self, M): 暴力法看起来可以求解的样子 但比较麻烦。。 :param M: :return:
- def imageSmoother2(self, M): 卷积神经网络里的平均池 :param M: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def imageSmoother(self, M): 暴力法看起来可以求解的样子 但比较麻烦。。 :param M: :return:
- def imageSmoother2(self, M): 卷积神经网络里的平均池 :param M: :return:
<|skeleton|>
class Solution:
def imageSmo... | 41f4b8b557cf15cbd602f187f6550184b3a108ec | <|skeleton|>
class Solution:
def imageSmoother(self, M):
"""暴力法看起来可以求解的样子 但比较麻烦。。 :param M: :return:"""
<|body_0|>
def imageSmoother2(self, M):
"""卷积神经网络里的平均池 :param M: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def imageSmoother(self, M):
"""暴力法看起来可以求解的样子 但比较麻烦。。 :param M: :return:"""
hang = len(M)
lie = len(M[0])
for i in range(hang):
for j in range(lie):
pass
def imageSmoother2(self, M):
"""卷积神经网络里的平均池 :param M: :return:"""
... | the_stack_v2_python_sparse | leetcode/661. 图片平滑器.py | zhongmb/suanfa | train | 0 | |
bb22159e1acc774ea384c7b2550ada26258c4daf | [
"if user.is_anonymous or user.is_client:\n return False\nif user.is_administrator:\n return True\nif user.is_manager or user.is_advisor:\n return organization.owning_group == user.group\nreturn self.admin_permission(user, organization, *args)",
"if user.is_anonymous or user.is_client:\n return False\n... | <|body_start_0|>
if user.is_anonymous or user.is_client:
return False
if user.is_administrator:
return True
if user.is_manager or user.is_advisor:
return organization.owning_group == user.group
return self.admin_permission(user, organization, *args)
<|... | OrganizationPermissionLogic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationPermissionLogic:
def view(self, user, organization, *args):
"""Permissions for viewing Organization"""
<|body_0|>
def create(self, user, organization, *args):
"""Permissions for creating Organization"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_018019 | 1,236 | no_license | [
{
"docstring": "Permissions for viewing Organization",
"name": "view",
"signature": "def view(self, user, organization, *args)"
},
{
"docstring": "Permissions for creating Organization",
"name": "create",
"signature": "def create(self, user, organization, *args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020047 | Implement the Python class `OrganizationPermissionLogic` described below.
Class description:
Implement the OrganizationPermissionLogic class.
Method signatures and docstrings:
- def view(self, user, organization, *args): Permissions for viewing Organization
- def create(self, user, organization, *args): Permissions f... | Implement the Python class `OrganizationPermissionLogic` described below.
Class description:
Implement the OrganizationPermissionLogic class.
Method signatures and docstrings:
- def view(self, user, organization, *args): Permissions for viewing Organization
- def create(self, user, organization, *args): Permissions f... | 95d21cd6036a99c5f399b700a5426e9e2e17e878 | <|skeleton|>
class OrganizationPermissionLogic:
def view(self, user, organization, *args):
"""Permissions for viewing Organization"""
<|body_0|>
def create(self, user, organization, *args):
"""Permissions for creating Organization"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrganizationPermissionLogic:
def view(self, user, organization, *args):
"""Permissions for viewing Organization"""
if user.is_anonymous or user.is_client:
return False
if user.is_administrator:
return True
if user.is_manager or user.is_advisor:
... | the_stack_v2_python_sparse | fac/perms/organization_perm.py | alexandrenorman/mixeur | train | 0 | |
0b7751a69f256d08956218b9ad7731f26a528e8f | [
"assert p != q\nif root is None:\n return (None, False, False)\npFound = root == p\nqFound = root == q\nleftCommonAncestor, leftPFound, leftQFound = self.lowestCommonAncestorHelper(root.left, p, q)\nif leftCommonAncestor:\n assert leftPFound and leftQFound\n return (leftCommonAncestor, True, True)\npFound ... | <|body_start_0|>
assert p != q
if root is None:
return (None, False, False)
pFound = root == p
qFound = root == q
leftCommonAncestor, leftPFound, leftQFound = self.lowestCommonAncestorHelper(root.left, p, q)
if leftCommonAncestor:
assert leftPFound... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestorHelper(self, root, p, q):
"""Return a tuple (commonAncestor, pFound, qFound) if not both pFound and qFound, commonAncestor is None"""
<|body_0|>
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :t... | stack_v2_sparse_classes_36k_train_018020 | 1,736 | no_license | [
{
"docstring": "Return a tuple (commonAncestor, pFound, qFound) if not both pFound and qFound, commonAncestor is None",
"name": "lowestCommonAncestorHelper",
"signature": "def lowestCommonAncestorHelper(self, root, p, q)"
},
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNod... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestorHelper(self, root, p, q): Return a tuple (commonAncestor, pFound, qFound) if not both pFound and qFound, commonAncestor is None
- def lowestCommonAncestor... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestorHelper(self, root, p, q): Return a tuple (commonAncestor, pFound, qFound) if not both pFound and qFound, commonAncestor is None
- def lowestCommonAncestor... | 6e051eb554d9cf6f424f1e0a77f3072adf7f64c4 | <|skeleton|>
class Solution:
def lowestCommonAncestorHelper(self, root, p, q):
"""Return a tuple (commonAncestor, pFound, qFound) if not both pFound and qFound, commonAncestor is None"""
<|body_0|>
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestorHelper(self, root, p, q):
"""Return a tuple (commonAncestor, pFound, qFound) if not both pFound and qFound, commonAncestor is None"""
assert p != q
if root is None:
return (None, False, False)
pFound = root == p
qFound = roo... | the_stack_v2_python_sparse | 236. Lowest Common Ancestor of a Binary Tree.py | vincent-kangzhou/LeetCode-Python | train | 0 | |
aa6423b1d307ad36269f059949735931367c653b | [
"super(CFDataGenerator, self).__init__()\nself.testData = testData\nself.reshapeDims = params['reshapeDims']\nself.batch_size = params['batch_size']\nself.normalize = params['normalize']\nself.n_classes = params['n_classes']\nself.batch_index = 0\nself.runThrough = False",
"currentTestData = []\nif self.batch_ind... | <|body_start_0|>
super(CFDataGenerator, self).__init__()
self.testData = testData
self.reshapeDims = params['reshapeDims']
self.batch_size = params['batch_size']
self.normalize = params['normalize']
self.n_classes = params['n_classes']
self.batch_index = 0
... | Generates preprocessed data in batches of given size. | CFDataGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CFDataGenerator:
"""Generates preprocessed data in batches of given size."""
def __init__(self, testData, **params):
"""# Arguments testData: directory location of the images params : dictionary containing pre processing parameters"""
<|body_0|>
def getNextBatch(self):
... | stack_v2_sparse_classes_36k_train_018021 | 9,223 | permissive | [
{
"docstring": "# Arguments testData: directory location of the images params : dictionary containing pre processing parameters",
"name": "__init__",
"signature": "def __init__(self, testData, **params)"
},
{
"docstring": "Cycles through the data one batch_size at a time # Returns Current batch ... | 3 | stack_v2_sparse_classes_30k_val_000944 | Implement the Python class `CFDataGenerator` described below.
Class description:
Generates preprocessed data in batches of given size.
Method signatures and docstrings:
- def __init__(self, testData, **params): # Arguments testData: directory location of the images params : dictionary containing pre processing parame... | Implement the Python class `CFDataGenerator` described below.
Class description:
Generates preprocessed data in batches of given size.
Method signatures and docstrings:
- def __init__(self, testData, **params): # Arguments testData: directory location of the images params : dictionary containing pre processing parame... | 976e6087ff629c45f7bbc79a3de25718ed143db5 | <|skeleton|>
class CFDataGenerator:
"""Generates preprocessed data in batches of given size."""
def __init__(self, testData, **params):
"""# Arguments testData: directory location of the images params : dictionary containing pre processing parameters"""
<|body_0|>
def getNextBatch(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CFDataGenerator:
"""Generates preprocessed data in batches of given size."""
def __init__(self, testData, **params):
"""# Arguments testData: directory location of the images params : dictionary containing pre processing parameters"""
super(CFDataGenerator, self).__init__()
self.t... | the_stack_v2_python_sparse | modeltasks/dataGen.py | AshivDhondea/DFTS_compat_v1 | train | 1 |
43491ccb78ad5d926715538405e405a91ea56563 | [
"app = SequencingExperimentGenomicFile.query.get(kf_id)\nif app is None:\n abort(404, 'could not find {} `{}`'.format('sequencing_experiment_genomic_file', kf_id))\nreturn SequencingExperimentGenomicFileSchema().jsonify(app)",
"app = SequencingExperimentGenomicFile.query.get(kf_id)\nif app is None:\n abort(... | <|body_start_0|>
app = SequencingExperimentGenomicFile.query.get(kf_id)
if app is None:
abort(404, 'could not find {} `{}`'.format('sequencing_experiment_genomic_file', kf_id))
return SequencingExperimentGenomicFileSchema().jsonify(app)
<|end_body_0|>
<|body_start_1|>
app = ... | SequencingExperimentGenomicFile API | SequencingExperimentGenomicFileAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequencingExperimentGenomicFileAPI:
"""SequencingExperimentGenomicFile API"""
def get(self, kf_id):
"""Get a sequencing_experiment_genomic_file by id --- template: path: get_by_id.yml properties: resource: SequencingExperimentGenomicFile"""
<|body_0|>
def patch(self, kf_... | stack_v2_sparse_classes_36k_train_018022 | 5,985 | permissive | [
{
"docstring": "Get a sequencing_experiment_genomic_file by id --- template: path: get_by_id.yml properties: resource: SequencingExperimentGenomicFile",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing sequencing_experiment_genomic_file. Allows partial upd... | 3 | stack_v2_sparse_classes_30k_train_000677 | Implement the Python class `SequencingExperimentGenomicFileAPI` described below.
Class description:
SequencingExperimentGenomicFile API
Method signatures and docstrings:
- def get(self, kf_id): Get a sequencing_experiment_genomic_file by id --- template: path: get_by_id.yml properties: resource: SequencingExperimentG... | Implement the Python class `SequencingExperimentGenomicFileAPI` described below.
Class description:
SequencingExperimentGenomicFile API
Method signatures and docstrings:
- def get(self, kf_id): Get a sequencing_experiment_genomic_file by id --- template: path: get_by_id.yml properties: resource: SequencingExperimentG... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class SequencingExperimentGenomicFileAPI:
"""SequencingExperimentGenomicFile API"""
def get(self, kf_id):
"""Get a sequencing_experiment_genomic_file by id --- template: path: get_by_id.yml properties: resource: SequencingExperimentGenomicFile"""
<|body_0|>
def patch(self, kf_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequencingExperimentGenomicFileAPI:
"""SequencingExperimentGenomicFile API"""
def get(self, kf_id):
"""Get a sequencing_experiment_genomic_file by id --- template: path: get_by_id.yml properties: resource: SequencingExperimentGenomicFile"""
app = SequencingExperimentGenomicFile.query.get(... | the_stack_v2_python_sparse | dataservice/api/sequencing_experiment_genomic_file/resources.py | kids-first/kf-api-dataservice | train | 9 |
07d1da86843f31bf6219b6c7fba661a3b0598a23 | [
"options = DBRunner.parse_args(['-m', 'foo.sqlite', '-s', '20180101', '5'])\nself.assertEqual('5', options.process_id)\nself.assertEqual('foo.sqlite', options.mission)\nself.assertEqual(datetime.datetime(2018, 1, 1), options.startDate)\nself.assertTrue(datetime.datetime.now() - options.endDate < datetime.timedelta(... | <|body_start_0|>
options = DBRunner.parse_args(['-m', 'foo.sqlite', '-s', '20180101', '5'])
self.assertEqual('5', options.process_id)
self.assertEqual('foo.sqlite', options.mission)
self.assertEqual(datetime.datetime(2018, 1, 1), options.startDate)
self.assertTrue(datetime.dateti... | DBRunner tests | DBRunnerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBRunnerTests:
"""DBRunner tests"""
def test_parse_dbrunner_args(self):
"""Parse the command line arguments"""
<|body_0|>
def test_parse_dbrunner_args_other(self):
"""Parse the command line with other options"""
<|body_1|>
def test_parse_dbrunner_arg... | stack_v2_sparse_classes_36k_train_018023 | 10,140 | no_license | [
{
"docstring": "Parse the command line arguments",
"name": "test_parse_dbrunner_args",
"signature": "def test_parse_dbrunner_args(self)"
},
{
"docstring": "Parse the command line with other options",
"name": "test_parse_dbrunner_args_other",
"signature": "def test_parse_dbrunner_args_oth... | 3 | stack_v2_sparse_classes_30k_train_015724 | Implement the Python class `DBRunnerTests` described below.
Class description:
DBRunner tests
Method signatures and docstrings:
- def test_parse_dbrunner_args(self): Parse the command line arguments
- def test_parse_dbrunner_args_other(self): Parse the command line with other options
- def test_parse_dbrunner_args_ba... | Implement the Python class `DBRunnerTests` described below.
Class description:
DBRunner tests
Method signatures and docstrings:
- def test_parse_dbrunner_args(self): Parse the command line arguments
- def test_parse_dbrunner_args_other(self): Parse the command line with other options
- def test_parse_dbrunner_args_ba... | a0bf5e682fb917bb707b4f66787b0ecb860efce1 | <|skeleton|>
class DBRunnerTests:
"""DBRunner tests"""
def test_parse_dbrunner_args(self):
"""Parse the command line arguments"""
<|body_0|>
def test_parse_dbrunner_args_other(self):
"""Parse the command line with other options"""
<|body_1|>
def test_parse_dbrunner_arg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DBRunnerTests:
"""DBRunner tests"""
def test_parse_dbrunner_args(self):
"""Parse the command line arguments"""
options = DBRunner.parse_args(['-m', 'foo.sqlite', '-s', '20180101', '5'])
self.assertEqual('5', options.process_id)
self.assertEqual('foo.sqlite', options.missio... | the_stack_v2_python_sparse | unit_tests/test_DBRunner.py | spacepy/dbprocessing | train | 4 |
a58b1024820dfe93db8a0816b54892ba8303acc8 | [
"interactive_interface.InteractiveInterface.__init__(self, default_rule_blacklist, default_rules, all_targets)\nself.pulled = self.active\nself.pull_all = self.add_all\nself.unpull_all = self.remove_all",
"pulled = utils.create_empty_connection_type_dictionary()\nnew_pulls = utils.create_empty_connection_type_dic... | <|body_start_0|>
interactive_interface.InteractiveInterface.__init__(self, default_rule_blacklist, default_rules, all_targets)
self.pulled = self.active
self.pull_all = self.add_all
self.unpull_all = self.remove_all
<|end_body_0|>
<|body_start_1|>
pulled = utils.create_empty_con... | The pulled interface is the set of rules (pubs/subs/services/actions) and rules controlling pulls from other gateways. | PulledInterface | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PulledInterface:
"""The pulled interface is the set of rules (pubs/subs/services/actions) and rules controlling pulls from other gateways."""
def __init__(self, default_rule_blacklist, default_rules, all_targets):
"""Initialises the pulled interface. @param default_rule_blacklist : u... | stack_v2_sparse_classes_36k_train_018024 | 7,732 | permissive | [
{
"docstring": "Initialises the pulled interface. @param default_rule_blacklist : used when in flip all mode @type dictionary of gateway @param default_rules : static rules to pull on startup @type gateway_msgs.msg.RemoteRule[] @param all_targets : static pull all targets to pull to on startup @type string[]",
... | 4 | null | Implement the Python class `PulledInterface` described below.
Class description:
The pulled interface is the set of rules (pubs/subs/services/actions) and rules controlling pulls from other gateways.
Method signatures and docstrings:
- def __init__(self, default_rule_blacklist, default_rules, all_targets): Initialise... | Implement the Python class `PulledInterface` described below.
Class description:
The pulled interface is the set of rules (pubs/subs/services/actions) and rules controlling pulls from other gateways.
Method signatures and docstrings:
- def __init__(self, default_rule_blacklist, default_rules, all_targets): Initialise... | 4a835a04b469360b11243405d4d1f19b706c510d | <|skeleton|>
class PulledInterface:
"""The pulled interface is the set of rules (pubs/subs/services/actions) and rules controlling pulls from other gateways."""
def __init__(self, default_rule_blacklist, default_rules, all_targets):
"""Initialises the pulled interface. @param default_rule_blacklist : u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PulledInterface:
"""The pulled interface is the set of rules (pubs/subs/services/actions) and rules controlling pulls from other gateways."""
def __init__(self, default_rule_blacklist, default_rules, all_targets):
"""Initialises the pulled interface. @param default_rule_blacklist : used when in f... | the_stack_v2_python_sparse | rocon_multimaster/rocon_gateway/src/rocon_gateway/pulled_interface.py | Playfish/cafe_demo | train | 0 |
823db0f1e05a9ed84be71856d9b3ec9558bf9634 | [
"load_file = LoadFileValidator(self.value)\nis_file_loaded = load_file.validate()\nself.append_report(load_file)\nif not is_file_loaded:\n return False\nload_yaml = LoadYamlValidator(load_file)\nis_yaml_loaded = load_yaml.validate()\nself.append_report(load_yaml)\nif not is_yaml_loaded:\n return False\nreques... | <|body_start_0|>
load_file = LoadFileValidator(self.value)
is_file_loaded = load_file.validate()
self.append_report(load_file)
if not is_file_loaded:
return False
load_yaml = LoadYamlValidator(load_file)
is_yaml_loaded = load_yaml.validate()
self.appen... | Validator for an request template. Attributes: - value: The file name or file path as Text. | RequestTemplateValidator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestTemplateValidator:
"""Validator for an request template. Attributes: - value: The file name or file path as Text."""
def validate(self) -> bool:
"""Validates the value. @return: Whether further Validators may continue validating."""
<|body_0|>
def result(self) -> ... | stack_v2_sparse_classes_36k_train_018025 | 7,622 | no_license | [
{
"docstring": "Validates the value. @return: Whether further Validators may continue validating.",
"name": "validate",
"signature": "def validate(self) -> bool"
},
{
"docstring": "TODO: Fill out",
"name": "result",
"signature": "def result(self) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_010773 | Implement the Python class `RequestTemplateValidator` described below.
Class description:
Validator for an request template. Attributes: - value: The file name or file path as Text.
Method signatures and docstrings:
- def validate(self) -> bool: Validates the value. @return: Whether further Validators may continue va... | Implement the Python class `RequestTemplateValidator` described below.
Class description:
Validator for an request template. Attributes: - value: The file name or file path as Text.
Method signatures and docstrings:
- def validate(self) -> bool: Validates the value. @return: Whether further Validators may continue va... | 09e970944f8bc07dc565576cb798c6db4f17b347 | <|skeleton|>
class RequestTemplateValidator:
"""Validator for an request template. Attributes: - value: The file name or file path as Text."""
def validate(self) -> bool:
"""Validates the value. @return: Whether further Validators may continue validating."""
<|body_0|>
def result(self) -> ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestTemplateValidator:
"""Validator for an request template. Attributes: - value: The file name or file path as Text."""
def validate(self) -> bool:
"""Validates the value. @return: Whether further Validators may continue validating."""
load_file = LoadFileValidator(self.value)
... | the_stack_v2_python_sparse | open_crypto/model/validating/request_template_validator.py | SergejUschakow/open-crypto | train | 0 |
d4587ee8eb5e8cd6030a70dbf8d9367a3e698bc6 | [
"super(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')\nself.F = tf.keras.layers.Dense(vocab)\nself.attention = SelfAttention(units)",
"context_v, _ =... | <|body_start_0|>
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')
self.F = tf.keras.layers.Dense(vocab)
self.atte... | class RNNDecoder | RNNDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""class RNNDecoder"""
def __init__(self, vocab, embedding, units, batch):
"""class constructor"""
<|body_0|>
def call(self, x, s_prev, hidden_states):
"""call function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(RNNDecoder... | stack_v2_sparse_classes_36k_train_018026 | 1,101 | no_license | [
{
"docstring": "class constructor",
"name": "__init__",
"signature": "def __init__(self, vocab, embedding, units, batch)"
},
{
"docstring": "call function",
"name": "call",
"signature": "def call(self, x, s_prev, hidden_states)"
}
] | 2 | null | Implement the Python class `RNNDecoder` described below.
Class description:
class RNNDecoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): class constructor
- def call(self, x, s_prev, hidden_states): call function | Implement the Python class `RNNDecoder` described below.
Class description:
class RNNDecoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): class constructor
- def call(self, x, s_prev, hidden_states): call function
<|skeleton|>
class RNNDecoder:
"""class RNNDecoder"""
... | a49eb348ff994f35b0efbbd5ac3ac8ae8ccb57d2 | <|skeleton|>
class RNNDecoder:
"""class RNNDecoder"""
def __init__(self, vocab, embedding, units, batch):
"""class constructor"""
<|body_0|>
def call(self, x, s_prev, hidden_states):
"""call function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNDecoder:
"""class RNNDecoder"""
def __init__(self, vocab, embedding, units, batch):
"""class constructor"""
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, return_sequences=True, retur... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | salmenz/holbertonschool-machine_learning | train | 4 |
8b818cf17d7db0c89971ca3e4d306511919ff490 | [
"import da.build\nimport datetime\nassert da.build.cfgserialiser(datetime.datetime(year=2015, month=10, day=21, hour=7, minute=28)) == '2015-10-21T07:28:00'",
"import da.build\nimport pytest\nwith pytest.raises(TypeError):\n da.build.cfgserialiser(None)"
] | <|body_start_0|>
import da.build
import datetime
assert da.build.cfgserialiser(datetime.datetime(year=2015, month=10, day=21, hour=7, minute=28)) == '2015-10-21T07:28:00'
<|end_body_0|>
<|body_start_1|>
import da.build
import pytest
with pytest.raises(TypeError):
... | Specify the da.build.cfgserialiser() function. | SpecifyCfgserialiser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecifyCfgserialiser:
"""Specify the da.build.cfgserialiser() function."""
def it_serialises_dates_as_iso8601_format_strings(self):
"""cfgserialiser returns ISO 8601 format date strings from datetime input."""
<|body_0|>
def it_raises_type_error_when_given_something_othe... | stack_v2_sparse_classes_36k_train_018027 | 2,391 | permissive | [
{
"docstring": "cfgserialiser returns ISO 8601 format date strings from datetime input.",
"name": "it_serialises_dates_as_iso8601_format_strings",
"signature": "def it_serialises_dates_as_iso8601_format_strings(self)"
},
{
"docstring": "cfgserialiser raises a Type Error when given non-datetime i... | 2 | stack_v2_sparse_classes_30k_train_014073 | Implement the Python class `SpecifyCfgserialiser` described below.
Class description:
Specify the da.build.cfgserialiser() function.
Method signatures and docstrings:
- def it_serialises_dates_as_iso8601_format_strings(self): cfgserialiser returns ISO 8601 format date strings from datetime input.
- def it_raises_type... | Implement the Python class `SpecifyCfgserialiser` described below.
Class description:
Specify the da.build.cfgserialiser() function.
Method signatures and docstrings:
- def it_serialises_dates_as_iso8601_format_strings(self): cfgserialiser returns ISO 8601 format date strings from datetime input.
- def it_raises_type... | 04a13be2792323e3f9fdb83fd236a8e9cfe6aa2d | <|skeleton|>
class SpecifyCfgserialiser:
"""Specify the da.build.cfgserialiser() function."""
def it_serialises_dates_as_iso8601_format_strings(self):
"""cfgserialiser returns ISO 8601 format date strings from datetime input."""
<|body_0|>
def it_raises_type_error_when_given_something_othe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpecifyCfgserialiser:
"""Specify the da.build.cfgserialiser() function."""
def it_serialises_dates_as_iso8601_format_strings(self):
"""cfgserialiser returns ISO 8601 format date strings from datetime input."""
import da.build
import datetime
assert da.build.cfgserialiser(d... | the_stack_v2_python_sparse | a3_src/h70_internal/da/spec/spec_build.py | wtpayne/hiai | train | 5 |
e50d4668751b33b8d5505a300d5236347070edc0 | [
"if classname in ['ElementDeclaration', 'TypeDefinition', 'LocalElementDeclaration']:\n return type.__new__(cls, classname, bases, classdict)\nif ElementDeclaration in bases:\n if not 'schema' in classdict or not 'literal' in classdict:\n raise AttributeError('ElementDeclaration must define schema and ... | <|body_start_0|>
if classname in ['ElementDeclaration', 'TypeDefinition', 'LocalElementDeclaration']:
return type.__new__(cls, classname, bases, classdict)
if ElementDeclaration in bases:
if not 'schema' in classdict or not 'literal' in classdict:
raise AttributeE... | Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing global type definitions. elements -- dict of typecode classes representing global el... | SchemaInstanceType | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaInstanceType:
"""Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing global type definitions. elements -- d... | stack_v2_sparse_classes_36k_train_018028 | 14,557 | permissive | [
{
"docstring": "If classdict has literal and schema register it as a element declaration, else if has type and schema register it as a type definition.",
"name": "__new__",
"signature": "def __new__(cls, classname, bases, classdict)"
},
{
"docstring": "Grab a type definition, returns a typecode ... | 3 | stack_v2_sparse_classes_30k_train_021113 | Implement the Python class `SchemaInstanceType` described below.
Class description:
Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing... | Implement the Python class `SchemaInstanceType` described below.
Class description:
Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing... | 9b890e6a25471037b7485e4999b480de7c86b656 | <|skeleton|>
class SchemaInstanceType:
"""Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing global type definitions. elements -- d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchemaInstanceType:
"""Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing global type definitions. elements -- dict of typeco... | the_stack_v2_python_sparse | Libraries/DUTs/Community/di_vsphere/pysphere/pysphere/ZSI/schema.py | Spirent/iTest-assets | train | 10 |
a0b1525c6d9b870087b3485a44b80141c555c98d | [
"self.__users = []\nself.__lookup = set()\nself.__chunks = collections.defaultdict(set)\nself.__min_heap = []",
"if self.__min_heap:\n userID = heapq.heappop(self.__min_heap)\nelse:\n userID = len(self.__users) + 1\n self.__users.append(set())\nself.__users[userID - 1] = set(ownedChunks)\nself.__lookup.a... | <|body_start_0|>
self.__users = []
self.__lookup = set()
self.__chunks = collections.defaultdict(set)
self.__min_heap = []
<|end_body_0|>
<|body_start_1|>
if self.__min_heap:
userID = heapq.heappop(self.__min_heap)
else:
userID = len(self.__users)... | FileSharing2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileSharing2:
def __init__(self, m):
""":type m: int"""
<|body_0|>
def join(self, ownedChunks):
""":type ownedChunks: List[int] :rtype: int"""
<|body_1|>
def leave(self, userID):
""":type userID: int :rtype: None"""
<|body_2|>
def re... | stack_v2_sparse_classes_36k_train_018029 | 3,320 | permissive | [
{
"docstring": ":type m: int",
"name": "__init__",
"signature": "def __init__(self, m)"
},
{
"docstring": ":type ownedChunks: List[int] :rtype: int",
"name": "join",
"signature": "def join(self, ownedChunks)"
},
{
"docstring": ":type userID: int :rtype: None",
"name": "leave"... | 4 | null | Implement the Python class `FileSharing2` described below.
Class description:
Implement the FileSharing2 class.
Method signatures and docstrings:
- def __init__(self, m): :type m: int
- def join(self, ownedChunks): :type ownedChunks: List[int] :rtype: int
- def leave(self, userID): :type userID: int :rtype: None
- de... | Implement the Python class `FileSharing2` described below.
Class description:
Implement the FileSharing2 class.
Method signatures and docstrings:
- def __init__(self, m): :type m: int
- def join(self, ownedChunks): :type ownedChunks: List[int] :rtype: int
- def leave(self, userID): :type userID: int :rtype: None
- de... | 4dc4e6642dc92f1983c13564cc0fd99917cab358 | <|skeleton|>
class FileSharing2:
def __init__(self, m):
""":type m: int"""
<|body_0|>
def join(self, ownedChunks):
""":type ownedChunks: List[int] :rtype: int"""
<|body_1|>
def leave(self, userID):
""":type userID: int :rtype: None"""
<|body_2|>
def re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileSharing2:
def __init__(self, m):
""":type m: int"""
self.__users = []
self.__lookup = set()
self.__chunks = collections.defaultdict(set)
self.__min_heap = []
def join(self, ownedChunks):
""":type ownedChunks: List[int] :rtype: int"""
if self.__m... | the_stack_v2_python_sparse | Python/design-a-file-sharing-system.py | kamyu104/LeetCode-Solutions | train | 4,549 | |
cc05ea08f9bfe3ed3750c2f942bec9dbee2b882e | [
"if NW1 > SE1 or NW2 > SE2:\n return []\nif NW1 == SE1:\n return matrix[NW1][NW2:SE2 + 1]\nif NW2 == SE2:\n return [matrix[x][SE2] for x in range(NW1, SE1 + 1)]\nrightward = matrix[NW1][NW2:SE2 + 1]\ndownward = [matrix[x][SE2] for x in range(NW1 + 1, SE1 + 1)]\nleftward = [matrix[SE1][x] for x in range(SE2... | <|body_start_0|>
if NW1 > SE1 or NW2 > SE2:
return []
if NW1 == SE1:
return matrix[NW1][NW2:SE2 + 1]
if NW2 == SE2:
return [matrix[x][SE2] for x in range(NW1, SE1 + 1)]
rightward = matrix[NW1][NW2:SE2 + 1]
downward = [matrix[x][SE2] for x in ra... | SpiralMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpiralMatrix:
def spiralOrderHelper(self, matrix, NW1, NW2, SE1, SE2):
"""(NW1, NW2) is the starting northwestern coordinate, (SE1, SE2) is the starting southeastern coordinate"""
<|body_0|>
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List... | stack_v2_sparse_classes_36k_train_018030 | 2,158 | no_license | [
{
"docstring": "(NW1, NW2) is the starting northwestern coordinate, (SE1, SE2) is the starting southeastern coordinate",
"name": "spiralOrderHelper",
"signature": "def spiralOrderHelper(self, matrix, NW1, NW2, SE1, SE2)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int]",
"n... | 2 | null | Implement the Python class `SpiralMatrix` described below.
Class description:
Implement the SpiralMatrix class.
Method signatures and docstrings:
- def spiralOrderHelper(self, matrix, NW1, NW2, SE1, SE2): (NW1, NW2) is the starting northwestern coordinate, (SE1, SE2) is the starting southeastern coordinate
- def spir... | Implement the Python class `SpiralMatrix` described below.
Class description:
Implement the SpiralMatrix class.
Method signatures and docstrings:
- def spiralOrderHelper(self, matrix, NW1, NW2, SE1, SE2): (NW1, NW2) is the starting northwestern coordinate, (SE1, SE2) is the starting southeastern coordinate
- def spir... | 035d760182094cf4a6ad44a9112bea4dcb8d58c1 | <|skeleton|>
class SpiralMatrix:
def spiralOrderHelper(self, matrix, NW1, NW2, SE1, SE2):
"""(NW1, NW2) is the starting northwestern coordinate, (SE1, SE2) is the starting southeastern coordinate"""
<|body_0|>
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpiralMatrix:
def spiralOrderHelper(self, matrix, NW1, NW2, SE1, SE2):
"""(NW1, NW2) is the starting northwestern coordinate, (SE1, SE2) is the starting southeastern coordinate"""
if NW1 > SE1 or NW2 > SE2:
return []
if NW1 == SE1:
return matrix[NW1][NW2:SE2 + 1... | the_stack_v2_python_sparse | SpiralMatrix.py | jingtaisong/LeetCodePython | train | 0 | |
dc5ede1c14d55a3946c904f5acf7db914fc1e712 | [
"if not head or not head.next or (not head.next.next):\n return\nhead2 = self.findMid(head)\nhead2 = self.reverseList(head2)\nself.zigZagMerge(head, head2)",
"slow, fast = (head, head.next)\nwhile fast:\n slow = slow.next\n fast = fast.next.next if fast.next else None\nhead2, slow.next = (slow.next, None... | <|body_start_0|>
if not head or not head.next or (not head.next.next):
return
head2 = self.findMid(head)
head2 = self.reverseList(head2)
self.zigZagMerge(head, head2)
<|end_body_0|>
<|body_start_1|>
slow, fast = (head, head.next)
while fast:
slow ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reorderList(self, head):
""":type head: ListNode :rtype: None Do not return anything, modify head in-place instead."""
<|body_0|>
def findMid(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
def reverseList(self, head):
... | stack_v2_sparse_classes_36k_train_018031 | 2,938 | no_license | [
{
"docstring": ":type head: ListNode :rtype: None Do not return anything, modify head in-place instead.",
"name": "reorderList",
"signature": "def reorderList(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "findMid",
"signature": "def findMid(self, head)"... | 4 | stack_v2_sparse_classes_30k_train_019742 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reorderList(self, head): :type head: ListNode :rtype: None Do not return anything, modify head in-place instead.
- def findMid(self, head): :type head: ListNode :rtype: ListN... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reorderList(self, head): :type head: ListNode :rtype: None Do not return anything, modify head in-place instead.
- def findMid(self, head): :type head: ListNode :rtype: ListN... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class Solution:
def reorderList(self, head):
""":type head: ListNode :rtype: None Do not return anything, modify head in-place instead."""
<|body_0|>
def findMid(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
def reverseList(self, head):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reorderList(self, head):
""":type head: ListNode :rtype: None Do not return anything, modify head in-place instead."""
if not head or not head.next or (not head.next.next):
return
head2 = self.findMid(head)
head2 = self.reverseList(head2)
self.... | the_stack_v2_python_sparse | Solutions/0143_reorderList.py | YoupengLi/leetcode-sorting | train | 3 | |
4dfa09e1565b6b96a428d2fb37b9789528f35d93 | [
"self.main_path = os.getcwd()\nself.model_name = params.model_name\nself.model_path = self.main_path + '\\\\' + self.model_name\nself.check_dir(self.model_path)\nself.log_path = self.main_path + '\\\\runs\\\\' + self.model_name\nself.check_dir(self.log_path, remove=True)\nself.save_model = params.save_model\nself.c... | <|body_start_0|>
self.main_path = os.getcwd()
self.model_name = params.model_name
self.model_path = self.main_path + '\\' + self.model_name
self.check_dir(self.model_path)
self.log_path = self.main_path + '\\runs\\' + self.model_name
self.check_dir(self.log_path, remove=T... | Initialize | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Initialize:
def __init__(self):
"""Constructor"""
<|body_0|>
def determine_device(self):
"""This function evaluates whether a GPU is accessible at the system and returns it as device to calculate on, otherwise it returns the CPU. :return: The device where tensor calc... | stack_v2_sparse_classes_36k_train_018032 | 3,336 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This function evaluates whether a GPU is accessible at the system and returns it as device to calculate on, otherwise it returns the CPU. :return: The device where tensor calculations shall be ... | 3 | stack_v2_sparse_classes_30k_train_010767 | Implement the Python class `Initialize` described below.
Class description:
Implement the Initialize class.
Method signatures and docstrings:
- def __init__(self): Constructor
- def determine_device(self): This function evaluates whether a GPU is accessible at the system and returns it as device to calculate on, othe... | Implement the Python class `Initialize` described below.
Class description:
Implement the Initialize class.
Method signatures and docstrings:
- def __init__(self): Constructor
- def determine_device(self): This function evaluates whether a GPU is accessible at the system and returns it as device to calculate on, othe... | ac74f3b7dfee21835fa0a29bf8202f33b9f15e28 | <|skeleton|>
class Initialize:
def __init__(self):
"""Constructor"""
<|body_0|>
def determine_device(self):
"""This function evaluates whether a GPU is accessible at the system and returns it as device to calculate on, otherwise it returns the CPU. :return: The device where tensor calc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Initialize:
def __init__(self):
"""Constructor"""
self.main_path = os.getcwd()
self.model_name = params.model_name
self.model_path = self.main_path + '\\' + self.model_name
self.check_dir(self.model_path)
self.log_path = self.main_path + '\\runs\\' + self.model_... | the_stack_v2_python_sparse | python/diffusion_sorption/experimental_data/exp02_init.py | cryptowealth-technology/finn | train | 0 | |
4a155b2bbdcb96728724e24e1968547f0ce4cc14 | [
"outs = ()\nrois = bbox2roi([proposals])\nif self.with_bbox:\n bbox_results = self._bbox_forward(x, rois)\n outs = outs + (bbox_results['cls_score'], bbox_results['bbox_pred'], bbox_results['fix_pred'], bbox_results['ratio_pred'])\nreturn outs",
"bbox_feats = self.bbox_roi_extractor(x[:self.bbox_roi_extract... | <|body_start_0|>
outs = ()
rois = bbox2roi([proposals])
if self.with_bbox:
bbox_results = self._bbox_forward(x, rois)
outs = outs + (bbox_results['cls_score'], bbox_results['bbox_pred'], bbox_results['fix_pred'], bbox_results['ratio_pred'])
return outs
<|end_body_... | Gliding vertex roi head including one bbox head. | GVRatioRoIHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GVRatioRoIHead:
"""Gliding vertex roi head including one bbox head."""
def forward_dummy(self, x, proposals):
"""Dummy forward function. Args: x (list[Tensors]): list of multi-level img features. proposals (list[Tensors]): list of region proposals. Returns: list[Tensors]: list of reg... | stack_v2_sparse_classes_36k_train_018033 | 6,341 | permissive | [
{
"docstring": "Dummy forward function. Args: x (list[Tensors]): list of multi-level img features. proposals (list[Tensors]): list of region proposals. Returns: list[Tensors]: list of region of interest.",
"name": "forward_dummy",
"signature": "def forward_dummy(self, x, proposals)"
},
{
"docstr... | 4 | stack_v2_sparse_classes_30k_train_012747 | Implement the Python class `GVRatioRoIHead` described below.
Class description:
Gliding vertex roi head including one bbox head.
Method signatures and docstrings:
- def forward_dummy(self, x, proposals): Dummy forward function. Args: x (list[Tensors]): list of multi-level img features. proposals (list[Tensors]): list... | Implement the Python class `GVRatioRoIHead` described below.
Class description:
Gliding vertex roi head including one bbox head.
Method signatures and docstrings:
- def forward_dummy(self, x, proposals): Dummy forward function. Args: x (list[Tensors]): list of multi-level img features. proposals (list[Tensors]): list... | 9ea1aeeef2da8b2cd5161b72f4e33e1e8293dcb2 | <|skeleton|>
class GVRatioRoIHead:
"""Gliding vertex roi head including one bbox head."""
def forward_dummy(self, x, proposals):
"""Dummy forward function. Args: x (list[Tensors]): list of multi-level img features. proposals (list[Tensors]): list of region proposals. Returns: list[Tensors]: list of reg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GVRatioRoIHead:
"""Gliding vertex roi head including one bbox head."""
def forward_dummy(self, x, proposals):
"""Dummy forward function. Args: x (list[Tensors]): list of multi-level img features. proposals (list[Tensors]): list of region proposals. Returns: list[Tensors]: list of region of intere... | the_stack_v2_python_sparse | mmrotate/models/roi_heads/gv_ratio_roi_head.py | open-mmlab/mmrotate | train | 1,473 |
61521c6292f5379d8267a6d69bf86cfc6c665445 | [
"n = SCons.Node.Node()\nbi = SCons.Node.BuildInfoBase()\nassert bi",
"n1 = SCons.Node.Node()\nbi1 = SCons.Node.BuildInfoBase()\nn2 = SCons.Node.Node()\nbi2 = SCons.Node.BuildInfoBase()\nbi1.bsources = 1\nbi1.bdepends = 2\nbi2.bdepends = 222\nbi2.bact = 333\nbi1.merge(bi2)\nassert bi1.bsources == 1, bi1.bsources\n... | <|body_start_0|>
n = SCons.Node.Node()
bi = SCons.Node.BuildInfoBase()
assert bi
<|end_body_0|>
<|body_start_1|>
n1 = SCons.Node.Node()
bi1 = SCons.Node.BuildInfoBase()
n2 = SCons.Node.Node()
bi2 = SCons.Node.BuildInfoBase()
bi1.bsources = 1
bi1.b... | BuildInfoBaseTestCase | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildInfoBaseTestCase:
def test___init__(self) -> None:
"""Test BuildInfoBase initialization"""
<|body_0|>
def test_merge(self) -> None:
"""Test merging BuildInfoBase attributes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = SCons.Node.Node()
... | stack_v2_sparse_classes_36k_train_018034 | 43,330 | permissive | [
{
"docstring": "Test BuildInfoBase initialization",
"name": "test___init__",
"signature": "def test___init__(self) -> None"
},
{
"docstring": "Test merging BuildInfoBase attributes",
"name": "test_merge",
"signature": "def test_merge(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_val_000783 | Implement the Python class `BuildInfoBaseTestCase` described below.
Class description:
Implement the BuildInfoBaseTestCase class.
Method signatures and docstrings:
- def test___init__(self) -> None: Test BuildInfoBase initialization
- def test_merge(self) -> None: Test merging BuildInfoBase attributes | Implement the Python class `BuildInfoBaseTestCase` described below.
Class description:
Implement the BuildInfoBaseTestCase class.
Method signatures and docstrings:
- def test___init__(self) -> None: Test BuildInfoBase initialization
- def test_merge(self) -> None: Test merging BuildInfoBase attributes
<|skeleton|>
c... | b2a7d7066a2b854460a334a5fe737ea389655e6e | <|skeleton|>
class BuildInfoBaseTestCase:
def test___init__(self) -> None:
"""Test BuildInfoBase initialization"""
<|body_0|>
def test_merge(self) -> None:
"""Test merging BuildInfoBase attributes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuildInfoBaseTestCase:
def test___init__(self) -> None:
"""Test BuildInfoBase initialization"""
n = SCons.Node.Node()
bi = SCons.Node.BuildInfoBase()
assert bi
def test_merge(self) -> None:
"""Test merging BuildInfoBase attributes"""
n1 = SCons.Node.Node()
... | the_stack_v2_python_sparse | SCons/Node/NodeTests.py | SCons/scons | train | 1,827 | |
65af988e10bdc94a5c147884d4f93bc35c01ffee | [
"length = len(nums)\nif length <= 1:\n return length\ndp = [1] * length\nfor i in range(1, length):\n if nums[i] > nums[i - 1]:\n dp[i] = dp[i - 1] + 1\nreturn max(dp)",
"if not nums:\n return 0\nl = len(nums)\nres = 0\ntmp = nums[0] - 1\ncount = 0\nfor x in range(l):\n if nums[x] > tmp:\n ... | <|body_start_0|>
length = len(nums)
if length <= 1:
return length
dp = [1] * length
for i in range(1, length):
if nums[i] > nums[i - 1]:
dp[i] = dp[i - 1] + 1
return max(dp)
<|end_body_0|>
<|body_start_1|>
if not nums:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLengthOfLCIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findLengthOfLCIS2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = len(nums)
if leng... | stack_v2_sparse_classes_36k_train_018035 | 1,878 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findLengthOfLCIS",
"signature": "def findLengthOfLCIS(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findLengthOfLCIS2",
"signature": "def findLengthOfLCIS2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018872 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLengthOfLCIS(self, nums): :type nums: List[int] :rtype: int
- def findLengthOfLCIS2(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 findLengthOfLCIS(self, nums): :type nums: List[int] :rtype: int
- def findLengthOfLCIS2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def ... | b0f498ebe84e46b7e17e94759dd462891dcc8f85 | <|skeleton|>
class Solution:
def findLengthOfLCIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findLengthOfLCIS2(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 findLengthOfLCIS(self, nums):
""":type nums: List[int] :rtype: int"""
length = len(nums)
if length <= 1:
return length
dp = [1] * length
for i in range(1, length):
if nums[i] > nums[i - 1]:
dp[i] = dp[i - 1] + 1
... | the_stack_v2_python_sparse | 字节跳动/array-and-sorting_4.py | wulinlw/leetcode_cn | train | 0 | |
b28c4c3f2782b9f2d343a3ae3dcfbfbcaadaad0a | [
"self._grammar = zinc_grammar\nself._model = models.model_zinc\nself.MAX_LEN = self._model.MAX_LEN\nself._productions = self._grammar.GCFG.productions()\nself._prod_map = {}\nfor ix, prod in enumerate(self._productions):\n self._prod_map[prod] = ix\nself._parser = nltk.ChartParser(self._grammar.GCFG)\nself._toke... | <|body_start_0|>
self._grammar = zinc_grammar
self._model = models.model_zinc
self.MAX_LEN = self._model.MAX_LEN
self._productions = self._grammar.GCFG.productions()
self._prod_map = {}
for ix, prod in enumerate(self._productions):
self._prod_map[prod] = ix
... | ZincGrammarModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZincGrammarModel:
def __init__(self, weights_file, latent_rep_size=56):
"""Load the (trained) zinc encoder/decoder, grammar model."""
<|body_0|>
def encode(self, smiles):
"""Encode a list of smiles strings into the latent space"""
<|body_1|>
def _sample_... | stack_v2_sparse_classes_36k_train_018036 | 6,515 | permissive | [
{
"docstring": "Load the (trained) zinc encoder/decoder, grammar model.",
"name": "__init__",
"signature": "def __init__(self, weights_file, latent_rep_size=56)"
},
{
"docstring": "Encode a list of smiles strings into the latent space",
"name": "encode",
"signature": "def encode(self, sm... | 4 | stack_v2_sparse_classes_30k_train_009422 | Implement the Python class `ZincGrammarModel` described below.
Class description:
Implement the ZincGrammarModel class.
Method signatures and docstrings:
- def __init__(self, weights_file, latent_rep_size=56): Load the (trained) zinc encoder/decoder, grammar model.
- def encode(self, smiles): Encode a list of smiles ... | Implement the Python class `ZincGrammarModel` described below.
Class description:
Implement the ZincGrammarModel class.
Method signatures and docstrings:
- def __init__(self, weights_file, latent_rep_size=56): Load the (trained) zinc encoder/decoder, grammar model.
- def encode(self, smiles): Encode a list of smiles ... | 23781fedaa942ca5614054f965cb7b6543e533fa | <|skeleton|>
class ZincGrammarModel:
def __init__(self, weights_file, latent_rep_size=56):
"""Load the (trained) zinc encoder/decoder, grammar model."""
<|body_0|>
def encode(self, smiles):
"""Encode a list of smiles strings into the latent space"""
<|body_1|>
def _sample_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZincGrammarModel:
def __init__(self, weights_file, latent_rep_size=56):
"""Load the (trained) zinc encoder/decoder, grammar model."""
self._grammar = zinc_grammar
self._model = models.model_zinc
self.MAX_LEN = self._model.MAX_LEN
self._productions = self._grammar.GCFG.p... | the_stack_v2_python_sparse | pretrained_mol_sim/molecule_vae.py | andreeadeac22/graph_coattention | train | 15 | |
ac8171c4df7f4c82148166709915cfce31a97b2b | [
"key = ''.join(map(str, cells))\nmemo = {key: 0}\nmemo_num2cell = {0: key}\ncount = 0\nwhile True:\n next_cells = [0] * 8\n for i in range(1, 7):\n if cells[i - 1] == cells[i + 1]:\n next_cells[i] = 1\n print('cells:', cells, count)\n cells = next_cells\n count += 1\n key = ''.jo... | <|body_start_0|>
key = ''.join(map(str, cells))
memo = {key: 0}
memo_num2cell = {0: key}
count = 0
while True:
next_cells = [0] * 8
for i in range(1, 7):
if cells[i - 1] == cells[i + 1]:
next_cells[i] = 1
pri... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def prisonAfterNDays(self, cells, N):
""":type cells: List[int] :type N: int :rtype: List[int] 52 ms"""
<|body_0|>
def prisonAfterNDays_1(self, cells, N):
""":type cells: List[int] :type N: int :rtype: List[int] 44MS"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_018037 | 2,973 | no_license | [
{
"docstring": ":type cells: List[int] :type N: int :rtype: List[int] 52 ms",
"name": "prisonAfterNDays",
"signature": "def prisonAfterNDays(self, cells, N)"
},
{
"docstring": ":type cells: List[int] :type N: int :rtype: List[int] 44MS",
"name": "prisonAfterNDays_1",
"signature": "def pr... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def prisonAfterNDays(self, cells, N): :type cells: List[int] :type N: int :rtype: List[int] 52 ms
- def prisonAfterNDays_1(self, cells, N): :type cells: List[int] :type N: int :r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def prisonAfterNDays(self, cells, N): :type cells: List[int] :type N: int :rtype: List[int] 52 ms
- def prisonAfterNDays_1(self, cells, N): :type cells: List[int] :type N: int :r... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def prisonAfterNDays(self, cells, N):
""":type cells: List[int] :type N: int :rtype: List[int] 52 ms"""
<|body_0|>
def prisonAfterNDays_1(self, cells, N):
""":type cells: List[int] :type N: int :rtype: List[int] 44MS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def prisonAfterNDays(self, cells, N):
""":type cells: List[int] :type N: int :rtype: List[int] 52 ms"""
key = ''.join(map(str, cells))
memo = {key: 0}
memo_num2cell = {0: key}
count = 0
while True:
next_cells = [0] * 8
for i in ... | the_stack_v2_python_sparse | PrisonCellsAfterNDays_MID_957.py | 953250587/leetcode-python | train | 2 | |
8c524ec2f4c642ede47ce65a41338d4cf013da93 | [
"self.agent_class = agent_class\nself.agent_count = agent_count\nself.agent_args = agent_args\nsuper().__init__(self.model_class, agents_per_model=2, seed=seed)\nself.dc = DataCollector(tables={'Interactions': ['Step', 'A', 'B', 'Outcome', 'SPE', 'quality'], 'Agents': ['Name', 'Assets', 'Capability', 'Bloc']})\nfor... | <|body_start_0|>
self.agent_class = agent_class
self.agent_count = agent_count
self.agent_args = agent_args
super().__init__(self.model_class, agents_per_model=2, seed=seed)
self.dc = DataCollector(tables={'Interactions': ['Step', 'A', 'B', 'Outcome', 'SPE', 'quality'], 'Agents':... | Basic MetaModel for running multiple iterations with a fixed population. By default, creates agents with random military strength, assets and bloc membership. Fixed agent parameters (e.g. learning rates) can be passed as a dictionary. To generate more complex behaviors, override the make_agents method. By default, the ... | CrisisWorld | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrisisWorld:
"""Basic MetaModel for running multiple iterations with a fixed population. By default, creates agents with random military strength, assets and bloc membership. Fixed agent parameters (e.g. learning rates) can be passed as a dictionary. To generate more complex behaviors, override t... | stack_v2_sparse_classes_36k_train_018038 | 8,721 | no_license | [
{
"docstring": "Instantiate a new CrisisWorld model. Args: agent_class: Class to instantiate the agents agent_count: How many agents to instantiate with. agent_args: Dictionary of arguments to pass to all agents. seed: Random seed to launch the model with.",
"name": "__init__",
"signature": "def __init_... | 4 | null | Implement the Python class `CrisisWorld` described below.
Class description:
Basic MetaModel for running multiple iterations with a fixed population. By default, creates agents with random military strength, assets and bloc membership. Fixed agent parameters (e.g. learning rates) can be passed as a dictionary. To gene... | Implement the Python class `CrisisWorld` described below.
Class description:
Basic MetaModel for running multiple iterations with a fixed population. By default, creates agents with random military strength, assets and bloc membership. Fixed agent parameters (e.g. learning rates) can be passed as a dictionary. To gene... | 5e9a0e03aa7ddf5e5ddf89943ccc68d94b539e95 | <|skeleton|>
class CrisisWorld:
"""Basic MetaModel for running multiple iterations with a fixed population. By default, creates agents with random military strength, assets and bloc membership. Fixed agent parameters (e.g. learning rates) can be passed as a dictionary. To generate more complex behaviors, override t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrisisWorld:
"""Basic MetaModel for running multiple iterations with a fixed population. By default, creates agents with random military strength, assets and bloc membership. Fixed agent parameters (e.g. learning rates) can be passed as a dictionary. To generate more complex behaviors, override the make_agent... | the_stack_v2_python_sparse | Predicting_Politics_Mesquita/Agents-In-Conflict-master/Code/WarReason/models/crisis_game/small_crisis.py | burakbayramli/books | train | 223 |
be253ce7d07cd3c3ddaa83a409c12f0c513cc5da | [
"user_list = None\nif query == None:\n user_list = User.objects.filter(Q(user_profile__isnull=False))\nelse:\n user_list = User.objects.filter(Q(first_name__icontains=query) | Q(last_name__icontains=query)).distinct()\nreturn user_list",
"user_list = None\nif query == None:\n user_list = User.objects.fil... | <|body_start_0|>
user_list = None
if query == None:
user_list = User.objects.filter(Q(user_profile__isnull=False))
else:
user_list = User.objects.filter(Q(first_name__icontains=query) | Q(last_name__icontains=query)).distinct()
return user_list
<|end_body_0|>
<|b... | This module contains service classes for performing services related searching user profiles. | UserSearchService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSearchService:
"""This module contains service classes for performing services related searching user profiles."""
def get_users_by_name(query):
"""This static method searches for all users with given query in their first name or last name or query as one of their skills."""
... | stack_v2_sparse_classes_36k_train_018039 | 1,909 | permissive | [
{
"docstring": "This static method searches for all users with given query in their first name or last name or query as one of their skills.",
"name": "get_users_by_name",
"signature": "def get_users_by_name(query)"
},
{
"docstring": "This static method searches for all users with given query as... | 3 | stack_v2_sparse_classes_30k_train_016273 | Implement the Python class `UserSearchService` described below.
Class description:
This module contains service classes for performing services related searching user profiles.
Method signatures and docstrings:
- def get_users_by_name(query): This static method searches for all users with given query in their first n... | Implement the Python class `UserSearchService` described below.
Class description:
This module contains service classes for performing services related searching user profiles.
Method signatures and docstrings:
- def get_users_by_name(query): This static method searches for all users with given query in their first n... | 3ad913e1030da5c4fb0ac4690488a48dec278f3b | <|skeleton|>
class UserSearchService:
"""This module contains service classes for performing services related searching user profiles."""
def get_users_by_name(query):
"""This static method searches for all users with given query in their first name or last name or query as one of their skills."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSearchService:
"""This module contains service classes for performing services related searching user profiles."""
def get_users_by_name(query):
"""This static method searches for all users with given query in their first name or last name or query as one of their skills."""
user_list... | the_stack_v2_python_sparse | sase/mycraze/services/search.py | SrikrishnanS/ProfilesHub | train | 0 |
fb6c99e65a41e15630519bfc7f0e9c1177af1eed | [
"super(LuongAttention, self).__init__()\nself.attention_func = attention_func\nif attention_func not in ['dot', 'general', 'concat']:\n raise ValueError('Unknown attention score function! Must be either dot, general or concat.')\nif attention_func == 'general':\n self.wa = tf.keras.layers.Dense(rnn_size)\neli... | <|body_start_0|>
super(LuongAttention, self).__init__()
self.attention_func = attention_func
if attention_func not in ['dot', 'general', 'concat']:
raise ValueError('Unknown attention score function! Must be either dot, general or concat.')
if attention_func == 'general':
... | Attention layer used with the gru model. | LuongAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LuongAttention:
"""Attention layer used with the gru model."""
def __init__(self, rnn_size, attention_func='dot'):
"""Create the attention layer."""
<|body_0|>
def call(self, decoder_output, encoder_output):
"""Call of the attention layer. Note that the call must... | stack_v2_sparse_classes_36k_train_018040 | 8,912 | no_license | [
{
"docstring": "Create the attention layer.",
"name": "__init__",
"signature": "def __init__(self, rnn_size, attention_func='dot')"
},
{
"docstring": "Call of the attention layer. Note that the call must be for one caracter/word at a time.",
"name": "call",
"signature": "def call(self, d... | 2 | stack_v2_sparse_classes_30k_train_001677 | Implement the Python class `LuongAttention` described below.
Class description:
Attention layer used with the gru model.
Method signatures and docstrings:
- def __init__(self, rnn_size, attention_func='dot'): Create the attention layer.
- def call(self, decoder_output, encoder_output): Call of the attention layer. No... | Implement the Python class `LuongAttention` described below.
Class description:
Attention layer used with the gru model.
Method signatures and docstrings:
- def __init__(self, rnn_size, attention_func='dot'): Create the attention layer.
- def call(self, decoder_output, encoder_output): Call of the attention layer. No... | 4502d9e7461520664e72165a91bedd8e65464bae | <|skeleton|>
class LuongAttention:
"""Attention layer used with the gru model."""
def __init__(self, rnn_size, attention_func='dot'):
"""Create the attention layer."""
<|body_0|>
def call(self, decoder_output, encoder_output):
"""Call of the attention layer. Note that the call must... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LuongAttention:
"""Attention layer used with the gru model."""
def __init__(self, rnn_size, attention_func='dot'):
"""Create the attention layer."""
super(LuongAttention, self).__init__()
self.attention_func = attention_func
if attention_func not in ['dot', 'general', 'con... | the_stack_v2_python_sparse | src/model/lstm_luong_attention.py | nathanielsimard/Low-Resource-Machine-Translation | train | 0 |
fbb6b021cfe2644005744a3e4d97f1ffa4cd8fa4 | [
"self.file_name = file_name\ndtype = np.dtype = [('lih', '<i4'), ('liu', '<i4'), ('liv', '<i4'), ('h', '<f4'), ('u', '<f4'), ('v', '<f4'), ('au', '<f4'), ('lit', '<i4'), ('t', '<f4'), ('at', '<f4'), ('bt', '<f4'), ('n', '<i4'), ('line', '<i4')]\nif file_name != '':\n core = [tuple(line.strip().split()[0:13]) for... | <|body_start_0|>
self.file_name = file_name
dtype = np.dtype = [('lih', '<i4'), ('liu', '<i4'), ('liv', '<i4'), ('h', '<f4'), ('u', '<f4'), ('v', '<f4'), ('au', '<f4'), ('lit', '<i4'), ('t', '<f4'), ('at', '<f4'), ('bt', '<f4'), ('n', '<i4'), ('line', '<i4')]
if file_name != '':
core... | Boundary conditions class | Conlim | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conlim:
"""Boundary conditions class"""
def __init__(self, file_name):
"""@brief Initializes the Conlim object @param file_name (string): name of the boundary conditions file @return None"""
<|body_0|>
def set_numliq(self, closed_contours):
"""@brief Sets the num... | stack_v2_sparse_classes_36k_train_018041 | 6,142 | no_license | [
{
"docstring": "@brief Initializes the Conlim object @param file_name (string): name of the boundary conditions file @return None",
"name": "__init__",
"signature": "def __init__(self, file_name)"
},
{
"docstring": "@brief Sets the number of liquid boundaries @param closed_contours (list): list ... | 3 | stack_v2_sparse_classes_30k_train_010033 | Implement the Python class `Conlim` described below.
Class description:
Boundary conditions class
Method signatures and docstrings:
- def __init__(self, file_name): @brief Initializes the Conlim object @param file_name (string): name of the boundary conditions file @return None
- def set_numliq(self, closed_contours)... | Implement the Python class `Conlim` described below.
Class description:
Boundary conditions class
Method signatures and docstrings:
- def __init__(self, file_name): @brief Initializes the Conlim object @param file_name (string): name of the boundary conditions file @return None
- def set_numliq(self, closed_contours)... | 738e8e491e10bbbc3c21afe01221ed4661ce8a87 | <|skeleton|>
class Conlim:
"""Boundary conditions class"""
def __init__(self, file_name):
"""@brief Initializes the Conlim object @param file_name (string): name of the boundary conditions file @return None"""
<|body_0|>
def set_numliq(self, closed_contours):
"""@brief Sets the num... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conlim:
"""Boundary conditions class"""
def __init__(self, file_name):
"""@brief Initializes the Conlim object @param file_name (string): name of the boundary conditions file @return None"""
self.file_name = file_name
dtype = np.dtype = [('lih', '<i4'), ('liu', '<i4'), ('liv', '<i... | the_stack_v2_python_sparse | scripts/python3/data_manip/formats/conlim.py | msecher/scripts_python_3_opentelemac_r14499 | train | 0 |
9f98e6ee8337efd32f2c7ed80d4d3f460fd37752 | [
"EasyFrame.__init__(self, 'Calculator')\nself.digits = self.addLabel('', row=0, column=0, columnspan=3, sticky='NSEW')\ndigit = 9\nfor row in range(1, 4):\n for column in range(0, 3):\n button = self.addButton(str(digit), row, column)\n button['command'] = self.makeCommand(button)\n digit -=... | <|body_start_0|>
EasyFrame.__init__(self, 'Calculator')
self.digits = self.addLabel('', row=0, column=0, columnspan=3, sticky='NSEW')
digit = 9
for row in range(1, 4):
for column in range(0, 3):
button = self.addButton(str(digit), row, column)
... | Illustrates command buttons and user events. | CalculatorDemo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalculatorDemo:
"""Illustrates command buttons and user events."""
def __init__(self):
"""Sets up the window, label, and buttons."""
<|body_0|>
def makeCommand(self, button):
"""Define and return the event handler for the button."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_018042 | 1,041 | no_license | [
{
"docstring": "Sets up the window, label, and buttons.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Define and return the event handler for the button.",
"name": "makeCommand",
"signature": "def makeCommand(self, button)"
}
] | 2 | null | Implement the Python class `CalculatorDemo` described below.
Class description:
Illustrates command buttons and user events.
Method signatures and docstrings:
- def __init__(self): Sets up the window, label, and buttons.
- def makeCommand(self, button): Define and return the event handler for the button. | Implement the Python class `CalculatorDemo` described below.
Class description:
Illustrates command buttons and user events.
Method signatures and docstrings:
- def __init__(self): Sets up the window, label, and buttons.
- def makeCommand(self, button): Define and return the event handler for the button.
<|skeleton|... | eca69d000dc77681a30734b073b2383c97ccc02e | <|skeleton|>
class CalculatorDemo:
"""Illustrates command buttons and user events."""
def __init__(self):
"""Sets up the window, label, and buttons."""
<|body_0|>
def makeCommand(self, button):
"""Define and return the event handler for the button."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CalculatorDemo:
"""Illustrates command buttons and user events."""
def __init__(self):
"""Sets up the window, label, and buttons."""
EasyFrame.__init__(self, 'Calculator')
self.digits = self.addLabel('', row=0, column=0, columnspan=3, sticky='NSEW')
digit = 9
for r... | the_stack_v2_python_sparse | gui/breezy/calculatordemo.py | lforet/robomow | train | 11 |
4678f8f99fd371d8d0bd044f556d5f8a447d82d4 | [
"params_dict = dict(self.initparams)\nparams_dict['custid'] = ''\nstatus_error_code = EnumCommonCode.STATUS_CODE_PARAM_ERROR.value\nreturn (params_dict, status_error_code)",
"params_dict = dict(self.initparams)\nparams_dict['custid'] = 12333321\nstatus_error_code = EnumCommonCode.STATUS_CODE_CUST_GET_NOT_EXISTS.v... | <|body_start_0|>
params_dict = dict(self.initparams)
params_dict['custid'] = ''
status_error_code = EnumCommonCode.STATUS_CODE_PARAM_ERROR.value
return (params_dict, status_error_code)
<|end_body_0|>
<|body_start_1|>
params_dict = dict(self.initparams)
params_dict['custi... | 根据custid取得用户信息(读库) | Get_USER_Viptype | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Get_USER_Viptype:
"""根据custid取得用户信息(读库)"""
def custid_empty(self):
"""custid为空"""
<|body_0|>
def custid_not_exist(self):
"""custid不存在"""
<|body_1|>
def success(self):
"""参数正确,返回用户信息"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_018043 | 1,648 | no_license | [
{
"docstring": "custid为空",
"name": "custid_empty",
"signature": "def custid_empty(self)"
},
{
"docstring": "custid不存在",
"name": "custid_not_exist",
"signature": "def custid_not_exist(self)"
},
{
"docstring": "参数正确,返回用户信息",
"name": "success",
"signature": "def success(self... | 3 | null | Implement the Python class `Get_USER_Viptype` described below.
Class description:
根据custid取得用户信息(读库)
Method signatures and docstrings:
- def custid_empty(self): custid为空
- def custid_not_exist(self): custid不存在
- def success(self): 参数正确,返回用户信息 | Implement the Python class `Get_USER_Viptype` described below.
Class description:
根据custid取得用户信息(读库)
Method signatures and docstrings:
- def custid_empty(self): custid为空
- def custid_not_exist(self): custid不存在
- def success(self): 参数正确,返回用户信息
<|skeleton|>
class Get_USER_Viptype:
"""根据custid取得用户信息(读库)"""
def... | 7f5c78e083812b49d32a394dd81b55dc90ccf080 | <|skeleton|>
class Get_USER_Viptype:
"""根据custid取得用户信息(读库)"""
def custid_empty(self):
"""custid为空"""
<|body_0|>
def custid_not_exist(self):
"""custid不存在"""
<|body_1|>
def success(self):
"""参数正确,返回用户信息"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Get_USER_Viptype:
"""根据custid取得用户信息(读库)"""
def custid_empty(self):
"""custid为空"""
params_dict = dict(self.initparams)
params_dict['custid'] = ''
status_error_code = EnumCommonCode.STATUS_CODE_PARAM_ERROR.value
return (params_dict, status_error_code)
def custid... | the_stack_v2_python_sparse | testcase/Loginapi/Get_User_Viptype_test.py | gitchenping/apitest | train | 0 |
89b5d892e6f735d7d98a625e8e96ce7cc071392c | [
"if N < 1 or N > 50:\n raise ValueError\nself.size = N",
"self.deck = Deck()\nself.deck.shuffle()\nself.cards_dealt = []\nfor i in range(self.size):\n self.cards_dealt.append(self.deck.deal())",
"self.repeated_cards = False\nif len(self.deck.cards) > 0:\n try:\n for i, j in itertools.combination... | <|body_start_0|>
if N < 1 or N > 50:
raise ValueError
self.size = N
<|end_body_0|>
<|body_start_1|>
self.deck = Deck()
self.deck.shuffle()
self.cards_dealt = []
for i in range(self.size):
self.cards_dealt.append(self.deck.deal())
<|end_body_1|>
<... | a simple Solitaire Game: N cards are dealt face up on the table. If two cards have a matching rank, new cards are dealt face up on top of them. Dealing continues until the deck is empty, or no two stacks have matching ranks. The player wins if all the cards are dealt. | SolitaireGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolitaireGame:
"""a simple Solitaire Game: N cards are dealt face up on the table. If two cards have a matching rank, new cards are dealt face up on top of them. Dealing continues until the deck is empty, or no two stacks have matching ranks. The player wins if all the cards are dealt."""
de... | stack_v2_sparse_classes_36k_train_018044 | 5,231 | no_license | [
{
"docstring": "Constructor pre: N is an integer, denotes the number of piles, s.t. 1 < N < 50 post: self.size is the number of piles",
"name": "__init__",
"signature": "def __init__(self, N)"
},
{
"docstring": "Creates a new game post: creates an instance of Solitaire game with N empty places",... | 4 | stack_v2_sparse_classes_30k_train_013656 | Implement the Python class `SolitaireGame` described below.
Class description:
a simple Solitaire Game: N cards are dealt face up on the table. If two cards have a matching rank, new cards are dealt face up on top of them. Dealing continues until the deck is empty, or no two stacks have matching ranks. The player wins... | Implement the Python class `SolitaireGame` described below.
Class description:
a simple Solitaire Game: N cards are dealt face up on the table. If two cards have a matching rank, new cards are dealt face up on top of them. Dealing continues until the deck is empty, or no two stacks have matching ranks. The player wins... | ab9184fa29b5519cc3168c121e636fa48073b03b | <|skeleton|>
class SolitaireGame:
"""a simple Solitaire Game: N cards are dealt face up on the table. If two cards have a matching rank, new cards are dealt face up on top of them. Dealing continues until the deck is empty, or no two stacks have matching ranks. The player wins if all the cards are dealt."""
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolitaireGame:
"""a simple Solitaire Game: N cards are dealt face up on the table. If two cards have a matching rank, new cards are dealt face up on top of them. Dealing continues until the deck is empty, or no two stacks have matching ranks. The player wins if all the cards are dealt."""
def __init__(se... | the_stack_v2_python_sparse | HW5/Solitaire.py | Jeffrey-A/Data_structures_and_algorithms_Programs | train | 0 |
71e5ec2702dcbbf9db7aac9fa1b5aadcec7e6d50 | [
"d = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}\nout = d[s[0]]\npre = out\nif len(s) == 1:\n return out\nfor c in s[1:]:\n num = d[c]\n out = out + num\n if num > pre:\n out = out - 2 * pre\n pre = num\nreturn out",
"def trans(s):\n d = {'M': 1000, 'D': 500, 'C': 10... | <|body_start_0|>
d = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
out = d[s[0]]
pre = out
if len(s) == 1:
return out
for c in s[1:]:
num = d[c]
out = out + num
if num > pre:
out = out - 2 * pre
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def romanToInt(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def romanToInt_myfirst(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, '... | stack_v2_sparse_classes_36k_train_018045 | 1,861 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "romanToInt",
"signature": "def romanToInt(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "romanToInt_myfirst",
"signature": "def romanToInt_myfirst(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def romanToInt(self, s): :type s: str :rtype: int
- def romanToInt_myfirst(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def romanToInt(self, s): :type s: str :rtype: int
- def romanToInt_myfirst(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def romanToInt(self, s):
... | f0d9070fa292ca36971a465a805faddb12025482 | <|skeleton|>
class Solution:
def romanToInt(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def romanToInt_myfirst(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def romanToInt(self, s):
""":type s: str :rtype: int"""
d = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
out = d[s[0]]
pre = out
if len(s) == 1:
return out
for c in s[1:]:
num = d[c]
out = out + ... | the_stack_v2_python_sparse | 13.RomantoInteger.py | JerryRoc/leetcode | train | 0 | |
5719de02c8b56e9c1a4c5b8efa338146b0461852 | [
"super(Generator, self).__init__()\ninitializer = tf.random_normal_initializer(0.0, 0.02)\nself.down1 = Downsample(64, 4, apply_batchnorm=False)\nself.down2 = Downsample(128, 4)\nself.down3 = Downsample(256, 4)\nself.down4 = Downsample(512, 4)\nself.down5 = Downsample(512, 4)\nself.down6 = Downsample(512, 4)\nself.... | <|body_start_0|>
super(Generator, self).__init__()
initializer = tf.random_normal_initializer(0.0, 0.02)
self.down1 = Downsample(64, 4, apply_batchnorm=False)
self.down2 = Downsample(128, 4)
self.down3 = Downsample(256, 4)
self.down4 = Downsample(512, 4)
self.down... | The architecture of generator is a modified U-Net. | Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""The architecture of generator is a modified U-Net."""
def __init__(self):
"""The construct function."""
<|body_0|>
def call(self, x, training=True):
"""Calls the model on new inputs. Args: x: The origin image before translation. training: If trainin... | stack_v2_sparse_classes_36k_train_018046 | 20,044 | no_license | [
{
"docstring": "The construct function.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Calls the model on new inputs. Args: x: The origin image before translation. training: If training. Returns: The generated image.",
"name": "call",
"signature": "def call(se... | 2 | stack_v2_sparse_classes_30k_train_017539 | Implement the Python class `Generator` described below.
Class description:
The architecture of generator is a modified U-Net.
Method signatures and docstrings:
- def __init__(self): The construct function.
- def call(self, x, training=True): Calls the model on new inputs. Args: x: The origin image before translation.... | Implement the Python class `Generator` described below.
Class description:
The architecture of generator is a modified U-Net.
Method signatures and docstrings:
- def __init__(self): The construct function.
- def call(self, x, training=True): Calls the model on new inputs. Args: x: The origin image before translation.... | d1b70b2a954f4665b628ba252b03c1a74b95559f | <|skeleton|>
class Generator:
"""The architecture of generator is a modified U-Net."""
def __init__(self):
"""The construct function."""
<|body_0|>
def call(self, x, training=True):
"""Calls the model on new inputs. Args: x: The origin image before translation. training: If trainin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
"""The architecture of generator is a modified U-Net."""
def __init__(self):
"""The construct function."""
super(Generator, self).__init__()
initializer = tf.random_normal_initializer(0.0, 0.02)
self.down1 = Downsample(64, 4, apply_batchnorm=False)
self.... | the_stack_v2_python_sparse | NeuralNetworks-tensorflow/generation_network_model/GAN/pix2pix.py | zhaocc1106/machine_learn | train | 15 |
e9ea34673f2ea4a4197f00f42f6e1590da0bf740 | [
"global PRINT_SETTINGS\npage_setup = paperstyle_to_pagesetup(self.paper)\noperation = Gtk.PrintOperation()\noperation.set_default_page_setup(page_setup)\noperation.connect('begin_print', self.on_begin_print)\noperation.connect('draw_page', self.on_draw_page)\noperation.connect('paginate', self.on_paginate)\noperati... | <|body_start_0|>
global PRINT_SETTINGS
page_setup = paperstyle_to_pagesetup(self.paper)
operation = Gtk.PrintOperation()
operation.set_default_page_setup(page_setup)
operation.connect('begin_print', self.on_begin_print)
operation.connect('draw_page', self.on_draw_page)
... | Print document via GtkPrint* interface. Requires Gtk+ 2.10. | GtkPrint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GtkPrint:
"""Print document via GtkPrint* interface. Requires Gtk+ 2.10."""
def run(self):
"""Run the Gtk Print operation."""
<|body_0|>
def on_begin_print(self, operation, context):
"""Setup environment for printing."""
<|body_1|>
def on_paginate(se... | stack_v2_sparse_classes_36k_train_018047 | 21,400 | no_license | [
{
"docstring": "Run the Gtk Print operation.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Setup environment for printing.",
"name": "on_begin_print",
"signature": "def on_begin_print(self, operation, context)"
},
{
"docstring": "Paginate the whole document in ... | 5 | null | Implement the Python class `GtkPrint` described below.
Class description:
Print document via GtkPrint* interface. Requires Gtk+ 2.10.
Method signatures and docstrings:
- def run(self): Run the Gtk Print operation.
- def on_begin_print(self, operation, context): Setup environment for printing.
- def on_paginate(self, ... | Implement the Python class `GtkPrint` described below.
Class description:
Print document via GtkPrint* interface. Requires Gtk+ 2.10.
Method signatures and docstrings:
- def run(self): Run the Gtk Print operation.
- def on_begin_print(self, operation, context): Setup environment for printing.
- def on_paginate(self, ... | 0c79561bed7ff42c88714edbc85197fa9235e188 | <|skeleton|>
class GtkPrint:
"""Print document via GtkPrint* interface. Requires Gtk+ 2.10."""
def run(self):
"""Run the Gtk Print operation."""
<|body_0|>
def on_begin_print(self, operation, context):
"""Setup environment for printing."""
<|body_1|>
def on_paginate(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GtkPrint:
"""Print document via GtkPrint* interface. Requires Gtk+ 2.10."""
def run(self):
"""Run the Gtk Print operation."""
global PRINT_SETTINGS
page_setup = paperstyle_to_pagesetup(self.paper)
operation = Gtk.PrintOperation()
operation.set_default_page_setup(pa... | the_stack_v2_python_sparse | plugins/docgen/gtkprint.py | balrok/gramps_addon | train | 2 |
1c2587e2e11a60265619963bdf60ef9e0b94f7ca | [
"if JoinCode.objects.filter(code=joincode).exists():\n JoinerCode = JoinCode.objects.get(code=joincode)\n if not JoinerCode.used:\n return True\nreturn False",
"JoinCodeInstance = JoinCode.objects.get(code=joincode)\nJoinCodeInstance.joiner = joiner\nJoinCodeInstance.used = True\nJoinCodeInstance.sav... | <|body_start_0|>
if JoinCode.objects.filter(code=joincode).exists():
JoinerCode = JoinCode.objects.get(code=joincode)
if not JoinerCode.used:
return True
return False
<|end_body_0|>
<|body_start_1|>
JoinCodeInstance = JoinCode.objects.get(code=joincode)
... | Creates the user account in admin group using the joincode | ShopOwnerSignUpAPIView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShopOwnerSignUpAPIView:
"""Creates the user account in admin group using the joincode"""
def _isJoinCodeValid(self, joincode):
"""Check if the joincode is valid"""
<|body_0|>
def _addJoinerInJoinCodeInstance(self, joincode, joiner):
"""The joiner will be saved wi... | stack_v2_sparse_classes_36k_train_018048 | 15,595 | permissive | [
{
"docstring": "Check if the joincode is valid",
"name": "_isJoinCodeValid",
"signature": "def _isJoinCodeValid(self, joincode)"
},
{
"docstring": "The joiner will be saved with the joincode instance",
"name": "_addJoinerInJoinCodeInstance",
"signature": "def _addJoinerInJoinCodeInstance... | 3 | stack_v2_sparse_classes_30k_train_019188 | Implement the Python class `ShopOwnerSignUpAPIView` described below.
Class description:
Creates the user account in admin group using the joincode
Method signatures and docstrings:
- def _isJoinCodeValid(self, joincode): Check if the joincode is valid
- def _addJoinerInJoinCodeInstance(self, joincode, joiner): The jo... | Implement the Python class `ShopOwnerSignUpAPIView` described below.
Class description:
Creates the user account in admin group using the joincode
Method signatures and docstrings:
- def _isJoinCodeValid(self, joincode): Check if the joincode is valid
- def _addJoinerInJoinCodeInstance(self, joincode, joiner): The jo... | 82820d93876a2c3e6caec2725b1c6078e79e3bfb | <|skeleton|>
class ShopOwnerSignUpAPIView:
"""Creates the user account in admin group using the joincode"""
def _isJoinCodeValid(self, joincode):
"""Check if the joincode is valid"""
<|body_0|>
def _addJoinerInJoinCodeInstance(self, joincode, joiner):
"""The joiner will be saved wi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShopOwnerSignUpAPIView:
"""Creates the user account in admin group using the joincode"""
def _isJoinCodeValid(self, joincode):
"""Check if the joincode is valid"""
if JoinCode.objects.filter(code=joincode).exists():
JoinerCode = JoinCode.objects.get(code=joincode)
... | the_stack_v2_python_sparse | grocery/shopowner/views.py | DeepakDk04/bigbasketClone | train | 0 |
2410ea9745e9297f2b51ec04e7f68dc291b3448c | [
"TITLE_TEXT = 'Scatter Plot Explorer - Data Commons'\nself.driver.get(self.url_ + SCATTER_URL)\nreq = urllib.request.Request(self.driver.current_url)\nwith urllib.request.urlopen(req) as response:\n self.assertEqual(response.getcode(), 200)\nreq = urllib.request.Request(self.url_ + '/scatter.js')\nwith urllib.re... | <|body_start_0|>
TITLE_TEXT = 'Scatter Plot Explorer - Data Commons'
self.driver.get(self.url_ + SCATTER_URL)
req = urllib.request.Request(self.driver.current_url)
with urllib.request.urlopen(req) as response:
self.assertEqual(response.getcode(), 200)
req = urllib.req... | TestScatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestScatter:
def test_server_and_page(self):
"""Test the server can run successfully."""
<|body_0|>
def test_charts_from_url(self):
"""Given the url directly, test the page shows up correctly"""
<|body_1|>
def test_manually_enter_options(self):
"... | stack_v2_sparse_classes_36k_train_018049 | 5,568 | permissive | [
{
"docstring": "Test the server can run successfully.",
"name": "test_server_and_page",
"signature": "def test_server_and_page(self)"
},
{
"docstring": "Given the url directly, test the page shows up correctly",
"name": "test_charts_from_url",
"signature": "def test_charts_from_url(self)... | 3 | stack_v2_sparse_classes_30k_train_001565 | Implement the Python class `TestScatter` described below.
Class description:
Implement the TestScatter class.
Method signatures and docstrings:
- def test_server_and_page(self): Test the server can run successfully.
- def test_charts_from_url(self): Given the url directly, test the page shows up correctly
- def test_... | Implement the Python class `TestScatter` described below.
Class description:
Implement the TestScatter class.
Method signatures and docstrings:
- def test_server_and_page(self): Test the server can run successfully.
- def test_charts_from_url(self): Given the url directly, test the page shows up correctly
- def test_... | 928625749a74dd9de473170b5683f62a4bbdbd15 | <|skeleton|>
class TestScatter:
def test_server_and_page(self):
"""Test the server can run successfully."""
<|body_0|>
def test_charts_from_url(self):
"""Given the url directly, test the page shows up correctly"""
<|body_1|>
def test_manually_enter_options(self):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestScatter:
def test_server_and_page(self):
"""Test the server can run successfully."""
TITLE_TEXT = 'Scatter Plot Explorer - Data Commons'
self.driver.get(self.url_ + SCATTER_URL)
req = urllib.request.Request(self.driver.current_url)
with urllib.request.urlopen(req) a... | the_stack_v2_python_sparse | server/webdriver_tests/scatter_test.py | localsite/website | train | 0 | |
6e87d7064119070ec564201a936b8feb20ae70ba | [
"signed_in_user = users.get_current_user()\nif not signed_in_user:\n return None\nuser_pref_list = UserPref.query().filter(UserPref.email == signed_in_user.email()).fetch(1)\nif user_pref_list:\n user_pref = user_pref_list[0]\nelse:\n user_pref = UserPref(email=signed_in_user.email())\nreturn user_pref",
... | <|body_start_0|>
signed_in_user = users.get_current_user()
if not signed_in_user:
return None
user_pref_list = UserPref.query().filter(UserPref.email == signed_in_user.email()).fetch(1)
if user_pref_list:
user_pref = user_pref_list[0]
else:
use... | Describes a user's application preferences. | UserPref | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPref:
"""Describes a user's application preferences."""
def get_signed_in_user_pref(cls):
"""Return a UserPref for the signed in user or None if anon."""
<|body_0|>
def dismiss_cue(cls, cue):
"""Add cue to the signed in user's dismissed_cues."""
<|bod... | stack_v2_sparse_classes_36k_train_018050 | 8,866 | permissive | [
{
"docstring": "Return a UserPref for the signed in user or None if anon.",
"name": "get_signed_in_user_pref",
"signature": "def get_signed_in_user_pref(cls)"
},
{
"docstring": "Add cue to the signed in user's dismissed_cues.",
"name": "dismiss_cue",
"signature": "def dismiss_cue(cls, cu... | 3 | null | Implement the Python class `UserPref` described below.
Class description:
Describes a user's application preferences.
Method signatures and docstrings:
- def get_signed_in_user_pref(cls): Return a UserPref for the signed in user or None if anon.
- def dismiss_cue(cls, cue): Add cue to the signed in user's dismissed_c... | Implement the Python class `UserPref` described below.
Class description:
Describes a user's application preferences.
Method signatures and docstrings:
- def get_signed_in_user_pref(cls): Return a UserPref for the signed in user or None if anon.
- def dismiss_cue(cls, cue): Add cue to the signed in user's dismissed_c... | 17f9886d064da5bda84006d5866077727646fff2 | <|skeleton|>
class UserPref:
"""Describes a user's application preferences."""
def get_signed_in_user_pref(cls):
"""Return a UserPref for the signed in user or None if anon."""
<|body_0|>
def dismiss_cue(cls, cue):
"""Add cue to the signed in user's dismissed_cues."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserPref:
"""Describes a user's application preferences."""
def get_signed_in_user_pref(cls):
"""Return a UserPref for the signed in user or None if anon."""
signed_in_user = users.get_current_user()
if not signed_in_user:
return None
user_pref_list = UserPref.... | the_stack_v2_python_sparse | internals/user_models.py | GoogleChrome/chromium-dashboard | train | 574 |
4f4f0ecc79e175706a982bf3f9a2faa91673e885 | [
"ENFORCER.enforce_call(action='identity:check_system_grant_for_user', build_target=_build_enforcement_target)\nPROVIDERS.assignment_api.check_system_grant_for_user(user_id, role_id)\nreturn (None, http_client.NO_CONTENT)",
"ENFORCER.enforce_call(action='identity:create_system_grant_for_user', build_target=_build_... | <|body_start_0|>
ENFORCER.enforce_call(action='identity:check_system_grant_for_user', build_target=_build_enforcement_target)
PROVIDERS.assignment_api.check_system_grant_for_user(user_id, role_id)
return (None, http_client.NO_CONTENT)
<|end_body_0|>
<|body_start_1|>
ENFORCER.enforce_cal... | SystemUsersResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemUsersResource:
def get(self, user_id, role_id):
"""Check if a user has a specific role on the system. GET/HEAD /system/users/{user_id}/roles/{role_id}"""
<|body_0|>
def put(self, user_id, role_id):
"""Grant a role to a user on the system. PUT /system/users/{use... | stack_v2_sparse_classes_36k_train_018051 | 7,288 | permissive | [
{
"docstring": "Check if a user has a specific role on the system. GET/HEAD /system/users/{user_id}/roles/{role_id}",
"name": "get",
"signature": "def get(self, user_id, role_id)"
},
{
"docstring": "Grant a role to a user on the system. PUT /system/users/{user_id}/roles/{role_id}",
"name": "... | 3 | null | Implement the Python class `SystemUsersResource` described below.
Class description:
Implement the SystemUsersResource class.
Method signatures and docstrings:
- def get(self, user_id, role_id): Check if a user has a specific role on the system. GET/HEAD /system/users/{user_id}/roles/{role_id}
- def put(self, user_id... | Implement the Python class `SystemUsersResource` described below.
Class description:
Implement the SystemUsersResource class.
Method signatures and docstrings:
- def get(self, user_id, role_id): Check if a user has a specific role on the system. GET/HEAD /system/users/{user_id}/roles/{role_id}
- def put(self, user_id... | 03a0a8146a78682ede9eca12a5a7fdacde2035c8 | <|skeleton|>
class SystemUsersResource:
def get(self, user_id, role_id):
"""Check if a user has a specific role on the system. GET/HEAD /system/users/{user_id}/roles/{role_id}"""
<|body_0|>
def put(self, user_id, role_id):
"""Grant a role to a user on the system. PUT /system/users/{use... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SystemUsersResource:
def get(self, user_id, role_id):
"""Check if a user has a specific role on the system. GET/HEAD /system/users/{user_id}/roles/{role_id}"""
ENFORCER.enforce_call(action='identity:check_system_grant_for_user', build_target=_build_enforcement_target)
PROVIDERS.assignm... | the_stack_v2_python_sparse | keystone/api/system.py | sapcc/keystone | train | 0 | |
6ced3c0472633753126be4992303a1f4c315f026 | [
"super(ConfidenceCalibratedAdversarialTrainingConfig, self).__init__()\nself.loss = None\nself.transition = None",
"super(ConfidenceCalibratedAdversarialTrainingConfig, self).validate()\nassert callable(self.loss)\nassert callable(self.transition)\nassert self.fraction > 0 and self.fraction < 1"
] | <|body_start_0|>
super(ConfidenceCalibratedAdversarialTrainingConfig, self).__init__()
self.loss = None
self.transition = None
<|end_body_0|>
<|body_start_1|>
super(ConfidenceCalibratedAdversarialTrainingConfig, self).validate()
assert callable(self.loss)
assert callable... | Configuration for confidence calibrated training. | ConfidenceCalibratedAdversarialTrainingConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfidenceCalibratedAdversarialTrainingConfig:
"""Configuration for confidence calibrated training."""
def __init__(self):
"""Constructor."""
<|body_0|>
def validate(self):
"""Check validity."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_36k_train_018052 | 16,771 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Check validity.",
"name": "validate",
"signature": "def validate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013008 | Implement the Python class `ConfidenceCalibratedAdversarialTrainingConfig` described below.
Class description:
Configuration for confidence calibrated training.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def validate(self): Check validity. | Implement the Python class `ConfidenceCalibratedAdversarialTrainingConfig` described below.
Class description:
Configuration for confidence calibrated training.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def validate(self): Check validity.
<|skeleton|>
class ConfidenceCalibratedAdversaria... | 736c99b55a77d0c650eae5ced2d8312d13af0baf | <|skeleton|>
class ConfidenceCalibratedAdversarialTrainingConfig:
"""Configuration for confidence calibrated training."""
def __init__(self):
"""Constructor."""
<|body_0|>
def validate(self):
"""Check validity."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfidenceCalibratedAdversarialTrainingConfig:
"""Configuration for confidence calibrated training."""
def __init__(self):
"""Constructor."""
super(ConfidenceCalibratedAdversarialTrainingConfig, self).__init__()
self.loss = None
self.transition = None
def validate(sel... | the_stack_v2_python_sparse | common/experiments.py | Adversarial-Intelligence-Group/color-adversarial-training | train | 0 |
79fd783e07972dd497efd314089114f536ced46f | [
"logger.info('Get all role')\nfilter_object = {'query_string': request.args.get('q', None), 'order_by_field': request.args.get('order_by_field', None), 'order_by': request.args.get('order_by', None), 'datefrom': request.args.get('datefrom', None), 'dateto': request.args.get('dateto', None), 'limit': request.args.ge... | <|body_start_0|>
logger.info('Get all role')
filter_object = {'query_string': request.args.get('q', None), 'order_by_field': request.args.get('order_by_field', None), 'order_by': request.args.get('order_by', None), 'datefrom': request.args.get('datefrom', None), 'dateto': request.args.get('dateto', None... | Role list functionalities | RoleList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleList:
"""Role list functionalities"""
def get(self):
"""Get all role"""
<|body_0|>
def post(self):
"""Insert a role"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
logger.info('Get all role')
filter_object = {'query_string': request.... | stack_v2_sparse_classes_36k_train_018053 | 3,667 | no_license | [
{
"docstring": "Get all role",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Insert a role",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007830 | Implement the Python class `RoleList` described below.
Class description:
Role list functionalities
Method signatures and docstrings:
- def get(self): Get all role
- def post(self): Insert a role | Implement the Python class `RoleList` described below.
Class description:
Role list functionalities
Method signatures and docstrings:
- def get(self): Get all role
- def post(self): Insert a role
<|skeleton|>
class RoleList:
"""Role list functionalities"""
def get(self):
"""Get all role"""
<... | 4dc5f5e816e3c461b8a60c5f61c7eafc08050579 | <|skeleton|>
class RoleList:
"""Role list functionalities"""
def get(self):
"""Get all role"""
<|body_0|>
def post(self):
"""Insert a role"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleList:
"""Role list functionalities"""
def get(self):
"""Get all role"""
logger.info('Get all role')
filter_object = {'query_string': request.args.get('q', None), 'order_by_field': request.args.get('order_by_field', None), 'order_by': request.args.get('order_by', None), 'datefr... | the_stack_v2_python_sparse | app/api/role.py | ekramulmostafa/ms-auth | train | 0 |
2b5f0e0897df9c1f5f0d5137c993215bf6d784a1 | [
"try:\n tag_ord = None\n if isinstance(tag, bytes) and len(tag) == 1:\n tag_ord = ord(tag)\n if tag_ord in (ord(self.GET_UTIM_STATUS), ord(self.NETWORK_READY), ord(self.DATA_FROM_NETWORK), ord(self.DATA_TO_SIGN)):\n return True\nexcept TypeError:\n pass\nreturn False",
"if isinstance(dat... | <|body_start_0|>
try:
tag_ord = None
if isinstance(tag, bytes) and len(tag) == 1:
tag_ord = ord(tag)
if tag_ord in (ord(self.GET_UTIM_STATUS), ord(self.NETWORK_READY), ord(self.DATA_FROM_NETWORK), ord(self.DATA_TO_SIGN)):
return True
ex... | Inbound data tag class | TagInbound | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagInbound:
"""Inbound data tag class"""
def in_this_scope(self, tag):
"""Check tag is in this scope"""
<|body_0|>
def assemble_for_utim(self, data):
"""Assemble data to sls"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
tag_or... | stack_v2_sparse_classes_36k_train_018054 | 8,293 | permissive | [
{
"docstring": "Check tag is in this scope",
"name": "in_this_scope",
"signature": "def in_this_scope(self, tag)"
},
{
"docstring": "Assemble data to sls",
"name": "assemble_for_utim",
"signature": "def assemble_for_utim(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018067 | Implement the Python class `TagInbound` described below.
Class description:
Inbound data tag class
Method signatures and docstrings:
- def in_this_scope(self, tag): Check tag is in this scope
- def assemble_for_utim(self, data): Assemble data to sls | Implement the Python class `TagInbound` described below.
Class description:
Inbound data tag class
Method signatures and docstrings:
- def in_this_scope(self, tag): Check tag is in this scope
- def assemble_for_utim(self, data): Assemble data to sls
<|skeleton|>
class TagInbound:
"""Inbound data tag class"""
... | ff4577c321b1ac3439856c98e9ca6d8b88462d7e | <|skeleton|>
class TagInbound:
"""Inbound data tag class"""
def in_this_scope(self, tag):
"""Check tag is in this scope"""
<|body_0|>
def assemble_for_utim(self, data):
"""Assemble data to sls"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TagInbound:
"""Inbound data tag class"""
def in_this_scope(self, tag):
"""Check tag is in this scope"""
try:
tag_ord = None
if isinstance(tag, bytes) and len(tag) == 1:
tag_ord = ord(tag)
if tag_ord in (ord(self.GET_UTIM_STATUS), ord(sel... | the_stack_v2_python_sparse | uhost/utilities/tag.py | connax-utim/uhost-python | train | 1 |
0811bfd6c73557a96d5ae94fc542ef1e1ed89eeb | [
"class SimplePlugin(ActionMixin, InvenTreePlugin):\n pass\nself.plugin = SimplePlugin()\n\nclass TestActionPlugin(ActionMixin, InvenTreePlugin):\n \"\"\"An action plugin.\"\"\"\n ACTION_NAME = 'abc123'\n\n def perform_action(self, user=None, data=None):\n return ActionMixinTests.ACTION_RETURN + '... | <|body_start_0|>
class SimplePlugin(ActionMixin, InvenTreePlugin):
pass
self.plugin = SimplePlugin()
class TestActionPlugin(ActionMixin, InvenTreePlugin):
"""An action plugin."""
ACTION_NAME = 'abc123'
def perform_action(self, user=None, data=Non... | Tests for ActionMixin. | ActionMixinTests | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionMixinTests:
"""Tests for ActionMixin."""
def setUp(self):
"""Setup environment for tests. Contains multiple sample plugins that are used in the tests"""
<|body_0|>
def test_action_name(self):
"""Check the name definition possibilities."""
<|body_1|>... | stack_v2_sparse_classes_36k_train_018055 | 3,146 | permissive | [
{
"docstring": "Setup environment for tests. Contains multiple sample plugins that are used in the tests",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Check the name definition possibilities.",
"name": "test_action_name",
"signature": "def test_action_name(self)"
... | 3 | null | Implement the Python class `ActionMixinTests` described below.
Class description:
Tests for ActionMixin.
Method signatures and docstrings:
- def setUp(self): Setup environment for tests. Contains multiple sample plugins that are used in the tests
- def test_action_name(self): Check the name definition possibilities.
... | Implement the Python class `ActionMixinTests` described below.
Class description:
Tests for ActionMixin.
Method signatures and docstrings:
- def setUp(self): Setup environment for tests. Contains multiple sample plugins that are used in the tests
- def test_action_name(self): Check the name definition possibilities.
... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class ActionMixinTests:
"""Tests for ActionMixin."""
def setUp(self):
"""Setup environment for tests. Contains multiple sample plugins that are used in the tests"""
<|body_0|>
def test_action_name(self):
"""Check the name definition possibilities."""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionMixinTests:
"""Tests for ActionMixin."""
def setUp(self):
"""Setup environment for tests. Contains multiple sample plugins that are used in the tests"""
class SimplePlugin(ActionMixin, InvenTreePlugin):
pass
self.plugin = SimplePlugin()
class TestActionP... | the_stack_v2_python_sparse | InvenTree/plugin/base/action/test_action.py | inventree/InvenTree | train | 3,077 |
447bc3d4c9ac10278eaf98e9bc9d544505062fa9 | [
"self.session = session\nself.user_input = user_input\nself.view = view",
"assignments = Assignment.get_assignments_list()\nself.view.show_assignments(assignments)\nif assignments:\n group_name = \"assignment's\"\n index = self.user_input.get_index_input(len(assignments), group_name)\n assignment = assig... | <|body_start_0|>
self.session = session
self.user_input = user_input
self.view = view
<|end_body_0|>
<|body_start_1|>
assignments = Assignment.get_assignments_list()
self.view.show_assignments(assignments)
if assignments:
group_name = "assignment's"
... | Represents SubmissionController object Attributes: user_input: object of UserInput class view: object of View class session: dict | SubmissionController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubmissionController:
"""Represents SubmissionController object Attributes: user_input: object of UserInput class view: object of View class session: dict"""
def __init__(self, session, user_input, view):
"""Instance initializer"""
<|body_0|>
def add_submission_action(se... | stack_v2_sparse_classes_36k_train_018056 | 3,990 | no_license | [
{
"docstring": "Instance initializer",
"name": "__init__",
"signature": "def __init__(self, session, user_input, view)"
},
{
"docstring": "Adds submission to class list in Submission Returns: None",
"name": "add_submission_action",
"signature": "def add_submission_action(self)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_001328 | Implement the Python class `SubmissionController` described below.
Class description:
Represents SubmissionController object Attributes: user_input: object of UserInput class view: object of View class session: dict
Method signatures and docstrings:
- def __init__(self, session, user_input, view): Instance initialize... | Implement the Python class `SubmissionController` described below.
Class description:
Represents SubmissionController object Attributes: user_input: object of UserInput class view: object of View class session: dict
Method signatures and docstrings:
- def __init__(self, session, user_input, view): Instance initialize... | ea65b50bc7087b71e6066b3b0d6aef60c6476aa8 | <|skeleton|>
class SubmissionController:
"""Represents SubmissionController object Attributes: user_input: object of UserInput class view: object of View class session: dict"""
def __init__(self, session, user_input, view):
"""Instance initializer"""
<|body_0|>
def add_submission_action(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubmissionController:
"""Represents SubmissionController object Attributes: user_input: object of UserInput class view: object of View class session: dict"""
def __init__(self, session, user_input, view):
"""Instance initializer"""
self.session = session
self.user_input = user_inp... | the_stack_v2_python_sparse | application/controller/submission_controller.py | iwoty/ccms-learning-platform | train | 0 |
63b9ee0995fde029fb25fc0d11e86cc8c016b7ca | [
"AxisFormat.__init__(self, 'jetsreduced')\nself._axes['tracktpt'] = 0\nself._axes['tracketa'] = 1\nself._axes['trackphi'] = 2\nself._axes['vertexz'] = 3\nself._axes['mbtrigger'] = 4",
"newobj = AxisFormatReducedJetTHnSparse()\nnewobj._Deepcopy(other, memo)\nreturn newobj",
"newobj = AxisFormatReducedJetTHnSpars... | <|body_start_0|>
AxisFormat.__init__(self, 'jetsreduced')
self._axes['tracktpt'] = 0
self._axes['tracketa'] = 1
self._axes['trackphi'] = 2
self._axes['vertexz'] = 3
self._axes['mbtrigger'] = 4
<|end_body_0|>
<|body_start_1|>
newobj = AxisFormatReducedJetTHnSparse... | Axis format for projected THnSparse | AxisFormatReducedJetTHnSparse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxisFormatReducedJetTHnSparse:
"""Axis format for projected THnSparse"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __deepcopy__(self, other, memo):
"""Deep copy constructor"""
<|body_1|>
def __copy__(self, other):
"""Shallow copy c... | stack_v2_sparse_classes_36k_train_018057 | 7,138 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Deep copy constructor",
"name": "__deepcopy__",
"signature": "def __deepcopy__(self, other, memo)"
},
{
"docstring": "Shallow copy constructor",
"name": "__copy__",
"sig... | 3 | null | Implement the Python class `AxisFormatReducedJetTHnSparse` described below.
Class description:
Axis format for projected THnSparse
Method signatures and docstrings:
- def __init__(self): Constructor
- def __deepcopy__(self, other, memo): Deep copy constructor
- def __copy__(self, other): Shallow copy constructor | Implement the Python class `AxisFormatReducedJetTHnSparse` described below.
Class description:
Axis format for projected THnSparse
Method signatures and docstrings:
- def __init__(self): Constructor
- def __deepcopy__(self, other, memo): Deep copy constructor
- def __copy__(self, other): Shallow copy constructor
<|s... | 5df28b2b415e78e81273b0d9bf5c1b99feda3348 | <|skeleton|>
class AxisFormatReducedJetTHnSparse:
"""Axis format for projected THnSparse"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __deepcopy__(self, other, memo):
"""Deep copy constructor"""
<|body_1|>
def __copy__(self, other):
"""Shallow copy c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AxisFormatReducedJetTHnSparse:
"""Axis format for projected THnSparse"""
def __init__(self):
"""Constructor"""
AxisFormat.__init__(self, 'jetsreduced')
self._axes['tracktpt'] = 0
self._axes['tracketa'] = 1
self._axes['trackphi'] = 2
self._axes['vertexz'] = ... | the_stack_v2_python_sparse | PWGJE/EMCALJetTasks/Tracks/analysis/base/struct/JetTHnSparse.py | alisw/AliPhysics | train | 129 |
ff72b17ca88df8e6af8d8a7e9184bd066bcb43ac | [
"n = len(nums)\nfor i in range(n):\n for j in range(i + 1, n):\n if nums[i] + nums[j] == target:\n return [i, j]",
"n = len(nums)\ndict = {}\nfor i in range(n):\n complement = target - nums[i]\n if complement in dict:\n return [dict[complement], i]\n else:\n dict[nums[i... | <|body_start_0|>
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i, j]
<|end_body_0|>
<|body_start_1|>
n = len(nums)
dict = {}
for i in range(n):
complement = target - ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums: list, target: int) -> list:
"""Bruce force solution"""
<|body_0|>
def twoSum_hash(self, nums: list, target: int) -> list:
"""One pass hash table solution"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
... | stack_v2_sparse_classes_36k_train_018058 | 663 | no_license | [
{
"docstring": "Bruce force solution",
"name": "twoSum",
"signature": "def twoSum(self, nums: list, target: int) -> list"
},
{
"docstring": "One pass hash table solution",
"name": "twoSum_hash",
"signature": "def twoSum_hash(self, nums: list, target: int) -> list"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums: list, target: int) -> list: Bruce force solution
- def twoSum_hash(self, nums: list, target: int) -> list: One pass hash table solution | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums: list, target: int) -> list: Bruce force solution
- def twoSum_hash(self, nums: list, target: int) -> list: One pass hash table solution
<|skeleton|>
class... | f33d004d7629d46fbc5670f5b384f8a604d7f1e7 | <|skeleton|>
class Solution:
def twoSum(self, nums: list, target: int) -> list:
"""Bruce force solution"""
<|body_0|>
def twoSum_hash(self, nums: list, target: int) -> list:
"""One pass hash table solution"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums: list, target: int) -> list:
"""Bruce force solution"""
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i, j]
def twoSum_hash(self, nums: list, target... | the_stack_v2_python_sparse | Two Sum.py | aulee888/LeetCode | train | 0 | |
fad5746a8c8b217881f9806551492838601c2aa6 | [
"self.Whf = np.random.randn(h + i, h)\nself.bhf = np.zeros((1, h))\nself.Whb = np.random.randn(h + i, h)\nself.bhb = np.zeros((1, h))\nself.Wy = np.random.randn(2 * h, o)\nself.by = np.zeros((1, o))",
"m, _ = x_t.shape\nh = np.concatenate((h_prev, x_t), axis=1)\nh_next = np.tanh(h @ self.Whf + self.bhf)\nreturn h... | <|body_start_0|>
self.Whf = np.random.randn(h + i, h)
self.bhf = np.zeros((1, h))
self.Whb = np.random.randn(h + i, h)
self.bhb = np.zeros((1, h))
self.Wy = np.random.randn(2 * h, o)
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
m, _ = x_t.shape
... | bidirectional cell | BidirectionalCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BidirectionalCell:
"""bidirectional cell"""
def __init__(self, i, h, o):
"""bidirectional cell contructor i: dimensionality of data h: dimensionality of hidden states o: dimensinality of outputs fields: (weights and biases) Whf, bhf: hidden states in forward direction Whb, bhb: hidde... | stack_v2_sparse_classes_36k_train_018059 | 2,276 | no_license | [
{
"docstring": "bidirectional cell contructor i: dimensionality of data h: dimensionality of hidden states o: dimensinality of outputs fields: (weights and biases) Whf, bhf: hidden states in forward direction Whb, bhb: hidden states in backward direction Wy, by: outputs",
"name": "__init__",
"signature"... | 4 | null | Implement the Python class `BidirectionalCell` described below.
Class description:
bidirectional cell
Method signatures and docstrings:
- def __init__(self, i, h, o): bidirectional cell contructor i: dimensionality of data h: dimensionality of hidden states o: dimensinality of outputs fields: (weights and biases) Whf... | Implement the Python class `BidirectionalCell` described below.
Class description:
bidirectional cell
Method signatures and docstrings:
- def __init__(self, i, h, o): bidirectional cell contructor i: dimensionality of data h: dimensionality of hidden states o: dimensinality of outputs fields: (weights and biases) Whf... | d86b0e0cae2dd07c761f84a493abc895007873ee | <|skeleton|>
class BidirectionalCell:
"""bidirectional cell"""
def __init__(self, i, h, o):
"""bidirectional cell contructor i: dimensionality of data h: dimensionality of hidden states o: dimensinality of outputs fields: (weights and biases) Whf, bhf: hidden states in forward direction Whb, bhb: hidde... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BidirectionalCell:
"""bidirectional cell"""
def __init__(self, i, h, o):
"""bidirectional cell contructor i: dimensionality of data h: dimensionality of hidden states o: dimensinality of outputs fields: (weights and biases) Whf, bhf: hidden states in forward direction Whb, bhb: hidden states in b... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/7-bi_output.py | mag389/holbertonschool-machine_learning | train | 2 |
01748e70cb0ed5a7a8237b9c3b3175dc3827d778 | [
"self.image = image\nself.segments = segments\nself.intercept = {}\nself.local_exp = {}\nself.local_pred = None",
"if label not in self.local_exp:\n raise KeyError('Label not in explanation')\nsegments = self.segments\nimage = self.image\nexp = self.local_exp[label]\nmask = np.zeros(segments.shape, segments.dt... | <|body_start_0|>
self.image = image
self.segments = segments
self.intercept = {}
self.local_exp = {}
self.local_pred = None
<|end_body_0|>
<|body_start_1|>
if label not in self.local_exp:
raise KeyError('Label not in explanation')
segments = self.segm... | ImageExplanation | [
"MIT",
"BSD-2-Clause",
"LGPL-2.1-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageExplanation:
def __init__(self, image, segments):
"""Init function. Args: image: 3d numpy array segments: 2d numpy array, with the output from skimage.segmentation"""
<|body_0|>
def get_image_and_mask(self, label, positive_only=True, hide_rest=False, num_features=5, min... | stack_v2_sparse_classes_36k_train_018060 | 10,934 | permissive | [
{
"docstring": "Init function. Args: image: 3d numpy array segments: 2d numpy array, with the output from skimage.segmentation",
"name": "__init__",
"signature": "def __init__(self, image, segments)"
},
{
"docstring": "Init function. Args: label: label to explain positive_only: if True, only tak... | 2 | stack_v2_sparse_classes_30k_train_008695 | Implement the Python class `ImageExplanation` described below.
Class description:
Implement the ImageExplanation class.
Method signatures and docstrings:
- def __init__(self, image, segments): Init function. Args: image: 3d numpy array segments: 2d numpy array, with the output from skimage.segmentation
- def get_imag... | Implement the Python class `ImageExplanation` described below.
Class description:
Implement the ImageExplanation class.
Method signatures and docstrings:
- def __init__(self, image, segments): Init function. Args: image: 3d numpy array segments: 2d numpy array, with the output from skimage.segmentation
- def get_imag... | f59730dc7a8735232ef417685800652372c3b5dd | <|skeleton|>
class ImageExplanation:
def __init__(self, image, segments):
"""Init function. Args: image: 3d numpy array segments: 2d numpy array, with the output from skimage.segmentation"""
<|body_0|>
def get_image_and_mask(self, label, positive_only=True, hide_rest=False, num_features=5, min... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageExplanation:
def __init__(self, image, segments):
"""Init function. Args: image: 3d numpy array segments: 2d numpy array, with the output from skimage.segmentation"""
self.image = image
self.segments = segments
self.intercept = {}
self.local_exp = {}
self.l... | the_stack_v2_python_sparse | tensorwatch/saliency/lime/lime_image.py | microsoft/tensorwatch | train | 3,626 | |
093a005127e9be9a85e1b164554f0123366f526b | [
"possibleparent = None\nptree = set()\ntemp = p\nwhile p:\n ptree.add(p)\n p = p.parent\nqtree = set()\np = temp\nwhile q:\n qtree.add(q)\n if p in qtree:\n return p\n if q in ptree:\n return q\n possibleParent = q\n q = q.parent\nreturn possibleParent",
"a, b = (p, q)\nwhile a ... | <|body_start_0|>
possibleparent = None
ptree = set()
temp = p
while p:
ptree.add(p)
p = p.parent
qtree = set()
p = temp
while q:
qtree.add(q)
if p in qtree:
return p
if q in ptree:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, p, q):
""":type node: Node :rtype: Node"""
<|body_0|>
def lowestCommonAncestorFaster(self, p, q):
""":type node: Node :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
possibleparent = None
... | stack_v2_sparse_classes_36k_train_018061 | 2,096 | no_license | [
{
"docstring": ":type node: Node :rtype: Node",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, p, q)"
},
{
"docstring": ":type node: Node :rtype: Node",
"name": "lowestCommonAncestorFaster",
"signature": "def lowestCommonAncestorFaster(self, p, q)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, p, q): :type node: Node :rtype: Node
- def lowestCommonAncestorFaster(self, p, q): :type node: Node :rtype: Node | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, p, q): :type node: Node :rtype: Node
- def lowestCommonAncestorFaster(self, p, q): :type node: Node :rtype: Node
<|skeleton|>
class Solution:
... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, p, q):
""":type node: Node :rtype: Node"""
<|body_0|>
def lowestCommonAncestorFaster(self, p, q):
""":type node: Node :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, p, q):
""":type node: Node :rtype: Node"""
possibleparent = None
ptree = set()
temp = p
while p:
ptree.add(p)
p = p.parent
qtree = set()
p = temp
while q:
qtree.add(q)
... | the_stack_v2_python_sparse | L/LowestCommonAncestorofaBinaryTreeIII.py | bssrdf/pyleet | train | 2 | |
1ebbfcb0a9d27f6dd8d5391a933ef9d3189bbcc1 | [
"self.reader = reader.Reader()\nid_handler = identifier.Identifier()\nself.machine_id = id_handler.get_id()\nself.connection = self.set_connection()",
"rabbit_connection = False\naddress = self.reader.get_c_value()[1]\nport = self.reader.get_c_value()[2]\ntry:\n rabbit_connection = rabbitmq.RabbitMQ(address, p... | <|body_start_0|>
self.reader = reader.Reader()
id_handler = identifier.Identifier()
self.machine_id = id_handler.get_id()
self.connection = self.set_connection()
<|end_body_0|>
<|body_start_1|>
rabbit_connection = False
address = self.reader.get_c_value()[1]
port... | Handles the sending of the packets formed from metric values and id to the rabbit mq server, based on the configured send time. | Packet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Packet:
"""Handles the sending of the packets formed from metric values and id to the rabbit mq server, based on the configured send time."""
def __init__(self):
"""Creates the dictionary containing the collected packet, unique id and the time when the object was sent. Uses the given... | stack_v2_sparse_classes_36k_train_018062 | 1,468 | no_license | [
{
"docstring": "Creates the dictionary containing the collected packet, unique id and the time when the object was sent. Uses the given port and address to connect to the rabbit queue and sends the packet dictionary.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Init... | 2 | stack_v2_sparse_classes_30k_train_008327 | Implement the Python class `Packet` described below.
Class description:
Handles the sending of the packets formed from metric values and id to the rabbit mq server, based on the configured send time.
Method signatures and docstrings:
- def __init__(self): Creates the dictionary containing the collected packet, unique... | Implement the Python class `Packet` described below.
Class description:
Handles the sending of the packets formed from metric values and id to the rabbit mq server, based on the configured send time.
Method signatures and docstrings:
- def __init__(self): Creates the dictionary containing the collected packet, unique... | db8b8cd05bd47ee99abcc8660453edf7fce1c7a1 | <|skeleton|>
class Packet:
"""Handles the sending of the packets formed from metric values and id to the rabbit mq server, based on the configured send time."""
def __init__(self):
"""Creates the dictionary containing the collected packet, unique id and the time when the object was sent. Uses the given... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Packet:
"""Handles the sending of the packets formed from metric values and id to the rabbit mq server, based on the configured send time."""
def __init__(self):
"""Creates the dictionary containing the collected packet, unique id and the time when the object was sent. Uses the given port and add... | the_stack_v2_python_sparse | client/packets.py | BabyCakes13/SMS | train | 0 |
894d068ac9d964bbbcbe791d4e891c2f63d78f4e | [
"data = []\ntry:\n while True:\n data.append(self.instrument.read())\nexcept pyvisa.VisaIOError:\n pass\nreturn data",
"data = []\ntry:\n while True:\n data.append(self.instrument.read_bytes(1))\nexcept pyvisa.VisaIOError:\n pass\nreturn data"
] | <|body_start_0|>
data = []
try:
while True:
data.append(self.instrument.read())
except pyvisa.VisaIOError:
pass
return data
<|end_body_0|>
<|body_start_1|>
data = []
try:
while True:
data.append(self.ins... | PyVisaInstrument | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyVisaInstrument:
def read_all(self):
"""Helper func for when read/writes are out of sync - consume all waiting reads until buffer is empty. :return list of read data."""
<|body_0|>
def read_all_bytes(self):
"""Helper func for when read/writes are out of sync - consu... | stack_v2_sparse_classes_36k_train_018063 | 1,224 | permissive | [
{
"docstring": "Helper func for when read/writes are out of sync - consume all waiting reads until buffer is empty. :return list of read data.",
"name": "read_all",
"signature": "def read_all(self)"
},
{
"docstring": "Helper func for when read/writes are out of sync - consume all waiting reads u... | 2 | stack_v2_sparse_classes_30k_train_007519 | Implement the Python class `PyVisaInstrument` described below.
Class description:
Implement the PyVisaInstrument class.
Method signatures and docstrings:
- def read_all(self): Helper func for when read/writes are out of sync - consume all waiting reads until buffer is empty. :return list of read data.
- def read_all_... | Implement the Python class `PyVisaInstrument` described below.
Class description:
Implement the PyVisaInstrument class.
Method signatures and docstrings:
- def read_all(self): Helper func for when read/writes are out of sync - consume all waiting reads until buffer is empty. :return list of read data.
- def read_all_... | c89dfbd87533b7a402d0ce8217daef5be25389c8 | <|skeleton|>
class PyVisaInstrument:
def read_all(self):
"""Helper func for when read/writes are out of sync - consume all waiting reads until buffer is empty. :return list of read data."""
<|body_0|>
def read_all_bytes(self):
"""Helper func for when read/writes are out of sync - consu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyVisaInstrument:
def read_all(self):
"""Helper func for when read/writes are out of sync - consume all waiting reads until buffer is empty. :return list of read data."""
data = []
try:
while True:
data.append(self.instrument.read())
except pyvisa.Vi... | the_stack_v2_python_sparse | catkit/hardware/pyvisa_instrument.py | spacetelescope/catkit | train | 3 | |
ab13cad3d494677b33821e9473c61a533631d073 | [
"res = []\n\ndef dfs(root):\n if not root:\n res.append('#')\n return\n res.append(str(root.val))\n dfs(root.left)\n dfs(root.right)\ndfs(root)\nreturn ','.join(res)",
"vals = data.split(',')\nvals = iter(vals)\n\ndef dfs():\n v = next(vals)\n if v == '#':\n return\n node... | <|body_start_0|>
res = []
def dfs(root):
if not root:
res.append('#')
return
res.append(str(root.val))
dfs(root.left)
dfs(root.right)
dfs(root)
return ','.join(res)
<|end_body_0|>
<|body_start_1|>
v... | 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_018064 | 4,279 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_001268 | 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:... | 7ffdb772ad7252f3d4b9aa2689a92cb1f10c8f37 | <|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"""
res = []
def dfs(root):
if not root:
res.append('#')
return
res.append(str(root.val))
dfs(root.left)
... | the_stack_v2_python_sparse | 二叉树/297-二叉树的序列化和反序列化.py | zhengsizuo/leetcode-zhs | train | 0 | |
b0b806c4de8b6d39389763d69419b7b1368cb475 | [
"subject = 'Close Client Account Request'\ncontext = {'account': self.account}\nif self.close_choice == CloseAccountRequest.CloseChoice.liquidate.value:\n send_mail(subject, '', None, [self.account.primary_owner.advisor.user.email], html_message=render_to_string('email/advisor_liquidate_account.html', context))\... | <|body_start_0|>
subject = 'Close Client Account Request'
context = {'account': self.account}
if self.close_choice == CloseAccountRequest.CloseChoice.liquidate.value:
send_mail(subject, '', None, [self.account.primary_owner.advisor.user.email], html_message=render_to_string('email/ad... | CloseAccountRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloseAccountRequest:
def send_advisor_email(self):
"""Email Client Advisor when an account is closed"""
<|body_0|>
def send_admin_email(self):
"""Email Betasmartz Admin when an account is closed"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
subjec... | stack_v2_sparse_classes_36k_train_018065 | 49,558 | no_license | [
{
"docstring": "Email Client Advisor when an account is closed",
"name": "send_advisor_email",
"signature": "def send_advisor_email(self)"
},
{
"docstring": "Email Betasmartz Admin when an account is closed",
"name": "send_admin_email",
"signature": "def send_admin_email(self)"
}
] | 2 | null | Implement the Python class `CloseAccountRequest` described below.
Class description:
Implement the CloseAccountRequest class.
Method signatures and docstrings:
- def send_advisor_email(self): Email Client Advisor when an account is closed
- def send_admin_email(self): Email Betasmartz Admin when an account is closed | Implement the Python class `CloseAccountRequest` described below.
Class description:
Implement the CloseAccountRequest class.
Method signatures and docstrings:
- def send_advisor_email(self): Email Client Advisor when an account is closed
- def send_admin_email(self): Email Betasmartz Admin when an account is closed
... | bbdbf0cff04dd4ca15134d324d783b81b2e1c028 | <|skeleton|>
class CloseAccountRequest:
def send_advisor_email(self):
"""Email Client Advisor when an account is closed"""
<|body_0|>
def send_admin_email(self):
"""Email Betasmartz Admin when an account is closed"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloseAccountRequest:
def send_advisor_email(self):
"""Email Client Advisor when an account is closed"""
subject = 'Close Client Account Request'
context = {'account': self.account}
if self.close_choice == CloseAccountRequest.CloseChoice.liquidate.value:
send_mail(su... | the_stack_v2_python_sparse | client/models.py | brightgems/beta_python | train | 0 | |
4a75ed0369f42d40271ad64b09eb91b402cd0582 | [
"with open(self.schema_path, encoding='UTF-8') as stream:\n config = next(yaml.safe_load_all(stream))\nschema = {'type': 'object', 'properties': {}}\nschema['required'] = ['reporting_status']\nfor field in config['prose']['metadata']['meta']:\n is_required = field['name'] in schema['required']\n key = self... | <|body_start_0|>
with open(self.schema_path, encoding='UTF-8') as stream:
config = next(yaml.safe_load_all(stream))
schema = {'type': 'object', 'properties': {}}
schema['required'] = ['reporting_status']
for field in config['prose']['metadata']['meta']:
is_require... | Input schema from Open SDG format and validate metadata. | SchemaInputOpenSdg | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaInputOpenSdg:
"""Input schema from Open SDG format and validate metadata."""
def load_schema(self):
"""Import a _prose.yml schema into JSON Schema. Overrides parent."""
<|body_0|>
def prose_field_to_jsonschema(self, prose_field, is_required):
"""Convert a P... | stack_v2_sparse_classes_36k_train_018066 | 4,925 | permissive | [
{
"docstring": "Import a _prose.yml schema into JSON Schema. Overrides parent.",
"name": "load_schema",
"signature": "def load_schema(self)"
},
{
"docstring": "Convert a Prose.io field to a JSON Schema property. Parameters ---------- prose_field : Dict A dict of information about a field, pulled... | 2 | null | Implement the Python class `SchemaInputOpenSdg` described below.
Class description:
Input schema from Open SDG format and validate metadata.
Method signatures and docstrings:
- def load_schema(self): Import a _prose.yml schema into JSON Schema. Overrides parent.
- def prose_field_to_jsonschema(self, prose_field, is_r... | Implement the Python class `SchemaInputOpenSdg` described below.
Class description:
Input schema from Open SDG format and validate metadata.
Method signatures and docstrings:
- def load_schema(self): Import a _prose.yml schema into JSON Schema. Overrides parent.
- def prose_field_to_jsonschema(self, prose_field, is_r... | 43b092f6a3acd25284951f9be11b6016b1f18dba | <|skeleton|>
class SchemaInputOpenSdg:
"""Input schema from Open SDG format and validate metadata."""
def load_schema(self):
"""Import a _prose.yml schema into JSON Schema. Overrides parent."""
<|body_0|>
def prose_field_to_jsonschema(self, prose_field, is_required):
"""Convert a P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchemaInputOpenSdg:
"""Input schema from Open SDG format and validate metadata."""
def load_schema(self):
"""Import a _prose.yml schema into JSON Schema. Overrides parent."""
with open(self.schema_path, encoding='UTF-8') as stream:
config = next(yaml.safe_load_all(stream))
... | the_stack_v2_python_sparse | sdg/schemas/SchemaInputOpenSdg.py | open-sdg/sdg-build | train | 7 |
806f59f4eafffa214b25d5e8bbadef45976cbd84 | [
"zip_file = ZipFile(text_input_path)\nxml_data = zip_file.read('word/document.xml')\nzip_file.close()\nreturn BeautifulSoup(xml_data, 'xml')",
"list_of_value = []\ntables = text_input_soup.find_all('tbl')\ndd_lists_content = tables[table_index].find_all('sdtContent')\nfor i in dd_lists_content:\n list_of_value... | <|body_start_0|>
zip_file = ZipFile(text_input_path)
xml_data = zip_file.read('word/document.xml')
zip_file.close()
return BeautifulSoup(xml_data, 'xml')
<|end_body_0|>
<|body_start_1|>
list_of_value = []
tables = text_input_soup.find_all('tbl')
dd_lists_content ... | DropDownLists | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DropDownLists:
def get_soup(text_input_path) -> BeautifulSoup:
"""Opens a .docx file as a .zip file and stores the XML data containing the infos about the .docx document in a BeautifulSoup object. Args: text_input_path: Path of the text input form. Returns: BeautifulSoup object that cont... | stack_v2_sparse_classes_36k_train_018067 | 1,611 | no_license | [
{
"docstring": "Opens a .docx file as a .zip file and stores the XML data containing the infos about the .docx document in a BeautifulSoup object. Args: text_input_path: Path of the text input form. Returns: BeautifulSoup object that contains the XML data of the .docx document.",
"name": "get_soup",
"si... | 2 | stack_v2_sparse_classes_30k_test_000722 | Implement the Python class `DropDownLists` described below.
Class description:
Implement the DropDownLists class.
Method signatures and docstrings:
- def get_soup(text_input_path) -> BeautifulSoup: Opens a .docx file as a .zip file and stores the XML data containing the infos about the .docx document in a BeautifulSo... | Implement the Python class `DropDownLists` described below.
Class description:
Implement the DropDownLists class.
Method signatures and docstrings:
- def get_soup(text_input_path) -> BeautifulSoup: Opens a .docx file as a .zip file and stores the XML data containing the infos about the .docx document in a BeautifulSo... | f0ce3f75756be5a1b377474882b66293be8ed5ac | <|skeleton|>
class DropDownLists:
def get_soup(text_input_path) -> BeautifulSoup:
"""Opens a .docx file as a .zip file and stores the XML data containing the infos about the .docx document in a BeautifulSoup object. Args: text_input_path: Path of the text input form. Returns: BeautifulSoup object that cont... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DropDownLists:
def get_soup(text_input_path) -> BeautifulSoup:
"""Opens a .docx file as a .zip file and stores the XML data containing the infos about the .docx document in a BeautifulSoup object. Args: text_input_path: Path of the text input form. Returns: BeautifulSoup object that contains the XML d... | the_stack_v2_python_sparse | docx_package/dropdown_lists.py | how2know/Usability_Testing_Report_Generator | train | 0 | |
0212a05a1567e225b0f29e9b380b947bf6e13a5a | [
"api = renson.RensonVentilation(data[CONF_HOST])\nif not await self.hass.async_add_executor_job(api.connect):\n raise CannotConnect\nreturn {'title': 'Renson'}",
"if user_input is None:\n return self.async_show_form(step_id='user', data_schema=STEP_USER_DATA_SCHEMA)\nerrors = {}\ntry:\n info = await self... | <|body_start_0|>
api = renson.RensonVentilation(data[CONF_HOST])
if not await self.hass.async_add_executor_job(api.connect):
raise CannotConnect
return {'title': 'Renson'}
<|end_body_0|>
<|body_start_1|>
if user_input is None:
return self.async_show_form(step_id=... | Handle a config flow for Renson. | ConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Renson."""
async def validate_input(self, hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
"""Validate the user input allows us to connect."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | Non... | stack_v2_sparse_classes_36k_train_018068 | 2,000 | permissive | [
{
"docstring": "Validate the user input allows us to connect.",
"name": "validate_input",
"signature": "async def validate_input(self, hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]"
},
{
"docstring": "Handle the initial step.",
"name": "async_step_user",
"signature": "asyn... | 2 | stack_v2_sparse_classes_30k_train_020919 | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Renson.
Method signatures and docstrings:
- async def validate_input(self, hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]: Validate the user input allows us to connect.
- async def async_step_user(self, ... | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Renson.
Method signatures and docstrings:
- async def validate_input(self, hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]: Validate the user input allows us to connect.
- async def async_step_user(self, ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Renson."""
async def validate_input(self, hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
"""Validate the user input allows us to connect."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigFlow:
"""Handle a config flow for Renson."""
async def validate_input(self, hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
"""Validate the user input allows us to connect."""
api = renson.RensonVentilation(data[CONF_HOST])
if not await self.hass.async_add_exec... | the_stack_v2_python_sparse | homeassistant/components/renson/config_flow.py | home-assistant/core | train | 35,501 |
70162431dec3dc01e0080c5ffb05165ea0fcfb8e | [
"self.fig = plt.figure(1)\nself.ax_arr = [None] * (num_traj * 2)\nfor k in range(num_traj * 2):\n num = 2 * 100 + num_traj * 10 + (k + 1)\n self.ax_arr[k] = self.fig.add_subplot(num, projection='3d')\nself.trajectories_in = np.zeros((0, 0, num_traj))\nself.in_hidden = np.zeros((0, num_traj))\nself.in_velocity... | <|body_start_0|>
self.fig = plt.figure(1)
self.ax_arr = [None] * (num_traj * 2)
for k in range(num_traj * 2):
num = 2 * 100 + num_traj * 10 + (k + 1)
self.ax_arr[k] = self.fig.add_subplot(num, projection='3d')
self.trajectories_in = np.zeros((0, 0, num_traj))
... | HiddenTrajectoryPlot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HiddenTrajectoryPlot:
def __init__(self, num_traj):
""":param num_traj: The amount of training and validation trajectories that are plotted"""
<|body_0|>
def update_trajectories(self, trajectories_in: np.ndarray, in_hidden: np.ndarray, in_velocity: np.ndarray, in_direction: ... | stack_v2_sparse_classes_36k_train_018069 | 3,759 | permissive | [
{
"docstring": ":param num_traj: The amount of training and validation trajectories that are plotted",
"name": "__init__",
"signature": "def __init__(self, num_traj)"
},
{
"docstring": "Updates the trajectories that are plotted in the next call to plot. :param trajectories_in: The trajectories p... | 3 | stack_v2_sparse_classes_30k_train_010327 | Implement the Python class `HiddenTrajectoryPlot` described below.
Class description:
Implement the HiddenTrajectoryPlot class.
Method signatures and docstrings:
- def __init__(self, num_traj): :param num_traj: The amount of training and validation trajectories that are plotted
- def update_trajectories(self, traject... | Implement the Python class `HiddenTrajectoryPlot` described below.
Class description:
Implement the HiddenTrajectoryPlot class.
Method signatures and docstrings:
- def __init__(self, num_traj): :param num_traj: The amount of training and validation trajectories that are plotted
- def update_trajectories(self, traject... | d07d1b0b54222f1b01624444591f2884b49462b0 | <|skeleton|>
class HiddenTrajectoryPlot:
def __init__(self, num_traj):
""":param num_traj: The amount of training and validation trajectories that are plotted"""
<|body_0|>
def update_trajectories(self, trajectories_in: np.ndarray, in_hidden: np.ndarray, in_velocity: np.ndarray, in_direction: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HiddenTrajectoryPlot:
def __init__(self, num_traj):
""":param num_traj: The amount of training and validation trajectories that are plotted"""
self.fig = plt.figure(1)
self.ax_arr = [None] * (num_traj * 2)
for k in range(num_traj * 2):
num = 2 * 100 + num_traj * 10 ... | the_stack_v2_python_sparse | src/plots/HiddenStatePlot.py | kosmitive/rnn-tetherball-dynamics | train | 0 | |
435f48322403ca8e571f3bccfe8cc3a0a1677b7e | [
"super().__init__()\ncheck_boundaries(boundaries)\nself.boundaries = boundaries",
"self.randomize(None)\nself.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1])\nlength = signal.shape[-1]\nmask = torch.zeros(round(self.magnitude * length))\ntrange = torch.arange(length)\nloc = trange[torc... | <|body_start_0|>
super().__init__()
check_boundaries(boundaries)
self.boundaries = boundaries
<|end_body_0|>
<|body_start_1|>
self.randomize(None)
self.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1])
length = signal.shape[-1]
mask = to... | Randomly drop a portion of a signal | SignalRandDrop | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalRandDrop:
"""Randomly drop a portion of a signal"""
def __init__(self, boundaries: Sequence[float]=(0.0, 1.0)) -> None:
"""Args: boundaries: list defining lower and upper boundaries for the signal drop, lower and upper values need to be positive default : ``[0.0, 1.0]``"""
... | stack_v2_sparse_classes_36k_train_018070 | 16,322 | permissive | [
{
"docstring": "Args: boundaries: list defining lower and upper boundaries for the signal drop, lower and upper values need to be positive default : ``[0.0, 1.0]``",
"name": "__init__",
"signature": "def __init__(self, boundaries: Sequence[float]=(0.0, 1.0)) -> None"
},
{
"docstring": "Args: sig... | 2 | stack_v2_sparse_classes_30k_train_007567 | Implement the Python class `SignalRandDrop` described below.
Class description:
Randomly drop a portion of a signal
Method signatures and docstrings:
- def __init__(self, boundaries: Sequence[float]=(0.0, 1.0)) -> None: Args: boundaries: list defining lower and upper boundaries for the signal drop, lower and upper va... | Implement the Python class `SignalRandDrop` described below.
Class description:
Randomly drop a portion of a signal
Method signatures and docstrings:
- def __init__(self, boundaries: Sequence[float]=(0.0, 1.0)) -> None: Args: boundaries: list defining lower and upper boundaries for the signal drop, lower and upper va... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class SignalRandDrop:
"""Randomly drop a portion of a signal"""
def __init__(self, boundaries: Sequence[float]=(0.0, 1.0)) -> None:
"""Args: boundaries: list defining lower and upper boundaries for the signal drop, lower and upper values need to be positive default : ``[0.0, 1.0]``"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignalRandDrop:
"""Randomly drop a portion of a signal"""
def __init__(self, boundaries: Sequence[float]=(0.0, 1.0)) -> None:
"""Args: boundaries: list defining lower and upper boundaries for the signal drop, lower and upper values need to be positive default : ``[0.0, 1.0]``"""
super()._... | the_stack_v2_python_sparse | monai/transforms/signal/array.py | Project-MONAI/MONAI | train | 4,805 |
49cc46ed1cff3d79bc1e9b3e06b7788150628448 | [
"if x not in range(HORIZONTAL_SIZE):\n return False\nreturn True",
"if y not in range(VERTICAL_SIZE):\n return False\nreturn True",
"if dir in DIRECTIONS:\n return True\nreturn False"
] | <|body_start_0|>
if x not in range(HORIZONTAL_SIZE):
return False
return True
<|end_body_0|>
<|body_start_1|>
if y not in range(VERTICAL_SIZE):
return False
return True
<|end_body_1|>
<|body_start_2|>
if dir in DIRECTIONS:
return True
... | Table provide the dimensions of tabletop and validate the positions | Table | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Table:
"""Table provide the dimensions of tabletop and validate the positions"""
def is_valid_horizontal_position(x):
"""Find out the valid horizontal position :param x: x coordinate :return: True, if valid or False"""
<|body_0|>
def is_valid_vertical_position(y):
... | stack_v2_sparse_classes_36k_train_018071 | 966 | no_license | [
{
"docstring": "Find out the valid horizontal position :param x: x coordinate :return: True, if valid or False",
"name": "is_valid_horizontal_position",
"signature": "def is_valid_horizontal_position(x)"
},
{
"docstring": "Find out the valid vertical position :param y: y coordinate :return: True... | 3 | stack_v2_sparse_classes_30k_train_015189 | Implement the Python class `Table` described below.
Class description:
Table provide the dimensions of tabletop and validate the positions
Method signatures and docstrings:
- def is_valid_horizontal_position(x): Find out the valid horizontal position :param x: x coordinate :return: True, if valid or False
- def is_va... | Implement the Python class `Table` described below.
Class description:
Table provide the dimensions of tabletop and validate the positions
Method signatures and docstrings:
- def is_valid_horizontal_position(x): Find out the valid horizontal position :param x: x coordinate :return: True, if valid or False
- def is_va... | 92058d58371ee5f8d15c7bb19a1ae330e705f89c | <|skeleton|>
class Table:
"""Table provide the dimensions of tabletop and validate the positions"""
def is_valid_horizontal_position(x):
"""Find out the valid horizontal position :param x: x coordinate :return: True, if valid or False"""
<|body_0|>
def is_valid_vertical_position(y):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Table:
"""Table provide the dimensions of tabletop and validate the positions"""
def is_valid_horizontal_position(x):
"""Find out the valid horizontal position :param x: x coordinate :return: True, if valid or False"""
if x not in range(HORIZONTAL_SIZE):
return False
r... | the_stack_v2_python_sparse | toy_simulator/table.py | rajangar/toy_robot_simulator | train | 0 |
9fa5d45acbc32e68ba927a65dc480dc1387b068b | [
"self.guesser = guesser\nself.entries = entries\nself.min_score = min_score\nself.entries_filtered = []",
"if len(self.entries_filtered) < 1:\n self.filter_aggregator_entries()\nentries = normalize_entries(self.entries_filtered)\nfor e in entries:\n e.date_fmt = self.date_fmt\nreturn entries",
"for e in s... | <|body_start_0|>
self.guesser = guesser
self.entries = entries
self.min_score = min_score
self.entries_filtered = []
<|end_body_0|>
<|body_start_1|>
if len(self.entries_filtered) < 1:
self.filter_aggregator_entries()
entries = normalize_entries(self.entries_f... | Filter feed entries using scores from a Bayesian classifier. | BayesFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesFilter:
"""Filter feed entries using scores from a Bayesian classifier."""
def __init__(self, guesser, entries, min_score=0.5):
"""Initialize with the feed URI for parsing."""
<|body_0|>
def produce_entries(self):
"""Filter entries from a feed using the rege... | stack_v2_sparse_classes_36k_train_018072 | 3,503 | no_license | [
{
"docstring": "Initialize with the feed URI for parsing.",
"name": "__init__",
"signature": "def __init__(self, guesser, entries, min_score=0.5)"
},
{
"docstring": "Filter entries from a feed using the regex map, use the feed normalizer to produce FeedEntryDict objects.",
"name": "produce_e... | 3 | stack_v2_sparse_classes_30k_train_013672 | Implement the Python class `BayesFilter` described below.
Class description:
Filter feed entries using scores from a Bayesian classifier.
Method signatures and docstrings:
- def __init__(self, guesser, entries, min_score=0.5): Initialize with the feed URI for parsing.
- def produce_entries(self): Filter entries from ... | Implement the Python class `BayesFilter` described below.
Class description:
Filter feed entries using scores from a Bayesian classifier.
Method signatures and docstrings:
- def __init__(self, guesser, entries, min_score=0.5): Initialize with the feed URI for parsing.
- def produce_entries(self): Filter entries from ... | a925c3bd9580c2d0463e4b645d2a84dec0109818 | <|skeleton|>
class BayesFilter:
"""Filter feed entries using scores from a Bayesian classifier."""
def __init__(self, guesser, entries, min_score=0.5):
"""Initialize with the feed URI for parsing."""
<|body_0|>
def produce_entries(self):
"""Filter entries from a feed using the rege... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BayesFilter:
"""Filter feed entries using scores from a Bayesian classifier."""
def __init__(self, guesser, entries, min_score=0.5):
"""Initialize with the feed URI for parsing."""
self.guesser = guesser
self.entries = entries
self.min_score = min_score
self.entrie... | the_stack_v2_python_sparse | ch15_bayes_filter.py | openstake/hacking_rss_and_atom | train | 0 |
9e9737110f5ac43796eb973d3b59a62294ade549 | [
"d, n = (Counter(t), len(t))\nans, j = ((0, float('inf')), 0)\nfor i in range(len(s)):\n n -= d[s[i]] > 0\n d[s[i]] -= 1\n if n == 0:\n while d[s[j]] < 0:\n d[s[j]] += 1\n j += 1\n if ans[1] - ans[0] > i - j:\n ans = (j, i)\nreturn s[ans[0]:ans[1] + 1] if ans[... | <|body_start_0|>
d, n = (Counter(t), len(t))
ans, j = ((0, float('inf')), 0)
for i in range(len(s)):
n -= d[s[i]] > 0
d[s[i]] -= 1
if n == 0:
while d[s[j]] < 0:
d[s[j]] += 1
j += 1
if ans[... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minWindow(self, s: str, t: str) -> str:
"""Sliding Window 1번 방법을 개선. i를 이동하면서 처음 조건을 만족할때까지 j를 이동하지 않음 Time : O(S+T), Space : O(1)"""
<|body_0|>
def minWindow1(self, s: str, t: str) -> str:
"""Sliding Window"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_018073 | 1,171 | no_license | [
{
"docstring": "Sliding Window 1번 방법을 개선. i를 이동하면서 처음 조건을 만족할때까지 j를 이동하지 않음 Time : O(S+T), Space : O(1)",
"name": "minWindow",
"signature": "def minWindow(self, s: str, t: str) -> str"
},
{
"docstring": "Sliding Window",
"name": "minWindow1",
"signature": "def minWindow1(self, s: str, t:... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minWindow(self, s: str, t: str) -> str: Sliding Window 1번 방법을 개선. i를 이동하면서 처음 조건을 만족할때까지 j를 이동하지 않음 Time : O(S+T), Space : O(1)
- def minWindow1(self, s: str, t: str) -> str:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minWindow(self, s: str, t: str) -> str: Sliding Window 1번 방법을 개선. i를 이동하면서 처음 조건을 만족할때까지 j를 이동하지 않음 Time : O(S+T), Space : O(1)
- def minWindow1(self, s: str, t: str) -> str:... | c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1 | <|skeleton|>
class Solution:
def minWindow(self, s: str, t: str) -> str:
"""Sliding Window 1번 방법을 개선. i를 이동하면서 처음 조건을 만족할때까지 j를 이동하지 않음 Time : O(S+T), Space : O(1)"""
<|body_0|>
def minWindow1(self, s: str, t: str) -> str:
"""Sliding Window"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minWindow(self, s: str, t: str) -> str:
"""Sliding Window 1번 방법을 개선. i를 이동하면서 처음 조건을 만족할때까지 j를 이동하지 않음 Time : O(S+T), Space : O(1)"""
d, n = (Counter(t), len(t))
ans, j = ((0, float('inf')), 0)
for i in range(len(s)):
n -= d[s[i]] > 0
d[s[i... | the_stack_v2_python_sparse | Leetcode/76.py | hanwgyu/algorithm_problem_solving | train | 5 | |
8585acedd0520c7be40a8137eb154ee11d17eeed | [
"if obstacleGrid is None or len(obstacleGrid) == 0:\n return 0\nif len(obstacleGrid) == 1:\n if sum(obstacleGrid[0]) == 0:\n return 1\n else:\n return 0\ndp = [[0] * len(obstacleGrid[0]) for i in range(len(obstacleGrid))]\ndp[0][0] = 1\nfor i in range(0, len(obstacleGrid)):\n for j in rang... | <|body_start_0|>
if obstacleGrid is None or len(obstacleGrid) == 0:
return 0
if len(obstacleGrid) == 1:
if sum(obstacleGrid[0]) == 0:
return 1
else:
return 0
dp = [[0] * len(obstacleGrid[0]) for i in range(len(obstacleGrid))]
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_0|>
def uniquePathsWithObstacles1(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_018074 | 2,150 | permissive | [
{
"docstring": ":type obstacleGrid: List[List[int]] :rtype: int",
"name": "uniquePathsWithObstacles",
"signature": "def uniquePathsWithObstacles(self, obstacleGrid)"
},
{
"docstring": ":type obstacleGrid: List[List[int]] :rtype: int",
"name": "uniquePathsWithObstacles1",
"signature": "de... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePathsWithObstacles(self, obstacleGrid): :type obstacleGrid: List[List[int]] :rtype: int
- def uniquePathsWithObstacles1(self, obstacleGrid): :type obstacleGrid: List[Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePathsWithObstacles(self, obstacleGrid): :type obstacleGrid: List[List[int]] :rtype: int
- def uniquePathsWithObstacles1(self, obstacleGrid): :type obstacleGrid: List[Li... | 64847cbb1adcaca4561b949e8acc52e8e031a6cb | <|skeleton|>
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_0|>
def uniquePathsWithObstacles1(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
if obstacleGrid is None or len(obstacleGrid) == 0:
return 0
if len(obstacleGrid) == 1:
if sum(obstacleGrid[0]) == 0:
return 1
... | the_stack_v2_python_sparse | UniquePathsII63.py | Bit64L/LeetCode-Python- | train | 0 | |
1ded29b013b3c8fc349828d6d63c7b41d569efb8 | [
"super(AutoAugmentation, self).__init__(n_level)\nself.policies = policies\nself.n_select = n_select",
"chosen_policies = random.sample(self.policies, k=self.n_select)\nfor name, pr, level in chain.from_iterable(chosen_policies):\n if random.random() > pr:\n continue\n img = self._apply_augment(img, ... | <|body_start_0|>
super(AutoAugmentation, self).__init__(n_level)
self.policies = policies
self.n_select = n_select
<|end_body_0|>
<|body_start_1|>
chosen_policies = random.sample(self.policies, k=self.n_select)
for name, pr, level in chain.from_iterable(chosen_policies):
... | Auto augmentation class. References: https://arxiv.org/pdf/1805.09501.pdf | AutoAugmentation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoAugmentation:
"""Auto augmentation class. References: https://arxiv.org/pdf/1805.09501.pdf"""
def __init__(self, policies: List[List[Tuple[str, float, int]]], n_select: int=1, n_level: int=10) -> None:
"""Initialize."""
<|body_0|>
def __call__(self, img: Image) -> Im... | stack_v2_sparse_classes_36k_train_018075 | 5,467 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, policies: List[List[Tuple[str, float, int]]], n_select: int=1, n_level: int=10) -> None"
},
{
"docstring": "Run augmentations.",
"name": "__call__",
"signature": "def __call__(self, img: Image) -> Image"
... | 2 | stack_v2_sparse_classes_30k_train_013347 | Implement the Python class `AutoAugmentation` described below.
Class description:
Auto augmentation class. References: https://arxiv.org/pdf/1805.09501.pdf
Method signatures and docstrings:
- def __init__(self, policies: List[List[Tuple[str, float, int]]], n_select: int=1, n_level: int=10) -> None: Initialize.
- def ... | Implement the Python class `AutoAugmentation` described below.
Class description:
Auto augmentation class. References: https://arxiv.org/pdf/1805.09501.pdf
Method signatures and docstrings:
- def __init__(self, policies: List[List[Tuple[str, float, int]]], n_select: int=1, n_level: int=10) -> None: Initialize.
- def ... | 88bcff70e93dd68058a5cf0dfeac119a57abc6de | <|skeleton|>
class AutoAugmentation:
"""Auto augmentation class. References: https://arxiv.org/pdf/1805.09501.pdf"""
def __init__(self, policies: List[List[Tuple[str, float, int]]], n_select: int=1, n_level: int=10) -> None:
"""Initialize."""
<|body_0|>
def __call__(self, img: Image) -> Im... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoAugmentation:
"""Auto augmentation class. References: https://arxiv.org/pdf/1805.09501.pdf"""
def __init__(self, policies: List[List[Tuple[str, float, int]]], n_select: int=1, n_level: int=10) -> None:
"""Initialize."""
super(AutoAugmentation, self).__init__(n_level)
self.poli... | the_stack_v2_python_sparse | src/augmentation/methods.py | scott-mao/DenseDepth_Pruning | train | 1 |
83600cc91e7b63d81b341cee88a7aeb8c2d577f5 | [
"if not root:\n return True\n\ndef recursive(l, r):\n if not l and (not r):\n return True\n elif l and r:\n return l.val == r.val and recursive(l.left, r.right) and recursive(l.right, r.left)\n else:\n return False\nreturn recursive(root.left, root.right)",
"if not root:\n retu... | <|body_start_0|>
if not root:
return True
def recursive(l, r):
if not l and (not r):
return True
elif l and r:
return l.val == r.val and recursive(l.left, r.right) and recursive(l.right, r.left)
else:
return... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return True
... | stack_v2_sparse_classes_36k_train_018076 | 1,394 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
<|skeleton|>
class Solution:
def isSymmetric... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
if not root:
return True
def recursive(l, r):
if not l and (not r):
return True
elif l and r:
return l.val == r.val and recursive(l.left, ... | the_stack_v2_python_sparse | problems/isSymmetric.py | joddiy/leetcode | train | 1 | |
e5f722146f38efcc2b41ea45217e4c2c9c2166ad | [
"client_redis = self.settings.get('client_redis')\nclient_motor = self.settings.get('client_motor')\nrequest = self.get_bytes_body_source()\nquery = request.get('query', '')\noperation_name = request.get('operationName', '')\nvariables = request.get('variables', {})\nresult = main_schema.execute(request_string=quer... | <|body_start_0|>
client_redis = self.settings.get('client_redis')
client_motor = self.settings.get('client_motor')
request = self.get_bytes_body_source()
query = request.get('query', '')
operation_name = request.get('operationName', '')
variables = request.get('variables'... | Публичный API - без требований авторизации. На этом этапе обработчик - есть общая точка входа для всех запросов. Нет механизма идентификации. | PublicHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PublicHandler:
"""Публичный API - без требований авторизации. На этом этапе обработчик - есть общая точка входа для всех запросов. Нет механизма идентификации."""
async def get(self):
"""GraphQL GET - запрос данных. http://graphql.org/learn/serving-over-http/#get-request http://graph... | stack_v2_sparse_classes_36k_train_018077 | 8,125 | no_license | [
{
"docstring": "GraphQL GET - запрос данных. http://graphql.org/learn/serving-over-http/#get-request http://graphql.org/learn/queries/#arguments",
"name": "get",
"signature": "async def get(self)"
},
{
"docstring": "GraphQL POST - модификация данных. http://graphql.org/learn/serving-over-http/#p... | 2 | stack_v2_sparse_classes_30k_train_010898 | Implement the Python class `PublicHandler` described below.
Class description:
Публичный API - без требований авторизации. На этом этапе обработчик - есть общая точка входа для всех запросов. Нет механизма идентификации.
Method signatures and docstrings:
- async def get(self): GraphQL GET - запрос данных. http://grap... | Implement the Python class `PublicHandler` described below.
Class description:
Публичный API - без требований авторизации. На этом этапе обработчик - есть общая точка входа для всех запросов. Нет механизма идентификации.
Method signatures and docstrings:
- async def get(self): GraphQL GET - запрос данных. http://grap... | c22b3bc4c533b2e1508dfbd211ce98e26517d079 | <|skeleton|>
class PublicHandler:
"""Публичный API - без требований авторизации. На этом этапе обработчик - есть общая точка входа для всех запросов. Нет механизма идентификации."""
async def get(self):
"""GraphQL GET - запрос данных. http://graphql.org/learn/serving-over-http/#get-request http://graph... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PublicHandler:
"""Публичный API - без требований авторизации. На этом этапе обработчик - есть общая точка входа для всех запросов. Нет механизма идентификации."""
async def get(self):
"""GraphQL GET - запрос данных. http://graphql.org/learn/serving-over-http/#get-request http://graphql.org/learn/... | the_stack_v2_python_sparse | server/modules/handler.py | Rey8d01/chimera | train | 10 |
037d5658e5e85f09b18e9b0cab84902de5aed6fe | [
"super().__init__()\nself.fft_size = fft_size\nif win_length is None:\n self.win_length = fft_size\nelse:\n self.win_length = win_length\nself.hop_size = hop_size\nself.center = center\nself.normalized = normalized\nself.onesided = onesided\nif window is not None and (not hasattr(signal.windows, f'{window}'))... | <|body_start_0|>
super().__init__()
self.fft_size = fft_size
if win_length is None:
self.win_length = fft_size
else:
self.win_length = win_length
self.hop_size = hop_size
self.center = center
self.normalized = normalized
self.onesid... | Calculate Mel-spectrogram. | MelSpectrogram | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MelSpectrogram:
"""Calculate Mel-spectrogram."""
def __init__(self, fs=22050, fft_size=1024, hop_size=256, win_length=None, window='hann', num_mels=80, fmin=80, fmax=7600, center=True, normalized=False, onesided=True, eps=1e-10, log_base=10.0):
"""Initialize MelSpectrogram module."""... | stack_v2_sparse_classes_36k_train_018078 | 46,210 | permissive | [
{
"docstring": "Initialize MelSpectrogram module.",
"name": "__init__",
"signature": "def __init__(self, fs=22050, fft_size=1024, hop_size=256, win_length=None, window='hann', num_mels=80, fmin=80, fmax=7600, center=True, normalized=False, onesided=True, eps=1e-10, log_base=10.0)"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_train_009322 | Implement the Python class `MelSpectrogram` described below.
Class description:
Calculate Mel-spectrogram.
Method signatures and docstrings:
- def __init__(self, fs=22050, fft_size=1024, hop_size=256, win_length=None, window='hann', num_mels=80, fmin=80, fmax=7600, center=True, normalized=False, onesided=True, eps=1e... | Implement the Python class `MelSpectrogram` described below.
Class description:
Calculate Mel-spectrogram.
Method signatures and docstrings:
- def __init__(self, fs=22050, fft_size=1024, hop_size=256, win_length=None, window='hann', num_mels=80, fmin=80, fmax=7600, center=True, normalized=False, onesided=True, eps=1e... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class MelSpectrogram:
"""Calculate Mel-spectrogram."""
def __init__(self, fs=22050, fft_size=1024, hop_size=256, win_length=None, window='hann', num_mels=80, fmin=80, fmax=7600, center=True, normalized=False, onesided=True, eps=1e-10, log_base=10.0):
"""Initialize MelSpectrogram module."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MelSpectrogram:
"""Calculate Mel-spectrogram."""
def __init__(self, fs=22050, fft_size=1024, hop_size=256, win_length=None, window='hann', num_mels=80, fmin=80, fmax=7600, center=True, normalized=False, onesided=True, eps=1e-10, log_base=10.0):
"""Initialize MelSpectrogram module."""
supe... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/losses.py | anniyanvr/DeepSpeech-1 | train | 0 |
d205a0585ccfdbb1075d2b33e40a4b0bbbd1cd71 | [
"super().__init__()\nself.vgg = vgg19(pretrained=True).features if not batch_norm else vgg19_bn(pretrained=True).features\nself.layers = [18, 27] if not batch_norm else [26, 39]\nself.model = nn.Sequential(nn.Conv2d(512, 512, kernel_size=1), nn.ReLU(inplace=True), nn.Dropout(0.8), nn.Conv2d(512, 512, kernel_size=1)... | <|body_start_0|>
super().__init__()
self.vgg = vgg19(pretrained=True).features if not batch_norm else vgg19_bn(pretrained=True).features
self.layers = [18, 27] if not batch_norm else [26, 39]
self.model = nn.Sequential(nn.Conv2d(512, 512, kernel_size=1), nn.ReLU(inplace=True), nn.Dropout... | TableNet. | TableNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TableNet:
"""TableNet."""
def __init__(self, num_class: int, batch_norm: bool=False):
"""Initialize TableNet. Args: num_class (int): Number of classes per point. batch_norm (bool): Select VGG with or without batch normalization."""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_36k_train_018079 | 5,468 | no_license | [
{
"docstring": "Initialize TableNet. Args: num_class (int): Number of classes per point. batch_norm (bool): Select VGG with or without batch normalization.",
"name": "__init__",
"signature": "def __init__(self, num_class: int, batch_norm: bool=False)"
},
{
"docstring": "Forward pass. Args: x (te... | 2 | stack_v2_sparse_classes_30k_test_001096 | Implement the Python class `TableNet` described below.
Class description:
TableNet.
Method signatures and docstrings:
- def __init__(self, num_class: int, batch_norm: bool=False): Initialize TableNet. Args: num_class (int): Number of classes per point. batch_norm (bool): Select VGG with or without batch normalization... | Implement the Python class `TableNet` described below.
Class description:
TableNet.
Method signatures and docstrings:
- def __init__(self, num_class: int, batch_norm: bool=False): Initialize TableNet. Args: num_class (int): Number of classes per point. batch_norm (bool): Select VGG with or without batch normalization... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class TableNet:
"""TableNet."""
def __init__(self, num_class: int, batch_norm: bool=False):
"""Initialize TableNet. Args: num_class (int): Number of classes per point. batch_norm (bool): Select VGG with or without batch normalization."""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TableNet:
"""TableNet."""
def __init__(self, num_class: int, batch_norm: bool=False):
"""Initialize TableNet. Args: num_class (int): Number of classes per point. batch_norm (bool): Select VGG with or without batch normalization."""
super().__init__()
self.vgg = vgg19(pretrained=Tr... | the_stack_v2_python_sparse | generated/test_tomassosorio_OCR_tablenet.py | jansel/pytorch-jit-paritybench | train | 35 |
cc15e2111cd96a422debe0d6bf491ae7cdd6723a | [
"self.level_id = kwargs.get('level_id')\nself.title = kwargs.get('title')\nself.task1 = kwargs.get('task1')\nself.task2 = kwargs.get('task2')\nself.task3 = kwargs.get('task3')\nself.bonuses = kwargs.get('bonuses')",
"self.level_id = kwargs['level_id']\nself.title = kwargs['title']\nself.task1 = kwargs['task1']\ns... | <|body_start_0|>
self.level_id = kwargs.get('level_id')
self.title = kwargs.get('title')
self.task1 = kwargs.get('task1')
self.task2 = kwargs.get('task2')
self.task3 = kwargs.get('task3')
self.bonuses = kwargs.get('bonuses')
<|end_body_0|>
<|body_start_1|>
self.l... | LevelInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LevelInfo:
def __init__(self, **kwargs):
"""Params: level_id: int title: str task1: str task2: str task3: str bonuses: str[]"""
<|body_0|>
def load(self, **kwargs):
"""load from dict Exception: KeyError"""
<|body_1|>
def dump(self):
"""dump -> di... | stack_v2_sparse_classes_36k_train_018080 | 26,590 | no_license | [
{
"docstring": "Params: level_id: int title: str task1: str task2: str task3: str bonuses: str[]",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "load from dict Exception: KeyError",
"name": "load",
"signature": "def load(self, **kwargs)"
},
{
... | 3 | stack_v2_sparse_classes_30k_val_000175 | Implement the Python class `LevelInfo` described below.
Class description:
Implement the LevelInfo class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Params: level_id: int title: str task1: str task2: str task3: str bonuses: str[]
- def load(self, **kwargs): load from dict Exception: KeyError
- ... | Implement the Python class `LevelInfo` described below.
Class description:
Implement the LevelInfo class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Params: level_id: int title: str task1: str task2: str task3: str bonuses: str[]
- def load(self, **kwargs): load from dict Exception: KeyError
- ... | aa0b2697e295889e8c23a7104889ea95f2a4b6b1 | <|skeleton|>
class LevelInfo:
def __init__(self, **kwargs):
"""Params: level_id: int title: str task1: str task2: str task3: str bonuses: str[]"""
<|body_0|>
def load(self, **kwargs):
"""load from dict Exception: KeyError"""
<|body_1|>
def dump(self):
"""dump -> di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LevelInfo:
def __init__(self, **kwargs):
"""Params: level_id: int title: str task1: str task2: str task3: str bonuses: str[]"""
self.level_id = kwargs.get('level_id')
self.title = kwargs.get('title')
self.task1 = kwargs.get('task1')
self.task2 = kwargs.get('task2')
... | the_stack_v2_python_sparse | message.py | songhui17/Server | train | 0 | |
c87ee79af6bd24fbbecb41be4fa66fbf5cf3b09b | [
"self.W = W\nself.b = b\nself.x = None\nself.db = None\nself.dW = None",
"self.x = x\nout = np.dot(x, self.W) + self.b\nreturn out",
"dx = np.dot(dout, self.W.T)\nself.dW = np.dot(self.x.T, dout)\nself.db = np.sum(dout, axis=0)\nreturn dx"
] | <|body_start_0|>
self.W = W
self.b = b
self.x = None
self.db = None
self.dW = None
<|end_body_0|>
<|body_start_1|>
self.x = x
out = np.dot(x, self.W) + self.b
return out
<|end_body_1|>
<|body_start_2|>
dx = np.dot(dout, self.W.T)
self.dW ... | 신경망의 순전파에서 행해지는 내적을 기하학에서는 어파인 변환 affine transformation 이라고 한다. | Affine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Affine:
"""신경망의 순전파에서 행해지는 내적을 기하학에서는 어파인 변환 affine transformation 이라고 한다."""
def __init__(self, W, b):
"""입력에 가중치를 곱하고 편향을 더하는 affine 변환 전체를 정의한 클래스이므로 가중치 W, 편향 b 를 포함하고, 이 값들을 갱신하기 위해 dW, db 값을 갖는다. 미분값을 역전파하기위해서 입력 x 를 보관한다. :param W: numpy matrix : 가중치 :param b: numpy array : 편향... | stack_v2_sparse_classes_36k_train_018081 | 7,302 | permissive | [
{
"docstring": "입력에 가중치를 곱하고 편향을 더하는 affine 변환 전체를 정의한 클래스이므로 가중치 W, 편향 b 를 포함하고, 이 값들을 갱신하기 위해 dW, db 값을 갖는다. 미분값을 역전파하기위해서 입력 x 를 보관한다. :param W: numpy matrix : 가중치 :param b: numpy array : 편향",
"name": "__init__",
"signature": "def __init__(self, W, b)"
},
{
"docstring": "순전파 :param x: numpy m... | 3 | null | Implement the Python class `Affine` described below.
Class description:
신경망의 순전파에서 행해지는 내적을 기하학에서는 어파인 변환 affine transformation 이라고 한다.
Method signatures and docstrings:
- def __init__(self, W, b): 입력에 가중치를 곱하고 편향을 더하는 affine 변환 전체를 정의한 클래스이므로 가중치 W, 편향 b 를 포함하고, 이 값들을 갱신하기 위해 dW, db 값을 갖는다. 미분값을 역전파하기위해서 입력 x 를 보관한다... | Implement the Python class `Affine` described below.
Class description:
신경망의 순전파에서 행해지는 내적을 기하학에서는 어파인 변환 affine transformation 이라고 한다.
Method signatures and docstrings:
- def __init__(self, W, b): 입력에 가중치를 곱하고 편향을 더하는 affine 변환 전체를 정의한 클래스이므로 가중치 W, 편향 b 를 포함하고, 이 값들을 갱신하기 위해 dW, db 값을 갖는다. 미분값을 역전파하기위해서 입력 x 를 보관한다... | 4d319c8729472cc5f490935854441a2d4b4e8818 | <|skeleton|>
class Affine:
"""신경망의 순전파에서 행해지는 내적을 기하학에서는 어파인 변환 affine transformation 이라고 한다."""
def __init__(self, W, b):
"""입력에 가중치를 곱하고 편향을 더하는 affine 변환 전체를 정의한 클래스이므로 가중치 W, 편향 b 를 포함하고, 이 값들을 갱신하기 위해 dW, db 값을 갖는다. 미분값을 역전파하기위해서 입력 x 를 보관한다. :param W: numpy matrix : 가중치 :param b: numpy array : 편향... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Affine:
"""신경망의 순전파에서 행해지는 내적을 기하학에서는 어파인 변환 affine transformation 이라고 한다."""
def __init__(self, W, b):
"""입력에 가중치를 곱하고 편향을 더하는 affine 변환 전체를 정의한 클래스이므로 가중치 W, 편향 b 를 포함하고, 이 값들을 갱신하기 위해 dW, db 값을 갖는다. 미분값을 역전파하기위해서 입력 x 를 보관한다. :param W: numpy matrix : 가중치 :param b: numpy array : 편향"""
s... | the_stack_v2_python_sparse | DeepLearning/DeepLearning/09_Deep_SongJW/ch5/layers.py | ghost9023/DeepLearningPythonStudy | train | 1 |
69dc9b7525580a3d95e2f725f1fa8d3025cbebbb | [
"if not l1:\n return l2\nif not l2:\n return l1\nif l1.val <= l2.val:\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1\nelse:\n l2.next = self.mergeTwoLists(l2.next, l1)\n return l2",
"if not l1:\n return l2\nif not l2:\n return l1\naux = []\nwhile l1 and l2:\n if l1.val <= l2.va... | <|body_start_0|>
if not l1:
return l2
if not l2:
return l1
if l1.val <= l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l2.next, l1)
return l2
<|end_body_0|>
<|body_sta... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""recursive version"""
<|body_0|>
def mergeTwoLists_iterative(self, l1: ListNode, l2: ListNode) -> ListNode:
"""iterative version 8'14''"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_018082 | 1,437 | no_license | [
{
"docstring": "recursive version",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode"
},
{
"docstring": "iterative version 8'14''",
"name": "mergeTwoLists_iterative",
"signature": "def mergeTwoLists_iterative(self, l1: ListNode, l2: L... | 2 | stack_v2_sparse_classes_30k_val_000542 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: recursive version
- def mergeTwoLists_iterative(self, l1: ListNode, l2: ListNode) -> ListNode: iterative version ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: recursive version
- def mergeTwoLists_iterative(self, l1: ListNode, l2: ListNode) -> ListNode: iterative version ... | d4d44e6dfd3df4cb47b855ad30e6849038cea0a5 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""recursive version"""
<|body_0|>
def mergeTwoLists_iterative(self, l1: ListNode, l2: ListNode) -> ListNode:
"""iterative version 8'14''"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""recursive version"""
if not l1:
return l2
if not l2:
return l1
if l1.val <= l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
... | the_stack_v2_python_sparse | leetcode/amazon/linked-lists/merge_two_sorted_lists.py | alvaronaschez/amazon | train | 0 | |
15ed22f7fffd066270fb8d0534cc859287a9c769 | [
"super().__init__(x, y)\nself.fill_color = QtCore.Qt.yellow\nself.line_color = QtCore.Qt.black\nself.dx = random.randint(2, 5)",
"self.x -= self.dx\nif self.x < -Bird.SIZE * 8:\n self.x = Bird.SIZE + w\n self.y = random.randint(Bird.SIZE, h - Bird.SIZE)"
] | <|body_start_0|>
super().__init__(x, y)
self.fill_color = QtCore.Qt.yellow
self.line_color = QtCore.Qt.black
self.dx = random.randint(2, 5)
<|end_body_0|>
<|body_start_1|>
self.x -= self.dx
if self.x < -Bird.SIZE * 8:
self.x = Bird.SIZE + w
self.y... | Class to represent a Canary. | Canary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Canary:
"""Class to represent a Canary."""
def __init__(self, x, y):
"""Create a new Canary with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero."""
<|body_0|>
def move(self, w, h):
"""A C... | stack_v2_sparse_classes_36k_train_018083 | 13,878 | no_license | [
{
"docstring": "Create a new Canary with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero.",
"name": "__init__",
"signature": "def __init__(self, x, y)"
},
{
"docstring": "A Cardinal flies straight across the aviary, left-... | 2 | stack_v2_sparse_classes_30k_train_019942 | Implement the Python class `Canary` described below.
Class description:
Class to represent a Canary.
Method signatures and docstrings:
- def __init__(self, x, y): Create a new Canary with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero.
- def ... | Implement the Python class `Canary` described below.
Class description:
Class to represent a Canary.
Method signatures and docstrings:
- def __init__(self, x, y): Create a new Canary with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero.
- def ... | 0e3470085083012f893adb22aa46d46039016965 | <|skeleton|>
class Canary:
"""Class to represent a Canary."""
def __init__(self, x, y):
"""Create a new Canary with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero."""
<|body_0|>
def move(self, w, h):
"""A C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Canary:
"""Class to represent a Canary."""
def __init__(self, x, y):
"""Create a new Canary with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero."""
super().__init__(x, y)
self.fill_color = QtCore.Qt.yellow... | the_stack_v2_python_sparse | CS_210 (Introduction to Programming)/Labs/Lab34_AviaryApp.py | JacobOrner/USAFA | train | 0 |
fa85356594516e061ccd3f217a6fa1729d4e52e6 | [
"try:\n key = request.Key\n value = request.Value\n expire = request.Expire\n if key == None or value == None:\n raise Exception('参数异常')\n oper.strSet(key, value)\n if expire != 0:\n oper.setKeyExpires(key, expire)\n return RedisHelper_pb2.RedisCacheResponse(Code=200, Message='缓存R... | <|body_start_0|>
try:
key = request.Key
value = request.Value
expire = request.Expire
if key == None or value == None:
raise Exception('参数异常')
oper.strSet(key, value)
if expire != 0:
oper.setKeyExpires(key, e... | RedisHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisHelper:
def RedisCacheStr(self, request, context):
"""缓存str值入redis :param request:请求对象 :param context:上下文 :return:缓存结果"""
<|body_0|>
def RedisCacheList(self, request, context):
"""缓存List值入redis :param request:请求对象 :param context:上下文 :return:缓存结果"""
<|bod... | stack_v2_sparse_classes_36k_train_018084 | 4,873 | no_license | [
{
"docstring": "缓存str值入redis :param request:请求对象 :param context:上下文 :return:缓存结果",
"name": "RedisCacheStr",
"signature": "def RedisCacheStr(self, request, context)"
},
{
"docstring": "缓存List值入redis :param request:请求对象 :param context:上下文 :return:缓存结果",
"name": "RedisCacheList",
"signature... | 5 | stack_v2_sparse_classes_30k_test_000629 | Implement the Python class `RedisHelper` described below.
Class description:
Implement the RedisHelper class.
Method signatures and docstrings:
- def RedisCacheStr(self, request, context): 缓存str值入redis :param request:请求对象 :param context:上下文 :return:缓存结果
- def RedisCacheList(self, request, context): 缓存List值入redis :par... | Implement the Python class `RedisHelper` described below.
Class description:
Implement the RedisHelper class.
Method signatures and docstrings:
- def RedisCacheStr(self, request, context): 缓存str值入redis :param request:请求对象 :param context:上下文 :return:缓存结果
- def RedisCacheList(self, request, context): 缓存List值入redis :par... | e4faadef0f094d5a02e9d77b1d53dbb1b362f649 | <|skeleton|>
class RedisHelper:
def RedisCacheStr(self, request, context):
"""缓存str值入redis :param request:请求对象 :param context:上下文 :return:缓存结果"""
<|body_0|>
def RedisCacheList(self, request, context):
"""缓存List值入redis :param request:请求对象 :param context:上下文 :return:缓存结果"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RedisHelper:
def RedisCacheStr(self, request, context):
"""缓存str值入redis :param request:请求对象 :param context:上下文 :return:缓存结果"""
try:
key = request.Key
value = request.Value
expire = request.Expire
if key == None or value == None:
r... | the_stack_v2_python_sparse | Redis/RedisHelper_Server.py | DapengSun/gRPC-Cloud | train | 0 | |
14952a22d4f5f65b2ad348b79c17ce790093b629 | [
"re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])\nresult = re\nAssertions().assert_in_text(result, expect['mockCarInMessage'])",
"re = cloudparking_service(centerMonitorLogin).mockCarInOut(send_data['carNum'], 1, send_data['outClientID'])\nresult = re\nAssertions().assert... | <|body_start_0|>
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
<|end_body_0|>
<|body_start_1|>
re = cloudparking_service(centerMonitorLogin).mockCarInOut(send_data['ca... | TestOperatorLog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestOperatorLog:
def test_mockCarIn(self, send_data, expect):
"""模拟车辆进场"""
<|body_0|>
def test_mockCarOut(self, centerMonitorLogin, send_data, expect):
"""模拟离场"""
<|body_1|>
def test_sendVoiceMsg(self, centerMonitorLogin, send_data, expect):
"""发... | stack_v2_sparse_classes_36k_train_018085 | 1,831 | no_license | [
{
"docstring": "模拟车辆进场",
"name": "test_mockCarIn",
"signature": "def test_mockCarIn(self, send_data, expect)"
},
{
"docstring": "模拟离场",
"name": "test_mockCarOut",
"signature": "def test_mockCarOut(self, centerMonitorLogin, send_data, expect)"
},
{
"docstring": "发送语音",
"name":... | 4 | stack_v2_sparse_classes_30k_train_001291 | Implement the Python class `TestOperatorLog` described below.
Class description:
Implement the TestOperatorLog class.
Method signatures and docstrings:
- def test_mockCarIn(self, send_data, expect): 模拟车辆进场
- def test_mockCarOut(self, centerMonitorLogin, send_data, expect): 模拟离场
- def test_sendVoiceMsg(self, centerMon... | Implement the Python class `TestOperatorLog` described below.
Class description:
Implement the TestOperatorLog class.
Method signatures and docstrings:
- def test_mockCarIn(self, send_data, expect): 模拟车辆进场
- def test_mockCarOut(self, centerMonitorLogin, send_data, expect): 模拟离场
- def test_sendVoiceMsg(self, centerMon... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestOperatorLog:
def test_mockCarIn(self, send_data, expect):
"""模拟车辆进场"""
<|body_0|>
def test_mockCarOut(self, centerMonitorLogin, send_data, expect):
"""模拟离场"""
<|body_1|>
def test_sendVoiceMsg(self, centerMonitorLogin, send_data, expect):
"""发... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestOperatorLog:
def test_mockCarIn(self, send_data, expect):
"""模拟车辆进场"""
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
def test_mockCarOut(self, center... | the_stack_v2_python_sparse | test_suite/centerMonitorRoom/personalInfo/test_operatorLog.py | oyebino/pomp_api | train | 1 | |
9a0c62c86f0d12e9acd8a43cf1d9692fcd68b662 | [
"random_bytes = Random.get_random_bytes(AccessToken._TOKEN_BYTE_LENGTH)\nsession_token = base64.b64encode(random_bytes)\ntoken = cls(parent=cls.default_ancestor(), associated_user=user.key, token_string=session_token)\ntoken.put()\nreturn token",
"results = cls.query(cls.associated_user == user.key, cls.valid == ... | <|body_start_0|>
random_bytes = Random.get_random_bytes(AccessToken._TOKEN_BYTE_LENGTH)
session_token = base64.b64encode(random_bytes)
token = cls(parent=cls.default_ancestor(), associated_user=user.key, token_string=session_token)
token.put()
return token
<|end_body_0|>
<|body_... | Access token ndb model | AccessToken | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessToken:
"""Access token ndb model"""
def create(cls, user):
"""Create a new secure session token for the user, the token_string is generated as a 32-byte cryptographic-random sequence then encoded using base64 encoding. The token is stored as a valid token in the datastore befor... | stack_v2_sparse_classes_36k_train_018086 | 3,487 | no_license | [
{
"docstring": "Create a new secure session token for the user, the token_string is generated as a 32-byte cryptographic-random sequence then encoded using base64 encoding. The token is stored as a valid token in the datastore before this method returns. Args: user: A valid instance of the User model. Returns: ... | 3 | stack_v2_sparse_classes_30k_train_014252 | Implement the Python class `AccessToken` described below.
Class description:
Access token ndb model
Method signatures and docstrings:
- def create(cls, user): Create a new secure session token for the user, the token_string is generated as a 32-byte cryptographic-random sequence then encoded using base64 encoding. Th... | Implement the Python class `AccessToken` described below.
Class description:
Access token ndb model
Method signatures and docstrings:
- def create(cls, user): Create a new secure session token for the user, the token_string is generated as a 32-byte cryptographic-random sequence then encoded using base64 encoding. Th... | 99af4ea077fc6abf8672834d88213ec93a9b7fdf | <|skeleton|>
class AccessToken:
"""Access token ndb model"""
def create(cls, user):
"""Create a new secure session token for the user, the token_string is generated as a 32-byte cryptographic-random sequence then encoded using base64 encoding. The token is stored as a valid token in the datastore befor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccessToken:
"""Access token ndb model"""
def create(cls, user):
"""Create a new secure session token for the user, the token_string is generated as a 32-byte cryptographic-random sequence then encoded using base64 encoding. The token is stored as a valid token in the datastore before this method... | the_stack_v2_python_sparse | src/python/xplore/database/models/auth.py | dballesteros7/explore-city-server | train | 0 |
661f6edd29e39bb4b1bebf2d748d83bafb4bc255 | [
"ciphertext = process_cfws()\nform_data = {'pageSize': '5', 'pageNum': '1', 'queryCondition': '[]', 'sortFields': '23_s:asc,16_s:asc', 'ciphertext': str(ciphertext)}\nyield scrapy.FormRequest(url=self.search_url, formdata=form_data, meta={'form_data': form_data})",
"form_data = response.meta.get('form_data')\nres... | <|body_start_0|>
ciphertext = process_cfws()
form_data = {'pageSize': '5', 'pageNum': '1', 'queryCondition': '[]', 'sortFields': '23_s:asc,16_s:asc', 'ciphertext': str(ciphertext)}
yield scrapy.FormRequest(url=self.search_url, formdata=form_data, meta={'form_data': form_data})
<|end_body_0|>
<|... | CfwsSamrSpider | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CfwsSamrSpider:
def start_requests(self):
"""搜索入口"""
<|body_0|>
def parse(self, response):
"""列表解析,翻页请求"""
<|body_1|>
def parse_detail(self, response):
"""解析详情页"""
<|body_2|>
def process_result(self, text: str) -> str:
"""处理特... | stack_v2_sparse_classes_36k_train_018087 | 6,921 | permissive | [
{
"docstring": "搜索入口",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "列表解析,翻页请求",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "解析详情页",
"name": "parse_detail",
"signature": "def parse_detail(self, respon... | 5 | stack_v2_sparse_classes_30k_train_006444 | Implement the Python class `CfwsSamrSpider` described below.
Class description:
Implement the CfwsSamrSpider class.
Method signatures and docstrings:
- def start_requests(self): 搜索入口
- def parse(self, response): 列表解析,翻页请求
- def parse_detail(self, response): 解析详情页
- def process_result(self, text: str) -> str: 处理特殊字符
-... | Implement the Python class `CfwsSamrSpider` described below.
Class description:
Implement the CfwsSamrSpider class.
Method signatures and docstrings:
- def start_requests(self): 搜索入口
- def parse(self, response): 列表解析,翻页请求
- def parse_detail(self, response): 解析详情页
- def process_result(self, text: str) -> str: 处理特殊字符
-... | 5922e39bee47bf4114ab06670f49e32eb1bc4b1d | <|skeleton|>
class CfwsSamrSpider:
def start_requests(self):
"""搜索入口"""
<|body_0|>
def parse(self, response):
"""列表解析,翻页请求"""
<|body_1|>
def parse_detail(self, response):
"""解析详情页"""
<|body_2|>
def process_result(self, text: str) -> str:
"""处理特... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CfwsSamrSpider:
def start_requests(self):
"""搜索入口"""
ciphertext = process_cfws()
form_data = {'pageSize': '5', 'pageNum': '1', 'queryCondition': '[]', 'sortFields': '23_s:asc,16_s:asc', 'ciphertext': str(ciphertext)}
yield scrapy.FormRequest(url=self.search_url, formdata=form_d... | the_stack_v2_python_sparse | credit_china/spiders/cfws_samr.py | pythonyhd/reverse_spider | train | 9 | |
92d56f759b54886237a4dae1977d96e1102af238 | [
"Path(file_name).touch()\nfile = open(file_name, 'w')\nfile.write(connection_params + '\\n')\nfile.close()",
"with open(file_name, 'r') as file:\n lines = file.readlines()\nidx = 0\nisExisting = False\nfor line in lines:\n if str.startswith(line, connection_name + ':'):\n line = connection_params + '... | <|body_start_0|>
Path(file_name).touch()
file = open(file_name, 'w')
file.write(connection_params + '\n')
file.close()
<|end_body_0|>
<|body_start_1|>
with open(file_name, 'r') as file:
lines = file.readlines()
idx = 0
isExisting = False
for l... | Database_connection_file_processor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Database_connection_file_processor:
def create_connection_file(file_name, connection_params):
"""create the default file @param file_name: the connection file full path @param connection_params: the new connection parameters (name:host=xxx,port=xxx,username=xxx,password=xxx)"""
<... | stack_v2_sparse_classes_36k_train_018088 | 3,962 | no_license | [
{
"docstring": "create the default file @param file_name: the connection file full path @param connection_params: the new connection parameters (name:host=xxx,port=xxx,username=xxx,password=xxx)",
"name": "create_connection_file",
"signature": "def create_connection_file(file_name, connection_params)"
... | 5 | null | Implement the Python class `Database_connection_file_processor` described below.
Class description:
Implement the Database_connection_file_processor class.
Method signatures and docstrings:
- def create_connection_file(file_name, connection_params): create the default file @param file_name: the connection file full p... | Implement the Python class `Database_connection_file_processor` described below.
Class description:
Implement the Database_connection_file_processor class.
Method signatures and docstrings:
- def create_connection_file(file_name, connection_params): create the default file @param file_name: the connection file full p... | d567b801ae27720674e0e528d4da0242954d1cf1 | <|skeleton|>
class Database_connection_file_processor:
def create_connection_file(file_name, connection_params):
"""create the default file @param file_name: the connection file full path @param connection_params: the new connection parameters (name:host=xxx,port=xxx,username=xxx,password=xxx)"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Database_connection_file_processor:
def create_connection_file(file_name, connection_params):
"""create the default file @param file_name: the connection file full path @param connection_params: the new connection parameters (name:host=xxx,port=xxx,username=xxx,password=xxx)"""
Path(file_name)... | the_stack_v2_python_sparse | src/main/pydev/com/ftd/generalutilities/metadata/service/fileproc/Database_connection_file_processor.py | RaistlinDai/python | train | 0 | |
437cd39a827415958dabd76a66bca2b5c198a697 | [
"super(Cell, self).__init__()\nself.reduction = reduction\nself.reduction_prev = reduction_prev\nif reduction_prev:\n self.preprocess0 = FactorizedReduce(cpp, c, affine=False)\nelse:\n self.preprocess0 = ConvBlock(cpp, c, 1, 1, 0, affine=False)\nself.preprocess1 = ConvBlock(cp, c, 1, 1, 0, affine=False)\nself... | <|body_start_0|>
super(Cell, self).__init__()
self.reduction = reduction
self.reduction_prev = reduction_prev
if reduction_prev:
self.preprocess0 = FactorizedReduce(cpp, c, affine=False)
else:
self.preprocess0 = ConvBlock(cpp, c, 1, 1, 0, affine=False)
... | Cell | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cell:
def __init__(self, num_nodes, multiplier, cpp, cp, c, reduction, reduction_prev):
""":param steps: 4, number of layers inside a cell :param multiplier: 4 :param cpp: 48 :param cp: 48 :param c: 16 :param reduction: indicates whether to reduce the output maps width :param reduction_p... | stack_v2_sparse_classes_36k_train_018089 | 3,080 | permissive | [
{
"docstring": ":param steps: 4, number of layers inside a cell :param multiplier: 4 :param cpp: 48 :param cp: 48 :param c: 16 :param reduction: indicates whether to reduce the output maps width :param reduction_prev: when previous cell reduced width, s1_d = s0_d//2 in order to keep same shape between s1 and s0... | 2 | stack_v2_sparse_classes_30k_train_018864 | Implement the Python class `Cell` described below.
Class description:
Implement the Cell class.
Method signatures and docstrings:
- def __init__(self, num_nodes, multiplier, cpp, cp, c, reduction, reduction_prev): :param steps: 4, number of layers inside a cell :param multiplier: 4 :param cpp: 48 :param cp: 48 :param... | Implement the Python class `Cell` described below.
Class description:
Implement the Cell class.
Method signatures and docstrings:
- def __init__(self, num_nodes, multiplier, cpp, cp, c, reduction, reduction_prev): :param steps: 4, number of layers inside a cell :param multiplier: 4 :param cpp: 48 :param cp: 48 :param... | f6a3da8818308c9edcd9fedbcf831dd5968efcdd | <|skeleton|>
class Cell:
def __init__(self, num_nodes, multiplier, cpp, cp, c, reduction, reduction_prev):
""":param steps: 4, number of layers inside a cell :param multiplier: 4 :param cpp: 48 :param cp: 48 :param c: 16 :param reduction: indicates whether to reduce the output maps width :param reduction_p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cell:
def __init__(self, num_nodes, multiplier, cpp, cp, c, reduction, reduction_prev):
""":param steps: 4, number of layers inside a cell :param multiplier: 4 :param cpp: 48 :param cp: 48 :param c: 16 :param reduction: indicates whether to reduce the output maps width :param reduction_prev: when prev... | the_stack_v2_python_sparse | common/darts/modules/conv/cell.py | ECP-CANDLE/Benchmarks | train | 65 | |
17de6e296d6854feb463d3e86f3dab73db2a017c | [
"self.Xtrain, self.Ytrain, self.Xtest = (Xtrain, Ytrain, Xtest)\nself.model_config = model_config\nself.booster_offline_list = []\nself.eval_result_list = []\nself.submission_online = None",
"feature_names = list(self.Xtrain.columns)\nfor train_index, valid_index in train_validate_index:\n X_train, X_valid, y_... | <|body_start_0|>
self.Xtrain, self.Ytrain, self.Xtest = (Xtrain, Ytrain, Xtest)
self.model_config = model_config
self.booster_offline_list = []
self.eval_result_list = []
self.submission_online = None
<|end_body_0|>
<|body_start_1|>
feature_names = list(self.Xtrain.colum... | 功能一: 线下验证,每折训练模型和验证结果分别保存在一个列表中 功能二: 线上预测,可决定是否使用oof,重新设置迭代次数 | ModelLightgbm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelLightgbm:
"""功能一: 线下验证,每折训练模型和验证结果分别保存在一个列表中 功能二: 线上预测,可决定是否使用oof,重新设置迭代次数"""
def __init__(self, Xtrain, Ytrain, Xtest, model_config):
""":param Xtrain: pd.DataFrame :param Ytrain: pd.DataFrame :param Xtest: pd.DataFrame :param model_config: dict"""
<|body_0|>
def o... | stack_v2_sparse_classes_36k_train_018090 | 3,853 | no_license | [
{
"docstring": ":param Xtrain: pd.DataFrame :param Ytrain: pd.DataFrame :param Xtest: pd.DataFrame :param model_config: dict",
"name": "__init__",
"signature": "def __init__(self, Xtrain, Ytrain, Xtest, model_config)"
},
{
"docstring": ":param train_validate_index: like list, [train_index, valid... | 3 | stack_v2_sparse_classes_30k_train_020623 | Implement the Python class `ModelLightgbm` described below.
Class description:
功能一: 线下验证,每折训练模型和验证结果分别保存在一个列表中 功能二: 线上预测,可决定是否使用oof,重新设置迭代次数
Method signatures and docstrings:
- def __init__(self, Xtrain, Ytrain, Xtest, model_config): :param Xtrain: pd.DataFrame :param Ytrain: pd.DataFrame :param Xtest: pd.DataFrame :... | Implement the Python class `ModelLightgbm` described below.
Class description:
功能一: 线下验证,每折训练模型和验证结果分别保存在一个列表中 功能二: 线上预测,可决定是否使用oof,重新设置迭代次数
Method signatures and docstrings:
- def __init__(self, Xtrain, Ytrain, Xtest, model_config): :param Xtrain: pd.DataFrame :param Ytrain: pd.DataFrame :param Xtest: pd.DataFrame :... | 8a2fb3cf47688d9c2f54e8adb64f0e4e849cdc4d | <|skeleton|>
class ModelLightgbm:
"""功能一: 线下验证,每折训练模型和验证结果分别保存在一个列表中 功能二: 线上预测,可决定是否使用oof,重新设置迭代次数"""
def __init__(self, Xtrain, Ytrain, Xtest, model_config):
""":param Xtrain: pd.DataFrame :param Ytrain: pd.DataFrame :param Xtest: pd.DataFrame :param model_config: dict"""
<|body_0|>
def o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelLightgbm:
"""功能一: 线下验证,每折训练模型和验证结果分别保存在一个列表中 功能二: 线上预测,可决定是否使用oof,重新设置迭代次数"""
def __init__(self, Xtrain, Ytrain, Xtest, model_config):
""":param Xtrain: pd.DataFrame :param Ytrain: pd.DataFrame :param Xtest: pd.DataFrame :param model_config: dict"""
self.Xtrain, self.Ytrain, self.Xte... | the_stack_v2_python_sparse | Code/Model/ModelLightgbm.py | datamininger/cardiovascularriskprediction | train | 0 |
610da2ac0e123fbfe8323133618a2b6b679703e8 | [
"build = Build.query.get(build_id)\nif build is None:\n return self.respond({}, status_code=404)\ntags = build.tags if build.tags else []\nreturn self.respond({'tags': tags})",
"args = self.post_parser.parse_args()\nif args.tags and (not all((len(tag) <= 16 for tag in args.tags))):\n return error('Tags must... | <|body_start_0|>
build = Build.query.get(build_id)
if build is None:
return self.respond({}, status_code=404)
tags = build.tags if build.tags else []
return self.respond({'tags': tags})
<|end_body_0|>
<|body_start_1|>
args = self.post_parser.parse_args()
if a... | BuildTagAPIView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildTagAPIView:
def get(self, build_id):
"""Retrieve all tags associated with a build."""
<|body_0|>
def post(self, build_id):
"""Set tags associated with a build."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
build = Build.query.get(build_id)
... | stack_v2_sparse_classes_36k_train_018091 | 1,270 | permissive | [
{
"docstring": "Retrieve all tags associated with a build.",
"name": "get",
"signature": "def get(self, build_id)"
},
{
"docstring": "Set tags associated with a build.",
"name": "post",
"signature": "def post(self, build_id)"
}
] | 2 | null | Implement the Python class `BuildTagAPIView` described below.
Class description:
Implement the BuildTagAPIView class.
Method signatures and docstrings:
- def get(self, build_id): Retrieve all tags associated with a build.
- def post(self, build_id): Set tags associated with a build. | Implement the Python class `BuildTagAPIView` described below.
Class description:
Implement the BuildTagAPIView class.
Method signatures and docstrings:
- def get(self, build_id): Retrieve all tags associated with a build.
- def post(self, build_id): Set tags associated with a build.
<|skeleton|>
class BuildTagAPIVie... | ae5159498f239a48184accf811cf36be2eab1e96 | <|skeleton|>
class BuildTagAPIView:
def get(self, build_id):
"""Retrieve all tags associated with a build."""
<|body_0|>
def post(self, build_id):
"""Set tags associated with a build."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuildTagAPIView:
def get(self, build_id):
"""Retrieve all tags associated with a build."""
build = Build.query.get(build_id)
if build is None:
return self.respond({}, status_code=404)
tags = build.tags if build.tags else []
return self.respond({'tags': tags}... | the_stack_v2_python_sparse | changes/api/build_tag.py | getsentry/changes | train | 6 | |
f6276073b6b60a7e1cbd0a64163932be07232dc2 | [
"def mps(root):\n if not root:\n return (-float('inf'), -float('inf'))\n ll, l = mps(root.left)\n rr, r = mps(root.right)\n connected = root.val + max(0, l, r)\n unconnected = max(ll, rr, l, r, l + r + root.val)\n return (unconnected, connected)\nreturn max(mps(root))",
"m = -float('inf')... | <|body_start_0|>
def mps(root):
if not root:
return (-float('inf'), -float('inf'))
ll, l = mps(root.left)
rr, r = mps(root.right)
connected = root.val + max(0, l, r)
unconnected = max(ll, rr, l, r, l + r + root.val)
return (... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxPathSum(self, root):
"""Aug 16, 2018 06:35"""
<|body_0|>
def maxPathSum(self, root: Optional[TreeNode]) -> int:
"""Feb 19, 2023 15:03"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def mps(root):
if not root:
... | stack_v2_sparse_classes_36k_train_018092 | 2,524 | no_license | [
{
"docstring": "Aug 16, 2018 06:35",
"name": "maxPathSum",
"signature": "def maxPathSum(self, root)"
},
{
"docstring": "Feb 19, 2023 15:03",
"name": "maxPathSum",
"signature": "def maxPathSum(self, root: Optional[TreeNode]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_016547 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxPathSum(self, root): Aug 16, 2018 06:35
- def maxPathSum(self, root: Optional[TreeNode]) -> int: Feb 19, 2023 15:03 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxPathSum(self, root): Aug 16, 2018 06:35
- def maxPathSum(self, root: Optional[TreeNode]) -> int: Feb 19, 2023 15:03
<|skeleton|>
class Solution:
def maxPathSum(self,... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def maxPathSum(self, root):
"""Aug 16, 2018 06:35"""
<|body_0|>
def maxPathSum(self, root: Optional[TreeNode]) -> int:
"""Feb 19, 2023 15:03"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxPathSum(self, root):
"""Aug 16, 2018 06:35"""
def mps(root):
if not root:
return (-float('inf'), -float('inf'))
ll, l = mps(root.left)
rr, r = mps(root.right)
connected = root.val + max(0, l, r)
unconn... | the_stack_v2_python_sparse | leetcode/solved/124_Binary_Tree_Maximum_Path_Sum/solution.py | sungminoh/algorithms | train | 0 | |
5cbab5ca770c8631b498657df7fe93be80e8b008 | [
"if len(nums) < 1:\n return []\nret = []\ndh = DualHeap()\nfor i in xrange(k):\n dh.add(nums[i])\nret.append(dh.median())\nfor i in xrange(k, len(nums)):\n dh.remove(nums[i - k])\n dh.add(nums[i])\n ret.append(dh.median())\nreturn ret",
"if len(nums) < 1:\n return []\npq = PriorityQueue()\nfor i... | <|body_start_0|>
if len(nums) < 1:
return []
ret = []
dh = DualHeap()
for i in xrange(k):
dh.add(nums[i])
ret.append(dh.median())
for i in xrange(k, len(nums)):
dh.remove(nums[i - k])
dh.add(nums[i])
ret.append(d... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def medianSlidingWindow(self, nums, k):
"""Use heap"""
<|body_0|>
def medianSlidingWindow_TLE(self, nums, k):
"""Use priority queue :param nums: A list of integers. :param k: size of window :return: The median of element inside the window at each moving."""... | stack_v2_sparse_classes_36k_train_018093 | 4,918 | permissive | [
{
"docstring": "Use heap",
"name": "medianSlidingWindow",
"signature": "def medianSlidingWindow(self, nums, k)"
},
{
"docstring": "Use priority queue :param nums: A list of integers. :param k: size of window :return: The median of element inside the window at each moving.",
"name": "medianSl... | 2 | stack_v2_sparse_classes_30k_train_010895 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def medianSlidingWindow(self, nums, k): Use heap
- def medianSlidingWindow_TLE(self, nums, k): Use priority queue :param nums: A list of integers. :param k: size of window :retur... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def medianSlidingWindow(self, nums, k): Use heap
- def medianSlidingWindow_TLE(self, nums, k): Use priority queue :param nums: A list of integers. :param k: size of window :retur... | 4629a3857b2c57418b86a3b3a7180ecb15e763e3 | <|skeleton|>
class Solution:
def medianSlidingWindow(self, nums, k):
"""Use heap"""
<|body_0|>
def medianSlidingWindow_TLE(self, nums, k):
"""Use priority queue :param nums: A list of integers. :param k: size of window :return: The median of element inside the window at each moving."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def medianSlidingWindow(self, nums, k):
"""Use heap"""
if len(nums) < 1:
return []
ret = []
dh = DualHeap()
for i in xrange(k):
dh.add(nums[i])
ret.append(dh.median())
for i in xrange(k, len(nums)):
dh.remove... | the_stack_v2_python_sparse | archive/Sliding Window Median TLE.py | RijuDasgupta9116/LintCode | train | 0 | |
0852477e5c0e6540406da6c6c0d822dd669e8550 | [
"self.fields = fields\nself.object_type = object_type\nself.record_count = record_count",
"if dictionary is None:\n return None\nfields = None\nif dictionary.get('fields') != None:\n fields = list()\n for structure in dictionary.get('fields'):\n fields.append(cohesity_management_sdk.models.sfdc_ob... | <|body_start_0|>
self.fields = fields
self.object_type = object_type
self.record_count = record_count
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
fields = None
if dictionary.get('fields') != None:
fields = list()
... | Implementation of the 'SfdcObject' model. Specifies an Object containing information about a Salseforce object. Attributes: fields (list of SfdcObjectFields): Type of this object object_type (ObjectTypeEnum): Type of this object Specifies the type of an Universal Data Adapter source entity. 'kStandard' indicates a Univ... | SfdcObject | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SfdcObject:
"""Implementation of the 'SfdcObject' model. Specifies an Object containing information about a Salseforce object. Attributes: fields (list of SfdcObjectFields): Type of this object object_type (ObjectTypeEnum): Type of this object Specifies the type of an Universal Data Adapter sourc... | stack_v2_sparse_classes_36k_train_018094 | 2,391 | permissive | [
{
"docstring": "Constructor for the SfdcObject class",
"name": "__init__",
"signature": "def __init__(self, fields=None, object_type=None, record_count=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the ... | 2 | stack_v2_sparse_classes_30k_train_004843 | Implement the Python class `SfdcObject` described below.
Class description:
Implementation of the 'SfdcObject' model. Specifies an Object containing information about a Salseforce object. Attributes: fields (list of SfdcObjectFields): Type of this object object_type (ObjectTypeEnum): Type of this object Specifies the ... | Implement the Python class `SfdcObject` described below.
Class description:
Implementation of the 'SfdcObject' model. Specifies an Object containing information about a Salseforce object. Attributes: fields (list of SfdcObjectFields): Type of this object object_type (ObjectTypeEnum): Type of this object Specifies the ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SfdcObject:
"""Implementation of the 'SfdcObject' model. Specifies an Object containing information about a Salseforce object. Attributes: fields (list of SfdcObjectFields): Type of this object object_type (ObjectTypeEnum): Type of this object Specifies the type of an Universal Data Adapter sourc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SfdcObject:
"""Implementation of the 'SfdcObject' model. Specifies an Object containing information about a Salseforce object. Attributes: fields (list of SfdcObjectFields): Type of this object object_type (ObjectTypeEnum): Type of this object Specifies the type of an Universal Data Adapter source entity. 'kS... | the_stack_v2_python_sparse | cohesity_management_sdk/models/sfdc_object.py | cohesity/management-sdk-python | train | 24 |
c69b2f50d31fd20524b885f9f6d70fe81b1c234a | [
"idx = -1\nfor i in range(len(nums) - 2, -1, -1):\n if nums[i] < nums[i + 1]:\n idx = i\n break\nif idx == -1:\n nums.sort()\n return\nbest = idx + 1\nfor i in range(idx + 1, len(nums)):\n if nums[idx] < nums[i] <= nums[best]:\n best = i\nnums[idx], nums[best] = (nums[best], nums[id... | <|body_start_0|>
idx = -1
for i in range(len(nums) - 2, -1, -1):
if nums[i] < nums[i + 1]:
idx = i
break
if idx == -1:
nums.sort()
return
best = idx + 1
for i in range(idx + 1, len(nums)):
if nums[idx... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def nextPermutation2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_018095 | 3,953 | permissive | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "nextPermutation",
"signature": "def nextPermutation(self, nums: List[int]) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "nextPermutation2",
"signature": "def ne... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextPermutation(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def nextPermutation2(self, nums: List[int]) -> None: Do not return any... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextPermutation(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def nextPermutation2(self, nums: List[int]) -> None: Do not return any... | c32b786e52dd25ff6e4f84242cec5ff1c5a869df | <|skeleton|>
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def nextPermutation2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
idx = -1
for i in range(len(nums) - 2, -1, -1):
if nums[i] < nums[i + 1]:
idx = i
break
if idx == -1:
... | the_stack_v2_python_sparse | python/next-permutation.py | alirezaghey/leetcode-solutions | train | 3 | |
f238de8468e2bc5cc002eccfdc03383d5fac6138 | [
"dt1 = datetime.timedelta(days=0, minutes=0, seconds=0)\ndt2 = datetime.timedelta(days=0, minutes=0, seconds=0)\ndt3 = datetime.timedelta(days=0, minutes=1, seconds=15)\ndt4 = datetime.timedelta(days=10, minutes=1, seconds=15, microseconds=300)\nfake_dt5 = None\nfake_dt6 = 'fake'\nfake_dt7 = 18.52\nself.assertEqual... | <|body_start_0|>
dt1 = datetime.timedelta(days=0, minutes=0, seconds=0)
dt2 = datetime.timedelta(days=0, minutes=0, seconds=0)
dt3 = datetime.timedelta(days=0, minutes=1, seconds=15)
dt4 = datetime.timedelta(days=10, minutes=1, seconds=15, microseconds=300)
fake_dt5 = None
... | Contains unit tests for the check module. | TestChecks | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestChecks:
"""Contains unit tests for the check module."""
def test_sum_time_delta(self):
"""Test the sum_time_delta() function"""
<|body_0|>
def test_get_i_from_job_name(self):
"""Test the get_i_from_job_name() function"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_018096 | 2,038 | permissive | [
{
"docstring": "Test the sum_time_delta() function",
"name": "test_sum_time_delta",
"signature": "def test_sum_time_delta(self)"
},
{
"docstring": "Test the get_i_from_job_name() function",
"name": "test_get_i_from_job_name",
"signature": "def test_get_i_from_job_name(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020891 | Implement the Python class `TestChecks` described below.
Class description:
Contains unit tests for the check module.
Method signatures and docstrings:
- def test_sum_time_delta(self): Test the sum_time_delta() function
- def test_get_i_from_job_name(self): Test the get_i_from_job_name() function | Implement the Python class `TestChecks` described below.
Class description:
Contains unit tests for the check module.
Method signatures and docstrings:
- def test_sum_time_delta(self): Test the sum_time_delta() function
- def test_get_i_from_job_name(self): Test the get_i_from_job_name() function
<|skeleton|>
class ... | 617b2c5430e409271e241eda0de3dd673ec41835 | <|skeleton|>
class TestChecks:
"""Contains unit tests for the check module."""
def test_sum_time_delta(self):
"""Test the sum_time_delta() function"""
<|body_0|>
def test_get_i_from_job_name(self):
"""Test the get_i_from_job_name() function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestChecks:
"""Contains unit tests for the check module."""
def test_sum_time_delta(self):
"""Test the sum_time_delta() function"""
dt1 = datetime.timedelta(days=0, minutes=0, seconds=0)
dt2 = datetime.timedelta(days=0, minutes=0, seconds=0)
dt3 = datetime.timedelta(days=0... | the_stack_v2_python_sparse | arc/checks/common_test.py | ReactionMechanismGenerator/ARC | train | 40 |
0b88e122f802246c646bd1bb554c62aaddcaf5cd | [
"self._device = device\nself._learn_rate = learn_rate\nself._net = net\nself._log_loss = log_loss\nself._batch_size = batch_size\nself._max_epochs = max_epochs\nself._optimizer = torch.optim.SGD(self._net.parameters(), lr=self._learn_rate)\nself._loss_func = torch.nn.CrossEntropyLoss()\nself._stopping_criterion = L... | <|body_start_0|>
self._device = device
self._learn_rate = learn_rate
self._net = net
self._log_loss = log_loss
self._batch_size = batch_size
self._max_epochs = max_epochs
self._optimizer = torch.optim.SGD(self._net.parameters(), lr=self._learn_rate)
self._... | A thing which trains a simple classifier until convergence. The accuracy of the classifier can be then used as an a measure of usefulness of the input data format (representation). | ClassifierTrainer | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassifierTrainer:
"""A thing which trains a simple classifier until convergence. The accuracy of the classifier can be then used as an a measure of usefulness of the input data format (representation)."""
def __init__(self, net: torch.nn.Module, device: str, learn_rate: float=0.01, max_loss... | stack_v2_sparse_classes_36k_train_018097 | 14,027 | permissive | [
{
"docstring": "This can train the network (until reasonable convergence) and compute accuracy (on the training set). Args: net: simple classifier with or without hidden layer, output is softmax device: cpu/gpu learn_rate: speed of learning through SGD max_loss_difference: if the max difference in the loss valu... | 3 | null | Implement the Python class `ClassifierTrainer` described below.
Class description:
A thing which trains a simple classifier until convergence. The accuracy of the classifier can be then used as an a measure of usefulness of the input data format (representation).
Method signatures and docstrings:
- def __init__(self,... | Implement the Python class `ClassifierTrainer` described below.
Class description:
A thing which trains a simple classifier until convergence. The accuracy of the classifier can be then used as an a measure of usefulness of the input data format (representation).
Method signatures and docstrings:
- def __init__(self,... | 81d72b82ec96948c26d292d709f18c9c77a17ba4 | <|skeleton|>
class ClassifierTrainer:
"""A thing which trains a simple classifier until convergence. The accuracy of the classifier can be then used as an a measure of usefulness of the input data format (representation)."""
def __init__(self, net: torch.nn.Module, device: str, learn_rate: float=0.01, max_loss... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassifierTrainer:
"""A thing which trains a simple classifier until convergence. The accuracy of the classifier can be then used as an a measure of usefulness of the input data format (representation)."""
def __init__(self, net: torch.nn.Module, device: str, learn_rate: float=0.01, max_loss_difference: ... | the_stack_v2_python_sparse | torchsim/core/eval/metrics/simple_classifier_nn.py | andreofner/torchsim | train | 0 |
bc1c98d3c79c8ef00f632237abf90120927a5443 | [
"n = len(s)\nadjMap = defaultdict(set)\nfor start in range(n):\n left, right = (start, start)\n while left >= 0 and right < n and (s[left] == s[right]):\n adjMap[left].add(right + 1)\n left -= 1\n right += 1\n left, right = (start, start + 1)\n while left >= 0 and right < n and (s[l... | <|body_start_0|>
n = len(s)
adjMap = defaultdict(set)
for start in range(n):
left, right = (start, start)
while left >= 0 and right < n and (s[left] == s[right]):
adjMap[left].add(right + 1)
left -= 1
right += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCut(self, s: str) -> int:
""":给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 返回符合要求的 最少分割次数 。"""
<|body_0|>
def minCut2(self, s: str) -> int:
""":给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 返回符合要求的 最少分割次数 。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_018098 | 2,494 | no_license | [
{
"docstring": ":给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 返回符合要求的 最少分割次数 。",
"name": "minCut",
"signature": "def minCut(self, s: str) -> int"
},
{
"docstring": ":给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 返回符合要求的 最少分割次数 。",
"name": "minCut2",
"signature": "def minCut2(self, s: str) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_015820 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCut(self, s: str) -> int: :给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 返回符合要求的 最少分割次数 。
- def minCut2(self, s: str) -> int: :给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 返回符合要求的 最少分割次数 。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCut(self, s: str) -> int: :给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 返回符合要求的 最少分割次数 。
- def minCut2(self, s: str) -> int: :给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 返回符合要求的 最少分割次数 。
<|... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def minCut(self, s: str) -> int:
""":给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 返回符合要求的 最少分割次数 。"""
<|body_0|>
def minCut2(self, s: str) -> int:
""":给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 返回符合要求的 最少分割次数 。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minCut(self, s: str) -> int:
""":给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 返回符合要求的 最少分割次数 。"""
n = len(s)
adjMap = defaultdict(set)
for start in range(n):
left, right = (start, start)
while left >= 0 and right < n and (s[left] == s[right]):
... | the_stack_v2_python_sparse | 11_动态规划/dp分类/区间dp/dfs/回文/分割回文串/132_分割回文串-最短路建图.py | 981377660LMT/algorithm-study | train | 225 | |
dfcccd914e906ae3195a9207a8ce633b00c22c44 | [
"super(Similarity_matrix, self).__init__(**kwargs)\nself._num_speakers = num_speakers\nself._num_utterance = num_utterance\nself._is_exclusive = is_exclusive",
"self.weight = self.add_weight('weight', shape=[1], dtype=tf.float32, initializer=tf.compat.v1.constant_initializer(value=[10], dtype=tf.float32), trainab... | <|body_start_0|>
super(Similarity_matrix, self).__init__(**kwargs)
self._num_speakers = num_speakers
self._num_utterance = num_utterance
self._is_exclusive = is_exclusive
<|end_body_0|>
<|body_start_1|>
self.weight = self.add_weight('weight', shape=[1], dtype=tf.float32, initial... | Note: Calculate the similarites of utterances & centroids Attributes: __init__: set up the configurations of similarity matrix build: add up the variables of similarity matrix call: calculate the similarities in two ways; exclusive, inclusive | Similarity_matrix | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Similarity_matrix:
"""Note: Calculate the similarites of utterances & centroids Attributes: __init__: set up the configurations of similarity matrix build: add up the variables of similarity matrix call: calculate the similarities in two ways; exclusive, inclusive"""
def __init__(self, num_s... | stack_v2_sparse_classes_36k_train_018099 | 2,948 | permissive | [
{
"docstring": "Note: set up the configurations of similarity matrix; Args: num_speakers: the number of speakers in a batch num_utterance: the number of utterances per speaker in a batch is_exclusive: whether the self-embedding is included or not, when calculating the centroids Returns:",
"name": "__init__"... | 3 | stack_v2_sparse_classes_30k_val_000196 | Implement the Python class `Similarity_matrix` described below.
Class description:
Note: Calculate the similarites of utterances & centroids Attributes: __init__: set up the configurations of similarity matrix build: add up the variables of similarity matrix call: calculate the similarities in two ways; exclusive, inc... | Implement the Python class `Similarity_matrix` described below.
Class description:
Note: Calculate the similarites of utterances & centroids Attributes: __init__: set up the configurations of similarity matrix build: add up the variables of similarity matrix call: calculate the similarities in two ways; exclusive, inc... | a4a53ac0c209a283cab4969d61305f056a99b6c3 | <|skeleton|>
class Similarity_matrix:
"""Note: Calculate the similarites of utterances & centroids Attributes: __init__: set up the configurations of similarity matrix build: add up the variables of similarity matrix call: calculate the similarities in two ways; exclusive, inclusive"""
def __init__(self, num_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Similarity_matrix:
"""Note: Calculate the similarites of utterances & centroids Attributes: __init__: set up the configurations of similarity matrix build: add up the variables of similarity matrix call: calculate the similarities in two ways; exclusive, inclusive"""
def __init__(self, num_speakers, num_... | the_stack_v2_python_sparse | Speaker_Verification/src/layers/similarity.py | TaeYoon2/KerasSpeakerEmbedding | train | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.