blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
7.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
378
8.64k
id
stringlengths
44
44
length_bytes
int64
505
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.88k
prompted_full_text
stringlengths
565
12.5k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
5.05k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
snapshot_total_rows
int64
75.8k
75.8k
solution
stringlengths
242
8.3k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
1ea4af1694f47282d97b6ecb88bd57e07d6fafdf
[ "if len(token) != 59:\n raise InvalidTokenError('Discord Token must have exactly 59 characters.')\nself.__token = token\nself.__keep_alive = True\nself.__socket: Optional[WebSocketClientProtocol] = None\n\nasync def identify_and_handle_hello(socket: WebSocketClientProtocol, payload: GatewayDispatch):\n \"\"\"...
<|body_start_0|> if len(token) != 59: raise InvalidTokenError('Discord Token must have exactly 59 characters.') self.__token = token self.__keep_alive = True self.__socket: Optional[WebSocketClientProtocol] = None async def identify_and_handle_hello(socket: WebSocket...
The Dispatcher handles all interactions with discord websocket API. This also contains the main event loop, and handles the heartbeat. Running the dispatcher will create a connection with the Discord WebSocket API on behalf of the provided token. This token must be a bot token. (Which can be found on `<https://discord....
Dispatcher
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dispatcher: """The Dispatcher handles all interactions with discord websocket API. This also contains the main event loop, and handles the heartbeat. Running the dispatcher will create a connection with the Discord WebSocket API on behalf of the provided token. This token must be a bot token. (Wh...
stack_v2_sparse_classes_75kplus_train_005800
9,329
permissive
[ { "docstring": ":param token: Bot token for discord's API. :raises InvalidTokenError: Discord Token length is not 59 characters.", "name": "__init__", "signature": "def __init__(self, token: str, *, handlers: Dict[int, Handler]) -> None" }, { "docstring": "This manages all handles for given OP c...
5
stack_v2_sparse_classes_30k_train_008999
Implement the Python class `Dispatcher` described below. Class description: The Dispatcher handles all interactions with discord websocket API. This also contains the main event loop, and handles the heartbeat. Running the dispatcher will create a connection with the Discord WebSocket API on behalf of the provided tok...
Implement the Python class `Dispatcher` described below. Class description: The Dispatcher handles all interactions with discord websocket API. This also contains the main event loop, and handles the heartbeat. Running the dispatcher will create a connection with the Discord WebSocket API on behalf of the provided tok...
d130d8e92eba259fa662a77e3b23549c5d0ef0ff
<|skeleton|> class Dispatcher: """The Dispatcher handles all interactions with discord websocket API. This also contains the main event loop, and handles the heartbeat. Running the dispatcher will create a connection with the Discord WebSocket API on behalf of the provided token. This token must be a bot token. (Wh...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Dispatcher: """The Dispatcher handles all interactions with discord websocket API. This also contains the main event loop, and handles the heartbeat. Running the dispatcher will create a connection with the Discord WebSocket API on behalf of the provided token. This token must be a bot token. (Which can be fo...
the_stack_v2_python_sparse
pincer/core/gateway.py
WhyDoWeLiveWithoutMeaning/Pincer
train
0
bb4ff44961b1f4f7f8c0acd86a4c99f12f4b84c9
[ "if isinstance(exc, NotImplementedError):\n return self._make_error_response(400, str(exc))\nif isinstance(exc, ItemNotFoundError):\n return self._make_error_response(400, str(exc))\nreturn super().handle_exception(exc)", "course_key = CourseKey.from_string(course_id)\nif not has_studio_write_access(request...
<|body_start_0|> if isinstance(exc, NotImplementedError): return self._make_error_response(400, str(exc)) if isinstance(exc, ItemNotFoundError): return self._make_error_response(400, str(exc)) return super().handle_exception(exc) <|end_body_0|> <|body_start_1|> c...
API view for course tabs settings.
CourseTabSettingsView
[ "AGPL-3.0-only", "AGPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CourseTabSettingsView: """API view for course tabs settings.""" def handle_exception(self, exc): """Handle NotImplementedError and return a proper response for it.""" <|body_0|> def post(self, request: Request, course_id: str) -> Response: """Change visibility of...
stack_v2_sparse_classes_75kplus_train_005801
8,341
permissive
[ { "docstring": "Handle NotImplementedError and return a proper response for it.", "name": "handle_exception", "signature": "def handle_exception(self, exc)" }, { "docstring": "Change visibility of tabs in a course. **Example Requests** You can provide either a tab_id or a tab_location. Hide a co...
2
stack_v2_sparse_classes_30k_train_023197
Implement the Python class `CourseTabSettingsView` described below. Class description: API view for course tabs settings. Method signatures and docstrings: - def handle_exception(self, exc): Handle NotImplementedError and return a proper response for it. - def post(self, request: Request, course_id: str) -> Response:...
Implement the Python class `CourseTabSettingsView` described below. Class description: API view for course tabs settings. Method signatures and docstrings: - def handle_exception(self, exc): Handle NotImplementedError and return a proper response for it. - def post(self, request: Request, course_id: str) -> Response:...
5809eaca7079a15ee56b0b7fcfea425337046c97
<|skeleton|> class CourseTabSettingsView: """API view for course tabs settings.""" def handle_exception(self, exc): """Handle NotImplementedError and return a proper response for it.""" <|body_0|> def post(self, request: Request, course_id: str) -> Response: """Change visibility of...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CourseTabSettingsView: """API view for course tabs settings.""" def handle_exception(self, exc): """Handle NotImplementedError and return a proper response for it.""" if isinstance(exc, NotImplementedError): return self._make_error_response(400, str(exc)) if isinstance...
the_stack_v2_python_sparse
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/cms/djangoapps/contentstore/rest_api/v0/views/tabs.py
luque/better-ways-of-thinking-about-software
train
3
06a9076f56e9c141773fd7deea07ea4144544863
[ "super().__init__(number, name, activation=activation, reg=reg, verbose=verbose)\nmu = 0\nstd = 1\nself.wts = np.random.normal(mu, std, (n_units_prev_layer, units)) * wt_scale\nself.b = np.random.normal(mu, std, (units,)) * wt_scale", "input = np.reshape(self.input, [self.input.shape[0], np.prod(self.input.shape[...
<|body_start_0|> super().__init__(number, name, activation=activation, reg=reg, verbose=verbose) mu = 0 std = 1 self.wts = np.random.normal(mu, std, (n_units_prev_layer, units)) * wt_scale self.b = np.random.normal(mu, std, (units,)) * wt_scale <|end_body_0|> <|body_start_1|> ...
Dense (fully-connected) layer. Each units recieves (weighted) input from all units in the previous layer. These are the layers used in a multilayer perceptron. NOTE: Units are spatially arranged in 1D only - no 2D like Conv2D.
Dense
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dense: """Dense (fully-connected) layer. Each units recieves (weighted) input from all units in the previous layer. These are the layers used in a multilayer perceptron. NOTE: Units are spatially arranged in 1D only - no 2D like Conv2D.""" def __init__(self, number, name, units, n_units_prev...
stack_v2_sparse_classes_75kplus_train_005802
28,030
no_license
[ { "docstring": "Parameters: ----------- number: int. Current layer number in the net. 0, ..., L-1, where L is the total number of layers. name: string. Human-readable string for identification/debugging. e.g. 'Conv2' units: int. Number of hidden units in the layer. n_units_prev_layer: int. Total number of units...
3
stack_v2_sparse_classes_30k_train_044368
Implement the Python class `Dense` described below. Class description: Dense (fully-connected) layer. Each units recieves (weighted) input from all units in the previous layer. These are the layers used in a multilayer perceptron. NOTE: Units are spatially arranged in 1D only - no 2D like Conv2D. Method signatures an...
Implement the Python class `Dense` described below. Class description: Dense (fully-connected) layer. Each units recieves (weighted) input from all units in the previous layer. These are the layers used in a multilayer perceptron. NOTE: Units are spatially arranged in 1D only - no 2D like Conv2D. Method signatures an...
924c5db8b7b7a70fae87d0fc30b28b6ce9cfa529
<|skeleton|> class Dense: """Dense (fully-connected) layer. Each units recieves (weighted) input from all units in the previous layer. These are the layers used in a multilayer perceptron. NOTE: Units are spatially arranged in 1D only - no 2D like Conv2D.""" def __init__(self, number, name, units, n_units_prev...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Dense: """Dense (fully-connected) layer. Each units recieves (weighted) input from all units in the previous layer. These are the layers used in a multilayer perceptron. NOTE: Units are spatially arranged in 1D only - no 2D like Conv2D.""" def __init__(self, number, name, units, n_units_prev_layer, wt_sc...
the_stack_v2_python_sparse
CNN and Optimizer/layer.py
luhangsnn/neuralnetworks
train
0
f2236117e4e9c1f865190bc568386c39a03b83b4
[ "if not root:\n return ''\nstack = [root]\nans = []\nwhile stack:\n node = stack.pop()\n ans.append(str(node.val))\n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\nreturn ','.join(ans)", "if not data:\n return None\ndata = data.split(',')\nroot...
<|body_start_0|> if not root: return '' stack = [root] ans = [] while stack: node = stack.pop() ans.append(str(node.val)) if node.right: stack.append(node.right) if node.left: stack.append(node.le...
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_75kplus_train_005803
1,684
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_039385
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:...
5e09a5d36ac55d782628a888ad57d48e234b61ac
<|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_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return '' stack = [root] ans = [] while stack: node = stack.pop() ans.append(str(node.val)) if node.r...
the_stack_v2_python_sparse
449/449.py
sjzyjc/leetcode
train
0
4ab08eb130502f424c6fe02c1518230a553f56e9
[ "self.numberClasses = numberClasses\nbatchSize = BATCH_SIZE\nprint('args!!!')\nprint(args)\nif args != []:\n batchSize = args.batch_size\n'\\n Data augmentation\\n transforms.RandomRotation(30),\\n transforms.RandomResizedCrop(224),\\n transforms.RandomHorizontalFlip()\\n INPUT...
<|body_start_0|> self.numberClasses = numberClasses batchSize = BATCH_SIZE print('args!!!') print(args) if args != []: batchSize = args.batch_size '\n Data augmentation\n transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\...
ModelManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModelManager: def loadData(self, numberClasses, args=[], kwargs=[]): """Creates the dataset loaders :param args, console argument names :param kwargs, data arguments :return training and test dataset loaders""" <|body_0|> def createModel(self, args, device): """Creat...
stack_v2_sparse_classes_75kplus_train_005804
7,833
no_license
[ { "docstring": "Creates the dataset loaders :param args, console argument names :param kwargs, data arguments :return training and test dataset loaders", "name": "loadData", "signature": "def loadData(self, numberClasses, args=[], kwargs=[])" }, { "docstring": "Creates the model, its optimizer w...
4
stack_v2_sparse_classes_30k_train_014706
Implement the Python class `ModelManager` described below. Class description: Implement the ModelManager class. Method signatures and docstrings: - def loadData(self, numberClasses, args=[], kwargs=[]): Creates the dataset loaders :param args, console argument names :param kwargs, data arguments :return training and ...
Implement the Python class `ModelManager` described below. Class description: Implement the ModelManager class. Method signatures and docstrings: - def loadData(self, numberClasses, args=[], kwargs=[]): Creates the dataset loaders :param args, console argument names :param kwargs, data arguments :return training and ...
2b9baa62c370feac0808212efe6b22295ae31044
<|skeleton|> class ModelManager: def loadData(self, numberClasses, args=[], kwargs=[]): """Creates the dataset loaders :param args, console argument names :param kwargs, data arguments :return training and test dataset loaders""" <|body_0|> def createModel(self, args, device): """Creat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ModelManager: def loadData(self, numberClasses, args=[], kwargs=[]): """Creates the dataset loaders :param args, console argument names :param kwargs, data arguments :return training and test dataset loaders""" self.numberClasses = numberClasses batchSize = BATCH_SIZE print('ar...
the_stack_v2_python_sparse
Src_unsharp_preprocessing/ModelManagerTemp.py
saul1917/PhD
train
1
1755ba81b0f11d4d4130ceff0b6418d46da612a9
[ "import da.lwc.file\nfilepath_design_document = '/package/module.py'\nfilepath_test = '/package/spec/spec_module.py'\nassert da.lwc.file.specification_filepath_for(filepath_design_document) == filepath_test", "import da.lwc.file\nfilepath_design_document = '/package/__init__.py'\nfilepath_test = '/package/spec/sp...
<|body_start_0|> import da.lwc.file filepath_design_document = '/package/module.py' filepath_test = '/package/spec/spec_module.py' assert da.lwc.file.specification_filepath_for(filepath_design_document) == filepath_test <|end_body_0|> <|body_start_1|> import da.lwc.file ...
Specify the specification_filepath_for() function.
SpecifySpecificationFilepathFor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpecifySpecificationFilepathFor: """Specify the specification_filepath_for() function.""" def it_returns_a_test_path_when_given_python_module_path(self): """When given a module path, the corresponding spec path is returned. When given a valid module path, the get_specification_filepa...
stack_v2_sparse_classes_75kplus_train_005805
16,001
permissive
[ { "docstring": "When given a module path, the corresponding spec path is returned. When given a valid module path, the get_specification_filepath_for() function shall return the specification path that corresponds to the path provided.", "name": "it_returns_a_test_path_when_given_python_module_path", "s...
3
null
Implement the Python class `SpecifySpecificationFilepathFor` described below. Class description: Specify the specification_filepath_for() function. Method signatures and docstrings: - def it_returns_a_test_path_when_given_python_module_path(self): When given a module path, the corresponding spec path is returned. Whe...
Implement the Python class `SpecifySpecificationFilepathFor` described below. Class description: Specify the specification_filepath_for() function. Method signatures and docstrings: - def it_returns_a_test_path_when_given_python_module_path(self): When given a module path, the corresponding spec path is returned. Whe...
04a13be2792323e3f9fdb83fd236a8e9cfe6aa2d
<|skeleton|> class SpecifySpecificationFilepathFor: """Specify the specification_filepath_for() function.""" def it_returns_a_test_path_when_given_python_module_path(self): """When given a module path, the corresponding spec path is returned. When given a valid module path, the get_specification_filepa...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SpecifySpecificationFilepathFor: """Specify the specification_filepath_for() function.""" def it_returns_a_test_path_when_given_python_module_path(self): """When given a module path, the corresponding spec path is returned. When given a valid module path, the get_specification_filepath_for() func...
the_stack_v2_python_sparse
a3_src/h70_internal/da/lwc/spec/spec_file.py
wtpayne/hiai
train
5
d467144b4b77c2d0c68fea639717ee5482a85bdb
[ "self.container = container\nself.search_manager = self.container.search.manager\nself.search_parser = self.container.search_parser\nself.link_manager = self.container.link_manager\nself.resource_id = self.container.resource_identity\nself.schema_validator = self.container.schema_validator", "search_path = '{0}={...
<|body_start_0|> self.container = container self.search_manager = self.container.search.manager self.search_parser = self.container.search_parser self.link_manager = self.container.link_manager self.resource_id = self.container.resource_identity self.schema_validator = se...
This class is the link between the request/view and the search layer.
SearchPortal
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SearchPortal: """This class is the link between the request/view and the search layer.""" def __init__(self, container): """Args: container(shelf.container.Container)""" <|body_0|> def search(self, criteria): """Searches based on criteria defined in request and a...
stack_v2_sparse_classes_75kplus_train_005806
2,410
permissive
[ { "docstring": "Args: container(shelf.container.Container)", "name": "__init__", "signature": "def __init__(self, container)" }, { "docstring": "Searches based on criteria defined in request and assigns links to response for each search hit. Args: criteria(schemas/search-request-criteria.json): ...
3
null
Implement the Python class `SearchPortal` described below. Class description: This class is the link between the request/view and the search layer. Method signatures and docstrings: - def __init__(self, container): Args: container(shelf.container.Container) - def search(self, criteria): Searches based on criteria def...
Implement the Python class `SearchPortal` described below. Class description: This class is the link between the request/view and the search layer. Method signatures and docstrings: - def __init__(self, container): Args: container(shelf.container.Container) - def search(self, criteria): Searches based on criteria def...
ea59703082402ad3b6454482f0487418295fbd19
<|skeleton|> class SearchPortal: """This class is the link between the request/view and the search layer.""" def __init__(self, container): """Args: container(shelf.container.Container)""" <|body_0|> def search(self, criteria): """Searches based on criteria defined in request and a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SearchPortal: """This class is the link between the request/view and the search layer.""" def __init__(self, container): """Args: container(shelf.container.Container)""" self.container = container self.search_manager = self.container.search.manager self.search_parser = sel...
the_stack_v2_python_sparse
shelf/search_portal.py
bfilipov/shelf
train
0
ad6b7a7363ac09990de09c4bac0707880a081c8a
[ "if not kwargs.get('zero_based_index', True):\n start = max(start - 1, 0)\n if end:\n end -= 1\n if pages:\n pages = [i - 1 for i in pages]\ncv = Converter(pdf_file)\ncv.convert(docx_file, start, end, pages, kwargs)\ncv.close()", "if not kwargs.get('zero_based_index', True):\n page_index...
<|body_start_0|> if not kwargs.get('zero_based_index', True): start = max(start - 1, 0) if end: end -= 1 if pages: pages = [i - 1 for i in pages] cv = Converter(pdf_file) cv.convert(docx_file, start, end, pages, kwargs) ...
Command line interface for ``pdf2docx``.
PDF2DOCX
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PDF2DOCX: """Command line interface for ``pdf2docx``.""" def convert(pdf_file: str, docx_file: str=None, start: int=0, end: int=None, pages: list=None, **kwargs): """Convert pdf file to docx file. Args: pdf_file (str) : PDF filename to read from. docx_file (str, optional): docx filen...
stack_v2_sparse_classes_75kplus_train_005807
3,158
permissive
[ { "docstring": "Convert pdf file to docx file. Args: pdf_file (str) : PDF filename to read from. docx_file (str, optional): docx filename to write to. Defaults to None. start (int, optional): First page to process. Defaults to 0. end (int, optional): Last page to process. Defaults to None. pages (list, optional...
3
stack_v2_sparse_classes_30k_train_016788
Implement the Python class `PDF2DOCX` described below. Class description: Command line interface for ``pdf2docx``. Method signatures and docstrings: - def convert(pdf_file: str, docx_file: str=None, start: int=0, end: int=None, pages: list=None, **kwargs): Convert pdf file to docx file. Args: pdf_file (str) : PDF fil...
Implement the Python class `PDF2DOCX` described below. Class description: Command line interface for ``pdf2docx``. Method signatures and docstrings: - def convert(pdf_file: str, docx_file: str=None, start: int=0, end: int=None, pages: list=None, **kwargs): Convert pdf file to docx file. Args: pdf_file (str) : PDF fil...
13cdbaa8acef8e1140e419ac488eb6f18d4ca6d5
<|skeleton|> class PDF2DOCX: """Command line interface for ``pdf2docx``.""" def convert(pdf_file: str, docx_file: str=None, start: int=0, end: int=None, pages: list=None, **kwargs): """Convert pdf file to docx file. Args: pdf_file (str) : PDF filename to read from. docx_file (str, optional): docx filen...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PDF2DOCX: """Command line interface for ``pdf2docx``.""" def convert(pdf_file: str, docx_file: str=None, start: int=0, end: int=None, pages: list=None, **kwargs): """Convert pdf file to docx file. Args: pdf_file (str) : PDF filename to read from. docx_file (str, optional): docx filename to write ...
the_stack_v2_python_sparse
CustomPdf2Docx/CustomPdf2Docx.py
ikdk5596/pdf_translate
train
0
e9c32f36a1365b4dfbe8c593f8d51cfe54fcedf0
[ "if widget.currentIndex() == -1:\n return None\nelse:\n return widget.itemText(widget.currentIndex())", "idx = widget.findText(value)\nif idx == -1:\n if value is not None:\n raise ValueError(\"Cannot find text '{0}' in combo box\".format(value))\nwidget.setCurrentIndex(idx)" ]
<|body_start_0|> if widget.currentIndex() == -1: return None else: return widget.itemText(widget.currentIndex()) <|end_body_0|> <|body_start_1|> idx = widget.findText(value) if idx == -1: if value is not None: raise ValueError("Cannot ...
Wrapper around the text in QComboBox.
CurrentComboTextProperty
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CurrentComboTextProperty: """Wrapper around the text in QComboBox.""" def getter(self, widget): """Return the itemData stored in the currently-selected item""" <|body_0|> def setter(self, widget, value): """Update the currently selected item to the one which stor...
stack_v2_sparse_classes_75kplus_train_005808
8,602
permissive
[ { "docstring": "Return the itemData stored in the currently-selected item", "name": "getter", "signature": "def getter(self, widget)" }, { "docstring": "Update the currently selected item to the one which stores value in its itemData", "name": "setter", "signature": "def setter(self, wid...
2
stack_v2_sparse_classes_30k_train_001785
Implement the Python class `CurrentComboTextProperty` described below. Class description: Wrapper around the text in QComboBox. Method signatures and docstrings: - def getter(self, widget): Return the itemData stored in the currently-selected item - def setter(self, widget, value): Update the currently selected item ...
Implement the Python class `CurrentComboTextProperty` described below. Class description: Wrapper around the text in QComboBox. Method signatures and docstrings: - def getter(self, widget): Return the itemData stored in the currently-selected item - def setter(self, widget, value): Update the currently selected item ...
4aa8c64a6f65629207e40df9963232473a24c9f6
<|skeleton|> class CurrentComboTextProperty: """Wrapper around the text in QComboBox.""" def getter(self, widget): """Return the itemData stored in the currently-selected item""" <|body_0|> def setter(self, widget, value): """Update the currently selected item to the one which stor...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CurrentComboTextProperty: """Wrapper around the text in QComboBox.""" def getter(self, widget): """Return the itemData stored in the currently-selected item""" if widget.currentIndex() == -1: return None else: return widget.itemText(widget.currentIndex()) ...
the_stack_v2_python_sparse
glue/utils/qt/widget_properties.py
astrofrog/glue
train
3
14875b035d162cb3559054657267b1b5387fdd7a
[ "index = template.find(COURSE_EMAIL_MESSAGE_BODY_TAG)\nif index < 0:\n msg = f'Missing tag: \"{COURSE_EMAIL_MESSAGE_BODY_TAG}\"'\n log.warning(msg)\n raise ValidationError(msg)\nif template.find(COURSE_EMAIL_MESSAGE_BODY_TAG, index + 1) >= 0:\n msg = f'Multiple instances of tag: \"{COURSE_EMAIL_MESSAGE_...
<|body_start_0|> index = template.find(COURSE_EMAIL_MESSAGE_BODY_TAG) if index < 0: msg = f'Missing tag: "{COURSE_EMAIL_MESSAGE_BODY_TAG}"' log.warning(msg) raise ValidationError(msg) if template.find(COURSE_EMAIL_MESSAGE_BODY_TAG, index + 1) >= 0: ...
Form providing validation of CourseEmail templates.
CourseEmailTemplateForm
[ "AGPL-3.0-only", "AGPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CourseEmailTemplateForm: """Form providing validation of CourseEmail templates.""" def _validate_template(self, template): """Check the template for required tags.""" <|body_0|> def clean_html_template(self): """Validate the HTML template.""" <|body_1|> ...
stack_v2_sparse_classes_75kplus_train_005809
3,011
permissive
[ { "docstring": "Check the template for required tags.", "name": "_validate_template", "signature": "def _validate_template(self, template)" }, { "docstring": "Validate the HTML template.", "name": "clean_html_template", "signature": "def clean_html_template(self)" }, { "docstring...
4
null
Implement the Python class `CourseEmailTemplateForm` described below. Class description: Form providing validation of CourseEmail templates. Method signatures and docstrings: - def _validate_template(self, template): Check the template for required tags. - def clean_html_template(self): Validate the HTML template. - ...
Implement the Python class `CourseEmailTemplateForm` described below. Class description: Form providing validation of CourseEmail templates. Method signatures and docstrings: - def _validate_template(self, template): Check the template for required tags. - def clean_html_template(self): Validate the HTML template. - ...
5809eaca7079a15ee56b0b7fcfea425337046c97
<|skeleton|> class CourseEmailTemplateForm: """Form providing validation of CourseEmail templates.""" def _validate_template(self, template): """Check the template for required tags.""" <|body_0|> def clean_html_template(self): """Validate the HTML template.""" <|body_1|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CourseEmailTemplateForm: """Form providing validation of CourseEmail templates.""" def _validate_template(self, template): """Check the template for required tags.""" index = template.find(COURSE_EMAIL_MESSAGE_BODY_TAG) if index < 0: msg = f'Missing tag: "{COURSE_EMAIL...
the_stack_v2_python_sparse
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/bulk_email/forms.py
luque/better-ways-of-thinking-about-software
train
3
c5c28dce8de151c3539f901e0cf23a30b8b4cc02
[ "self.access_token = options.get('access_token')\nif self.access_token is None:\n self.authorization_code = options.get('authorization_code')\nself.client_secret = options.get('client_secret')\nself.base_url = options['base_url'] if 'base_url' in options else 'https://api.fortnox.se'\nself.timeout = options['tim...
<|body_start_0|> self.access_token = options.get('access_token') if self.access_token is None: self.authorization_code = options.get('authorization_code') self.client_secret = options.get('client_secret') self.base_url = options['base_url'] if 'base_url' in options else 'http...
Base CRM client configuration :class:`Configuration <Configuration>` object. Used by :class:`HttpClient <HttpClient>` to send requests to Fortnox's servers.
Configuration
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Configuration: """Base CRM client configuration :class:`Configuration <Configuration>` object. Used by :class:`HttpClient <HttpClient>` to send requests to Fortnox's servers.""" def __init__(self, **options): """:param str access_token: Personal access token. :param str base_url: (op...
stack_v2_sparse_classes_75kplus_train_005810
3,332
permissive
[ { "docstring": ":param str access_token: Personal access token. :param str base_url: (optional) Base url for the api. Default: ``https://api.fortnox.se``. :param bool verbose: (optional) Verbose/debug mode. Default: ``False``. :param int timeout: (optional) Connection and response timeout. Default: **30** secon...
2
null
Implement the Python class `Configuration` described below. Class description: Base CRM client configuration :class:`Configuration <Configuration>` object. Used by :class:`HttpClient <HttpClient>` to send requests to Fortnox's servers. Method signatures and docstrings: - def __init__(self, **options): :param str acce...
Implement the Python class `Configuration` described below. Class description: Base CRM client configuration :class:`Configuration <Configuration>` object. Used by :class:`HttpClient <HttpClient>` to send requests to Fortnox's servers. Method signatures and docstrings: - def __init__(self, **options): :param str acce...
4d4fcfea09c5665350240770a773e326f43ad23d
<|skeleton|> class Configuration: """Base CRM client configuration :class:`Configuration <Configuration>` object. Used by :class:`HttpClient <HttpClient>` to send requests to Fortnox's servers.""" def __init__(self, **options): """:param str access_token: Personal access token. :param str base_url: (op...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Configuration: """Base CRM client configuration :class:`Configuration <Configuration>` object. Used by :class:`HttpClient <HttpClient>` to send requests to Fortnox's servers.""" def __init__(self, **options): """:param str access_token: Personal access token. :param str base_url: (optional) Base ...
the_stack_v2_python_sparse
fortnox/configuration.py
xalien10/pyfortnox
train
21
fd854992638f09ffa09dc0e18bee2ecd95db20d1
[ "print(f'{Fore.YELLOW}SERVICES CHECK FOR {Env.environment} ENVIRONMENT STARTS:{Fore.RESET}')\nservice_check = TestService.test_service_runner()\nprint('*************************************************************')\nprint()\nif service_check:\n cls.test_suite_runner()\nelse:\n Tenv.overall_result = 'FAIL!'",...
<|body_start_0|> print(f'{Fore.YELLOW}SERVICES CHECK FOR {Env.environment} ENVIRONMENT STARTS:{Fore.RESET}') service_check = TestService.test_service_runner() print('*************************************************************') print() if service_check: cls.test_sui...
This class handles running of Test Suite for particular sport and entity.
TestSuiteRunner
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestSuiteRunner: """This class handles running of Test Suite for particular sport and entity.""" def services_check(cls): """This method is starting all the Automation Test by checking of availability of all services necessary for executing particular tests. In case of all services a...
stack_v2_sparse_classes_75kplus_train_005811
3,229
no_license
[ { "docstring": "This method is starting all the Automation Test by checking of availability of all services necessary for executing particular tests. In case of all services are available, testing starts by calling test_suite_runner method. In case of some service is unavailable, test running are cancelled.", ...
2
stack_v2_sparse_classes_30k_train_006750
Implement the Python class `TestSuiteRunner` described below. Class description: This class handles running of Test Suite for particular sport and entity. Method signatures and docstrings: - def services_check(cls): This method is starting all the Automation Test by checking of availability of all services necessary ...
Implement the Python class `TestSuiteRunner` described below. Class description: This class handles running of Test Suite for particular sport and entity. Method signatures and docstrings: - def services_check(cls): This method is starting all the Automation Test by checking of availability of all services necessary ...
f5d3483bd40610bbbe241c81067101efcc4932ad
<|skeleton|> class TestSuiteRunner: """This class handles running of Test Suite for particular sport and entity.""" def services_check(cls): """This method is starting all the Automation Test by checking of availability of all services necessary for executing particular tests. In case of all services a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestSuiteRunner: """This class handles running of Test Suite for particular sport and entity.""" def services_check(cls): """This method is starting all the Automation Test by checking of availability of all services necessary for executing particular tests. In case of all services are available,...
the_stack_v2_python_sparse
src/TestSuiteRunner.py
PeterAugustinak/frontend-auto-test-sample-project
train
0
653d0e56877183e3b3e47cb2230dc65a5d0e150e
[ "scrolled.ScrolledPanel.__init__(self, parent, -1, size=(100, 500))\nself.visualizer = visualizer\nself.mode = mode\nself.sizer = wx.GridBagSizer()\nself.projectionBox = wx.RadioBox(self, -1, 'View projection', choices=['Max. IP', 'Avg. IP'], majorDimension=1, style=wx.RA_SPECIFY_COLS)\nself.updateButton = wx.Butto...
<|body_start_0|> scrolled.ScrolledPanel.__init__(self, parent, -1, size=(100, 500)) self.visualizer = visualizer self.mode = mode self.sizer = wx.GridBagSizer() self.projectionBox = wx.RadioBox(self, -1, 'View projection', choices=['Max. IP', 'Avg. IP'], majorDimension=1, style=w...
A configuration panel for the projection view
SimpleConfigurationPanel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleConfigurationPanel: """A configuration panel for the projection view""" def __init__(self, parent, visualizer, mode, **kws): """Initialization""" <|body_0|> def onSetProjectionMode(self, event): """Configure what projection to show""" <|body_1|> <|...
stack_v2_sparse_classes_75kplus_train_005812
6,623
no_license
[ { "docstring": "Initialization", "name": "__init__", "signature": "def __init__(self, parent, visualizer, mode, **kws)" }, { "docstring": "Configure what projection to show", "name": "onSetProjectionMode", "signature": "def onSetProjectionMode(self, event)" } ]
2
stack_v2_sparse_classes_30k_train_005298
Implement the Python class `SimpleConfigurationPanel` described below. Class description: A configuration panel for the projection view Method signatures and docstrings: - def __init__(self, parent, visualizer, mode, **kws): Initialization - def onSetProjectionMode(self, event): Configure what projection to show
Implement the Python class `SimpleConfigurationPanel` described below. Class description: A configuration panel for the projection view Method signatures and docstrings: - def __init__(self, parent, visualizer, mode, **kws): Initialization - def onSetProjectionMode(self, event): Configure what projection to show <|s...
ea8bafa073de5090bd8f83fb4f5ca16669d0211f
<|skeleton|> class SimpleConfigurationPanel: """A configuration panel for the projection view""" def __init__(self, parent, visualizer, mode, **kws): """Initialization""" <|body_0|> def onSetProjectionMode(self, event): """Configure what projection to show""" <|body_1|> <|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SimpleConfigurationPanel: """A configuration panel for the projection view""" def __init__(self, parent, visualizer, mode, **kws): """Initialization""" scrolled.ScrolledPanel.__init__(self, parent, -1, size=(100, 500)) self.visualizer = visualizer self.mode = mode ...
the_stack_v2_python_sparse
Graphs/LX-2/molecule_otsu = False/BioImageXD-1.0/Modules/Visualization/Simple.py
giacomo21/Image-analysis
train
1
f9aa7f112d4cae5ee007ed15c67de5ef4b735bdc
[ "from cupy.cuda import nccl\nsuper(CustomParallelUpdater, self).__init__(train_iters, optimizer, converter=converter, devices=devices)\nself.accum_grad = accum_grad\nself.forward_count = 0\nself.nccl = nccl\nlogging.debug('using custom parallel updater for transformer')", "self.setup_workers()\nself._send_message...
<|body_start_0|> from cupy.cuda import nccl super(CustomParallelUpdater, self).__init__(train_iters, optimizer, converter=converter, devices=devices) self.accum_grad = accum_grad self.forward_count = 0 self.nccl = nccl logging.debug('using custom parallel updater for tran...
Custom Parallel Updater for chainer. Defines the main update routine. Args: train_iter (iterator | dict[str, iterator]): Dataset iterator for the training dataset. It can also be a dictionary that maps strings to iterators. If this is just an iterator, then the iterator is registered by the name ``'main'``. optimizer (...
CustomParallelUpdater
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomParallelUpdater: """Custom Parallel Updater for chainer. Defines the main update routine. Args: train_iter (iterator | dict[str, iterator]): Dataset iterator for the training dataset. It can also be a dictionary that maps strings to iterators. If this is just an iterator, then the iterator ...
stack_v2_sparse_classes_75kplus_train_005813
11,798
permissive
[ { "docstring": "Initialize custom parallel updater.", "name": "__init__", "signature": "def __init__(self, train_iters, optimizer, converter, devices, accum_grad=1)" }, { "docstring": "Process main update routine for Custom Parallel Updater.", "name": "update_core", "signature": "def upd...
3
stack_v2_sparse_classes_30k_train_036964
Implement the Python class `CustomParallelUpdater` described below. Class description: Custom Parallel Updater for chainer. Defines the main update routine. Args: train_iter (iterator | dict[str, iterator]): Dataset iterator for the training dataset. It can also be a dictionary that maps strings to iterators. If this ...
Implement the Python class `CustomParallelUpdater` described below. Class description: Custom Parallel Updater for chainer. Defines the main update routine. Args: train_iter (iterator | dict[str, iterator]): Dataset iterator for the training dataset. It can also be a dictionary that maps strings to iterators. If this ...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class CustomParallelUpdater: """Custom Parallel Updater for chainer. Defines the main update routine. Args: train_iter (iterator | dict[str, iterator]): Dataset iterator for the training dataset. It can also be a dictionary that maps strings to iterators. If this is just an iterator, then the iterator ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomParallelUpdater: """Custom Parallel Updater for chainer. Defines the main update routine. Args: train_iter (iterator | dict[str, iterator]): Dataset iterator for the training dataset. It can also be a dictionary that maps strings to iterators. If this is just an iterator, then the iterator is registered...
the_stack_v2_python_sparse
espnet/nets/chainer_backend/transformer/training.py
espnet/espnet
train
7,242
8fb476bf92308c545637b83d705c1e155ddd018b
[ "self.grid_size = n\nself.grid = []\nfor i in range(n):\n row = [0] * n\n self.grid.append(row)\nself.init_animals(prey_count, predator_count)", "if 0 <= x < self.grid_size and 0 <= y < self.grid_size:\n return self.grid[x][y]\nelse:\n return -1", "count = 0\nwhile count < prey_count:\n x = rando...
<|body_start_0|> self.grid_size = n self.grid = [] for i in range(n): row = [0] * n self.grid.append(row) self.init_animals(prey_count, predator_count) <|end_body_0|> <|body_start_1|> if 0 <= x < self.grid_size and 0 <= y < self.grid_size: ret...
Island
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Island: def __init__(self, n, prey_count=0, predator_count=0): """Initialize grid to all 0s, then fill with animals""" <|body_0|> def animal(self, x, y): """Return animal at location (x,y)""" <|body_1|> def init_animals(self, prey_count, predator_count):...
stack_v2_sparse_classes_75kplus_train_005814
1,591
no_license
[ { "docstring": "Initialize grid to all 0s, then fill with animals", "name": "__init__", "signature": "def __init__(self, n, prey_count=0, predator_count=0)" }, { "docstring": "Return animal at location (x,y)", "name": "animal", "signature": "def animal(self, x, y)" }, { "docstrin...
3
null
Implement the Python class `Island` described below. Class description: Implement the Island class. Method signatures and docstrings: - def __init__(self, n, prey_count=0, predator_count=0): Initialize grid to all 0s, then fill with animals - def animal(self, x, y): Return animal at location (x,y) - def init_animals(...
Implement the Python class `Island` described below. Class description: Implement the Island class. Method signatures and docstrings: - def __init__(self, n, prey_count=0, predator_count=0): Initialize grid to all 0s, then fill with animals - def animal(self, x, y): Return animal at location (x,y) - def init_animals(...
28fd3c344c49d004e20322e8d33b1f0bfec38e0c
<|skeleton|> class Island: def __init__(self, n, prey_count=0, predator_count=0): """Initialize grid to all 0s, then fill with animals""" <|body_0|> def animal(self, x, y): """Return animal at location (x,y)""" <|body_1|> def init_animals(self, prey_count, predator_count):...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Island: def __init__(self, n, prey_count=0, predator_count=0): """Initialize grid to all 0s, then fill with animals""" self.grid_size = n self.grid = [] for i in range(n): row = [0] * n self.grid.append(row) self.init_animals(prey_count, predator...
the_stack_v2_python_sparse
ch13/codeListing13-5.py
oilmcut2019/Teaching_material_python
train
0
25c42d4b23294fbd3df79e038134f53debdec550
[ "name = clean_name(name)\ndistrict = clean_string(district).replace('&', 'and')\nrole = clean_string(role)\nif role == 'City Councillor':\n role = 'Councillor'\nfor k, v in kwargs.items():\n if isinstance(v, str):\n kwargs[k] = clean_string(v)\nif not district:\n raise Exception('No district')\nsupe...
<|body_start_0|> name = clean_name(name) district = clean_string(district).replace('&', 'and') role = clean_string(role) if role == 'City Councillor': role = 'Councillor' for k, v in kwargs.items(): if isinstance(v, str): kwargs[k] = clean_...
CanadianPerson
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CanadianPerson: def __init__(self, *, name, district, role, **kwargs): """Cleans a person's name, district, role and any other attributes.""" <|body_0|> def __setattr__(self, name, value): """Corrects gender values.""" <|body_1|> def add_link(self, url, ...
stack_v2_sparse_classes_75kplus_train_005815
27,455
permissive
[ { "docstring": "Cleans a person's name, district, role and any other attributes.", "name": "__init__", "signature": "def __init__(self, *, name, district, role, **kwargs)" }, { "docstring": "Corrects gender values.", "name": "__setattr__", "signature": "def __setattr__(self, name, value)...
6
stack_v2_sparse_classes_30k_train_007131
Implement the Python class `CanadianPerson` described below. Class description: Implement the CanadianPerson class. Method signatures and docstrings: - def __init__(self, *, name, district, role, **kwargs): Cleans a person's name, district, role and any other attributes. - def __setattr__(self, name, value): Corrects...
Implement the Python class `CanadianPerson` described below. Class description: Implement the CanadianPerson class. Method signatures and docstrings: - def __init__(self, *, name, district, role, **kwargs): Cleans a person's name, district, role and any other attributes. - def __setattr__(self, name, value): Corrects...
ef7bd9990e2a31c731d3bd1e7c2616fbfa7f2882
<|skeleton|> class CanadianPerson: def __init__(self, *, name, district, role, **kwargs): """Cleans a person's name, district, role and any other attributes.""" <|body_0|> def __setattr__(self, name, value): """Corrects gender values.""" <|body_1|> def add_link(self, url, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CanadianPerson: def __init__(self, *, name, district, role, **kwargs): """Cleans a person's name, district, role and any other attributes.""" name = clean_name(name) district = clean_string(district).replace('&', 'and') role = clean_string(role) if role == 'City Council...
the_stack_v2_python_sparse
utils.py
opencivicdata/scrapers-ca
train
21
615790fe38c460aae7f01acb5e9e111d9a8b05aa
[ "self.titulo = titulo\nself.autores = autores\nself.editor = editor\nself.isbn = isbn\nself.precio = precio", "num = 0\nfor i in range(len(self.autores)):\n num += 1\nreturn num" ]
<|body_start_0|> self.titulo = titulo self.autores = autores self.editor = editor self.isbn = isbn self.precio = precio <|end_body_0|> <|body_start_1|> num = 0 for i in range(len(self.autores)): num += 1 return num <|end_body_1|>
Información acerca de un libro, incluye título, lista de autores, editorial, ISBN y precio.
Libro
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Libro: """Información acerca de un libro, incluye título, lista de autores, editorial, ISBN y precio.""" def __init__(self, titulo, autores, editor, isbn, precio): """Construtor principal con parámetros por defecto.""" <|body_0|> def num_autores(self): """Método ...
stack_v2_sparse_classes_75kplus_train_005816
976
no_license
[ { "docstring": "Construtor principal con parámetros por defecto.", "name": "__init__", "signature": "def __init__(self, titulo, autores, editor, isbn, precio)" }, { "docstring": "Método que cuenta el número de autores del libro y devuelve dicho número.", "name": "num_autores", "signature...
2
stack_v2_sparse_classes_30k_train_025600
Implement the Python class `Libro` described below. Class description: Información acerca de un libro, incluye título, lista de autores, editorial, ISBN y precio. Method signatures and docstrings: - def __init__(self, titulo, autores, editor, isbn, precio): Construtor principal con parámetros por defecto. - def num_a...
Implement the Python class `Libro` described below. Class description: Información acerca de un libro, incluye título, lista de autores, editorial, ISBN y precio. Method signatures and docstrings: - def __init__(self, titulo, autores, editor, isbn, precio): Construtor principal con parámetros por defecto. - def num_a...
5b86a497a7f2337aeb9711f0500a7fc7cebc986a
<|skeleton|> class Libro: """Información acerca de un libro, incluye título, lista de autores, editorial, ISBN y precio.""" def __init__(self, titulo, autores, editor, isbn, precio): """Construtor principal con parámetros por defecto.""" <|body_0|> def num_autores(self): """Método ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Libro: """Información acerca de un libro, incluye título, lista de autores, editorial, ISBN y precio.""" def __init__(self, titulo, autores, editor, isbn, precio): """Construtor principal con parámetros por defecto.""" self.titulo = titulo self.autores = autores self.edito...
the_stack_v2_python_sparse
Sergey_Examen/ej3.py
2dam-spopov/di
train
0
27701991639a3d2aeeb7689fba6321c07836db99
[ "pygame.font.init()\nbasicfont = pygame.font.Font(None, fontsize)\nself.linewidths = []\nfor x in text:\n self.texttemp = basicfont.render(x, 0, (1, 1, 1))\n self.linewidths.append(self.texttemp.get_width())\nself.imagewidth = basicfont.render(text[self.linewidths.index(max(self.linewidths))], 0, (1, 1, 1)).g...
<|body_start_0|> pygame.font.init() basicfont = pygame.font.Font(None, fontsize) self.linewidths = [] for x in text: self.texttemp = basicfont.render(x, 0, (1, 1, 1)) self.linewidths.append(self.texttemp.get_width()) self.imagewidth = basicfont.render(text...
Linesoftext
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Linesoftext: def __init__(self, text, position, xmid=False, fontsize=36, backgroundcolor=(200, 200, 200), surface=None): """This object will create an image of text that is passed in as a list of strings. It will put a new line for each element in the list. Use its image attribute to put...
stack_v2_sparse_classes_75kplus_train_005817
5,935
no_license
[ { "docstring": "This object will create an image of text that is passed in as a list of strings. It will put a new line for each element in the list. Use its image attribute to put this text on your screen", "name": "__init__", "signature": "def __init__(self, text, position, xmid=False, fontsize=36, ba...
2
stack_v2_sparse_classes_30k_val_002057
Implement the Python class `Linesoftext` described below. Class description: Implement the Linesoftext class. Method signatures and docstrings: - def __init__(self, text, position, xmid=False, fontsize=36, backgroundcolor=(200, 200, 200), surface=None): This object will create an image of text that is passed in as a ...
Implement the Python class `Linesoftext` described below. Class description: Implement the Linesoftext class. Method signatures and docstrings: - def __init__(self, text, position, xmid=False, fontsize=36, backgroundcolor=(200, 200, 200), surface=None): This object will create an image of text that is passed in as a ...
3eae1428fdd30fddc66669d40b8bb0a715d5595a
<|skeleton|> class Linesoftext: def __init__(self, text, position, xmid=False, fontsize=36, backgroundcolor=(200, 200, 200), surface=None): """This object will create an image of text that is passed in as a list of strings. It will put a new line for each element in the list. Use its image attribute to put...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Linesoftext: def __init__(self, text, position, xmid=False, fontsize=36, backgroundcolor=(200, 200, 200), surface=None): """This object will create an image of text that is passed in as a list of strings. It will put a new line for each element in the list. Use its image attribute to put this text on ...
the_stack_v2_python_sparse
General Python/Guessing_game_with_gui/pygametools.py
jbm950/personal_projects
train
0
6fdbb45f1266e953964fbe6e539a6c4880df45ff
[ "course_key, _ = _get_course_with_access(request, course_key_string)\ntry:\n cohort = cohorts.get_cohort_by_id(course_key, cohort_id)\nexcept CourseUserGroup.DoesNotExist:\n msg = 'Cohort (ID {cohort_id}) not found for {course_key_string}'.format(cohort_id=cohort_id, course_key_string=course_key_string)\n ...
<|body_start_0|> course_key, _ = _get_course_with_access(request, course_key_string) try: cohort = cohorts.get_cohort_by_id(course_key, cohort_id) except CourseUserGroup.DoesNotExist: msg = 'Cohort (ID {cohort_id}) not found for {course_key_string}'.format(cohort_id=cohor...
**Use Cases** List users in a cohort Removes an user from a cohort. Add a user to a specific cohort. **Example Requests** GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users DELETE /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users/{username} POST /api/cohorts/v1/courses/{course_id}/cohorts/{co...
CohortUsers
[ "AGPL-3.0-only", "AGPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CohortUsers: """**Use Cases** List users in a cohort Removes an user from a cohort. Add a user to a specific cohort. **Example Requests** GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users DELETE /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users/{username} POST /api/coh...
stack_v2_sparse_classes_75kplus_train_005818
31,213
permissive
[ { "docstring": "Return the course and cohort for the given course_key_string and cohort_id.", "name": "_get_course_and_cohort", "signature": "def _get_course_and_cohort(self, request, course_key_string, cohort_id)" }, { "docstring": "Lists the users in a specific cohort.", "name": "get", ...
4
stack_v2_sparse_classes_30k_train_014971
Implement the Python class `CohortUsers` described below. Class description: **Use Cases** List users in a cohort Removes an user from a cohort. Add a user to a specific cohort. **Example Requests** GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users DELETE /api/cohorts/v1/courses/{course_id}/cohorts/{co...
Implement the Python class `CohortUsers` described below. Class description: **Use Cases** List users in a cohort Removes an user from a cohort. Add a user to a specific cohort. **Example Requests** GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users DELETE /api/cohorts/v1/courses/{course_id}/cohorts/{co...
5809eaca7079a15ee56b0b7fcfea425337046c97
<|skeleton|> class CohortUsers: """**Use Cases** List users in a cohort Removes an user from a cohort. Add a user to a specific cohort. **Example Requests** GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users DELETE /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users/{username} POST /api/coh...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CohortUsers: """**Use Cases** List users in a cohort Removes an user from a cohort. Add a user to a specific cohort. **Example Requests** GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users DELETE /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users/{username} POST /api/cohorts/v1/cours...
the_stack_v2_python_sparse
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/course_groups/views.py
luque/better-ways-of-thinking-about-software
train
3
ceb4452c1d2962045cef531f5f74ea60a19c819d
[ "super(CustomBatchNormAutograd, self).__init__()\nself.n_neurons = n_neurons\nself.eps = eps\nself.params = nn.ParameterDict({'gamma': nn.Parameter(torch.ones(n_neurons)), 'beta': nn.Parameter(torch.zeros(n_neurons))})", "_n_batch, n_neurons = input.shape\nassert n_neurons == self.n_neurons\nmean = input.mean(dim...
<|body_start_0|> super(CustomBatchNormAutograd, self).__init__() self.n_neurons = n_neurons self.eps = eps self.params = nn.ParameterDict({'gamma': nn.Parameter(torch.ones(n_neurons)), 'beta': nn.Parameter(torch.zeros(n_neurons))}) <|end_body_0|> <|body_start_1|> _n_batch, n_neu...
This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by the automatic differentiation provided by PyTorch.
CustomBatchNormAutograd
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomBatchNormAutograd: """This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by...
stack_v2_sparse_classes_75kplus_train_005819
7,737
no_license
[ { "docstring": "Initializes CustomBatchNormAutograd object. Args: n_neurons: int specifying the number of neurons eps: small float to be added to the variance for stability", "name": "__init__", "signature": "def __init__(self, n_neurons, eps=1e-05)" }, { "docstring": "Compute the batch normaliz...
2
stack_v2_sparse_classes_30k_train_013063
Implement the Python class `CustomBatchNormAutograd` described below. Class description: This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need...
Implement the Python class `CustomBatchNormAutograd` described below. Class description: This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need...
b2cd0d67337b101f3e204e519625e1aaf3cea43b
<|skeleton|> class CustomBatchNormAutograd: """This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomBatchNormAutograd: """This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by the automati...
the_stack_v2_python_sparse
assignment_1/code/custom_batchnorm.py
Ivan-Yovchev/uvadlc_practicals_2019
train
0
9397719eded0c48fd704ed1d50788d7b4fe3366e
[ "i = infos.copy()\ni['device_number'] = infos['serial_number']\ndel i['serial_number']\nreturn i", "c = self.format_connection_infos(connection)\nc.update(settings)\ndriver = None\n'\\n try:\\n driver = driver_cls(c)\\n res = driver.connected\\n except Exception:\\n ...
<|body_start_0|> i = infos.copy() i['device_number'] = infos['serial_number'] del i['serial_number'] return i <|end_body_0|> <|body_start_1|> c = self.format_connection_infos(connection) c.update(settings) driver = None '\n try:\n driver...
Starter for ZI instruments.
ZIQCircuitStarter
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ZIQCircuitStarter: """Starter for ZI instruments.""" def format_connection_infos(self, infos): """Rename serial_number to device_number.""" <|body_0|> def check_infos(self, driver_cls, connection, settings): """Attempt to open the connection to the instrument."""...
stack_v2_sparse_classes_75kplus_train_005820
1,604
permissive
[ { "docstring": "Rename serial_number to device_number.", "name": "format_connection_infos", "signature": "def format_connection_infos(self, infos)" }, { "docstring": "Attempt to open the connection to the instrument.", "name": "check_infos", "signature": "def check_infos(self, driver_cls...
2
stack_v2_sparse_classes_30k_train_014287
Implement the Python class `ZIQCircuitStarter` described below. Class description: Starter for ZI instruments. Method signatures and docstrings: - def format_connection_infos(self, infos): Rename serial_number to device_number. - def check_infos(self, driver_cls, connection, settings): Attempt to open the connection ...
Implement the Python class `ZIQCircuitStarter` described below. Class description: Starter for ZI instruments. Method signatures and docstrings: - def format_connection_infos(self, infos): Rename serial_number to device_number. - def check_infos(self, driver_cls, connection, settings): Attempt to open the connection ...
dedbf77062e0a8af0275f231e374867fa0342e78
<|skeleton|> class ZIQCircuitStarter: """Starter for ZI instruments.""" def format_connection_infos(self, infos): """Rename serial_number to device_number.""" <|body_0|> def check_infos(self, driver_cls, connection, settings): """Attempt to open the connection to the instrument."""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ZIQCircuitStarter: """Starter for ZI instruments.""" def format_connection_infos(self, infos): """Rename serial_number to device_number.""" i = infos.copy() i['device_number'] = infos['serial_number'] del i['serial_number'] return i def check_infos(self, drive...
the_stack_v2_python_sparse
exopy_qcircuits/instruments/starters/ZIQCircuitStarter.py
jerjohste/ecpy_qcircuits
train
0
d4ab58c68de28b35e72a7c2a1c61603e502f909e
[ "genre = Genre.query.filter_by(id=id).first()\nif genre is None:\n return ({'message': 'Genre does not exist'}, 404)\nreturn genre_schema.dump(genre)", "req = api.payload\ngenre = Genre.query.filter_by(id=id).first()\nif genre is None:\n return ({'message': 'Genre does not exist'}, 404)\ntry:\n edit_genr...
<|body_start_0|> genre = Genre.query.filter_by(id=id).first() if genre is None: return ({'message': 'Genre does not exist'}, 404) return genre_schema.dump(genre) <|end_body_0|> <|body_start_1|> req = api.payload genre = Genre.query.filter_by(id=id).first() if...
SingleGenre
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SingleGenre: def get(self, id): """Get Genre by id""" <|body_0|> def put(self, id): """Update a Genre""" <|body_1|> def delete(self, id): """Delete a Genre by id""" <|body_2|> <|end_skeleton|> <|body_start_0|> genre = Genre.quer...
stack_v2_sparse_classes_75kplus_train_005821
3,163
no_license
[ { "docstring": "Get Genre by id", "name": "get", "signature": "def get(self, id)" }, { "docstring": "Update a Genre", "name": "put", "signature": "def put(self, id)" }, { "docstring": "Delete a Genre by id", "name": "delete", "signature": "def delete(self, id)" } ]
3
stack_v2_sparse_classes_30k_train_044598
Implement the Python class `SingleGenre` described below. Class description: Implement the SingleGenre class. Method signatures and docstrings: - def get(self, id): Get Genre by id - def put(self, id): Update a Genre - def delete(self, id): Delete a Genre by id
Implement the Python class `SingleGenre` described below. Class description: Implement the SingleGenre class. Method signatures and docstrings: - def get(self, id): Get Genre by id - def put(self, id): Update a Genre - def delete(self, id): Delete a Genre by id <|skeleton|> class SingleGenre: def get(self, id):...
ae78fff9888b0f68d9403d7f65cba086dabb3802
<|skeleton|> class SingleGenre: def get(self, id): """Get Genre by id""" <|body_0|> def put(self, id): """Update a Genre""" <|body_1|> def delete(self, id): """Delete a Genre by id""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SingleGenre: def get(self, id): """Get Genre by id""" genre = Genre.query.filter_by(id=id).first() if genre is None: return ({'message': 'Genre does not exist'}, 404) return genre_schema.dump(genre) def put(self, id): """Update a Genre""" req = ...
the_stack_v2_python_sparse
api/v1/genres.py
mythril-io/flask-api
train
0
3c5fbc0bef2154d6a23d67b22beda73d26d1aa73
[ "super().__init__(parent)\nself.parent = parent\nself.setupUi(self)\nself.search_btn.clicked.connect(self.search_city)\nself.search_inp.setText('')", "self.error_label.setText('')\nself.label_name.setText('')\nself.label_place.setText('')\nself.label_v1.setText('')\nself.label_v2.setText('')\nself.label_v3.setTex...
<|body_start_0|> super().__init__(parent) self.parent = parent self.setupUi(self) self.search_btn.clicked.connect(self.search_city) self.search_inp.setText('') <|end_body_0|> <|body_start_1|> self.error_label.setText('') self.label_name.setText('') self.l...
SearchWindow
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SearchWindow: def __init__(self, parent=None): """:does: init Search Window""" <|body_0|> def search_city(self): """:does: search city by name in dataframe""" <|body_1|> <|end_skeleton|> <|body_start_0|> super().__init__(parent) self.parent ...
stack_v2_sparse_classes_75kplus_train_005822
11,130
no_license
[ { "docstring": ":does: init Search Window", "name": "__init__", "signature": "def __init__(self, parent=None)" }, { "docstring": ":does: search city by name in dataframe", "name": "search_city", "signature": "def search_city(self)" } ]
2
stack_v2_sparse_classes_30k_train_040274
Implement the Python class `SearchWindow` described below. Class description: Implement the SearchWindow class. Method signatures and docstrings: - def __init__(self, parent=None): :does: init Search Window - def search_city(self): :does: search city by name in dataframe
Implement the Python class `SearchWindow` described below. Class description: Implement the SearchWindow class. Method signatures and docstrings: - def __init__(self, parent=None): :does: init Search Window - def search_city(self): :does: search city by name in dataframe <|skeleton|> class SearchWindow: def __i...
5b2e4d0b63318c4d8c32c3e546cfef84e1006eed
<|skeleton|> class SearchWindow: def __init__(self, parent=None): """:does: init Search Window""" <|body_0|> def search_city(self): """:does: search city by name in dataframe""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SearchWindow: def __init__(self, parent=None): """:does: init Search Window""" super().__init__(parent) self.parent = parent self.setupUi(self) self.search_btn.clicked.connect(self.search_city) self.search_inp.setText('') def search_city(self): """:...
the_stack_v2_python_sparse
menu.py
vodovozovaliza/SmartCity
train
0
85a384044dc73fa4202517f680d806dd78db5f80
[ "cmd = 'python3 poll_http_endpoint.py --endpoint={endpoint} --max_retries={retries} --retry_interval={retry_interval} --timeout={timeout}'.format(endpoint=endpoint, retries=retries, retry_interval=retry_interval, timeout=timeout)\nif expected_response:\n cmd += ' --expected_response=%s' % expected_response\nif e...
<|body_start_0|> cmd = 'python3 poll_http_endpoint.py --endpoint={endpoint} --max_retries={retries} --retry_interval={retry_interval} --timeout={timeout}'.format(endpoint=endpoint, retries=retries, retry_interval=retry_interval, timeout=timeout) if expected_response: cmd += ' --expected_resp...
Polls http endpoint.
HttpPoller
[ "Classpath-exception-2.0", "BSD-3-Clause", "AGPL-3.0-only", "MIT", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HttpPoller: """Polls http endpoint.""" def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response): """Builds command for polling script.""" <|body_0|> def Run(self, vm, endpoint, headers=(), retries=0, retry_in...
stack_v2_sparse_classes_75kplus_train_005823
3,784
permissive
[ { "docstring": "Builds command for polling script.", "name": "_BuildCommand", "signature": "def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response)" }, { "docstring": "Polls HTTP endpoint. Args: vm: VirtualMachine object. endpoint: ...
2
stack_v2_sparse_classes_30k_train_035352
Implement the Python class `HttpPoller` described below. Class description: Polls http endpoint. Method signatures and docstrings: - def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response): Builds command for polling script. - def Run(self, vm, endpoint,...
Implement the Python class `HttpPoller` described below. Class description: Polls http endpoint. Method signatures and docstrings: - def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response): Builds command for polling script. - def Run(self, vm, endpoint,...
d0699f32998898757b036704fba39e5471641f01
<|skeleton|> class HttpPoller: """Polls http endpoint.""" def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response): """Builds command for polling script.""" <|body_0|> def Run(self, vm, endpoint, headers=(), retries=0, retry_in...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HttpPoller: """Polls http endpoint.""" def _BuildCommand(self, endpoint, headers, retries, retry_interval, timeout, expected_response_code, expected_response): """Builds command for polling script.""" cmd = 'python3 poll_http_endpoint.py --endpoint={endpoint} --max_retries={retries} --ret...
the_stack_v2_python_sparse
perfkitbenchmarker/linux_packages/http_poller.py
GoogleCloudPlatform/PerfKitBenchmarker
train
1,923
34c9390051b20e4ba71c6b229863dabac924e83a
[ "super(SourceLoss, self).__init__()\nself.cheaptrick = CheapTrick(sampling_rate=sampling_rate, hop_size=hop_size, fft_size=fft_size, f0_floor=f0_floor, f0_ceil=f0_ceil, uv_threshold=uv_threshold, q1=q1)\nself.loss = nn.MSELoss()", "spectral_envelope = self.cheaptrick.forward(x, f0)\nzeros = torch.zeros_like(spect...
<|body_start_0|> super(SourceLoss, self).__init__() self.cheaptrick = CheapTrick(sampling_rate=sampling_rate, hop_size=hop_size, fft_size=fft_size, f0_floor=f0_floor, f0_ceil=f0_ceil, uv_threshold=uv_threshold, q1=q1) self.loss = nn.MSELoss() <|end_body_0|> <|body_start_1|> spectral_env...
SourceLoss
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SourceLoss: def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15): """Initialize source loss module. Args: fft_size (int): FFT size. hop_size (int): Hop size. win_length (int): Window length. window (str): Window function type.""" <|bo...
stack_v2_sparse_classes_75kplus_train_005824
1,728
permissive
[ { "docstring": "Initialize source loss module. Args: fft_size (int): FFT size. hop_size (int): Hop size. win_length (int): Window length. window (str): Window function type.", "name": "__init__", "signature": "def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0...
2
stack_v2_sparse_classes_30k_train_046808
Implement the Python class `SourceLoss` described below. Class description: Implement the SourceLoss class. Method signatures and docstrings: - def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15): Initialize source loss module. Args: fft_size (int): FFT size. hop_size (i...
Implement the Python class `SourceLoss` described below. Class description: Implement the SourceLoss class. Method signatures and docstrings: - def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15): Initialize source loss module. Args: fft_size (int): FFT size. hop_size (i...
67331ddb5d6a7227120818842c61b6e07de52ba7
<|skeleton|> class SourceLoss: def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15): """Initialize source loss module. Args: fft_size (int): FFT size. hop_size (int): Hop size. win_length (int): Window length. window (str): Window function type.""" <|bo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SourceLoss: def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15): """Initialize source loss module. Args: fft_size (int): FFT size. hop_size (int): Hop size. win_length (int): Window length. window (str): Window function type.""" super(SourceLoss, ...
the_stack_v2_python_sparse
usfgan/losses/source_loss.py
hendrikTpl/UnifiedSourceFilterGAN
train
0
a0136f176b762c86bd3915de10a5ac47cac1e8cb
[ "self.schema = generic_ast_graphs.build_ast_graph_schema(self.ast_spec)\nself.edge_types = sorted({graph_edge_util.SAME_IDENTIFIER_EDGE_TYPE, *graph_edge_util.PROGRAM_GRAPH_EDGE_TYPES, *graph_edge_util.schema_edge_types(self.schema), *graph_edge_util.nth_child_edge_types(EDGE_NTH_CHILD_MAX)})\nself.builder = automa...
<|body_start_0|> self.schema = generic_ast_graphs.build_ast_graph_schema(self.ast_spec) self.edge_types = sorted({graph_edge_util.SAME_IDENTIFIER_EDGE_TYPE, *graph_edge_util.PROGRAM_GRAPH_EDGE_TYPES, *graph_edge_util.schema_edge_types(self.schema), *graph_edge_util.nth_child_edge_types(EDGE_NTH_CHILD_MA...
Keeps track of objects needed to encode and decode examples. Attributes: ast_spec: AST spec defining how to encode an AST. token_encoder: Subword encoder for encoding syntax tokens. schema: Automaton schema for the produced graphs. Generated automatically. edge_types: List of all edge types produced by the encoding. Ge...
ExampleEncodingInfo
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExampleEncodingInfo: """Keeps track of objects needed to encode and decode examples. Attributes: ast_spec: AST spec defining how to encode an AST. token_encoder: Subword encoder for encoding syntax tokens. schema: Automaton schema for the produced graphs. Generated automatically. edge_types: List...
stack_v2_sparse_classes_75kplus_train_005825
8,664
permissive
[ { "docstring": "Populates non-init fields based on `ast_spec`.", "name": "__post_init__", "signature": "def __post_init__(self)" }, { "docstring": "Builds an ExampleEncodingInfo object from files. Args: ast_spec_path: Path to a text file containing an AST spec definition. Format is expected to b...
2
stack_v2_sparse_classes_30k_train_044231
Implement the Python class `ExampleEncodingInfo` described below. Class description: Keeps track of objects needed to encode and decode examples. Attributes: ast_spec: AST spec defining how to encode an AST. token_encoder: Subword encoder for encoding syntax tokens. schema: Automaton schema for the produced graphs. Ge...
Implement the Python class `ExampleEncodingInfo` described below. Class description: Keeps track of objects needed to encode and decode examples. Attributes: ast_spec: AST spec defining how to encode an AST. token_encoder: Subword encoder for encoding syntax tokens. schema: Automaton schema for the produced graphs. Ge...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class ExampleEncodingInfo: """Keeps track of objects needed to encode and decode examples. Attributes: ast_spec: AST spec defining how to encode an AST. token_encoder: Subword encoder for encoding syntax tokens. schema: Automaton schema for the produced graphs. Generated automatically. edge_types: List...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExampleEncodingInfo: """Keeps track of objects needed to encode and decode examples. Attributes: ast_spec: AST spec defining how to encode an AST. token_encoder: Subword encoder for encoding syntax tokens. schema: Automaton schema for the produced graphs. Generated automatically. edge_types: List of all edge ...
the_stack_v2_python_sparse
gfsa/datasets/var_misuse/example_definition.py
Jimmy-INL/google-research
train
1
6c7451715302ae65863d2ecf89f0e80d2682f32d
[ "super().__init__()\nself.image = pygame.Surface([15, 15])\nself.image.fill(BLUE)\nself.rect = self.image.get_rect()\nself.rect.x = x\nself.rect.y = y\nself.change_x = 0\nself.change_y = 0", "if stop != True:\n self.change_x += w\n self.change_y += z", "self.rect.x += self.change_x\nself.rect.y += self.ch...
<|body_start_0|> super().__init__() self.image = pygame.Surface([15, 15]) self.image.fill(BLUE) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.change_x = 0 self.change_y = 0 <|end_body_0|> <|body_start_1|> if stop != True: ...
The class is the player-controlled sprite.
Player
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Player: """The class is the player-controlled sprite.""" def __init__(self, x, y): """Constructor function""" <|body_0|> def changespeed(self, w, z, stop): """Change the speed of the player""" <|body_1|> def update(self): """Find a new positi...
stack_v2_sparse_classes_75kplus_train_005826
17,606
no_license
[ { "docstring": "Constructor function", "name": "__init__", "signature": "def __init__(self, x, y)" }, { "docstring": "Change the speed of the player", "name": "changespeed", "signature": "def changespeed(self, w, z, stop)" }, { "docstring": "Find a new position for the player", ...
3
null
Implement the Python class `Player` described below. Class description: The class is the player-controlled sprite. Method signatures and docstrings: - def __init__(self, x, y): Constructor function - def changespeed(self, w, z, stop): Change the speed of the player - def update(self): Find a new position for the play...
Implement the Python class `Player` described below. Class description: The class is the player-controlled sprite. Method signatures and docstrings: - def __init__(self, x, y): Constructor function - def changespeed(self, w, z, stop): Change the speed of the player - def update(self): Find a new position for the play...
31aa808a5516e653a1e06dec53b4cb74bd820c00
<|skeleton|> class Player: """The class is the player-controlled sprite.""" def __init__(self, x, y): """Constructor function""" <|body_0|> def changespeed(self, w, z, stop): """Change the speed of the player""" <|body_1|> def update(self): """Find a new positi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Player: """The class is the player-controlled sprite.""" def __init__(self, x, y): """Constructor function""" super().__init__() self.image = pygame.Surface([15, 15]) self.image.fill(BLUE) self.rect = self.image.get_rect() self.rect.x = x self.rect....
the_stack_v2_python_sparse
Fa18_student_games/Alex Kick Return/TARIK.py
fwparkercode/IntroGames
train
0
69f503963c93393f8ae7bea02c28b2f87b025c0d
[ "super(TowLayerNet, self).__init__()\nself.linear1 = torch.nn.Linear(D_in, H)\nself.linear2 = torch.nn.Linear(H, D_out)", "h_relu = self.linear1(x).clamp(min=0)\ny_pred = self.linear2(h_relu)\nreturn y_pred" ]
<|body_start_0|> super(TowLayerNet, self).__init__() self.linear1 = torch.nn.Linear(D_in, H) self.linear2 = torch.nn.Linear(H, D_out) <|end_body_0|> <|body_start_1|> h_relu = self.linear1(x).clamp(min=0) y_pred = self.linear2(h_relu) return y_pred <|end_body_1|>
TowLayerNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TowLayerNet: def __init__(self, D_in, H, D_out): """在构造函数中,我们实例化两个nn.Linear模块并将其分配为成员变量。""" <|body_0|> def forward(self, x): """在前向函数中,我们接受输入数据的张量,并且必须返回输出数据的张量。 我们可以使用构造函数中定义的模块以及张量中的任意运算符。""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(TowL...
stack_v2_sparse_classes_75kplus_train_005827
2,467
no_license
[ { "docstring": "在构造函数中,我们实例化两个nn.Linear模块并将其分配为成员变量。", "name": "__init__", "signature": "def __init__(self, D_in, H, D_out)" }, { "docstring": "在前向函数中,我们接受输入数据的张量,并且必须返回输出数据的张量。 我们可以使用构造函数中定义的模块以及张量中的任意运算符。", "name": "forward", "signature": "def forward(self, x)" } ]
2
null
Implement the Python class `TowLayerNet` described below. Class description: Implement the TowLayerNet class. Method signatures and docstrings: - def __init__(self, D_in, H, D_out): 在构造函数中,我们实例化两个nn.Linear模块并将其分配为成员变量。 - def forward(self, x): 在前向函数中,我们接受输入数据的张量,并且必须返回输出数据的张量。 我们可以使用构造函数中定义的模块以及张量中的任意运算符。
Implement the Python class `TowLayerNet` described below. Class description: Implement the TowLayerNet class. Method signatures and docstrings: - def __init__(self, D_in, H, D_out): 在构造函数中,我们实例化两个nn.Linear模块并将其分配为成员变量。 - def forward(self, x): 在前向函数中,我们接受输入数据的张量,并且必须返回输出数据的张量。 我们可以使用构造函数中定义的模块以及张量中的任意运算符。 <|skeleton|...
e06596fad4c689a6d19ae6d82cd9ab3795ae307a
<|skeleton|> class TowLayerNet: def __init__(self, D_in, H, D_out): """在构造函数中,我们实例化两个nn.Linear模块并将其分配为成员变量。""" <|body_0|> def forward(self, x): """在前向函数中,我们接受输入数据的张量,并且必须返回输出数据的张量。 我们可以使用构造函数中定义的模块以及张量中的任意运算符。""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TowLayerNet: def __init__(self, D_in, H, D_out): """在构造函数中,我们实例化两个nn.Linear模块并将其分配为成员变量。""" super(TowLayerNet, self).__init__() self.linear1 = torch.nn.Linear(D_in, H) self.linear2 = torch.nn.Linear(H, D_out) def forward(self, x): """在前向函数中,我们接受输入数据的张量,并且必须返回输出数据的张...
the_stack_v2_python_sparse
DP_PyTorch/PyTorchTutorials/PyT1.5_5_TowLayerNet.py
SunWeiKeS/dataScience
train
0
535ad59d4610e926b0e20e227c7191559f5b5469
[ "organization = Organization.objects.get(id=id)\nserializer = AttachmentSerializer(Organization.attachments, many=True)\nreturn Response(serializer.data)", "jsonString = self.request.POST['item']\ndata = json.loads(jsonString)\nfile_name = request.FILES['file'].name\nfileData = request.FILES['file'].read()\norgan...
<|body_start_0|> organization = Organization.objects.get(id=id) serializer = AttachmentSerializer(Organization.attachments, many=True) return Response(serializer.data) <|end_body_0|> <|body_start_1|> jsonString = self.request.POST['item'] data = json.loads(jsonString) fi...
Returns attachments for a particular Organization
organizationsIdAttachmentsGet
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class organizationsIdAttachmentsGet: """Returns attachments for a particular Organization""" def get(self, request, id): """Returns attachments for a particular Fuel Supplier""" <|body_0|> def post(self, request, id): """Accepts a new file upload.""" <|body_1|>...
stack_v2_sparse_classes_75kplus_train_005828
11,433
permissive
[ { "docstring": "Returns attachments for a particular Fuel Supplier", "name": "get", "signature": "def get(self, request, id)" }, { "docstring": "Accepts a new file upload.", "name": "post", "signature": "def post(self, request, id)" } ]
2
stack_v2_sparse_classes_30k_train_014420
Implement the Python class `organizationsIdAttachmentsGet` described below. Class description: Returns attachments for a particular Organization Method signatures and docstrings: - def get(self, request, id): Returns attachments for a particular Fuel Supplier - def post(self, request, id): Accepts a new file upload.
Implement the Python class `organizationsIdAttachmentsGet` described below. Class description: Returns attachments for a particular Organization Method signatures and docstrings: - def get(self, request, id): Returns attachments for a particular Fuel Supplier - def post(self, request, id): Accepts a new file upload. ...
83e1805312d3f13c6a7235e99840b44f399c8fde
<|skeleton|> class organizationsIdAttachmentsGet: """Returns attachments for a particular Organization""" def get(self, request, id): """Returns attachments for a particular Fuel Supplier""" <|body_0|> def post(self, request, id): """Accepts a new file upload.""" <|body_1|>...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class organizationsIdAttachmentsGet: """Returns attachments for a particular Organization""" def get(self, request, id): """Returns attachments for a particular Fuel Supplier""" organization = Organization.objects.get(id=id) serializer = AttachmentSerializer(Organization.attachments, ma...
the_stack_v2_python_sparse
backend/api/views_custom.py
ActionAnalytics/tfrs
train
0
e639acd1c4c57d897078d5f1dd62f794007ca024
[ "extra = extra_context or {}\nextra['SPECTATOR_MAPS'] = app_settings.MAPS\nreturn super().add_view(request, form_url, extra_context=extra)", "extra = extra_context or {}\nextra['SPECTATOR_MAPS'] = app_settings.MAPS\nreturn super().change_view(request, object_id, form_url, extra_context=extra)" ]
<|body_start_0|> extra = extra_context or {} extra['SPECTATOR_MAPS'] = app_settings.MAPS return super().add_view(request, form_url, extra_context=extra) <|end_body_0|> <|body_start_1|> extra = extra_context or {} extra['SPECTATOR_MAPS'] = app_settings.MAPS return super()...
VenueAdmin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VenueAdmin: def add_view(self, request, form_url='', extra_context=None): """Add the SPECTATOR_MAPS setting to context. Only currently needed if we're using Mapbox, because we need to set the API key in JS in the page.""" <|body_0|> def change_view(self, request, object_id, ...
stack_v2_sparse_classes_75kplus_train_005829
7,693
permissive
[ { "docstring": "Add the SPECTATOR_MAPS setting to context. Only currently needed if we're using Mapbox, because we need to set the API key in JS in the page.", "name": "add_view", "signature": "def add_view(self, request, form_url='', extra_context=None)" }, { "docstring": "Add the SPECTATOR_MAP...
2
stack_v2_sparse_classes_30k_test_000010
Implement the Python class `VenueAdmin` described below. Class description: Implement the VenueAdmin class. Method signatures and docstrings: - def add_view(self, request, form_url='', extra_context=None): Add the SPECTATOR_MAPS setting to context. Only currently needed if we're using Mapbox, because we need to set t...
Implement the Python class `VenueAdmin` described below. Class description: Implement the VenueAdmin class. Method signatures and docstrings: - def add_view(self, request, form_url='', extra_context=None): Add the SPECTATOR_MAPS setting to context. Only currently needed if we're using Mapbox, because we need to set t...
2d89dcdb624b01452a5b6ca0ee092774fcc0aa52
<|skeleton|> class VenueAdmin: def add_view(self, request, form_url='', extra_context=None): """Add the SPECTATOR_MAPS setting to context. Only currently needed if we're using Mapbox, because we need to set the API key in JS in the page.""" <|body_0|> def change_view(self, request, object_id, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VenueAdmin: def add_view(self, request, form_url='', extra_context=None): """Add the SPECTATOR_MAPS setting to context. Only currently needed if we're using Mapbox, because we need to set the API key in JS in the page.""" extra = extra_context or {} extra['SPECTATOR_MAPS'] = app_settin...
the_stack_v2_python_sparse
spectator/events/admin.py
philgyford/django-spectator
train
45
509d14ccce49086d167a85c7e2e2c37960668e60
[ "if v and isinstance(v, dict):\n return ElasticContainerRegistryRepository.parse_obj({'repo_name': v.get('repo_name'), 'registry': ElasticContainerRegistry.parse_obj({'account_id': v.get('account_id'), 'alias': v.get('registry_alias'), 'aws_region': v.get('aws_region'), 'context': values.get('context')})})\nretu...
<|body_start_0|> if v and isinstance(v, dict): return ElasticContainerRegistryRepository.parse_obj({'repo_name': v.get('repo_name'), 'registry': ElasticContainerRegistry.parse_obj({'account_id': v.get('account_id'), 'alias': v.get('registry_alias'), 'aws_region': v.get('aws_region'), 'context': valu...
Args passed to image.push.
ImagePushArgs
[ "Apache-2.0", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImagePushArgs: """Args passed to image.push.""" def _set_ecr_repo(cls, v: Any, values: Dict[str, Any]) -> Any: """Set the value of ``ecr_repo``.""" <|body_0|> def _set_repo(cls, v: Optional[str], values: Dict[str, Any]) -> Optional[str]: """Set the value of ``rep...
stack_v2_sparse_classes_75kplus_train_005830
3,744
permissive
[ { "docstring": "Set the value of ``ecr_repo``.", "name": "_set_ecr_repo", "signature": "def _set_ecr_repo(cls, v: Any, values: Dict[str, Any]) -> Any" }, { "docstring": "Set the value of ``repo``.", "name": "_set_repo", "signature": "def _set_repo(cls, v: Optional[str], values: Dict[str,...
3
stack_v2_sparse_classes_30k_train_048942
Implement the Python class `ImagePushArgs` described below. Class description: Args passed to image.push. Method signatures and docstrings: - def _set_ecr_repo(cls, v: Any, values: Dict[str, Any]) -> Any: Set the value of ``ecr_repo``. - def _set_repo(cls, v: Optional[str], values: Dict[str, Any]) -> Optional[str]: S...
Implement the Python class `ImagePushArgs` described below. Class description: Args passed to image.push. Method signatures and docstrings: - def _set_ecr_repo(cls, v: Any, values: Dict[str, Any]) -> Any: Set the value of ``ecr_repo``. - def _set_repo(cls, v: Optional[str], values: Dict[str, Any]) -> Optional[str]: S...
0763b06aee07d2cf3f037a49ca0cb81a048c5deb
<|skeleton|> class ImagePushArgs: """Args passed to image.push.""" def _set_ecr_repo(cls, v: Any, values: Dict[str, Any]) -> Any: """Set the value of ``ecr_repo``.""" <|body_0|> def _set_repo(cls, v: Optional[str], values: Dict[str, Any]) -> Optional[str]: """Set the value of ``rep...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ImagePushArgs: """Args passed to image.push.""" def _set_ecr_repo(cls, v: Any, values: Dict[str, Any]) -> Any: """Set the value of ``ecr_repo``.""" if v and isinstance(v, dict): return ElasticContainerRegistryRepository.parse_obj({'repo_name': v.get('repo_name'), 'registry': E...
the_stack_v2_python_sparse
runway/cfngin/hooks/docker/image/_push.py
onicagroup/runway
train
156
907caa2a83650a1a70c7d3873e5cb5114f5cc913
[ "self.tasks = tasks\nself.task_validation = task_validation\nself.settings = EmmetBuildSettings.autoload(settings)\nself.query = query\nself.kwargs = kwargs\nself.potcar_hashes = potcar_hashes\nif self.settings.VASP_VALIDATE_POTCAR_HASHES:\n if not self.potcar_hashes:\n from pymatgen.io.vasp.inputs import...
<|body_start_0|> self.tasks = tasks self.task_validation = task_validation self.settings = EmmetBuildSettings.autoload(settings) self.query = query self.kwargs = kwargs self.potcar_hashes = potcar_hashes if self.settings.VASP_VALIDATE_POTCAR_HASHES: if...
TaskValidator
[ "LicenseRef-scancode-hdf5", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskValidator: def __init__(self, tasks: Store, task_validation: Store, potcar_hashes: Optional[Dict[CalcType, Dict[str, str]]]=None, settings: Optional[EmmetBuildSettings]=None, query: Optional[Dict]=None, **kwargs): """Creates task_types from tasks and type definitions Args: tasks: Sto...
stack_v2_sparse_classes_75kplus_train_005831
3,600
permissive
[ { "docstring": "Creates task_types from tasks and type definitions Args: tasks: Store of task documents task_validation: Store of task_types for tasks potcar_hashes: Optional dictionary of potcar hash data. Mapping is calculation type -> potcar symbol -> hash value.", "name": "__init__", "signature": "d...
2
stack_v2_sparse_classes_30k_train_022774
Implement the Python class `TaskValidator` described below. Class description: Implement the TaskValidator class. Method signatures and docstrings: - def __init__(self, tasks: Store, task_validation: Store, potcar_hashes: Optional[Dict[CalcType, Dict[str, str]]]=None, settings: Optional[EmmetBuildSettings]=None, quer...
Implement the Python class `TaskValidator` described below. Class description: Implement the TaskValidator class. Method signatures and docstrings: - def __init__(self, tasks: Store, task_validation: Store, potcar_hashes: Optional[Dict[CalcType, Dict[str, str]]]=None, settings: Optional[EmmetBuildSettings]=None, quer...
90e121d5cf1b6b57a33233c927e1044c59354bc5
<|skeleton|> class TaskValidator: def __init__(self, tasks: Store, task_validation: Store, potcar_hashes: Optional[Dict[CalcType, Dict[str, str]]]=None, settings: Optional[EmmetBuildSettings]=None, query: Optional[Dict]=None, **kwargs): """Creates task_types from tasks and type definitions Args: tasks: Sto...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TaskValidator: def __init__(self, tasks: Store, task_validation: Store, potcar_hashes: Optional[Dict[CalcType, Dict[str, str]]]=None, settings: Optional[EmmetBuildSettings]=None, query: Optional[Dict]=None, **kwargs): """Creates task_types from tasks and type definitions Args: tasks: Store of task doc...
the_stack_v2_python_sparse
emmet-builders/emmet/builders/vasp/task_validator.py
materialsproject/emmet
train
37
af119c70a07694a998762cdd6329b3fe73841182
[ "self.text = text\nself.th = th\nself.attrs = attrs", "if not self.th:\n return ' <td%s>%s</td>\\n' % (attrs2str(self.attrs), self.text)\nelse:\n return ' <th%s>%s</th>\\n' % (attrs2str(self.attrs), self.text)" ]
<|body_start_0|> self.text = text self.th = th self.attrs = attrs <|end_body_0|> <|body_start_1|> if not self.th: return ' <td%s>%s</td>\n' % (attrs2str(self.attrs), self.text) else: return ' <th%s>%s</th>\n' % (attrs2str(self.attrs), self.text) <|end...
Предназначен для хранения информации об одной ячейке, даже несуществующей.
TableCell
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TableCell: """Предназначен для хранения информации об одной ячейке, даже несуществующей.""" def __init__(self, text='&nbsp;', th=False, attrs={}): """Инициализирует объект ячейки таблицы. Аргументы: text - содержимое ячейки, по умолчанию неразрывный пробел; th - Отрисовывать с помощь...
stack_v2_sparse_classes_75kplus_train_005832
9,419
no_license
[ { "docstring": "Инициализирует объект ячейки таблицы. Аргументы: text - содержимое ячейки, по умолчанию неразрывный пробел; th - Отрисовывать с помощью тега th; attrs - атрибуты, выводимые непосредственно в теге <td>/<th>,", "name": "__init__", "signature": "def __init__(self, text='&nbsp;', th=False, a...
2
stack_v2_sparse_classes_30k_train_054553
Implement the Python class `TableCell` described below. Class description: Предназначен для хранения информации об одной ячейке, даже несуществующей. Method signatures and docstrings: - def __init__(self, text='&nbsp;', th=False, attrs={}): Инициализирует объект ячейки таблицы. Аргументы: text - содержимое ячейки, по...
Implement the Python class `TableCell` described below. Class description: Предназначен для хранения информации об одной ячейке, даже несуществующей. Method signatures and docstrings: - def __init__(self, text='&nbsp;', th=False, attrs={}): Инициализирует объект ячейки таблицы. Аргументы: text - содержимое ячейки, по...
5f0af16ba2727faceb6b7e1b98073cd7d3c60d4c
<|skeleton|> class TableCell: """Предназначен для хранения информации об одной ячейке, даже несуществующей.""" def __init__(self, text='&nbsp;', th=False, attrs={}): """Инициализирует объект ячейки таблицы. Аргументы: text - содержимое ячейки, по умолчанию неразрывный пробел; th - Отрисовывать с помощь...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TableCell: """Предназначен для хранения информации об одной ячейке, даже несуществующей.""" def __init__(self, text='&nbsp;', th=False, attrs={}): """Инициализирует объект ячейки таблицы. Аргументы: text - содержимое ячейки, по умолчанию неразрывный пробел; th - Отрисовывать с помощью тега th; at...
the_stack_v2_python_sparse
src/lib/Table.py
andbar-ru/traceyourself.appspot.com
train
1
68f103121e26adb536b71f8abe698682ec4a691a
[ "self.event_type = event_type\nself.sources = sources\nif not isinstance(mc_info, list):\n mc_info = [mc_info]\nself.mc_info = mc_info", "if isinstance(other, MCRecord):\n new_ev_type = self.event_type + other.event_type\n new_src = self.sources + other.sources\n new_mcinfo = self.mc_info + other.mc_i...
<|body_start_0|> self.event_type = event_type self.sources = sources if not isinstance(mc_info, list): mc_info = [mc_info] self.mc_info = mc_info <|end_body_0|> <|body_start_1|> if isinstance(other, MCRecord): new_ev_type = self.event_type + other.event_t...
Stores MC Truth information. Properties: event_type: str sources: List[PhotonSource_] List of photon sources mc_info: List[Dict[str, Any]] List of dictionaries containing MCTruth information.
MCRecord
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MCRecord: """Stores MC Truth information. Properties: event_type: str sources: List[PhotonSource_] List of photon sources mc_info: List[Dict[str, Any]] List of dictionaries containing MCTruth information.""" def __init__(self, event_type, sources, mc_info): """Initialize MCRecord."""...
stack_v2_sparse_classes_75kplus_train_005833
972
no_license
[ { "docstring": "Initialize MCRecord.", "name": "__init__", "signature": "def __init__(self, event_type, sources, mc_info)" }, { "docstring": "Combine two MCRecords.", "name": "__add__", "signature": "def __add__(self, other)" } ]
2
stack_v2_sparse_classes_30k_train_053312
Implement the Python class `MCRecord` described below. Class description: Stores MC Truth information. Properties: event_type: str sources: List[PhotonSource_] List of photon sources mc_info: List[Dict[str, Any]] List of dictionaries containing MCTruth information. Method signatures and docstrings: - def __init__(sel...
Implement the Python class `MCRecord` described below. Class description: Stores MC Truth information. Properties: event_type: str sources: List[PhotonSource_] List of photon sources mc_info: List[Dict[str, Any]] List of dictionaries containing MCTruth information. Method signatures and docstrings: - def __init__(sel...
24f847a1ab9bfe3b1bafe1a19569f13fede7f2f6
<|skeleton|> class MCRecord: """Stores MC Truth information. Properties: event_type: str sources: List[PhotonSource_] List of photon sources mc_info: List[Dict[str, Any]] List of dictionaries containing MCTruth information.""" def __init__(self, event_type, sources, mc_info): """Initialize MCRecord."""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MCRecord: """Stores MC Truth information. Properties: event_type: str sources: List[PhotonSource_] List of photon sources mc_info: List[Dict[str, Any]] List of dictionaries containing MCTruth information.""" def __init__(self, event_type, sources, mc_info): """Initialize MCRecord.""" self...
the_stack_v2_python_sparse
gnn_testbed/event_generation/mc_record.py
chrhck/gnn_testbed
train
0
de644062d2e674f73e7c3865a69f4e5449092fc9
[ "self.coresys: CoreSys = coresys\nself.repositories: Dict[str, Any] = {}\nself.addons: Dict[str, Any] = {}", "self.repositories.clear()\nself.addons.clear()\nself._read_addons_folder(self.sys_config.path_addons_core, REPOSITORY_CORE)\nself._read_addons_folder(self.sys_config.path_addons_local, REPOSITORY_LOCAL)\n...
<|body_start_0|> self.coresys: CoreSys = coresys self.repositories: Dict[str, Any] = {} self.addons: Dict[str, Any] = {} <|end_body_0|> <|body_start_1|> self.repositories.clear() self.addons.clear() self._read_addons_folder(self.sys_config.path_addons_core, REPOSITORY_CO...
Hold data for Add-ons inside Supervisor.
StoreData
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StoreData: """Hold data for Add-ons inside Supervisor.""" def __init__(self, coresys: CoreSys): """Initialize data holder.""" <|body_0|> def update(self): """Read data from add-on repository.""" <|body_1|> def _read_git_repository(self, path): ...
stack_v2_sparse_classes_75kplus_train_005834
3,860
permissive
[ { "docstring": "Initialize data holder.", "name": "__init__", "signature": "def __init__(self, coresys: CoreSys)" }, { "docstring": "Read data from add-on repository.", "name": "update", "signature": "def update(self)" }, { "docstring": "Process a custom repository folder.", ...
5
stack_v2_sparse_classes_30k_train_036080
Implement the Python class `StoreData` described below. Class description: Hold data for Add-ons inside Supervisor. Method signatures and docstrings: - def __init__(self, coresys: CoreSys): Initialize data holder. - def update(self): Read data from add-on repository. - def _read_git_repository(self, path): Process a ...
Implement the Python class `StoreData` described below. Class description: Hold data for Add-ons inside Supervisor. Method signatures and docstrings: - def __init__(self, coresys: CoreSys): Initialize data holder. - def update(self): Read data from add-on repository. - def _read_git_repository(self, path): Process a ...
d62aabc01be312417969ce177e080d5147e32749
<|skeleton|> class StoreData: """Hold data for Add-ons inside Supervisor.""" def __init__(self, coresys: CoreSys): """Initialize data holder.""" <|body_0|> def update(self): """Read data from add-on repository.""" <|body_1|> def _read_git_repository(self, path): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StoreData: """Hold data for Add-ons inside Supervisor.""" def __init__(self, coresys: CoreSys): """Initialize data holder.""" self.coresys: CoreSys = coresys self.repositories: Dict[str, Any] = {} self.addons: Dict[str, Any] = {} def update(self): """Read data...
the_stack_v2_python_sparse
supervisor/store/data.py
mories76/supervisor
train
24
1eb3edc4948f2d7a8a2f7bf6908311519bb30962
[ "super().__init__()\nself.image_uri_key = image_uri_key\nself.image_good_counter = Metrics.counter(self.__class__, 'image_good')\nself.image_bad_counter = Metrics.counter(self.__class__, 'image_bad')", "d = {}\ntry:\n image_uri = element.pop(self.image_uri_key)\n image = load(image_uri)\n element['image_...
<|body_start_0|> super().__init__() self.image_uri_key = image_uri_key self.image_good_counter = Metrics.counter(self.__class__, 'image_good') self.image_bad_counter = Metrics.counter(self.__class__, 'image_bad') <|end_body_0|> <|body_start_1|> d = {} try: im...
Adds image to PCollection.
ExtractImagesDoFn
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExtractImagesDoFn: """Adds image to PCollection.""" def __init__(self, image_uri_key: str): """Constructor.""" <|body_0|> def process(self, element: Dict[str, Any], *args: Tuple[Any, ...], **kwargs: Dict) -> Generator[Dict[str, Any], None, None]: """Loads image a...
stack_v2_sparse_classes_75kplus_train_005835
3,408
permissive
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self, image_uri_key: str)" }, { "docstring": "Loads image and creates image features. This DoFn extracts an image being stored on local disk or GCS and yields a base64 encoded image, the image height, image width, and ...
2
stack_v2_sparse_classes_30k_train_002635
Implement the Python class `ExtractImagesDoFn` described below. Class description: Adds image to PCollection. Method signatures and docstrings: - def __init__(self, image_uri_key: str): Constructor. - def process(self, element: Dict[str, Any], *args: Tuple[Any, ...], **kwargs: Dict) -> Generator[Dict[str, Any], None,...
Implement the Python class `ExtractImagesDoFn` described below. Class description: Adds image to PCollection. Method signatures and docstrings: - def __init__(self, image_uri_key: str): Constructor. - def process(self, element: Dict[str, Any], *args: Tuple[Any, ...], **kwargs: Dict) -> Generator[Dict[str, Any], None,...
80f421ef53778ad2dc793d344d079ab4a814687a
<|skeleton|> class ExtractImagesDoFn: """Adds image to PCollection.""" def __init__(self, image_uri_key: str): """Constructor.""" <|body_0|> def process(self, element: Dict[str, Any], *args: Tuple[Any, ...], **kwargs: Dict) -> Generator[Dict[str, Any], None, None]: """Loads image a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExtractImagesDoFn: """Adds image to PCollection.""" def __init__(self, image_uri_key: str): """Constructor.""" super().__init__() self.image_uri_key = image_uri_key self.image_good_counter = Metrics.counter(self.__class__, 'image_good') self.image_bad_counter = Met...
the_stack_v2_python_sparse
tfrecorder/beam_image.py
jared-burns/tensorflow-recorder
train
0
b2d09fd9c253f55b159d990cdc611ad436947beb
[ "super().__init__()\nself._op = op\nself._param_sampler = RandBool(probability=probability)", "apply = self._param_sampler.sample()\nsample_dict[op_id] = apply\nif apply:\n sample_dict = op_call(self._op, sample_dict, f'{op_id}.apply', **kwargs)\nreturn sample_dict", "apply = sample_dict[op_id]\nif apply:\n ...
<|body_start_0|> super().__init__() self._op = op self._param_sampler = RandBool(probability=probability) <|end_body_0|> <|body_start_1|> apply = self._param_sampler.sample() sample_dict[op_id] = apply if apply: sample_dict = op_call(self._op, sample_dict, f'...
OpRandApply
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OpRandApply: def __init__(self, op: OpBase, probability: float): """Randomly apply the op (according to the given probability) :param op: op""" <|body_0|> def __call__(self, sample_dict: NDict, op_id: Optional[str], **kwargs: dict) -> Union[None, dict, List[dict]]: "...
stack_v2_sparse_classes_75kplus_train_005836
6,356
permissive
[ { "docstring": "Randomly apply the op (according to the given probability) :param op: op", "name": "__init__", "signature": "def __init__(self, op: OpBase, probability: float)" }, { "docstring": "See super class", "name": "__call__", "signature": "def __call__(self, sample_dict: NDict, o...
3
stack_v2_sparse_classes_30k_train_033467
Implement the Python class `OpRandApply` described below. Class description: Implement the OpRandApply class. Method signatures and docstrings: - def __init__(self, op: OpBase, probability: float): Randomly apply the op (according to the given probability) :param op: op - def __call__(self, sample_dict: NDict, op_id:...
Implement the Python class `OpRandApply` described below. Class description: Implement the OpRandApply class. Method signatures and docstrings: - def __init__(self, op: OpBase, probability: float): Randomly apply the op (according to the given probability) :param op: op - def __call__(self, sample_dict: NDict, op_id:...
8f22cd46c836245b9394b73ce2957afc03706bfc
<|skeleton|> class OpRandApply: def __init__(self, op: OpBase, probability: float): """Randomly apply the op (according to the given probability) :param op: op""" <|body_0|> def __call__(self, sample_dict: NDict, op_id: Optional[str], **kwargs: dict) -> Union[None, dict, List[dict]]: "...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OpRandApply: def __init__(self, op: OpBase, probability: float): """Randomly apply the op (according to the given probability) :param op: op""" super().__init__() self._op = op self._param_sampler = RandBool(probability=probability) def __call__(self, sample_dict: NDict, o...
the_stack_v2_python_sparse
fuse/data/ops/ops_aug_common.py
BiomedSciAI/fuse-med-ml
train
45
512fa7d7c5fe95444ef6b8b6d2eae9f9aea660cf
[ "assert not kwargs, kwargs\nattributes = AttributesHelper(self, attributes)\nif not attributes.iswildcard:\n warnings.warn(UnsupportedSelectiveCommunitySetConfig, 'IOS-XR does not support selective community-set configuration.')\n attributes = AttributesHelper(self)\nconfigurations = CliConfigBuilder()\nif Fa...
<|body_start_0|> assert not kwargs, kwargs attributes = AttributesHelper(self, attributes) if not attributes.iswildcard: warnings.warn(UnsupportedSelectiveCommunitySetConfig, 'IOS-XR does not support selective community-set configuration.') attributes = AttributesHelper(s...
DeviceAttributes
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeviceAttributes: def build_config(self, apply=True, attributes=None, **kwargs): """IOS-XR CommunitySet configuration. Note: Selective configuration is not supported on IOS-XR; The whole community-set is always removed and re-configured.""" <|body_0|> def build_unconfig(self...
stack_v2_sparse_classes_75kplus_train_005837
7,073
permissive
[ { "docstring": "IOS-XR CommunitySet configuration. Note: Selective configuration is not supported on IOS-XR; The whole community-set is always removed and re-configured.", "name": "build_config", "signature": "def build_config(self, apply=True, attributes=None, **kwargs)" }, { "docstring": "IOS-...
2
stack_v2_sparse_classes_30k_train_041108
Implement the Python class `DeviceAttributes` described below. Class description: Implement the DeviceAttributes class. Method signatures and docstrings: - def build_config(self, apply=True, attributes=None, **kwargs): IOS-XR CommunitySet configuration. Note: Selective configuration is not supported on IOS-XR; The wh...
Implement the Python class `DeviceAttributes` described below. Class description: Implement the DeviceAttributes class. Method signatures and docstrings: - def build_config(self, apply=True, attributes=None, **kwargs): IOS-XR CommunitySet configuration. Note: Selective configuration is not supported on IOS-XR; The wh...
e42e51475cddcb10f5c7814d0fe892ac865742ba
<|skeleton|> class DeviceAttributes: def build_config(self, apply=True, attributes=None, **kwargs): """IOS-XR CommunitySet configuration. Note: Selective configuration is not supported on IOS-XR; The whole community-set is always removed and re-configured.""" <|body_0|> def build_unconfig(self...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DeviceAttributes: def build_config(self, apply=True, attributes=None, **kwargs): """IOS-XR CommunitySet configuration. Note: Selective configuration is not supported on IOS-XR; The whole community-set is always removed and re-configured.""" assert not kwargs, kwargs attributes = Attrib...
the_stack_v2_python_sparse
pkgs/conf-pkg/src/genie/libs/conf/community_set/iosxr/community_set.py
CiscoTestAutomation/genielibs
train
109
15ed22f7fffd066270fb8d0534cc859287a9c769
[ "super().__init__(x, y)\nself.fill_color = QtCore.Qt.black\nself.line_color = QtCore.Qt.black\nself.center_x = self.x\nself.center_y = self.y\nself.time = random.randint(0, 360)\nself.radius = random.randint(64, 128)", "self.time += 1\nself.x = math.sin(math.radians(self.time)) * self.radius + self.center_x\nself...
<|body_start_0|> super().__init__(x, y) self.fill_color = QtCore.Qt.black self.line_color = QtCore.Qt.black self.center_x = self.x self.center_y = self.y self.time = random.randint(0, 360) self.radius = random.randint(64, 128) <|end_body_0|> <|body_start_1|> ...
Class to represent a Vulture.
Vulture
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Vulture: """Class to represent a Vulture.""" def __init__(self, x, y): """Create a new Vulture 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): """...
stack_v2_sparse_classes_75kplus_train_005838
13,878
no_license
[ { "docstring": "Create a new Vulture 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 Vulture flies in a circle centered around it's ...
2
stack_v2_sparse_classes_30k_train_021031
Implement the Python class `Vulture` described below. Class description: Class to represent a Vulture. Method signatures and docstrings: - def __init__(self, x, y): Create a new Vulture 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. - d...
Implement the Python class `Vulture` described below. Class description: Class to represent a Vulture. Method signatures and docstrings: - def __init__(self, x, y): Create a new Vulture 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. - d...
0e3470085083012f893adb22aa46d46039016965
<|skeleton|> class Vulture: """Class to represent a Vulture.""" def __init__(self, x, y): """Create a new Vulture 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): """...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Vulture: """Class to represent a Vulture.""" def __init__(self, x, y): """Create a new Vulture 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.bla...
the_stack_v2_python_sparse
CS_210 (Introduction to Programming)/Labs/Lab34_AviaryApp.py
JacobOrner/USAFA
train
0
a5b717474c93ac5edfe8beaa1ea73d7598f7737d
[ "if not id:\n return Response(json='ID not found', status=404)\ntry:\n portfolio = Portfolio.one(request=request, pk=id)\nexcept (DataError, AttributeError):\n return Response(json='Not Found', status=404)\nschema = PortfolioSchema()\ndata = schema.dump(portfolio).data\nreturn Response(json=data, status=20...
<|body_start_0|> if not id: return Response(json='ID not found', status=404) try: portfolio = Portfolio.one(request=request, pk=id) except (DataError, AttributeError): return Response(json='Not Found', status=404) schema = PortfolioSchema() dat...
CRUD class for portfolio
PortfolioAPIView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PortfolioAPIView: """CRUD class for portfolio""" def retrieve(self, request, id=None): """Getting a single portfolio""" <|body_0|> def create(self, request): """Posting a new portfolio""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not id: ...
stack_v2_sparse_classes_75kplus_train_005839
4,737
no_license
[ { "docstring": "Getting a single portfolio", "name": "retrieve", "signature": "def retrieve(self, request, id=None)" }, { "docstring": "Posting a new portfolio", "name": "create", "signature": "def create(self, request)" } ]
2
null
Implement the Python class `PortfolioAPIView` described below. Class description: CRUD class for portfolio Method signatures and docstrings: - def retrieve(self, request, id=None): Getting a single portfolio - def create(self, request): Posting a new portfolio
Implement the Python class `PortfolioAPIView` described below. Class description: CRUD class for portfolio Method signatures and docstrings: - def retrieve(self, request, id=None): Getting a single portfolio - def create(self, request): Posting a new portfolio <|skeleton|> class PortfolioAPIView: """CRUD class f...
6d018c849baca593d78ca08e3bf4222e860cd4b3
<|skeleton|> class PortfolioAPIView: """CRUD class for portfolio""" def retrieve(self, request, id=None): """Getting a single portfolio""" <|body_0|> def create(self, request): """Posting a new portfolio""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PortfolioAPIView: """CRUD class for portfolio""" def retrieve(self, request, id=None): """Getting a single portfolio""" if not id: return Response(json='ID not found', status=404) try: portfolio = Portfolio.one(request=request, pk=id) except (DataEr...
the_stack_v2_python_sparse
stocks_api/views/portfolio.py
AndrewBaik/stocks_api
train
0
abe6bc443e3c794542712adef4130caad60a009b
[ "Box2D.b2.rayCastCallback.__init__(self)\nself.agent_mask_filter = agent_mask_filter\nself.fixture = None", "if fixture.filterData.categoryBits & self.agent_mask_filter == 0:\n return -1\nself.p2 = point\nself.fraction = fraction\nreturn fraction" ]
<|body_start_0|> Box2D.b2.rayCastCallback.__init__(self) self.agent_mask_filter = agent_mask_filter self.fixture = None <|end_body_0|> <|body_start_1|> if fixture.filterData.categoryBits & self.agent_mask_filter == 0: return -1 self.p2 = point self.fraction =...
Callback function triggered when lidar detects an object.
LidarCallback
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LidarCallback: """Callback function triggered when lidar detects an object.""" def __init__(self, agent_mask_filter): """Args: agent_mask_filter: Mask filter used to avoid detecting collisions with the agent's body""" <|body_0|> def ReportFixture(self, fixture, point, no...
stack_v2_sparse_classes_75kplus_train_005840
23,651
permissive
[ { "docstring": "Args: agent_mask_filter: Mask filter used to avoid detecting collisions with the agent's body", "name": "__init__", "signature": "def __init__(self, agent_mask_filter)" }, { "docstring": "Triggered when a body is detected by the lidar. Returns: Distance to object detected.", ...
2
stack_v2_sparse_classes_30k_train_021240
Implement the Python class `LidarCallback` described below. Class description: Callback function triggered when lidar detects an object. Method signatures and docstrings: - def __init__(self, agent_mask_filter): Args: agent_mask_filter: Mask filter used to avoid detecting collisions with the agent's body - def Report...
Implement the Python class `LidarCallback` described below. Class description: Callback function triggered when lidar detects an object. Method signatures and docstrings: - def __init__(self, agent_mask_filter): Args: agent_mask_filter: Mask filter used to avoid detecting collisions with the agent's body - def Report...
6c157511a609e84596c4f8aad99e7576a015ee15
<|skeleton|> class LidarCallback: """Callback function triggered when lidar detects an object.""" def __init__(self, agent_mask_filter): """Args: agent_mask_filter: Mask filter used to avoid detecting collisions with the agent's body""" <|body_0|> def ReportFixture(self, fixture, point, no...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LidarCallback: """Callback function triggered when lidar detects an object.""" def __init__(self, agent_mask_filter): """Args: agent_mask_filter: Mask filter used to avoid detecting collisions with the agent's body""" Box2D.b2.rayCastCallback.__init__(self) self.agent_mask_filter ...
the_stack_v2_python_sparse
TeachMyAgent/environments/envs/parametric_continuous_stump_tracks.py
flowersteam/TeachMyAgent
train
70
fb7e236b28634dc11f3d015dab398e6661adb1b0
[ "if n < 3:\n return 0\nprimes = [True] * n\nprimes[0] = primes[1] = False\nfor i in range(2, int(n ** 0.5) + 1):\n if primes[i]:\n primes[i * i:n:i] = [False] * len(primes[i * i:n:i])\nreturn sum(primes)", "if n < 3:\n return 0\nprimes = [True] * n\nprimes[0] = primes[1] = False\nfor i in range(2,...
<|body_start_0|> if n < 3: return 0 primes = [True] * n primes[0] = primes[1] = False for i in range(2, int(n ** 0.5) + 1): if primes[i]: primes[i * i:n:i] = [False] * len(primes[i * i:n:i]) return sum(primes) <|end_body_0|> <|body_start_1...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countPrimes(self, n): """:type n: int :rtype: int https://leetcode.com/problems/count-primes/discuss/57595/ primes[i * i: n: i] = [False] * len(primes[i * i: n: i]) let's assume n == 100, we need to count all the primes which are less than 100: when i == 2: It will mark out...
stack_v2_sparse_classes_75kplus_train_005841
1,863
no_license
[ { "docstring": ":type n: int :rtype: int https://leetcode.com/problems/count-primes/discuss/57595/ primes[i * i: n: i] = [False] * len(primes[i * i: n: i]) let's assume n == 100, we need to count all the primes which are less than 100: when i == 2: It will mark out the numbers as none-prime: 4: 100 : 2 -> 4,6,8...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countPrimes(self, n): :type n: int :rtype: int https://leetcode.com/problems/count-primes/discuss/57595/ primes[i * i: n: i] = [False] * len(primes[i * i: n: i]) let's assume...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countPrimes(self, n): :type n: int :rtype: int https://leetcode.com/problems/count-primes/discuss/57595/ primes[i * i: n: i] = [False] * len(primes[i * i: n: i]) let's assume...
7e0e917c15d3e35f49da3a00ef395bd5ff180d79
<|skeleton|> class Solution: def countPrimes(self, n): """:type n: int :rtype: int https://leetcode.com/problems/count-primes/discuss/57595/ primes[i * i: n: i] = [False] * len(primes[i * i: n: i]) let's assume n == 100, we need to count all the primes which are less than 100: when i == 2: It will mark out...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def countPrimes(self, n): """:type n: int :rtype: int https://leetcode.com/problems/count-primes/discuss/57595/ primes[i * i: n: i] = [False] * len(primes[i * i: n: i]) let's assume n == 100, we need to count all the primes which are less than 100: when i == 2: It will mark out the numbers a...
the_stack_v2_python_sparse
LeetCode/204_count_primes.py
yao23/Machine_Learning_Playground
train
12
5c13d84db54c5a8fc3f5179bdfb30c203a2f5c91
[ "nums.sort()\nif len(nums) < 3:\n return None\nres = nums[0] + nums[1] + nums[2]\nfor i in xrange(len(nums) - 2):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n l, r = (i + 1, len(nums) - 1)\n while l < r:\n value = nums[i] + nums[l] + nums[r]\n offset = abs(value - target)\n ...
<|body_start_0|> nums.sort() if len(nums) < 3: return None res = nums[0] + nums[1] + nums[2] for i in xrange(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue l, r = (i + 1, len(nums) - 1) while l < r: ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def threeSumClosest(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_0|> def threeSumClosest_v1(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_75kplus_train_005842
2,983
permissive
[ { "docstring": ":type nums: List[int] :type target: int :rtype: int", "name": "threeSumClosest", "signature": "def threeSumClosest(self, nums, target)" }, { "docstring": ":type nums: List[int] :type target: int :rtype: int", "name": "threeSumClosest_v1", "signature": "def threeSumClosest...
2
stack_v2_sparse_classes_30k_train_032299
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def threeSumClosest(self, nums, target): :type nums: List[int] :type target: int :rtype: int - def threeSumClosest_v1(self, nums, target): :type nums: List[int] :type target: int...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def threeSumClosest(self, nums, target): :type nums: List[int] :type target: int :rtype: int - def threeSumClosest_v1(self, nums, target): :type nums: List[int] :type target: int...
05420b73d28220681cd7be8253bebcaa83966954
<|skeleton|> class Solution: def threeSumClosest(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_0|> def threeSumClosest_v1(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def threeSumClosest(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" nums.sort() if len(nums) < 3: return None res = nums[0] + nums[1] + nums[2] for i in xrange(len(nums) - 2): if i > 0 and nums[i] == nums[...
the_stack_v2_python_sparse
3sum-closest/test.py
optionalg/challenges-leetcode-interesting
train
0
50b52f41d7ecbd3781a4daa10041b5cc8448e97f
[ "super(KNNClassifier, self).__init__(**kwargs)\nself.model = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm='brute', metric='precomputed')\nself.use_model = True\nself.model_out = None", "if len(np.unique(y)) == 1:\n self.use_model = False\n self.model_out = list(np.unique(y))[0]\nelse:\n...
<|body_start_0|> super(KNNClassifier, self).__init__(**kwargs) self.model = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm='brute', metric='precomputed') self.use_model = True self.model_out = None <|end_body_0|> <|body_start_1|> if len(np.unique(y)) == 1: ...
KNNClassifier
KNNClassifier
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KNNClassifier: """KNNClassifier""" def __init__(self, n_neighbors: int, **kwargs): """__init__. Args: n_neighbors (int): Number of neighbors kwargs: kwargs""" <|body_0|> def fit(self, X, y, **kwargs): """fit. For this model, make sure that X is a pairwise distanc...
stack_v2_sparse_classes_75kplus_train_005843
12,286
no_license
[ { "docstring": "__init__. Args: n_neighbors (int): Number of neighbors kwargs: kwargs", "name": "__init__", "signature": "def __init__(self, n_neighbors: int, **kwargs)" }, { "docstring": "fit. For this model, make sure that X is a pairwise distance matrix in the fit loop Args: X: X y: y kwargs:...
3
stack_v2_sparse_classes_30k_train_052948
Implement the Python class `KNNClassifier` described below. Class description: KNNClassifier Method signatures and docstrings: - def __init__(self, n_neighbors: int, **kwargs): __init__. Args: n_neighbors (int): Number of neighbors kwargs: kwargs - def fit(self, X, y, **kwargs): fit. For this model, make sure that X ...
Implement the Python class `KNNClassifier` described below. Class description: KNNClassifier Method signatures and docstrings: - def __init__(self, n_neighbors: int, **kwargs): __init__. Args: n_neighbors (int): Number of neighbors kwargs: kwargs - def fit(self, X, y, **kwargs): fit. For this model, make sure that X ...
84c9026c78bec9a2267960a87080b71beba5c305
<|skeleton|> class KNNClassifier: """KNNClassifier""" def __init__(self, n_neighbors: int, **kwargs): """__init__. Args: n_neighbors (int): Number of neighbors kwargs: kwargs""" <|body_0|> def fit(self, X, y, **kwargs): """fit. For this model, make sure that X is a pairwise distanc...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KNNClassifier: """KNNClassifier""" def __init__(self, n_neighbors: int, **kwargs): """__init__. Args: n_neighbors (int): Number of neighbors kwargs: kwargs""" super(KNNClassifier, self).__init__(**kwargs) self.model = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorit...
the_stack_v2_python_sparse
enzpred/models/sklearn_models.py
liudongliangHI/enz-pred
train
0
2710effbac552ef12ecfc8ad7d45104b25f771a6
[ "self.drizzle_params = drizzle_params.copy()\nself.mult_drizzle_par = mult_drizzle_par.copy()\nself.cont_info = cont_info\nself.opt_extr = opt_extr\nself.back = back\nif drztmp_dir != None:\n self.drztmp_dir = drztmp_dir\nelse:\n self.drztmp_dir = axeutils.getDRZTMP()\nif drizzle_dir != None:\n self.drizzl...
<|body_start_0|> self.drizzle_params = drizzle_params.copy() self.mult_drizzle_par = mult_drizzle_par.copy() self.cont_info = cont_info self.opt_extr = opt_extr self.back = back if drztmp_dir != None: self.drztmp_dir = drztmp_dir else: self...
List class for all objects to be drizzled
MulDrzObjList
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MulDrzObjList: """List class for all objects to be drizzled""" def __init__(self, drizzle_params, mult_drizzle_par, cont_info=None, opt_extr=False, back=False, drztmp_dir=None, drizzle_dir=None): """Initializes the class""" <|body_0|> def _objlist_to_drzobjects(self, obj...
stack_v2_sparse_classes_75kplus_train_005844
10,632
permissive
[ { "docstring": "Initializes the class", "name": "__init__", "signature": "def __init__(self, drizzle_params, mult_drizzle_par, cont_info=None, opt_extr=False, back=False, drztmp_dir=None, drizzle_dir=None)" }, { "docstring": "Converts the object list into drizzle objects", "name": "_objlist_...
4
stack_v2_sparse_classes_30k_train_051124
Implement the Python class `MulDrzObjList` described below. Class description: List class for all objects to be drizzled Method signatures and docstrings: - def __init__(self, drizzle_params, mult_drizzle_par, cont_info=None, opt_extr=False, back=False, drztmp_dir=None, drizzle_dir=None): Initializes the class - def ...
Implement the Python class `MulDrzObjList` described below. Class description: List class for all objects to be drizzled Method signatures and docstrings: - def __init__(self, drizzle_params, mult_drizzle_par, cont_info=None, opt_extr=False, back=False, drztmp_dir=None, drizzle_dir=None): Initializes the class - def ...
043c173fd5497c18c2b1bfe8bcff65180bca3996
<|skeleton|> class MulDrzObjList: """List class for all objects to be drizzled""" def __init__(self, drizzle_params, mult_drizzle_par, cont_info=None, opt_extr=False, back=False, drztmp_dir=None, drizzle_dir=None): """Initializes the class""" <|body_0|> def _objlist_to_drzobjects(self, obj...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MulDrzObjList: """List class for all objects to be drizzled""" def __init__(self, drizzle_params, mult_drizzle_par, cont_info=None, opt_extr=False, back=False, drztmp_dir=None, drizzle_dir=None): """Initializes the class""" self.drizzle_params = drizzle_params.copy() self.mult_dri...
the_stack_v2_python_sparse
stsdas/pkg/analysis/slitless/axe/axesrc/mdrzobjects.py
spacetelescope/stsdas_stripped
train
1
e7fb8a32158117a6c4ec4170d28107c8dd2d2034
[ "self.log.debug(\"Submitting Inference request for model '%s' with '%s' objects and top_n '%s' \", model_name, len(objects), top_n)\nendpoint = InferencePaths.format_inference_endpoint_by_name(model_name)\nresponse = self.session.post_to_endpoint(endpoint, payload={'topN': top_n, 'objects': objects}, retry=retry)\n...
<|body_start_0|> self.log.debug("Submitting Inference request for model '%s' with '%s' objects and top_n '%s' ", model_name, len(objects), top_n) endpoint = InferencePaths.format_inference_endpoint_by_name(model_name) response = self.session.post_to_endpoint(endpoint, payload={'topN': top_n, 'ob...
A client for the DAR Inference microservice. This class implements all basic API calls as well as some convenience methods which wrap individual API calls. If the API call fails, all methods will raise an :exc:`DARHTTPException`.
InferenceClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InferenceClient: """A client for the DAR Inference microservice. This class implements all basic API calls as well as some convenience methods which wrap individual API calls. If the API call fails, all methods will raise an :exc:`DARHTTPException`.""" def create_inference_request(self, mode...
stack_v2_sparse_classes_75kplus_train_005845
9,582
permissive
[ { "docstring": "Performs inference for the given *objects* with *model_name*. For each object in *objects*, returns the *topN* best predictions. The *retry* parameter determines whether to retry on HTTP errors indicated by the remote API endpoint or for other connection problems. See :ref:`retry` for trade-offs...
3
stack_v2_sparse_classes_30k_test_000565
Implement the Python class `InferenceClient` described below. Class description: A client for the DAR Inference microservice. This class implements all basic API calls as well as some convenience methods which wrap individual API calls. If the API call fails, all methods will raise an :exc:`DARHTTPException`. Method ...
Implement the Python class `InferenceClient` described below. Class description: A client for the DAR Inference microservice. This class implements all basic API calls as well as some convenience methods which wrap individual API calls. If the API call fails, all methods will raise an :exc:`DARHTTPException`. Method ...
445131264e81b5d98ca4b74690e467eb276a22df
<|skeleton|> class InferenceClient: """A client for the DAR Inference microservice. This class implements all basic API calls as well as some convenience methods which wrap individual API calls. If the API call fails, all methods will raise an :exc:`DARHTTPException`.""" def create_inference_request(self, mode...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class InferenceClient: """A client for the DAR Inference microservice. This class implements all basic API calls as well as some convenience methods which wrap individual API calls. If the API call fails, all methods will raise an :exc:`DARHTTPException`.""" def create_inference_request(self, model_name: str, ...
the_stack_v2_python_sparse
sap/aibus/dar/client/inference_client.py
SAP/data-attribute-recommendation-python-sdk
train
13
6145367d89190aac19d6fc0b35bf12eca8e6707c
[ "name = 'DavisBirner'\nsuper(STJDavisBirner, self).__init__(name=name, props=props, data=data)\nself.upper_p_level = self.props['upper_p_level']\nself.lower_p_level = self.props['lower_p_level']\nself.surf_p_level = self.props['surface_p_level']\nif self.data[self.data.cfg['lev']].units in ['mb', 'millibars', 'hPa'...
<|body_start_0|> name = 'DavisBirner' super(STJDavisBirner, self).__init__(name=name, props=props, data=data) self.upper_p_level = self.props['upper_p_level'] self.lower_p_level = self.props['lower_p_level'] self.surf_p_level = self.props['surface_p_level'] if self.data[s...
Subtropical jet position metric using the method of Davis and Birner 2016. Parameters ---------- props : :py:meth:`~STJ_PV.run_stj.JetFindRun` Class containing properties about the current search for the STJ data : :py:meth:`~STJ_PV.input_data.InputData` Input data class containing a year (or more) of required data Not...
STJDavisBirner
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class STJDavisBirner: """Subtropical jet position metric using the method of Davis and Birner 2016. Parameters ---------- props : :py:meth:`~STJ_PV.run_stj.JetFindRun` Class containing properties about the current search for the STJ data : :py:meth:`~STJ_PV.input_data.InputData` Input data class contai...
stack_v2_sparse_classes_75kplus_train_005846
34,635
no_license
[ { "docstring": "Initialise Metric using Davis and Birner 2016 method.", "name": "__init__", "signature": "def __init__(self, props, data)" }, { "docstring": "Find the subtropical jet using method from Davis and Birner (2016). doi:10.1175/JCLI-D-15-0336.1 Parameters ---------- shemis : logical, o...
4
stack_v2_sparse_classes_30k_train_002565
Implement the Python class `STJDavisBirner` described below. Class description: Subtropical jet position metric using the method of Davis and Birner 2016. Parameters ---------- props : :py:meth:`~STJ_PV.run_stj.JetFindRun` Class containing properties about the current search for the STJ data : :py:meth:`~STJ_PV.input_...
Implement the Python class `STJDavisBirner` described below. Class description: Subtropical jet position metric using the method of Davis and Birner 2016. Parameters ---------- props : :py:meth:`~STJ_PV.run_stj.JetFindRun` Class containing properties about the current search for the STJ data : :py:meth:`~STJ_PV.input_...
092dc88fab708084a3136a1c1c08153ea6157721
<|skeleton|> class STJDavisBirner: """Subtropical jet position metric using the method of Davis and Birner 2016. Parameters ---------- props : :py:meth:`~STJ_PV.run_stj.JetFindRun` Class containing properties about the current search for the STJ data : :py:meth:`~STJ_PV.input_data.InputData` Input data class contai...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class STJDavisBirner: """Subtropical jet position metric using the method of Davis and Birner 2016. Parameters ---------- props : :py:meth:`~STJ_PV.run_stj.JetFindRun` Class containing properties about the current search for the STJ data : :py:meth:`~STJ_PV.input_data.InputData` Input data class containing a year (...
the_stack_v2_python_sparse
STJ_PV/stj_metric.py
LMXB/stj_pv
train
0
cb3dae7c167d323c9070b34391adb5b90d5fe68c
[ "loaded = models.TimeSlot.load(uid)\nif loaded is None:\n abort(404)\nreturn loaded", "loaded = models.TimeSlot.load(uid)\nif loaded is None:\n return ('', 404)\nloaded.delete()\nreturn ('', 204)", "data = request.json\nstart = parse(data['start'])\nend = parse(data['end'])\nduration = end - start\ncapaci...
<|body_start_0|> loaded = models.TimeSlot.load(uid) if loaded is None: abort(404) return loaded <|end_body_0|> <|body_start_1|> loaded = models.TimeSlot.load(uid) if loaded is None: return ('', 404) loaded.delete() return ('', 204) <|end_b...
Operations related to the management of a single timeslot.
Timeslot
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Timeslot: """Operations related to the management of a single timeslot.""" def get(self, uid): """Get a particular timeslot""" <|body_0|> def delete(self, uid): """Delete a particular timeslot""" <|body_1|> def put(self, uid): """Updates all ...
stack_v2_sparse_classes_75kplus_train_005847
6,359
no_license
[ { "docstring": "Get a particular timeslot", "name": "get", "signature": "def get(self, uid)" }, { "docstring": "Delete a particular timeslot", "name": "delete", "signature": "def delete(self, uid)" }, { "docstring": "Updates all non-readonly fields of a timeslot", "name": "pu...
4
stack_v2_sparse_classes_30k_train_034918
Implement the Python class `Timeslot` described below. Class description: Operations related to the management of a single timeslot. Method signatures and docstrings: - def get(self, uid): Get a particular timeslot - def delete(self, uid): Delete a particular timeslot - def put(self, uid): Updates all non-readonly fi...
Implement the Python class `Timeslot` described below. Class description: Operations related to the management of a single timeslot. Method signatures and docstrings: - def get(self, uid): Get a particular timeslot - def delete(self, uid): Delete a particular timeslot - def put(self, uid): Updates all non-readonly fi...
ab874354e94e789fbea090f29e507fca2223284d
<|skeleton|> class Timeslot: """Operations related to the management of a single timeslot.""" def get(self, uid): """Get a particular timeslot""" <|body_0|> def delete(self, uid): """Delete a particular timeslot""" <|body_1|> def put(self, uid): """Updates all ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Timeslot: """Operations related to the management of a single timeslot.""" def get(self, uid): """Get a particular timeslot""" loaded = models.TimeSlot.load(uid) if loaded is None: abort(404) return loaded def delete(self, uid): """Delete a particu...
the_stack_v2_python_sparse
app/apis/timeslot_api.py
TheWinch/flask-tuto
train
0
0048e1501de9b748b7effbd9f61339aa8d7aceec
[ "num_dic = {}\nfor num in nums:\n if num in num_dic:\n num_dic[num] += 1\n else:\n num_dic[num] = 1\nfor key in num_dic.keys():\n if num_dic[key] >= len(nums) / 2:\n return key\nreturn -1", "majority, count = (0, 0)\nfor num in nums:\n if count == 0:\n majority = num\n ...
<|body_start_0|> num_dic = {} for num in nums: if num in num_dic: num_dic[num] += 1 else: num_dic[num] = 1 for key in num_dic.keys(): if num_dic[key] >= len(nums) / 2: return key return -1 <|end_body_0|> ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def majority_element(self, nums: List[int]) -> int: """大多数元素 Args: nums: 数组 Returns: 元素""" <|body_0|> def majority_element2(self, nums: List[int]) -> int: """大多数元素 Args: nums: 数组 Returns: 元素""" <|body_1|> def majority_element3(self, nums: List[...
stack_v2_sparse_classes_75kplus_train_005848
3,141
permissive
[ { "docstring": "大多数元素 Args: nums: 数组 Returns: 元素", "name": "majority_element", "signature": "def majority_element(self, nums: List[int]) -> int" }, { "docstring": "大多数元素 Args: nums: 数组 Returns: 元素", "name": "majority_element2", "signature": "def majority_element2(self, nums: List[int]) -...
4
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def majority_element(self, nums: List[int]) -> int: 大多数元素 Args: nums: 数组 Returns: 元素 - def majority_element2(self, nums: List[int]) -> int: 大多数元素 Args: nums: 数组 Returns: 元素 - def...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def majority_element(self, nums: List[int]) -> int: 大多数元素 Args: nums: 数组 Returns: 元素 - def majority_element2(self, nums: List[int]) -> int: 大多数元素 Args: nums: 数组 Returns: 元素 - def...
50f35eef6a0ad63173efed10df3c835b1dceaa3f
<|skeleton|> class Solution: def majority_element(self, nums: List[int]) -> int: """大多数元素 Args: nums: 数组 Returns: 元素""" <|body_0|> def majority_element2(self, nums: List[int]) -> int: """大多数元素 Args: nums: 数组 Returns: 元素""" <|body_1|> def majority_element3(self, nums: List[...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def majority_element(self, nums: List[int]) -> int: """大多数元素 Args: nums: 数组 Returns: 元素""" num_dic = {} for num in nums: if num in num_dic: num_dic[num] += 1 else: num_dic[num] = 1 for key in num_dic.keys(): ...
the_stack_v2_python_sparse
src/leetcodepython/array/majority_element_169.py
zhangyu345293721/leetcode
train
101
653175143676eb16895c0e12bf6e9ef0ce704a82
[ "self.name = name\nself.end = end\nself.start = start", "if self.start <= other.start < self.end:\n return True\nelif self.start <= other.end < self.end:\n return True\nelse:\n return False" ]
<|body_start_0|> self.name = name self.end = end self.start = start <|end_body_0|> <|body_start_1|> if self.start <= other.start < self.end: return True elif self.start <= other.end < self.end: return True else: return False <|end_body...
Appointment
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Appointment: def __init__(self, name, start, end): """Initializes the name, end,and start.""" <|body_0|> def overlaps(self, other): """Checks for overlaps by using the start and end times using another appointment onject named other. Returns a boolean of true or fals...
stack_v2_sparse_classes_75kplus_train_005849
657
no_license
[ { "docstring": "Initializes the name, end,and start.", "name": "__init__", "signature": "def __init__(self, name, start, end)" }, { "docstring": "Checks for overlaps by using the start and end times using another appointment onject named other. Returns a boolean of true or false depending on the...
2
stack_v2_sparse_classes_30k_train_037785
Implement the Python class `Appointment` described below. Class description: Implement the Appointment class. Method signatures and docstrings: - def __init__(self, name, start, end): Initializes the name, end,and start. - def overlaps(self, other): Checks for overlaps by using the start and end times using another a...
Implement the Python class `Appointment` described below. Class description: Implement the Appointment class. Method signatures and docstrings: - def __init__(self, name, start, end): Initializes the name, end,and start. - def overlaps(self, other): Checks for overlaps by using the start and end times using another a...
45c8c29b99ed619a8a4318bf22e645399dba8e57
<|skeleton|> class Appointment: def __init__(self, name, start, end): """Initializes the name, end,and start.""" <|body_0|> def overlaps(self, other): """Checks for overlaps by using the start and end times using another appointment onject named other. Returns a boolean of true or fals...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Appointment: def __init__(self, name, start, end): """Initializes the name, end,and start.""" self.name = name self.end = end self.start = start def overlaps(self, other): """Checks for overlaps by using the start and end times using another appointment onject name...
the_stack_v2_python_sparse
Appointment/appointment.py
shima3434/Introductory_Python_Projects
train
0
b616952a6a8b0366211dcad6c25aefc5b2390fa1
[ "p, node = (head, None)\nwhile p:\n tmp = ListNode(p.val)\n tmp.next = node\n node = tmp\n p = p.next\nreturn node", "if not head or not head.next:\n return head\na = head\nb = head.next\na.next = None\nwhile a and b:\n n = a\n a = b\n b = b.next\n a.next = n\nreturn a" ]
<|body_start_0|> p, node = (head, None) while p: tmp = ListNode(p.val) tmp.next = node node = tmp p = p.next return node <|end_body_0|> <|body_start_1|> if not head or not head.next: return head a = head b = hea...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseList_1(self, head: ListNode) -> ListNode: """time: O(N), space: O(N) input 바꾸지 않고 새롭게 노드를 생성 iterative""" <|body_0|> def reverseList_2(self, head: ListNode) -> ListNode: """time: O(N), space: O(1) in place iterative""" <|body_1|> <|end_s...
stack_v2_sparse_classes_75kplus_train_005850
886
no_license
[ { "docstring": "time: O(N), space: O(N) input 바꾸지 않고 새롭게 노드를 생성 iterative", "name": "reverseList_1", "signature": "def reverseList_1(self, head: ListNode) -> ListNode" }, { "docstring": "time: O(N), space: O(1) in place iterative", "name": "reverseList_2", "signature": "def reverseList_2...
2
stack_v2_sparse_classes_30k_train_000712
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList_1(self, head: ListNode) -> ListNode: time: O(N), space: O(N) input 바꾸지 않고 새롭게 노드를 생성 iterative - def reverseList_2(self, head: ListNode) -> ListNode: time: O(N), ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList_1(self, head: ListNode) -> ListNode: time: O(N), space: O(N) input 바꾸지 않고 새롭게 노드를 생성 iterative - def reverseList_2(self, head: ListNode) -> ListNode: time: O(N), ...
8f90a33abf451f2490f1d8d9993b64d60ef0bed0
<|skeleton|> class Solution: def reverseList_1(self, head: ListNode) -> ListNode: """time: O(N), space: O(N) input 바꾸지 않고 새롭게 노드를 생성 iterative""" <|body_0|> def reverseList_2(self, head: ListNode) -> ListNode: """time: O(N), space: O(1) in place iterative""" <|body_1|> <|end_s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def reverseList_1(self, head: ListNode) -> ListNode: """time: O(N), space: O(N) input 바꾸지 않고 새롭게 노드를 생성 iterative""" p, node = (head, None) while p: tmp = ListNode(p.val) tmp.next = node node = tmp p = p.next return node...
the_stack_v2_python_sparse
leetcode/leetcode_0206_Reverse_Linked_List.py
YunjinPark/algorithms
train
0
7ca337d1a0185b1e7015242c1cce698e9f0330b1
[ "try:\n numberString = float(numberString)\n numberString = int(numberString)\nexcept ValueError:\n pass\nreturn numberString", "if os.path.isfile(inputFile) == False:\n print('Invalid file path')\n return 0\nelse:\n with open(inputFile) as f:\n if ignoreHeader:\n next(f)\n ...
<|body_start_0|> try: numberString = float(numberString) numberString = int(numberString) except ValueError: pass return numberString <|end_body_0|> <|body_start_1|> if os.path.isfile(inputFile) == False: print('Invalid file path') ...
This is InputHandler class responsible for reading inputs to the program
InputHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InputHandler: """This is InputHandler class responsible for reading inputs to the program""" def convertToInteger(self, numberString): """This function checks if input is number and if yes then convert it into integer. :param numberString: Number string to convert into integer :retur...
stack_v2_sparse_classes_75kplus_train_005851
2,549
no_license
[ { "docstring": "This function checks if input is number and if yes then convert it into integer. :param numberString: Number string to convert into integer :return: Converted integer if string is digit else the same string", "name": "convertToInteger", "signature": "def convertToInteger(self, numberStri...
3
stack_v2_sparse_classes_30k_train_024759
Implement the Python class `InputHandler` described below. Class description: This is InputHandler class responsible for reading inputs to the program Method signatures and docstrings: - def convertToInteger(self, numberString): This function checks if input is number and if yes then convert it into integer. :param n...
Implement the Python class `InputHandler` described below. Class description: This is InputHandler class responsible for reading inputs to the program Method signatures and docstrings: - def convertToInteger(self, numberString): This function checks if input is number and if yes then convert it into integer. :param n...
e67a831f92335e725d1c495e7d67401d1b30ed1e
<|skeleton|> class InputHandler: """This is InputHandler class responsible for reading inputs to the program""" def convertToInteger(self, numberString): """This function checks if input is number and if yes then convert it into integer. :param numberString: Number string to convert into integer :retur...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class InputHandler: """This is InputHandler class responsible for reading inputs to the program""" def convertToInteger(self, numberString): """This function checks if input is number and if yes then convert it into integer. :param numberString: Number string to convert into integer :return: Converted ...
the_stack_v2_python_sparse
DecisionTree/InputHandler.py
anwarsk/DecisionTree
train
0
3d2d66b9de56ef158bb2106e3d821648d502f901
[ "if version is None:\n return False\nif self.min_version is not None:\n if version < self.min_version:\n return False\nif self.max_version is not None:\n if version > self.max_version:\n return False\nreturn True", "if sql is None:\n return []\ndatabase = conninfo['dbname']\noutput = []\...
<|body_start_0|> if version is None: return False if self.min_version is not None: if version < self.min_version: return False if self.max_version is not None: if version > self.max_version: return False return True <|en...
postgres probe base class
SqlProbe
[ "PostgreSQL" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SqlProbe: """postgres probe base class""" def check(self, version=None): """Check if the plugin can run on the target version of PostgreSQL.""" <|body_0|> def run_sql(self, conn, conninfo, sql): """Get the result of the SQL query""" <|body_1|> def ru...
stack_v2_sparse_classes_75kplus_train_005852
30,100
permissive
[ { "docstring": "Check if the plugin can run on the target version of PostgreSQL.", "name": "check", "signature": "def check(self, version=None)" }, { "docstring": "Get the result of the SQL query", "name": "run_sql", "signature": "def run_sql(self, conn, conninfo, sql)" }, { "doc...
3
stack_v2_sparse_classes_30k_train_021689
Implement the Python class `SqlProbe` described below. Class description: postgres probe base class Method signatures and docstrings: - def check(self, version=None): Check if the plugin can run on the target version of PostgreSQL. - def run_sql(self, conn, conninfo, sql): Get the result of the SQL query - def run(se...
Implement the Python class `SqlProbe` described below. Class description: postgres probe base class Method signatures and docstrings: - def check(self, version=None): Check if the plugin can run on the target version of PostgreSQL. - def run_sql(self, conn, conninfo, sql): Get the result of the SQL query - def run(se...
d26cb848f4b064e05d5e422ecc001889f224bd74
<|skeleton|> class SqlProbe: """postgres probe base class""" def check(self, version=None): """Check if the plugin can run on the target version of PostgreSQL.""" <|body_0|> def run_sql(self, conn, conninfo, sql): """Get the result of the SQL query""" <|body_1|> def ru...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SqlProbe: """postgres probe base class""" def check(self, version=None): """Check if the plugin can run on the target version of PostgreSQL.""" if version is None: return False if self.min_version is not None: if version < self.min_version: ...
the_stack_v2_python_sparse
agent/temboardagent/plugins/monitoring/probes.py
dalibo/temboard
train
400
9f617bdbb01cb79f5218632d75c858a4626b2b4a
[ "for op in self.operations:\n if op.name == op_name:\n return op\nraise KeyError('Operation with name %s was not found in dataClay class %s' % (op_name, self.name))", "if not hasattr(self, '_implementation_id_to_operation_cache'):\n setattr(self, '_implementation_id_to_operation_cache', LRU(50))\ntry...
<|body_start_0|> for op in self.operations: if op.name == op_name: return op raise KeyError('Operation with name %s was not found in dataClay class %s' % (op_name, self.name)) <|end_body_0|> <|body_start_1|> if not hasattr(self, '_implementation_id_to_operation_cache...
MetaClass
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetaClass: def get_operation_from_name(self, op_name): """Return the operation from its name.""" <|body_0|> def get_operation(self, implementation_id): """Return an Operation (management object) from an ImplementationID :param uuid.UUID implementation_id: The request...
stack_v2_sparse_classes_75kplus_train_005853
5,420
permissive
[ { "docstring": "Return the operation from its name.", "name": "get_operation_from_name", "signature": "def get_operation_from_name(self, op_name)" }, { "docstring": "Return an Operation (management object) from an ImplementationID :param uuid.UUID implementation_id: The requested ImplementationI...
3
stack_v2_sparse_classes_30k_train_018875
Implement the Python class `MetaClass` described below. Class description: Implement the MetaClass class. Method signatures and docstrings: - def get_operation_from_name(self, op_name): Return the operation from its name. - def get_operation(self, implementation_id): Return an Operation (management object) from an Im...
Implement the Python class `MetaClass` described below. Class description: Implement the MetaClass class. Method signatures and docstrings: - def get_operation_from_name(self, op_name): Return the operation from its name. - def get_operation(self, implementation_id): Return an Operation (management object) from an Im...
33df8fa9fff5c42bad6c2c772c8ee60a3d07dcbb
<|skeleton|> class MetaClass: def get_operation_from_name(self, op_name): """Return the operation from its name.""" <|body_0|> def get_operation(self, implementation_id): """Return an Operation (management object) from an ImplementationID :param uuid.UUID implementation_id: The request...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MetaClass: def get_operation_from_name(self, op_name): """Return the operation from its name.""" for op in self.operations: if op.name == op_name: return op raise KeyError('Operation with name %s was not found in dataClay class %s' % (op_name, self.name)) ...
the_stack_v2_python_sparse
src/dataclay/util/management/classmgr/MetaClass.py
bsc-dom/pyclay
train
3
69266f372ee307b9cb8178aecd307b8555366b44
[ "objreader = ObjReader.ObjReader()\ndatlist = [['1'], ['1', '2'], ['1', '2', '3'], ['1', '', '3'], ['1', '2', ''], ['1', '', '']]\nanslist = [[True, False, False], [True, True, False], [True, True, True], [True, False, True], [True, True, False], [True, False, False]]\nn = len(datlist)\ni = 0\nwhile i < n:\n ite...
<|body_start_0|> objreader = ObjReader.ObjReader() datlist = [['1'], ['1', '2'], ['1', '2', '3'], ['1', '', '3'], ['1', '2', ''], ['1', '', '']] anslist = [[True, False, False], [True, True, False], [True, True, True], [True, False, True], [True, True, False], [True, False, False]] n = l...
test for obj file reader
TestObjReader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestObjReader: """test for obj file reader""" def test_objreader_unit0(self): """objreader test 0""" <|body_0|> def test_objreader_sample0(self): """objreader sample0""" <|body_1|> def test_objreader_sample2(self): """objreader sample2""" ...
stack_v2_sparse_classes_75kplus_train_005854
2,131
no_license
[ { "docstring": "objreader test 0", "name": "test_objreader_unit0", "signature": "def test_objreader_unit0(self)" }, { "docstring": "objreader sample0", "name": "test_objreader_sample0", "signature": "def test_objreader_sample0(self)" }, { "docstring": "objreader sample2", "na...
3
stack_v2_sparse_classes_30k_train_018495
Implement the Python class `TestObjReader` described below. Class description: test for obj file reader Method signatures and docstrings: - def test_objreader_unit0(self): objreader test 0 - def test_objreader_sample0(self): objreader sample0 - def test_objreader_sample2(self): objreader sample2
Implement the Python class `TestObjReader` described below. Class description: test for obj file reader Method signatures and docstrings: - def test_objreader_unit0(self): objreader test 0 - def test_objreader_sample0(self): objreader sample0 - def test_objreader_sample2(self): objreader sample2 <|skeleton|> class T...
f163b6b9e15100d223ddf4e180727a2b63fbae2d
<|skeleton|> class TestObjReader: """test for obj file reader""" def test_objreader_unit0(self): """objreader test 0""" <|body_0|> def test_objreader_sample0(self): """objreader sample0""" <|body_1|> def test_objreader_sample2(self): """objreader sample2""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestObjReader: """test for obj file reader""" def test_objreader_unit0(self): """objreader test 0""" objreader = ObjReader.ObjReader() datlist = [['1'], ['1', '2'], ['1', '2', '3'], ['1', '', '3'], ['1', '2', ''], ['1', '', '']] anslist = [[True, False, False], [True, True...
the_stack_v2_python_sparse
ifgi/scene/test_ObjReader.py
yamauchih/ifgi-path-tracer
train
0
d6d013ecf9167030c28e20f045494d47640981d2
[ "n = len(nums)\nans = 0\nfor i in range(n):\n prod = 1\n for j in range(i, n):\n prod *= nums[j]\n if prod >= k:\n continue\n else:\n ans += 1\nreturn ans", "if k <= 1:\n return 0\nn = len(nums)\nl = 0\nprod = 1\nans = 0\nfor r in range(n):\n prod *= nums[r]\...
<|body_start_0|> n = len(nums) ans = 0 for i in range(n): prod = 1 for j in range(i, n): prod *= nums[j] if prod >= k: continue else: ans += 1 return ans <|end_body_0|> <|body...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: """Brute Force, Time: O(n^2), Space: O(1)""" <|body_0|> def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: """Sliding Window, Time: O(n), Space: O(1)""" <|bod...
stack_v2_sparse_classes_75kplus_train_005855
1,521
no_license
[ { "docstring": "Brute Force, Time: O(n^2), Space: O(1)", "name": "numSubarrayProductLessThanK", "signature": "def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int" }, { "docstring": "Sliding Window, Time: O(n), Space: O(1)", "name": "numSubarrayProductLessThanK", "signat...
2
stack_v2_sparse_classes_30k_train_004555
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: Brute Force, Time: O(n^2), Space: O(1) - def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: Brute Force, Time: O(n^2), Space: O(1) - def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> ...
72136e3487d239f5b37e2d6393e034262a6bf599
<|skeleton|> class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: """Brute Force, Time: O(n^2), Space: O(1)""" <|body_0|> def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: """Sliding Window, Time: O(n), Space: O(1)""" <|bod...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: """Brute Force, Time: O(n^2), Space: O(1)""" n = len(nums) ans = 0 for i in range(n): prod = 1 for j in range(i, n): prod *= nums[j] if prod ...
the_stack_v2_python_sparse
python/713-Subarray Product Less Than K.py
cwza/leetcode
train
0
35eb14f18f7d14b130427e4c9492aa8f7a77a4b4
[ "pows = np.array(pows)\nnx = len(pows)\nmaxpow = np.max(pows)\nif np.any(pows < 0):\n raise ValueError('All elements of pows must be non-negative integers.')\nsuper().__init__(self._monomial, nf=1, nx=nx, maxderiv=None, zlevel=maxpow)\nself.pows = pows\nreturn", "nd, nvar = dfun.ndnvar(deriv, var, self.nx)\nif...
<|body_start_0|> pows = np.array(pows) nx = len(pows) maxpow = np.max(pows) if np.any(pows < 0): raise ValueError('All elements of pows must be non-negative integers.') super().__init__(self._monomial, nf=1, nx=nx, maxderiv=None, zlevel=maxpow) self.pows = pow...
The monominal in multiple variables
Monomial
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Monomial: """The monominal in multiple variables""" def __init__(self, pows): """Parameters ---------- pows : array_like A list of non-negative integer exponents.""" <|body_0|> def _monomial(self, X, deriv=0, out=None, var=None): """evaluation function""" ...
stack_v2_sparse_classes_75kplus_train_005856
39,055
permissive
[ { "docstring": "Parameters ---------- pows : array_like A list of non-negative integer exponents.", "name": "__init__", "signature": "def __init__(self, pows)" }, { "docstring": "evaluation function", "name": "_monomial", "signature": "def _monomial(self, X, deriv=0, out=None, var=None)"...
2
stack_v2_sparse_classes_30k_train_049466
Implement the Python class `Monomial` described below. Class description: The monominal in multiple variables Method signatures and docstrings: - def __init__(self, pows): Parameters ---------- pows : array_like A list of non-negative integer exponents. - def _monomial(self, X, deriv=0, out=None, var=None): evaluatio...
Implement the Python class `Monomial` described below. Class description: The monominal in multiple variables Method signatures and docstrings: - def __init__(self, pows): Parameters ---------- pows : array_like A list of non-negative integer exponents. - def _monomial(self, X, deriv=0, out=None, var=None): evaluatio...
c6341a58331deef3728cc43c627c556139deb673
<|skeleton|> class Monomial: """The monominal in multiple variables""" def __init__(self, pows): """Parameters ---------- pows : array_like A list of non-negative integer exponents.""" <|body_0|> def _monomial(self, X, deriv=0, out=None, var=None): """evaluation function""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Monomial: """The monominal in multiple variables""" def __init__(self, pows): """Parameters ---------- pows : array_like A list of non-negative integer exponents.""" pows = np.array(pows) nx = len(pows) maxpow = np.max(pows) if np.any(pows < 0): raise V...
the_stack_v2_python_sparse
nitrogen/special.py
bchangala/nitrogen
train
11
03d7ef71403e445c77fc720711810bb338f93751
[ "self.mask = np.copy(mask)\nself.masked_vol = np.copy(vol)\nself.masked_vol[self.mask == 0] = 0", "min_intensity = np.float64(np.min(self.masked_vol[self.masked_vol != 0]))\nmax_intensity = np.max(self.masked_vol)\nw1 = np.copy(self.masked_vol)\nw1 = (w1 - min_intensity) / (max_intensity - min_intensity)\nw1[w1 <...
<|body_start_0|> self.mask = np.copy(mask) self.masked_vol = np.copy(vol) self.masked_vol[self.mask == 0] = 0 <|end_body_0|> <|body_start_1|> min_intensity = np.float64(np.min(self.masked_vol[self.masked_vol != 0])) max_intensity = np.max(self.masked_vol) w1 = np.copy(se...
vertices
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class vertices: def __init__(self, mask, vol): """Constructor""" <|body_0|> def compute_w1(self): """Compute W1 for vertex weight computation""" <|body_1|> def compute_w2(self): """Compute W2 for vertex weight computation; Distance from boundaries.""" ...
stack_v2_sparse_classes_75kplus_train_005857
8,906
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, mask, vol)" }, { "docstring": "Compute W1 for vertex weight computation", "name": "compute_w1", "signature": "def compute_w1(self)" }, { "docstring": "Compute W2 for vertex weight computation; Dist...
5
stack_v2_sparse_classes_30k_train_015466
Implement the Python class `vertices` described below. Class description: Implement the vertices class. Method signatures and docstrings: - def __init__(self, mask, vol): Constructor - def compute_w1(self): Compute W1 for vertex weight computation - def compute_w2(self): Compute W2 for vertex weight computation; Dist...
Implement the Python class `vertices` described below. Class description: Implement the vertices class. Method signatures and docstrings: - def __init__(self, mask, vol): Constructor - def compute_w1(self): Compute W1 for vertex weight computation - def compute_w2(self): Compute W2 for vertex weight computation; Dist...
f966200d09d03a75ff9f56ab5c08b03b7bc3aadb
<|skeleton|> class vertices: def __init__(self, mask, vol): """Constructor""" <|body_0|> def compute_w1(self): """Compute W1 for vertex weight computation""" <|body_1|> def compute_w2(self): """Compute W2 for vertex weight computation; Distance from boundaries.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class vertices: def __init__(self, mask, vol): """Constructor""" self.mask = np.copy(mask) self.masked_vol = np.copy(vol) self.masked_vol[self.mask == 0] = 0 def compute_w1(self): """Compute W1 for vertex weight computation""" min_intensity = np.float64(np.min(se...
the_stack_v2_python_sparse
src/jupyter/kkarbasi/cobalt_tractography/cobalt_tractography/tractography.py
neurodata-cobalt/cobalt
train
0
54c6c231c648e443008bc18d68c301b635f4b6e6
[ "self.training_path = kwargs.get('train_data_path')\nself.predict_path = kwargs.get('predict_data_path')\nself.output_path = kwargs.get('output_path')", "training_dataset = load_fn(self.training_path)\nprediction_dataset = load_fn(self.predict_path)\nmodel = train_fn(training_dataset, **options)\npredictions = so...
<|body_start_0|> self.training_path = kwargs.get('train_data_path') self.predict_path = kwargs.get('predict_data_path') self.output_path = kwargs.get('output_path') <|end_body_0|> <|body_start_1|> training_dataset = load_fn(self.training_path) prediction_dataset = load_fn(self.p...
Generic model class for fitting a recommendation model.
Model
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Model: """Generic model class for fitting a recommendation model.""" def __init__(self, **kwargs): """Initialize a Model object.""" <|body_0|> def train(self, load_fn, train_fn, predict_fn, store_fn, **options): """Given the functions indicated below, load the tr...
stack_v2_sparse_classes_75kplus_train_005858
8,553
permissive
[ { "docstring": "Initialize a Model object.", "name": "__init__", "signature": "def __init__(self, **kwargs)" }, { "docstring": "Given the functions indicated below, load the training and prediction datasets, train with the training dataset and predict the values for the prediction dataset. Write...
2
stack_v2_sparse_classes_30k_train_026634
Implement the Python class `Model` described below. Class description: Generic model class for fitting a recommendation model. Method signatures and docstrings: - def __init__(self, **kwargs): Initialize a Model object. - def train(self, load_fn, train_fn, predict_fn, store_fn, **options): Given the functions indicat...
Implement the Python class `Model` described below. Class description: Generic model class for fitting a recommendation model. Method signatures and docstrings: - def __init__(self, **kwargs): Initialize a Model object. - def train(self, load_fn, train_fn, predict_fn, store_fn, **options): Given the functions indicat...
5e0c9efe3405245119bf5aa9bd81a4ca5159eab1
<|skeleton|> class Model: """Generic model class for fitting a recommendation model.""" def __init__(self, **kwargs): """Initialize a Model object.""" <|body_0|> def train(self, load_fn, train_fn, predict_fn, store_fn, **options): """Given the functions indicated below, load the tr...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Model: """Generic model class for fitting a recommendation model.""" def __init__(self, **kwargs): """Initialize a Model object.""" self.training_path = kwargs.get('train_data_path') self.predict_path = kwargs.get('predict_data_path') self.output_path = kwargs.get('output_...
the_stack_v2_python_sparse
project2/src/train.py
errikos/ml-makarona
train
0
a211f98408db22db80974db7affa69d671d0ca0e
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Invitation()", "from .entity import Entity\nfrom .invited_user_message_info import InvitedUserMessageInfo\nfrom .user import User\nfrom .entity import Entity\nfrom .invited_user_message_info import InvitedUserMessageInfo\nfrom .user im...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return Invitation() <|end_body_0|> <|body_start_1|> from .entity import Entity from .invited_user_message_info import InvitedUserMessageInfo from .user import User from .entity ...
Invitation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Invitation: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Invitation: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Invi...
stack_v2_sparse_classes_75kplus_train_005859
6,140
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Invitation", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value(pa...
3
null
Implement the Python class `Invitation` described below. Class description: Implement the Invitation class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Invitation: Creates a new instance of the appropriate class based on discriminator value Args: pa...
Implement the Python class `Invitation` described below. Class description: Implement the Invitation class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Invitation: Creates a new instance of the appropriate class based on discriminator value Args: pa...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class Invitation: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Invitation: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Invi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Invitation: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Invitation: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Invitation""" ...
the_stack_v2_python_sparse
msgraph/generated/models/invitation.py
microsoftgraph/msgraph-sdk-python
train
135
080f763229dc6df2d2a54807ffab2b120f726c4e
[ "super(PointWiseFeedForward, self).__init__()\nself.conv1 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1)\nself.dropout1 = torch.nn.Dropout(p=dropout_rate)\nself.relu = torch.nn.ReLU()\nself.conv2 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1)\nself.dropout2 = torch.nn.Dropout(p=dropout_r...
<|body_start_0|> super(PointWiseFeedForward, self).__init__() self.conv1 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1) self.dropout1 = torch.nn.Dropout(p=dropout_rate) self.relu = torch.nn.ReLU() self.conv2 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=...
PointWise forward Module. Args: torch ([type]): [description]
PointWiseFeedForward
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PointWiseFeedForward: """PointWise forward Module. Args: torch ([type]): [description]""" def __init__(self, hidden_units, dropout_rate): """Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate.""" <|body_0|> def for...
stack_v2_sparse_classes_75kplus_train_005860
15,823
permissive
[ { "docstring": "Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate.", "name": "__init__", "signature": "def __init__(self, hidden_units, dropout_rate)" }, { "docstring": "Forward function. Args: inputs ([type]): [description] Returns: [typ...
2
stack_v2_sparse_classes_30k_train_030429
Implement the Python class `PointWiseFeedForward` described below. Class description: PointWise forward Module. Args: torch ([type]): [description] Method signatures and docstrings: - def __init__(self, hidden_units, dropout_rate): Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([...
Implement the Python class `PointWiseFeedForward` described below. Class description: PointWise forward Module. Args: torch ([type]): [description] Method signatures and docstrings: - def __init__(self, hidden_units, dropout_rate): Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([...
625189d5e1002a3edc27c3e3ce075fddf7ae1c92
<|skeleton|> class PointWiseFeedForward: """PointWise forward Module. Args: torch ([type]): [description]""" def __init__(self, hidden_units, dropout_rate): """Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate.""" <|body_0|> def for...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PointWiseFeedForward: """PointWise forward Module. Args: torch ([type]): [description]""" def __init__(self, hidden_units, dropout_rate): """Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate.""" super(PointWiseFeedForward, self).__...
the_stack_v2_python_sparse
beta_rec/models/tisasrec.py
beta-team/beta-recsys
train
156
9fbc97084b552f68d7c4b3cff0648c0abcbeaa9b
[ "Formulation.__init__(self, space, **kwargs)\nself._vertices = vertices\nif weights:\n assert len(vertices) == len(weights), 'if weights are provided, must be same dim as vertices'\nelse:\n weights = np.ones(len(vertices))\nself._weights = weights", "C = []\nfor p in self._actions:\n M_p = np.ones(len(p)...
<|body_start_0|> Formulation.__init__(self, space, **kwargs) self._vertices = vertices if weights: assert len(vertices) == len(weights), 'if weights are provided, must be same dim as vertices' else: weights = np.ones(len(vertices)) self._weights = weights ...
VerticesNotOnInterior
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VerticesNotOnInterior: def __init__(self, space, vertices=[], weights=[], **kwargs): """statement: 'These vertices must be on the boundary of tile placements' -- or-- 'These vertices cannot be on the interior of tile placements' :param space: mesh space :param vertices: list of indices""...
stack_v2_sparse_classes_75kplus_train_005861
12,011
no_license
[ { "docstring": "statement: 'These vertices must be on the boundary of tile placements' -- or-- 'These vertices cannot be on the interior of tile placements' :param space: mesh space :param vertices: list of indices", "name": "__init__", "signature": "def __init__(self, space, vertices=[], weights=[], **...
3
stack_v2_sparse_classes_30k_train_015443
Implement the Python class `VerticesNotOnInterior` described below. Class description: Implement the VerticesNotOnInterior class. Method signatures and docstrings: - def __init__(self, space, vertices=[], weights=[], **kwargs): statement: 'These vertices must be on the boundary of tile placements' -- or-- 'These vert...
Implement the Python class `VerticesNotOnInterior` described below. Class description: Implement the VerticesNotOnInterior class. Method signatures and docstrings: - def __init__(self, space, vertices=[], weights=[], **kwargs): statement: 'These vertices must be on the boundary of tile placements' -- or-- 'These vert...
5928c1ef1eb0d60bfa0726227e690c0a66570f45
<|skeleton|> class VerticesNotOnInterior: def __init__(self, space, vertices=[], weights=[], **kwargs): """statement: 'These vertices must be on the boundary of tile placements' -- or-- 'These vertices cannot be on the interior of tile placements' :param space: mesh space :param vertices: list of indices""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VerticesNotOnInterior: def __init__(self, space, vertices=[], weights=[], **kwargs): """statement: 'These vertices must be on the boundary of tile placements' -- or-- 'These vertices cannot be on the interior of tile placements' :param space: mesh space :param vertices: list of indices""" Form...
the_stack_v2_python_sparse
src/cvopt/formulate/formulations.py
psavine42/juststuff
train
0
c0e42e8e9c17861f7169739cd1683759866ee304
[ "self.disable_vlan = disable_vlan\nself.interface_name = interface_name\nself.vlan = vlan", "if dictionary is None:\n return None\ndisable_vlan = dictionary.get('disableVlan')\ninterface_name = dictionary.get('interfaceName')\nvlan = dictionary.get('vlan')\nreturn cls(disable_vlan, interface_name, vlan)" ]
<|body_start_0|> self.disable_vlan = disable_vlan self.interface_name = interface_name self.vlan = vlan <|end_body_0|> <|body_start_1|> if dictionary is None: return None disable_vlan = dictionary.get('disableVlan') interface_name = dictionary.get('interfaceN...
Implementation of the 'VlanParameters' model. Specifies VLAN parameters for the restore operation. Attributes: disable_vlan (bool): Specifies whether to use the VIPs even when VLANs are configured on the Cluster. If configured, VLAN IP addresses are used by default. If VLANs are not configured, this flag is ignored. Se...
VlanParameters
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VlanParameters: """Implementation of the 'VlanParameters' model. Specifies VLAN parameters for the restore operation. Attributes: disable_vlan (bool): Specifies whether to use the VIPs even when VLANs are configured on the Cluster. If configured, VLAN IP addresses are used by default. If VLANs ar...
stack_v2_sparse_classes_75kplus_train_005862
2,414
permissive
[ { "docstring": "Constructor for the VlanParameters class", "name": "__init__", "signature": "def __init__(self, disable_vlan=None, interface_name=None, vlan=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of...
2
null
Implement the Python class `VlanParameters` described below. Class description: Implementation of the 'VlanParameters' model. Specifies VLAN parameters for the restore operation. Attributes: disable_vlan (bool): Specifies whether to use the VIPs even when VLANs are configured on the Cluster. If configured, VLAN IP add...
Implement the Python class `VlanParameters` described below. Class description: Implementation of the 'VlanParameters' model. Specifies VLAN parameters for the restore operation. Attributes: disable_vlan (bool): Specifies whether to use the VIPs even when VLANs are configured on the Cluster. If configured, VLAN IP add...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class VlanParameters: """Implementation of the 'VlanParameters' model. Specifies VLAN parameters for the restore operation. Attributes: disable_vlan (bool): Specifies whether to use the VIPs even when VLANs are configured on the Cluster. If configured, VLAN IP addresses are used by default. If VLANs ar...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VlanParameters: """Implementation of the 'VlanParameters' model. Specifies VLAN parameters for the restore operation. Attributes: disable_vlan (bool): Specifies whether to use the VIPs even when VLANs are configured on the Cluster. If configured, VLAN IP addresses are used by default. If VLANs are not configu...
the_stack_v2_python_sparse
cohesity_management_sdk/models/vlan_parameters.py
cohesity/management-sdk-python
train
24
7cafc0356301b96505e5f57c2cfab529384dbe38
[ "ans = 0\ntotalLength = 0\nstack = [(-1, 0)]\nfor p in input.split('\\n'):\n currDepth = p.count('\\t')\n currLength = len(p.replace('\\t', ''))\n depth, length = stack[-1]\n while depth >= currDepth:\n totalLength -= length\n stack.pop()\n depth, length = stack[-1]\n if currDept...
<|body_start_0|> ans = 0 totalLength = 0 stack = [(-1, 0)] for p in input.split('\n'): currDepth = p.count('\t') currLength = len(p.replace('\t', '')) depth, length = stack[-1] while depth >= currDepth: totalLength -= length...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lengthLongestPath(self, input): """:type input: str :rtype: int""" <|body_0|> def lengthLongestPath2(self, input): """:type input: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> ans = 0 totalLength = 0 ...
stack_v2_sparse_classes_75kplus_train_005863
6,317
no_license
[ { "docstring": ":type input: str :rtype: int", "name": "lengthLongestPath", "signature": "def lengthLongestPath(self, input)" }, { "docstring": ":type input: str :rtype: int", "name": "lengthLongestPath2", "signature": "def lengthLongestPath2(self, input)" } ]
2
stack_v2_sparse_classes_30k_train_023120
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthLongestPath(self, input): :type input: str :rtype: int - def lengthLongestPath2(self, input): :type input: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthLongestPath(self, input): :type input: str :rtype: int - def lengthLongestPath2(self, input): :type input: str :rtype: int <|skeleton|> class Solution: def length...
2d5fa4cd696d5035ea8859befeadc5cc436959c9
<|skeleton|> class Solution: def lengthLongestPath(self, input): """:type input: str :rtype: int""" <|body_0|> def lengthLongestPath2(self, input): """:type input: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def lengthLongestPath(self, input): """:type input: str :rtype: int""" ans = 0 totalLength = 0 stack = [(-1, 0)] for p in input.split('\n'): currDepth = p.count('\t') currLength = len(p.replace('\t', '')) depth, length = sta...
the_stack_v2_python_sparse
SourceCode/Python/Problem/00388.Longest_Absolute_File_Path.py
roger6blog/LeetCode
train
0
b9982c155149e77bf1e62c06ec173ba725160e20
[ "self.mPos = position\nself.mLen1 = 100\nself.mLen2 = 100\nself.mAlpha = 0\nself.mPhi = 0\nself.mObsts = obstacles", "self.mAlpha = alpha\nself.mPhi = phi\nbase = self.mPos\nend1 = (base[0] + self.mLen1 * math.cos(alpha), base[1] + self.mLen1 * math.sin(alpha))\nend2 = (end1[0] + self.mLen2 * math.cos(phi + alpha...
<|body_start_0|> self.mPos = position self.mLen1 = 100 self.mLen2 = 100 self.mAlpha = 0 self.mPhi = 0 self.mObsts = obstacles <|end_body_0|> <|body_start_1|> self.mAlpha = alpha self.mPhi = phi base = self.mPos end1 = (base[0] + self.mLen1...
description of class
RobotArm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RobotArm: """description of class""" def __init__(self, position, obstacles): """Create a 1-joint robot arm @parm position: the base position. @parm obstacles: a list of spheres as obstacles.""" <|body_0|> def setParams(self, alpha, phi): """Set angles of the rob...
stack_v2_sparse_classes_75kplus_train_005864
3,453
no_license
[ { "docstring": "Create a 1-joint robot arm @parm position: the base position. @parm obstacles: a list of spheres as obstacles.", "name": "__init__", "signature": "def __init__(self, position, obstacles)" }, { "docstring": "Set angles of the robot arm, return if collide with obstacles.", "nam...
5
stack_v2_sparse_classes_30k_train_045355
Implement the Python class `RobotArm` described below. Class description: description of class Method signatures and docstrings: - def __init__(self, position, obstacles): Create a 1-joint robot arm @parm position: the base position. @parm obstacles: a list of spheres as obstacles. - def setParams(self, alpha, phi): ...
Implement the Python class `RobotArm` described below. Class description: description of class Method signatures and docstrings: - def __init__(self, position, obstacles): Create a 1-joint robot arm @parm position: the base position. @parm obstacles: a list of spheres as obstacles. - def setParams(self, alpha, phi): ...
98724e32b932da0e92fc6354f7750ff0558f3005
<|skeleton|> class RobotArm: """description of class""" def __init__(self, position, obstacles): """Create a 1-joint robot arm @parm position: the base position. @parm obstacles: a list of spheres as obstacles.""" <|body_0|> def setParams(self, alpha, phi): """Set angles of the rob...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RobotArm: """description of class""" def __init__(self, position, obstacles): """Create a 1-joint robot arm @parm position: the base position. @parm obstacles: a list of spheres as obstacles.""" self.mPos = position self.mLen1 = 100 self.mLen2 = 100 self.mAlpha = 0...
the_stack_v2_python_sparse
SphereSamplingMotionPlanning/RobotArm.py
IanZhang1990/Robotics-MotionPlanning
train
0
cc95fc34723ddc51a7162f768f2b4cae9ab980bd
[ "assert isinstance(errors, int) or errors in ('raise', 'ignore', 'report')\nself.function = function\nself.errors = errors\nself.error_count = 0", "try:\n return self.function(*args, **kwds)\nexcept Exception as e:\n self.error_count += 1\n if self.errors == 'raise':\n raise\n if self.errors ==...
<|body_start_0|> assert isinstance(errors, int) or errors in ('raise', 'ignore', 'report') self.function = function self.errors = errors self.error_count = 0 <|end_body_0|> <|body_start_1|> try: return self.function(*args, **kwds) except Exception as e: ...
Wraps a function call to catch and report exceptions.
LogErrors
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LogErrors: """Wraps a function call to catch and report exceptions.""" def __init__(self, function, errors): """:param function: the function to wrap :param errors: either a number, indicating how many errors to report before ignoring them, or one of these strings: 'raise', meaning t...
stack_v2_sparse_classes_75kplus_train_005865
1,450
permissive
[ { "docstring": ":param function: the function to wrap :param errors: either a number, indicating how many errors to report before ignoring them, or one of these strings: 'raise', meaning to raise an exception 'ignore', meaning to ignore all errors 'report', meaning to report all errors", "name": "__init__",...
2
stack_v2_sparse_classes_30k_train_031237
Implement the Python class `LogErrors` described below. Class description: Wraps a function call to catch and report exceptions. Method signatures and docstrings: - def __init__(self, function, errors): :param function: the function to wrap :param errors: either a number, indicating how many errors to report before i...
Implement the Python class `LogErrors` described below. Class description: Wraps a function call to catch and report exceptions. Method signatures and docstrings: - def __init__(self, function, errors): :param function: the function to wrap :param errors: either a number, indicating how many errors to report before i...
fd97e6c651a4bbcade64733847f4eec8f7704b7c
<|skeleton|> class LogErrors: """Wraps a function call to catch and report exceptions.""" def __init__(self, function, errors): """:param function: the function to wrap :param errors: either a number, indicating how many errors to report before ignoring them, or one of these strings: 'raise', meaning t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LogErrors: """Wraps a function call to catch and report exceptions.""" def __init__(self, function, errors): """:param function: the function to wrap :param errors: either a number, indicating how many errors to report before ignoring them, or one of these strings: 'raise', meaning to raise an ex...
the_stack_v2_python_sparse
bibliopixel/util/log_errors.py
dr-aryone/BiblioPixel
train
2
4188f54d95e85a21e0ba58a3c913bd827c174202
[ "counts = 0\nis_primes = [1] * n\nfor i in range(2, n):\n if is_primes[i]:\n counts += 1\n for j in range(i * i, n, i):\n is_primes[j] = 0\nreturn counts", "primes = []\nis_primes = [1] * n\nfor i in range(2, n):\n if is_primes[i] == 1:\n primes.append(i)\n j = 0\n whil...
<|body_start_0|> counts = 0 is_primes = [1] * n for i in range(2, n): if is_primes[i]: counts += 1 for j in range(i * i, n, i): is_primes[j] = 0 return counts <|end_body_0|> <|body_start_1|> primes = [] is_p...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countPrimes(self, n: int) -> int: """埃氏筛 :param n: :return:""" <|body_0|> def countPrimes1(self, n: int) -> int: """线性筛 :param n: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> counts = 0 is_primes = [1] * n f...
stack_v2_sparse_classes_75kplus_train_005866
1,697
no_license
[ { "docstring": "埃氏筛 :param n: :return:", "name": "countPrimes", "signature": "def countPrimes(self, n: int) -> int" }, { "docstring": "线性筛 :param n: :return:", "name": "countPrimes1", "signature": "def countPrimes1(self, n: int) -> int" } ]
2
stack_v2_sparse_classes_30k_train_046229
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countPrimes(self, n: int) -> int: 埃氏筛 :param n: :return: - def countPrimes1(self, n: int) -> int: 线性筛 :param n: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countPrimes(self, n: int) -> int: 埃氏筛 :param n: :return: - def countPrimes1(self, n: int) -> int: 线性筛 :param n: :return: <|skeleton|> class Solution: def countPrimes(se...
578cacff5851c5c2522981693c34e3c318002d30
<|skeleton|> class Solution: def countPrimes(self, n: int) -> int: """埃氏筛 :param n: :return:""" <|body_0|> def countPrimes1(self, n: int) -> int: """线性筛 :param n: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def countPrimes(self, n: int) -> int: """埃氏筛 :param n: :return:""" counts = 0 is_primes = [1] * n for i in range(2, n): if is_primes[i]: counts += 1 for j in range(i * i, n, i): is_primes[j] = 0 r...
the_stack_v2_python_sparse
计数质数.py
cjrzs/MyLeetCode
train
8
b2390f948ae8888d5f30f6c382ed2705667eca12
[ "if token:\n user = self.validate_token(token)\n if user:\n password_form = PasswordForm().get_form()\n self.render_template('user/password.html', form=password_form, token=token)\n else:\n error_message = _('Sorry, your link is expired, please try again.')\n logging.info(\"(Pro...
<|body_start_0|> if token: user = self.validate_token(token) if user: password_form = PasswordForm().get_form() self.render_template('user/password.html', form=password_form, token=token) else: error_message = _('Sorry, your lin...
ResetPasswordHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResetPasswordHandler: def get(self, token=None): """Someone coming back with a password reset token""" <|body_0|> def post(self): """Someone forgot their password, generate a token and send email""" <|body_1|> <|end_skeleton|> <|body_start_0|> if to...
stack_v2_sparse_classes_75kplus_train_005867
5,630
no_license
[ { "docstring": "Someone coming back with a password reset token", "name": "get", "signature": "def get(self, token=None)" }, { "docstring": "Someone forgot their password, generate a token and send email", "name": "post", "signature": "def post(self)" } ]
2
null
Implement the Python class `ResetPasswordHandler` described below. Class description: Implement the ResetPasswordHandler class. Method signatures and docstrings: - def get(self, token=None): Someone coming back with a password reset token - def post(self): Someone forgot their password, generate a token and send emai...
Implement the Python class `ResetPasswordHandler` described below. Class description: Implement the ResetPasswordHandler class. Method signatures and docstrings: - def get(self, token=None): Someone coming back with a password reset token - def post(self): Someone forgot their password, generate a token and send emai...
c81873cff6f51a2326833c47557f66204c048779
<|skeleton|> class ResetPasswordHandler: def get(self, token=None): """Someone coming back with a password reset token""" <|body_0|> def post(self): """Someone forgot their password, generate a token and send email""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ResetPasswordHandler: def get(self, token=None): """Someone coming back with a password reset token""" if token: user = self.validate_token(token) if user: password_form = PasswordForm().get_form() self.render_template('user/password.html...
the_stack_v2_python_sparse
GAE/veosan/handler/user_pkg/password_handler.py
deltron/veosan
train
0
adfe19b9cf9c1ef924d9da4b27a34313254058f7
[ "fake_command_file = 'cros_command_test.py'\nfiltered_file = 'cros_command_unittest.py'\nmydir = 'mydir'\nself.PatchObject(glob, 'glob', return_value=[fake_command_file, filtered_file])\nself.assertEqual(command._FindModules(mydir), [fake_command_file])", "fake_module = 'cros_command_test'\nfake_command_file = os...
<|body_start_0|> fake_command_file = 'cros_command_test.py' filtered_file = 'cros_command_unittest.py' mydir = 'mydir' self.PatchObject(glob, 'glob', return_value=[fake_command_file, filtered_file]) self.assertEqual(command._FindModules(mydir), [fake_command_file]) <|end_body_0|>...
This test class tests that we can load modules correctly.
CommandTest
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommandTest: """This test class tests that we can load modules correctly.""" def testFindModules(self): """Tests that we can return modules correctly when mocking out glob.""" <|body_0|> def testLoadCommands(self): """Tests import commands correctly.""" <...
stack_v2_sparse_classes_75kplus_train_005868
4,291
permissive
[ { "docstring": "Tests that we can return modules correctly when mocking out glob.", "name": "testFindModules", "signature": "def testFindModules(self)" }, { "docstring": "Tests import commands correctly.", "name": "testLoadCommands", "signature": "def testLoadCommands(self)" }, { ...
3
stack_v2_sparse_classes_30k_train_048600
Implement the Python class `CommandTest` described below. Class description: This test class tests that we can load modules correctly. Method signatures and docstrings: - def testFindModules(self): Tests that we can return modules correctly when mocking out glob. - def testLoadCommands(self): Tests import commands co...
Implement the Python class `CommandTest` described below. Class description: This test class tests that we can load modules correctly. Method signatures and docstrings: - def testFindModules(self): Tests that we can return modules correctly when mocking out glob. - def testLoadCommands(self): Tests import commands co...
72a05af97787001756bae2511b7985e61498c965
<|skeleton|> class CommandTest: """This test class tests that we can load modules correctly.""" def testFindModules(self): """Tests that we can return modules correctly when mocking out glob.""" <|body_0|> def testLoadCommands(self): """Tests import commands correctly.""" <...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CommandTest: """This test class tests that we can load modules correctly.""" def testFindModules(self): """Tests that we can return modules correctly when mocking out glob.""" fake_command_file = 'cros_command_test.py' filtered_file = 'cros_command_unittest.py' mydir = 'my...
the_stack_v2_python_sparse
third_party/chromite/cli/command_unittest.py
metux/chromium-suckless
train
5
d73fcc40a7f87da5d45ec25788941593e69084b3
[ "movies = response.xpath('//div[@class=\"box clearfix\"]/ul/li')\nfor movie in movies:\n item = Rrys2019Top24Item()\n movieType = movie.xpath('./em/text()').extract_first().strip()\n movieTop = movie.xpath('./span/text()').extract_first().strip()\n rid = movie.xpath('./a/@href').extract_first().strip()....
<|body_start_0|> movies = response.xpath('//div[@class="box clearfix"]/ul/li') for movie in movies: item = Rrys2019Top24Item() movieType = movie.xpath('./em/text()').extract_first().strip() movieTop = movie.xpath('./span/text()').extract_first().strip() ri...
Rrys2019Spider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Rrys2019Spider: def parse(self, response): """解析首页 获取最近 24 小时热门:排名、名称、类型、详情 url""" <|body_0|> def parse2(self, response): """解析详情页 获取:电影分级、本站排名、收藏次数、简介""" <|body_1|> def parse3(self, response): """从接口获取 浏览次数""" <|body_2|> <|end_skeleton|...
stack_v2_sparse_classes_75kplus_train_005869
3,320
no_license
[ { "docstring": "解析首页 获取最近 24 小时热门:排名、名称、类型、详情 url", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "解析详情页 获取:电影分级、本站排名、收藏次数、简介", "name": "parse2", "signature": "def parse2(self, response)" }, { "docstring": "从接口获取 浏览次数", "name": "parse3", "sig...
3
stack_v2_sparse_classes_30k_train_000180
Implement the Python class `Rrys2019Spider` described below. Class description: Implement the Rrys2019Spider class. Method signatures and docstrings: - def parse(self, response): 解析首页 获取最近 24 小时热门:排名、名称、类型、详情 url - def parse2(self, response): 解析详情页 获取:电影分级、本站排名、收藏次数、简介 - def parse3(self, response): 从接口获取 浏览次数
Implement the Python class `Rrys2019Spider` described below. Class description: Implement the Rrys2019Spider class. Method signatures and docstrings: - def parse(self, response): 解析首页 获取最近 24 小时热门:排名、名称、类型、详情 url - def parse2(self, response): 解析详情页 获取:电影分级、本站排名、收藏次数、简介 - def parse3(self, response): 从接口获取 浏览次数 <|skel...
982ebae5e3256a274392a0e4c64dafd55226b8df
<|skeleton|> class Rrys2019Spider: def parse(self, response): """解析首页 获取最近 24 小时热门:排名、名称、类型、详情 url""" <|body_0|> def parse2(self, response): """解析详情页 获取:电影分级、本站排名、收藏次数、简介""" <|body_1|> def parse3(self, response): """从接口获取 浏览次数""" <|body_2|> <|end_skeleton|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Rrys2019Spider: def parse(self, response): """解析首页 获取最近 24 小时热门:排名、名称、类型、详情 url""" movies = response.xpath('//div[@class="box clearfix"]/ul/li') for movie in movies: item = Rrys2019Top24Item() movieType = movie.xpath('./em/text()').extract_first().strip() ...
the_stack_v2_python_sparse
Week_03/G20200389010137/rrys2019Top24_/rrys2019Top24/spiders/rrys2019.py
kavanchen/Python000-class01
train
0
2874baaa24f1c2cdafe8577cd7b68d50be0329b1
[ "items = range(15)\nall_items = set()\nfor _ in xrange(50):\n combination = random_combination(items, 5)\n all_items |= set(combination)\neq_(all_items, set(items))", "items = range(15)\nfor _ in xrange(50):\n combination = random_combination(items, len(items))\n eq_(len(combination), len(set(combinat...
<|body_start_0|> items = range(15) all_items = set() for _ in xrange(50): combination = random_combination(items, 5) all_items |= set(combination) eq_(all_items, set(items)) <|end_body_0|> <|body_start_1|> items = range(15) for _ in xrange(50): ...
Tests for ``random_combination()``
RandomCombinationTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomCombinationTests: """Tests for ``random_combination()``""" def test_psuedorandomness(self): """ensure different subsets of the iterable get returned over many samplings of random combinations""" <|body_0|> def test_no_replacement(self): """ensure that eleme...
stack_v2_sparse_classes_75kplus_train_005870
47,145
no_license
[ { "docstring": "ensure different subsets of the iterable get returned over many samplings of random combinations", "name": "test_psuedorandomness", "signature": "def test_psuedorandomness(self)" }, { "docstring": "ensure that elements are sampled without replacement", "name": "test_no_replac...
2
stack_v2_sparse_classes_30k_train_048675
Implement the Python class `RandomCombinationTests` described below. Class description: Tests for ``random_combination()`` Method signatures and docstrings: - def test_psuedorandomness(self): ensure different subsets of the iterable get returned over many samplings of random combinations - def test_no_replacement(sel...
Implement the Python class `RandomCombinationTests` described below. Class description: Tests for ``random_combination()`` Method signatures and docstrings: - def test_psuedorandomness(self): ensure different subsets of the iterable get returned over many samplings of random combinations - def test_no_replacement(sel...
0ac6653219c2701c13c508c5c4fc9bc3437eea06
<|skeleton|> class RandomCombinationTests: """Tests for ``random_combination()``""" def test_psuedorandomness(self): """ensure different subsets of the iterable get returned over many samplings of random combinations""" <|body_0|> def test_no_replacement(self): """ensure that eleme...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RandomCombinationTests: """Tests for ``random_combination()``""" def test_psuedorandomness(self): """ensure different subsets of the iterable get returned over many samplings of random combinations""" items = range(15) all_items = set() for _ in xrange(50): com...
the_stack_v2_python_sparse
repoData/erikrose-more-itertools/allPythonContent.py
aCoffeeYin/pyreco
train
0
390ffa2a5858a7af46141971311853352efc9d7d
[ "last = None\nfor i in nums:\n if last == None:\n last = i\n elif last > i:\n return i\n else:\n last = i\nreturn nums[0]", "start, end = (0, len(nums) - 1)\nwhile start <= end:\n mid = (start + end) / 2\n if mid > 0 and nums[mid - 1] > nums[mid]:\n return nums[mid]\n ...
<|body_start_0|> last = None for i in nums: if last == None: last = i elif last > i: return i else: last = i return nums[0] <|end_body_0|> <|body_start_1|> start, end = (0, len(nums) - 1) while s...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findMin(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findMin_v2(self, nums): """Use binary search :param nums: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> last = None for i in nums: ...
stack_v2_sparse_classes_75kplus_train_005871
1,017
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "findMin", "signature": "def findMin(self, nums)" }, { "docstring": "Use binary search :param nums: :return:", "name": "findMin_v2", "signature": "def findMin_v2(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_054352
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMin(self, nums): :type nums: List[int] :rtype: int - def findMin_v2(self, nums): Use binary search :param nums: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMin(self, nums): :type nums: List[int] :rtype: int - def findMin_v2(self, nums): Use binary search :param nums: :return: <|skeleton|> class Solution: def findMin(se...
0b4f293260e5ffa52cb0434619bcbb73be7dd5a6
<|skeleton|> class Solution: def findMin(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findMin_v2(self, nums): """Use binary search :param nums: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findMin(self, nums): """:type nums: List[int] :rtype: int""" last = None for i in nums: if last == None: last = i elif last > i: return i else: last = i return nums[0] def fin...
the_stack_v2_python_sparse
LeetCode/153_Find_Minimum_in_Rotated_Sorted_Array.py
wangruowen/leetcode_practice
train
0
d82e1222fa043dd9194812e0d5ef1447152d9c40
[ "n = len(A)\nprefix_sum = [0 for _ in range(n + 1)]\nfor i in range(1, n + 1):\n prefix_sum[i] = prefix_sum[i - 1] + A[i - 1]\nF = {}\nself.dfs(A, n, prefix_sum, F, K)\nreturn F[n, K]", "if l < k:\n return -float('inf')\nif (l, k) not in F:\n if k == 1:\n ret = prefix_sum[l] / l\n else:\n ...
<|body_start_0|> n = len(A) prefix_sum = [0 for _ in range(n + 1)] for i in range(1, n + 1): prefix_sum[i] = prefix_sum[i - 1] + A[i - 1] F = {} self.dfs(A, n, prefix_sum, F, K) return F[n, K] <|end_body_0|> <|body_start_1|> if l < k: retu...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def largestSumOfAverages(self, A: List[int], K: int) -> float: """Memoized Backtracking + Prefix sum My first hunch is correct Complexity O(N^2 * K), mark sum and different way of forming groups (inserting dividers) calculating each F[l, k] will need O(N) time, thus total O(n^2...
stack_v2_sparse_classes_75kplus_train_005872
2,622
no_license
[ { "docstring": "Memoized Backtracking + Prefix sum My first hunch is correct Complexity O(N^2 * K), mark sum and different way of forming groups (inserting dividers) calculating each F[l, k] will need O(N) time, thus total O(n^2 k)", "name": "largestSumOfAverages", "signature": "def largestSumOfAverages...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def largestSumOfAverages(self, A: List[int], K: int) -> float: Memoized Backtracking + Prefix sum My first hunch is correct Complexity O(N^2 * K), mark sum and different way of f...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def largestSumOfAverages(self, A: List[int], K: int) -> float: Memoized Backtracking + Prefix sum My first hunch is correct Complexity O(N^2 * K), mark sum and different way of f...
929dde1723fb2f54870c8a9badc80fc23e8400d3
<|skeleton|> class Solution: def largestSumOfAverages(self, A: List[int], K: int) -> float: """Memoized Backtracking + Prefix sum My first hunch is correct Complexity O(N^2 * K), mark sum and different way of forming groups (inserting dividers) calculating each F[l, k] will need O(N) time, thus total O(n^2...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def largestSumOfAverages(self, A: List[int], K: int) -> float: """Memoized Backtracking + Prefix sum My first hunch is correct Complexity O(N^2 * K), mark sum and different way of forming groups (inserting dividers) calculating each F[l, k] will need O(N) time, thus total O(n^2 k)""" ...
the_stack_v2_python_sparse
_algorithms_challenges/leetcode/LeetCode/813 Largest Sum of Averages.py
syurskyi/Algorithms_and_Data_Structure
train
4
f9fbb6daf384254d9b6ea34657362af4cf8abfdb
[ "if hasattr(self, 'client'):\n context = {self.client_context_object_name: self.client}\nelse:\n client_slug = self.kwargs.get(self.client_slug_url_kwarg)\n if client_slug:\n client = get_object_or_404(Client, slug__iexact=client_slug)\n context = {self.client_context_object_name: client}\n ...
<|body_start_0|> if hasattr(self, 'client'): context = {self.client_context_object_name: self.client} else: client_slug = self.kwargs.get(self.client_slug_url_kwarg) if client_slug: client = get_object_or_404(Client, slug__iexact=client_slug) ...
OrderCreateClientMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrderCreateClientMixin: def get_context_data(self, **kwargs): """Добавляет клиента и объект в контекст заказа""" <|body_0|> def get_initial(self): """Добавляет клиента и объект в заказ""" <|body_1|> <|end_skeleton|> <|body_start_0|> if hasattr(self,...
stack_v2_sparse_classes_75kplus_train_005873
4,913
permissive
[ { "docstring": "Добавляет клиента и объект в контекст заказа", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" }, { "docstring": "Добавляет клиента и объект в заказ", "name": "get_initial", "signature": "def get_initial(self)" } ]
2
stack_v2_sparse_classes_30k_train_021396
Implement the Python class `OrderCreateClientMixin` described below. Class description: Implement the OrderCreateClientMixin class. Method signatures and docstrings: - def get_context_data(self, **kwargs): Добавляет клиента и объект в контекст заказа - def get_initial(self): Добавляет клиента и объект в заказ
Implement the Python class `OrderCreateClientMixin` described below. Class description: Implement the OrderCreateClientMixin class. Method signatures and docstrings: - def get_context_data(self, **kwargs): Добавляет клиента и объект в контекст заказа - def get_initial(self): Добавляет клиента и объект в заказ <|skel...
7246b4f524d138d48aadf4866e0b218bb924f69c
<|skeleton|> class OrderCreateClientMixin: def get_context_data(self, **kwargs): """Добавляет клиента и объект в контекст заказа""" <|body_0|> def get_initial(self): """Добавляет клиента и объект в заказ""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OrderCreateClientMixin: def get_context_data(self, **kwargs): """Добавляет клиента и объект в контекст заказа""" if hasattr(self, 'client'): context = {self.client_context_object_name: self.client} else: client_slug = self.kwargs.get(self.client_slug_url_kwarg) ...
the_stack_v2_python_sparse
locker/calc/utils.py
crowmurk/locker
train
0
bfa2d8ac032899dd7d685ac4f19e0b9d501c78ea
[ "Validate.required(unit_cost, 'unit_cost')\nValidate.non_negative(unit_cost, 'unit_cost')\nValidate.required(demand_quantity, 'demand_quantity')\nValidate.non_negative(demand_quantity, 'demand_quantity')\nreturn unit_cost * demand_quantity", "Validate.required(ordering_cost, 'ordering_cost')\nValidate.non_negativ...
<|body_start_0|> Validate.required(unit_cost, 'unit_cost') Validate.non_negative(unit_cost, 'unit_cost') Validate.required(demand_quantity, 'demand_quantity') Validate.non_negative(demand_quantity, 'demand_quantity') return unit_cost * demand_quantity <|end_body_0|> <|body_start...
Provides methods for calculating costs, both at the "detail" level (e.g. purchase cost, ordering cost, etc.) and at the "combined" level (i.e. total relevant cost (TRC) and total cost (TC).
Costs
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Costs: """Provides methods for calculating costs, both at the "detail" level (e.g. purchase cost, ordering cost, etc.) and at the "combined" level (i.e. total relevant cost (TRC) and total cost (TC).""" def purchase_cost(unit_cost, demand_quantity): """Calculate the purchase cost - t...
stack_v2_sparse_classes_75kplus_train_005874
6,030
no_license
[ { "docstring": "Calculate the purchase cost - the total landed cost for acquiring product needed to satisfy a given amount of demand. Parameters ---------- unit_cost : int or float Cost per unit, in dollars demand_quantity : int The amount of demand, in units Returns ------- purchase_cost: float", "name": "...
6
stack_v2_sparse_classes_30k_train_011711
Implement the Python class `Costs` described below. Class description: Provides methods for calculating costs, both at the "detail" level (e.g. purchase cost, ordering cost, etc.) and at the "combined" level (i.e. total relevant cost (TRC) and total cost (TC). Method signatures and docstrings: - def purchase_cost(uni...
Implement the Python class `Costs` described below. Class description: Provides methods for calculating costs, both at the "detail" level (e.g. purchase cost, ordering cost, etc.) and at the "combined" level (i.e. total relevant cost (TRC) and total cost (TC). Method signatures and docstrings: - def purchase_cost(uni...
230b7bead81265dfee2e0e5c5819ae7a9c46acbc
<|skeleton|> class Costs: """Provides methods for calculating costs, both at the "detail" level (e.g. purchase cost, ordering cost, etc.) and at the "combined" level (i.e. total relevant cost (TRC) and total cost (TC).""" def purchase_cost(unit_cost, demand_quantity): """Calculate the purchase cost - t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Costs: """Provides methods for calculating costs, both at the "detail" level (e.g. purchase cost, ordering cost, etc.) and at the "combined" level (i.e. total relevant cost (TRC) and total cost (TC).""" def purchase_cost(unit_cost, demand_quantity): """Calculate the purchase cost - the total land...
the_stack_v2_python_sparse
costs.py
rickhaffey/supply-chain-python
train
2
c755d8ac977aff1e7aed3d5ee69884c591fb2ed1
[ "self.alpha = 0.1\nself.alphadecay = 1.0\nself.momentum = 0.0\nself.momentumvector = None\nself.rprop = False\nself.deltamax = 5.0\nself.deltamin = 0.01\nself.deltanull = 0.1\nself.etaplus = 1.2\nself.etaminus = 0.5\nself.lastgradient = None", "assert isinstance(values, ndarray)\nself.values = values.copy()\nif s...
<|body_start_0|> self.alpha = 0.1 self.alphadecay = 1.0 self.momentum = 0.0 self.momentumvector = None self.rprop = False self.deltamax = 5.0 self.deltamin = 0.01 self.deltanull = 0.1 self.etaplus = 1.2 self.etaminus = 0.5 self.last...
GradientDescent
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GradientDescent: def __init__(self): """initialize algorithms with standard parameters (typical values given in parentheses)""" <|body_0|> def init(self, values): """call this to initialize data structures *after* algorithm to use has been selected :arg values: the l...
stack_v2_sparse_classes_75kplus_train_005875
5,966
permissive
[ { "docstring": "initialize algorithms with standard parameters (typical values given in parentheses)", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "call this to initialize data structures *after* algorithm to use has been selected :arg values: the list (or array) of p...
3
null
Implement the Python class `GradientDescent` described below. Class description: Implement the GradientDescent class. Method signatures and docstrings: - def __init__(self): initialize algorithms with standard parameters (typical values given in parentheses) - def init(self, values): call this to initialize data stru...
Implement the Python class `GradientDescent` described below. Class description: Implement the GradientDescent class. Method signatures and docstrings: - def __init__(self): initialize algorithms with standard parameters (typical values given in parentheses) - def init(self, values): call this to initialize data stru...
33ead60704d126e58c10d458ddd1e5e5fd17b65d
<|skeleton|> class GradientDescent: def __init__(self): """initialize algorithms with standard parameters (typical values given in parentheses)""" <|body_0|> def init(self, values): """call this to initialize data structures *after* algorithm to use has been selected :arg values: the l...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GradientDescent: def __init__(self): """initialize algorithms with standard parameters (typical values given in parentheses)""" self.alpha = 0.1 self.alphadecay = 1.0 self.momentum = 0.0 self.momentumvector = None self.rprop = False self.deltamax = 5.0 ...
the_stack_v2_python_sparse
pybrain/auxiliary/gradientdescent.py
pybrain2/pybrain2
train
14
cb68199199f518639e8d7314347556e2be7fa244
[ "triplet = [nums[0], None, None]\nfor elem in nums[1:]:\n if not triplet[1] and elem < triplet[0]:\n triplet[0] = elem\n elif not triplet[1] or (not triplet[2] and triplet[0] < elem < triplet[1]):\n triplet[1] = elem\n elif not triplet[2] and elem > triplet[1]:\n print(triplet)\n ...
<|body_start_0|> triplet = [nums[0], None, None] for elem in nums[1:]: if not triplet[1] and elem < triplet[0]: triplet[0] = elem elif not triplet[1] or (not triplet[2] and triplet[0] < elem < triplet[1]): triplet[1] = elem elif not tri...
Solution
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def increasingTriplet(self, nums) -> bool: """the code is wrong, but it could be a reference of the right code. There is a hidden trick between two versions""" <|body_0|> def increasingTriplet(self, nums) -> bool: """trick: we can directly replace the small...
stack_v2_sparse_classes_75kplus_train_005876
2,078
permissive
[ { "docstring": "the code is wrong, but it could be a reference of the right code. There is a hidden trick between two versions", "name": "increasingTriplet", "signature": "def increasingTriplet(self, nums) -> bool" }, { "docstring": "trick: we can directly replace the small when meet a value sma...
2
stack_v2_sparse_classes_30k_train_051649
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def increasingTriplet(self, nums) -> bool: the code is wrong, but it could be a reference of the right code. There is a hidden trick between two versions - def increasingTriplet(...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def increasingTriplet(self, nums) -> bool: the code is wrong, but it could be a reference of the right code. There is a hidden trick between two versions - def increasingTriplet(...
226cecde136531341ce23cdf88529345be1912fc
<|skeleton|> class Solution: def increasingTriplet(self, nums) -> bool: """the code is wrong, but it could be a reference of the right code. There is a hidden trick between two versions""" <|body_0|> def increasingTriplet(self, nums) -> bool: """trick: we can directly replace the small...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def increasingTriplet(self, nums) -> bool: """the code is wrong, but it could be a reference of the right code. There is a hidden trick between two versions""" triplet = [nums[0], None, None] for elem in nums[1:]: if not triplet[1] and elem < triplet[0]: ...
the_stack_v2_python_sparse
Leetcode/Intermediate/Array_and_string/334_Increasing_Triplet_Subsequence.py
ZR-Huang/AlgorithmsPractices
train
1
dbf36004be77fc1c80331e3a64a7ec8fde1ff267
[ "partname = package.next_partname('/word/footer%d.xml')\ncontent_type = CT.WML_FOOTER\nelement = parse_xml(cls._default_footer_xml())\nreturn cls(partname, content_type, element, package)", "path = os.path.join(os.path.split(__file__)[0], '..', 'templates', 'default-footer.xml')\nwith open(path, 'rb') as f:\n ...
<|body_start_0|> partname = package.next_partname('/word/footer%d.xml') content_type = CT.WML_FOOTER element = parse_xml(cls._default_footer_xml()) return cls(partname, content_type, element, package) <|end_body_0|> <|body_start_1|> path = os.path.join(os.path.split(__file__)[0]...
Definition of a section footer.
FooterPart
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FooterPart: """Definition of a section footer.""" def new(cls, package): """Return newly created footer part.""" <|body_0|> def _default_footer_xml(cls): """Return bytes containing XML for a default footer part.""" <|body_1|> <|end_skeleton|> <|body_sta...
stack_v2_sparse_classes_75kplus_train_005877
1,717
permissive
[ { "docstring": "Return newly created footer part.", "name": "new", "signature": "def new(cls, package)" }, { "docstring": "Return bytes containing XML for a default footer part.", "name": "_default_footer_xml", "signature": "def _default_footer_xml(cls)" } ]
2
stack_v2_sparse_classes_30k_train_015577
Implement the Python class `FooterPart` described below. Class description: Definition of a section footer. Method signatures and docstrings: - def new(cls, package): Return newly created footer part. - def _default_footer_xml(cls): Return bytes containing XML for a default footer part.
Implement the Python class `FooterPart` described below. Class description: Definition of a section footer. Method signatures and docstrings: - def new(cls, package): Return newly created footer part. - def _default_footer_xml(cls): Return bytes containing XML for a default footer part. <|skeleton|> class FooterPart...
2bfcf6b9779bf1abd41e1bc42c27007127ddbefb
<|skeleton|> class FooterPart: """Definition of a section footer.""" def new(cls, package): """Return newly created footer part.""" <|body_0|> def _default_footer_xml(cls): """Return bytes containing XML for a default footer part.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FooterPart: """Definition of a section footer.""" def new(cls, package): """Return newly created footer part.""" partname = package.next_partname('/word/footer%d.xml') content_type = CT.WML_FOOTER element = parse_xml(cls._default_footer_xml()) return cls(partname, ...
the_stack_v2_python_sparse
anuvaad-etl/anuvaad-extractor/file_translator/etl-file-translator/docx/parts/hdrftr.py
project-anuvaad/anuvaad
train
41
8c5e3965c769d433df6974223c9281e50d513eb7
[ "assert bias.shape[0] == 1\nassert weight_hh.shape[0] == 1\nassert weight_hh.shape[1] == 1\nself.hidden_size: int = 1\nself.input_size: int = input_size\nself.bias: np.ndarray = bias\nself.weight_hh: np.ndarray = weight_hh\nself.weight_xh: np.ndarray = weight_xh\nself.hx: np.ndarray = np.asarray([])", "if len(sel...
<|body_start_0|> assert bias.shape[0] == 1 assert weight_hh.shape[0] == 1 assert weight_hh.shape[1] == 1 self.hidden_size: int = 1 self.input_size: int = input_size self.bias: np.ndarray = bias self.weight_hh: np.ndarray = weight_hh self.weight_xh: np.ndar...
Small variation of the PyTorch implementation of the simple RNN-cell.
RNNCell
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNNCell: """Small variation of the PyTorch implementation of the simple RNN-cell.""" def __init__(self, input_size: int, bias: np.ndarray, weight_hh: np.ndarray, weight_xh: np.ndarray): """Create the RNN-cell with the provided parameters. :param input_size: Number of inputs going int...
stack_v2_sparse_classes_75kplus_train_005878
1,677
permissive
[ { "docstring": "Create the RNN-cell with the provided parameters. :param input_size: Number of inputs going into the cell :param bias: Bias for the internal node :param weight_hh: Weight of the hidden-state connection :param weight_xh: Weight-vector from input to hidden state", "name": "__init__", "sign...
2
stack_v2_sparse_classes_30k_train_012225
Implement the Python class `RNNCell` described below. Class description: Small variation of the PyTorch implementation of the simple RNN-cell. Method signatures and docstrings: - def __init__(self, input_size: int, bias: np.ndarray, weight_hh: np.ndarray, weight_xh: np.ndarray): Create the RNN-cell with the provided ...
Implement the Python class `RNNCell` described below. Class description: Small variation of the PyTorch implementation of the simple RNN-cell. Method signatures and docstrings: - def __init__(self, input_size: int, bias: np.ndarray, weight_hh: np.ndarray, weight_xh: np.ndarray): Create the RNN-cell with the provided ...
818a4ce941536611c0f1780f7c4a6238f0e1884e
<|skeleton|> class RNNCell: """Small variation of the PyTorch implementation of the simple RNN-cell.""" def __init__(self, input_size: int, bias: np.ndarray, weight_hh: np.ndarray, weight_xh: np.ndarray): """Create the RNN-cell with the provided parameters. :param input_size: Number of inputs going int...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RNNCell: """Small variation of the PyTorch implementation of the simple RNN-cell.""" def __init__(self, input_size: int, bias: np.ndarray, weight_hh: np.ndarray, weight_xh: np.ndarray): """Create the RNN-cell with the provided parameters. :param input_size: Number of inputs going into the cell :p...
the_stack_v2_python_sparse
population/utils/rnn_cell_util/simple_rnn.py
RubenPants/EvolvableRNN
train
1
a97217f2b360b28bebbbbb2f80da67c2b826e01e
[ "left = 0\nright = len(numbers) - 1\nres = []\nif len(numbers) < 2 or numbers == None:\n return res\nwhile left < right:\n t = numbers[left] + numbers[right]\n if t == target:\n res.append(left + 1)\n res.append(right + 1)\n break\n if t > target:\n right -= 1\n else:\n ...
<|body_start_0|> left = 0 right = len(numbers) - 1 res = [] if len(numbers) < 2 or numbers == None: return res while left < right: t = numbers[left] + numbers[right] if t == target: res.append(left + 1) res.appen...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def twoSum(self, numbers, target): """:type numbers: List[int] :type target: int :rtype: List[int]""" <|body_0|> def twoSumv2(self, numbers, target): """:type numbers: List[int] :type target: int :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|...
stack_v2_sparse_classes_75kplus_train_005879
969
no_license
[ { "docstring": ":type numbers: List[int] :type target: int :rtype: List[int]", "name": "twoSum", "signature": "def twoSum(self, numbers, target)" }, { "docstring": ":type numbers: List[int] :type target: int :rtype: List[int]", "name": "twoSumv2", "signature": "def twoSumv2(self, numbers...
2
stack_v2_sparse_classes_30k_val_001163
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :rtype: List[int] - def twoSumv2(self, numbers, target): :type numbers: List[int] :type target: int ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :rtype: List[int] - def twoSumv2(self, numbers, target): :type numbers: List[int] :type target: int ...
dbb9be177c5e572eb72a79508bb6e24f357d54b3
<|skeleton|> class Solution: def twoSum(self, numbers, target): """:type numbers: List[int] :type target: int :rtype: List[int]""" <|body_0|> def twoSumv2(self, numbers, target): """:type numbers: List[int] :type target: int :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def twoSum(self, numbers, target): """:type numbers: List[int] :type target: int :rtype: List[int]""" left = 0 right = len(numbers) - 1 res = [] if len(numbers) < 2 or numbers == None: return res while left < right: t = numbers[...
the_stack_v2_python_sparse
Leetcode/167. Two Sum II - Input array is sorted.py
GuanzhouSong/Leetcode_Python
train
0
c0ea3dc7c1c0a7e085b22955c446bf65334b5b16
[ "self._edge_color = _get_hex_color(_get_value(kwargs, ['color', 'c', 'edge_color', 'ec'], 'black'))\nself._edge_alpha = _get_value(kwargs, ['alpha', 'edge_alpha', 'ea'], 1.0)\nself._edge_width = _get_value(kwargs, ['edge_width', 'ew'], 1)\nself._face_alpha = _get_value(kwargs, ['alpha', 'face_alpha', 'fa'], 0.3)\ns...
<|body_start_0|> self._edge_color = _get_hex_color(_get_value(kwargs, ['color', 'c', 'edge_color', 'ec'], 'black')) self._edge_alpha = _get_value(kwargs, ['alpha', 'edge_alpha', 'ea'], 1.0) self._edge_width = _get_value(kwargs, ['edge_width', 'ew'], 1) self._face_alpha = _get_value(kwarg...
_Polygon
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _Polygon: def __init__(self, lats, lngs, **kwargs): """Args: lats ([float]): Latitudes. lngs ([float]): Longitudes. Optional: Args: color/c/edge_color/ec (str): Color of the polygon's edge. Can be hex ('#00FFFF'), named ('cyan'), or matplotlib-like ('c'). Defaults to black. alpha/edge_al...
stack_v2_sparse_classes_75kplus_train_005880
2,491
permissive
[ { "docstring": "Args: lats ([float]): Latitudes. lngs ([float]): Longitudes. Optional: Args: color/c/edge_color/ec (str): Color of the polygon's edge. Can be hex ('#00FFFF'), named ('cyan'), or matplotlib-like ('c'). Defaults to black. alpha/edge_alpha/ea (float): Opacity of the polygon's edge, ranging from 0 t...
2
null
Implement the Python class `_Polygon` described below. Class description: Implement the _Polygon class. Method signatures and docstrings: - def __init__(self, lats, lngs, **kwargs): Args: lats ([float]): Latitudes. lngs ([float]): Longitudes. Optional: Args: color/c/edge_color/ec (str): Color of the polygon's edge. C...
Implement the Python class `_Polygon` described below. Class description: Implement the _Polygon class. Method signatures and docstrings: - def __init__(self, lats, lngs, **kwargs): Args: lats ([float]): Latitudes. lngs ([float]): Longitudes. Optional: Args: color/c/edge_color/ec (str): Color of the polygon's edge. C...
0979c51467e25cfe870668d3990ce7885e317f85
<|skeleton|> class _Polygon: def __init__(self, lats, lngs, **kwargs): """Args: lats ([float]): Latitudes. lngs ([float]): Longitudes. Optional: Args: color/c/edge_color/ec (str): Color of the polygon's edge. Can be hex ('#00FFFF'), named ('cyan'), or matplotlib-like ('c'). Defaults to black. alpha/edge_al...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _Polygon: def __init__(self, lats, lngs, **kwargs): """Args: lats ([float]): Latitudes. lngs ([float]): Longitudes. Optional: Args: color/c/edge_color/ec (str): Color of the polygon's edge. Can be hex ('#00FFFF'), named ('cyan'), or matplotlib-like ('c'). Defaults to black. alpha/edge_alpha/ea (float)...
the_stack_v2_python_sparse
gmplot/drawables/polygon.py
tirkarthi/gmplot
train
0
53f6d7ae93a90485397b67e1978952deef31b6a2
[ "self.username = username\nself.template_lookup = LOOKUP\nself.mako_template = 'recover_pwd.mako'\nself.mako_template2 = 'ask_question.mako'\nself.mako_template3 = 'new_pwd.mako'", "resp = Response()\ntemplate_args = self.templ_arg_func(end_point_index, **kwargs)\nmako_template_engine = self.template_lookup.get_t...
<|body_start_0|> self.username = username self.template_lookup = LOOKUP self.mako_template = 'recover_pwd.mako' self.mako_template2 = 'ask_question.mako' self.mako_template3 = 'new_pwd.mako' <|end_body_0|> <|body_start_1|> resp = Response() template_args = self.t...
recovery_module
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class recovery_module: def __init__(self, username): """:param username: Username :param template_lookup: template lookup :return:""" <|body_0|> def __call__(self, cookie=None, end_point_index=0, **kwargs): """Put up the username form""" <|body_1|> def show_qu...
stack_v2_sparse_classes_75kplus_train_005881
5,495
no_license
[ { "docstring": ":param username: Username :param template_lookup: template lookup :return:", "name": "__init__", "signature": "def __init__(self, username)" }, { "docstring": "Put up the username form", "name": "__call__", "signature": "def __call__(self, cookie=None, end_point_index=0, ...
5
stack_v2_sparse_classes_30k_train_044160
Implement the Python class `recovery_module` described below. Class description: Implement the recovery_module class. Method signatures and docstrings: - def __init__(self, username): :param username: Username :param template_lookup: template lookup :return: - def __call__(self, cookie=None, end_point_index=0, **kwar...
Implement the Python class `recovery_module` described below. Class description: Implement the recovery_module class. Method signatures and docstrings: - def __init__(self, username): :param username: Username :param template_lookup: template lookup :return: - def __call__(self, cookie=None, end_point_index=0, **kwar...
4455de4eb61fb4bddf6cfa8a4ce9e5f9f8e9d812
<|skeleton|> class recovery_module: def __init__(self, username): """:param username: Username :param template_lookup: template lookup :return:""" <|body_0|> def __call__(self, cookie=None, end_point_index=0, **kwargs): """Put up the username form""" <|body_1|> def show_qu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class recovery_module: def __init__(self, username): """:param username: Username :param template_lookup: template lookup :return:""" self.username = username self.template_lookup = LOOKUP self.mako_template = 'recover_pwd.mako' self.mako_template2 = 'ask_question.mako' ...
the_stack_v2_python_sparse
server/recovery.py
CarlosGonzalezLuzardo/SECAS
train
0
5ce8b5059b2ed15ef699e0467d7d0b354739b260
[ "self.color = color\nself.width = width\nself.beg_x = beg_x\nself.beg_y = beg_y\nself.end_x = end_x\nself.end_y = end_y", "w_str = f'Wall2d:{self.color}'\nw_str += f' w:{self.width}'\nw_str += f' beg_xy:{self.beg_x},{self.beg_y}'\nw_str += f' end_xy:{self.end_x},{self.end_y}'\nreturn w_str" ]
<|body_start_0|> self.color = color self.width = width self.beg_x = beg_x self.beg_y = beg_y self.end_x = end_x self.end_y = end_y <|end_body_0|> <|body_start_1|> w_str = f'Wall2d:{self.color}' w_str += f' w:{self.width}' w_str += f' beg_xy:{self....
Wall2d
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Wall2d: def __init__(self, color='green', width=1, beg_x=0, beg_y=0, end_x=300, end_y=0): """Define/Setup Wall's attributes :color: wall's color default: black :width: width(thickness) in default units default: 1 :beg_x: x (horizontal right) in default units default: 0 :beg_y: y (vertica...
stack_v2_sparse_classes_75kplus_train_005882
1,446
no_license
[ { "docstring": "Define/Setup Wall's attributes :color: wall's color default: black :width: width(thickness) in default units default: 1 :beg_x: x (horizontal right) in default units default: 0 :beg_y: y (vertical down) in default units default: 0 :end_x: x (horizontal right) default units, default time inc defa...
2
stack_v2_sparse_classes_30k_train_010516
Implement the Python class `Wall2d` described below. Class description: Implement the Wall2d class. Method signatures and docstrings: - def __init__(self, color='green', width=1, beg_x=0, beg_y=0, end_x=300, end_y=0): Define/Setup Wall's attributes :color: wall's color default: black :width: width(thickness) in defau...
Implement the Python class `Wall2d` described below. Class description: Implement the Wall2d class. Method signatures and docstrings: - def __init__(self, color='green', width=1, beg_x=0, beg_y=0, end_x=300, end_y=0): Define/Setup Wall's attributes :color: wall's color default: black :width: width(thickness) in defau...
bedc16eb5f6db0ad3b313355df6d51b5161c3835
<|skeleton|> class Wall2d: def __init__(self, color='green', width=1, beg_x=0, beg_y=0, end_x=300, end_y=0): """Define/Setup Wall's attributes :color: wall's color default: black :width: width(thickness) in default units default: 1 :beg_x: x (horizontal right) in default units default: 0 :beg_y: y (vertica...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Wall2d: def __init__(self, color='green', width=1, beg_x=0, beg_y=0, end_x=300, end_y=0): """Define/Setup Wall's attributes :color: wall's color default: black :width: width(thickness) in default units default: 1 :beg_x: x (horizontal right) in default units default: 0 :beg_y: y (vertical down) in def...
the_stack_v2_python_sparse
exercises/classes/ball_classes/walll_2d.py
raysmith619/Introduction-To-Programming
train
3
1c82d096d7c6bdea7d863c8d1db7ea065e8f127a
[ "raise ApiError(500, 1, 'vlan status is null')\nobj = {'vlan_arr': []}\nargs = Verify.dict(self.req_args, {'limit?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid limit')), 'index?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid index'))})\narr = vcmd.get_arr_simple('cdbctl read/cdb/...
<|body_start_0|> raise ApiError(500, 1, 'vlan status is null') obj = {'vlan_arr': []} args = Verify.dict(self.req_args, {'limit?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid limit')), 'index?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid index'))}) ar...
VlanApi
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VlanApi: def get(self): """get vlan array""" <|body_0|> def post(self): """add vlan""" <|body_1|> def put(self): """modify vlan name""" <|body_2|> def delete(self): """delete vlans""" <|body_3|> <|end_skeleton|> <|b...
stack_v2_sparse_classes_75kplus_train_005883
3,263
no_license
[ { "docstring": "get vlan array", "name": "get", "signature": "def get(self)" }, { "docstring": "add vlan", "name": "post", "signature": "def post(self)" }, { "docstring": "modify vlan name", "name": "put", "signature": "def put(self)" }, { "docstring": "delete vla...
4
stack_v2_sparse_classes_30k_train_012383
Implement the Python class `VlanApi` described below. Class description: Implement the VlanApi class. Method signatures and docstrings: - def get(self): get vlan array - def post(self): add vlan - def put(self): modify vlan name - def delete(self): delete vlans
Implement the Python class `VlanApi` described below. Class description: Implement the VlanApi class. Method signatures and docstrings: - def get(self): get vlan array - def post(self): add vlan - def put(self): modify vlan name - def delete(self): delete vlans <|skeleton|> class VlanApi: def get(self): ...
2fee6115caec25fd040188dda0cb922bfca1a55f
<|skeleton|> class VlanApi: def get(self): """get vlan array""" <|body_0|> def post(self): """add vlan""" <|body_1|> def put(self): """modify vlan name""" <|body_2|> def delete(self): """delete vlans""" <|body_3|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VlanApi: def get(self): """get vlan array""" raise ApiError(500, 1, 'vlan status is null') obj = {'vlan_arr': []} args = Verify.dict(self.req_args, {'limit?': (lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid limit')), 'index?': (lambda x: x.type('int') and x > 0, A...
the_stack_v2_python_sparse
osp_sai_2.1.8/system/apps/web/api_class/vlan.py
bonald/vim_cfg
train
0
d67be9963d1ff3e8431591af26382a2c4182ecf2
[ "res = {}\n\ndef dfs(node, order):\n if not node:\n return\n res[order] = node.val\n dfs(node.left, order * 2 + 1)\n dfs(node.right, order * 2 + 2)\ndfs(root, 0)\nreturn str(res)", "l = eval(data)\nfor key in l:\n l[key] = TreeNode(l[key])\nfor k in l:\n if k * 2 + 1 in l:\n l[k].l...
<|body_start_0|> res = {} def dfs(node, order): if not node: return res[order] = node.val dfs(node.left, order * 2 + 1) dfs(node.right, order * 2 + 2) dfs(root, 0) return str(res) <|end_body_0|> <|body_start_1|> l ...
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_75kplus_train_005884
1,234
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_009288
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:...
9ae68ada9f63483323cdeaa0f7da3410a0669371
<|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_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" res = {} def dfs(node, order): if not node: return res[order] = node.val dfs(node.left, order * 2 + 1) dfs(node.r...
the_stack_v2_python_sparse
problems/0297.serialize-and-deserialize-binary-tree/serialize-and-deserialize-binary-tree.py
tirsott/lc-go
train
0
e0076ffc2e5a25011085118bd93a86122f31dbdd
[ "super(TverskyLoss2D, self).__init__()\nself.alpha = alpha\nself.beta = beta\nself.weight = weight\nself.ignore_index = ignore_index", "smooth = 1.0\npredictions = F.softmax(predictions, dim=1)\nencoded_target = predictions.detach() * 0\nmask = None\nif self.ignore_index is not None:\n mask = targets == self.i...
<|body_start_0|> super(TverskyLoss2D, self).__init__() self.alpha = alpha self.beta = beta self.weight = weight self.ignore_index = ignore_index <|end_body_0|> <|body_start_1|> smooth = 1.0 predictions = F.softmax(predictions, dim=1) encoded_target = pred...
TverskyLoss2D
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TverskyLoss2D: def __init__(self, alpha=0.4, beta=0.6, weight=None, ignore_index=-100): """Tversky Loss for Semantic Segmentation :param alpha: <int> Parameter to control precision and recall :param beta: <int> Parameter to control precision and recall :param weight: <torch.Tensor, optio...
stack_v2_sparse_classes_75kplus_train_005885
35,592
permissive
[ { "docstring": "Tversky Loss for Semantic Segmentation :param alpha: <int> Parameter to control precision and recall :param beta: <int> Parameter to control precision and recall :param weight: <torch.Tensor, optional> A manual rescaling weight given to each class. If given, has to be a Tensor of size C, where C...
2
stack_v2_sparse_classes_30k_train_033527
Implement the Python class `TverskyLoss2D` described below. Class description: Implement the TverskyLoss2D class. Method signatures and docstrings: - def __init__(self, alpha=0.4, beta=0.6, weight=None, ignore_index=-100): Tversky Loss for Semantic Segmentation :param alpha: <int> Parameter to control precision and r...
Implement the Python class `TverskyLoss2D` described below. Class description: Implement the TverskyLoss2D class. Method signatures and docstrings: - def __init__(self, alpha=0.4, beta=0.6, weight=None, ignore_index=-100): Tversky Loss for Semantic Segmentation :param alpha: <int> Parameter to control precision and r...
ed226e5454b2144063a6d8132b07c90e6a64e2d3
<|skeleton|> class TverskyLoss2D: def __init__(self, alpha=0.4, beta=0.6, weight=None, ignore_index=-100): """Tversky Loss for Semantic Segmentation :param alpha: <int> Parameter to control precision and recall :param beta: <int> Parameter to control precision and recall :param weight: <torch.Tensor, optio...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TverskyLoss2D: def __init__(self, alpha=0.4, beta=0.6, weight=None, ignore_index=-100): """Tversky Loss for Semantic Segmentation :param alpha: <int> Parameter to control precision and recall :param beta: <int> Parameter to control precision and recall :param weight: <torch.Tensor, optional> A manual ...
the_stack_v2_python_sparse
utils/losses.py
tansyab1/LightNetPlus
train
0
8443889d7c9b25c593b4fdd14bbcb8cae5e2e6f8
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DeviceComplianceActionItem()", "from .device_compliance_action_type import DeviceComplianceActionType\nfrom .entity import Entity\nfrom .device_compliance_action_type import DeviceComplianceActionType\nfrom .entity import Entity\nfield...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return DeviceComplianceActionItem() <|end_body_0|> <|body_start_1|> from .device_compliance_action_type import DeviceComplianceActionType from .entity import Entity from .device_complia...
Scheduled Action Configuration
DeviceComplianceActionItem
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeviceComplianceActionItem: """Scheduled Action Configuration""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceActionItem: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node t...
stack_v2_sparse_classes_75kplus_train_005886
3,346
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: DeviceComplianceActionItem", "name": "create_from_discriminator_value", "signature": "def create_from_discri...
3
stack_v2_sparse_classes_30k_train_047133
Implement the Python class `DeviceComplianceActionItem` described below. Class description: Scheduled Action Configuration Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceActionItem: Creates a new instance of the appropriate class based ...
Implement the Python class `DeviceComplianceActionItem` described below. Class description: Scheduled Action Configuration Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceActionItem: Creates a new instance of the appropriate class based ...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class DeviceComplianceActionItem: """Scheduled Action Configuration""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceActionItem: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DeviceComplianceActionItem: """Scheduled Action Configuration""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceActionItem: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read...
the_stack_v2_python_sparse
msgraph/generated/models/device_compliance_action_item.py
microsoftgraph/msgraph-sdk-python
train
135
8614f6c3c28f4f35ae86fd6b151814cd353ae817
[ "def get(root, items):\n if root is None:\n items.append('null')\n return\n items.append(str(root.val))\n get(root.left, items)\n get(root.right, items)\nitems = []\nget(root, items)\nreturn ','.join(items)", "def get_root(data):\n if not data:\n return\n curr = data.popleft...
<|body_start_0|> def get(root, items): if root is None: items.append('null') return items.append(str(root.val)) get(root.left, items) get(root.right, items) items = [] get(root, items) return ','.join(items) ...
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_75kplus_train_005887
1,352
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_033229
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:...
8e87b10bd77289b891591b770a6f7adc2c00fdf0
<|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_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" def get(root, items): if root is None: items.append('null') return items.append(str(root.val)) get(root.left, items) ...
the_stack_v2_python_sparse
Temp/serialize_and_deserialize_bst.py
karthik4636/practice_problems
train
0
240dfe17f8091c20f806de1d17dcb81569eaaff6
[ "super(RandomBrightness, self).__init__()\nself.probability = p\nself.min_factor = min_factor\nself.max_factor = max_factor", "if np.random.random() < self.probability:\n factor = np.random.uniform(self.min_factor, self.max_factor)\n image_enhancer_brightness = ImageEnhance.Brightness(img)\n img = image_...
<|body_start_0|> super(RandomBrightness, self).__init__() self.probability = p self.min_factor = min_factor self.max_factor = max_factor <|end_body_0|> <|body_start_1|> if np.random.random() < self.probability: factor = np.random.uniform(self.min_factor, self.max_fac...
This class is used to random change image brightness.
RandomBrightness
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomBrightness: """This class is used to random change image brightness.""" def __init__(self, p=0.8, min_factor=0.4, max_factor=1.33): """required :attr:`probability` parameter :func:`~Augmentor.Pipeline.Pipeline.random_brightness` function. :param probability: Controls the probab...
stack_v2_sparse_classes_75kplus_train_005888
40,740
no_license
[ { "docstring": "required :attr:`probability` parameter :func:`~Augmentor.Pipeline.Pipeline.random_brightness` function. :param probability: Controls the probability that the operation is performed when it is invoked in the pipeline. :param min_factor: The value between 0.0 and max_factor that define the minimum...
2
stack_v2_sparse_classes_30k_train_006796
Implement the Python class `RandomBrightness` described below. Class description: This class is used to random change image brightness. Method signatures and docstrings: - def __init__(self, p=0.8, min_factor=0.4, max_factor=1.33): required :attr:`probability` parameter :func:`~Augmentor.Pipeline.Pipeline.random_brig...
Implement the Python class `RandomBrightness` described below. Class description: This class is used to random change image brightness. Method signatures and docstrings: - def __init__(self, p=0.8, min_factor=0.4, max_factor=1.33): required :attr:`probability` parameter :func:`~Augmentor.Pipeline.Pipeline.random_brig...
a9c19225733b1a61eb0b006e6afc1bd2826bba2b
<|skeleton|> class RandomBrightness: """This class is used to random change image brightness.""" def __init__(self, p=0.8, min_factor=0.4, max_factor=1.33): """required :attr:`probability` parameter :func:`~Augmentor.Pipeline.Pipeline.random_brightness` function. :param probability: Controls the probab...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RandomBrightness: """This class is used to random change image brightness.""" def __init__(self, p=0.8, min_factor=0.4, max_factor=1.33): """required :attr:`probability` parameter :func:`~Augmentor.Pipeline.Pipeline.random_brightness` function. :param probability: Controls the probability that th...
the_stack_v2_python_sparse
imcls/data/transforms/operations.py
iYuqinL/imcls
train
0
5aab340e2768227da0c6e154bd0c3fbadbb76e44
[ "B, npoints, nsample = idx.size()\n_, N, C = points.size()\noutput = torch.cuda.FloatTensor(B, npoints, nsample, C)\npoints = points.contiguous()\nidx = idx.contiguous()\noutput = output.contiguous()\npointnet2.group_points_wrapper(B, N, C, npoints, nsample, points, idx, output)\nctx.idx_N_C_for_backward = (idx, N,...
<|body_start_0|> B, npoints, nsample = idx.size() _, N, C = points.size() output = torch.cuda.FloatTensor(B, npoints, nsample, C) points = points.contiguous() idx = idx.contiguous() output = output.contiguous() pointnet2.group_points_wrapper(B, N, C, npoints, nsam...
GroupPoints
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroupPoints: def forward(ctx, points: torch.Tensor, idx: torch.Tensor) -> torch.Tensor: """Parameters ---------- points : torch.Tensor (B, N, C) tensor of points to group idx : torch.Tensor (B, npoint, nsample) tensor containing the indicies of points to group with Returns ------- torch....
stack_v2_sparse_classes_75kplus_train_005889
10,672
no_license
[ { "docstring": "Parameters ---------- points : torch.Tensor (B, N, C) tensor of points to group idx : torch.Tensor (B, npoint, nsample) tensor containing the indicies of points to group with Returns ------- torch.Tensor (B, npoint, nsample, C) tensor", "name": "forward", "signature": "def forward(ctx, p...
2
stack_v2_sparse_classes_30k_test_000208
Implement the Python class `GroupPoints` described below. Class description: Implement the GroupPoints class. Method signatures and docstrings: - def forward(ctx, points: torch.Tensor, idx: torch.Tensor) -> torch.Tensor: Parameters ---------- points : torch.Tensor (B, N, C) tensor of points to group idx : torch.Tenso...
Implement the Python class `GroupPoints` described below. Class description: Implement the GroupPoints class. Method signatures and docstrings: - def forward(ctx, points: torch.Tensor, idx: torch.Tensor) -> torch.Tensor: Parameters ---------- points : torch.Tensor (B, N, C) tensor of points to group idx : torch.Tenso...
a573daa07b815f909771b8f648e34f52338129ef
<|skeleton|> class GroupPoints: def forward(ctx, points: torch.Tensor, idx: torch.Tensor) -> torch.Tensor: """Parameters ---------- points : torch.Tensor (B, N, C) tensor of points to group idx : torch.Tensor (B, npoint, nsample) tensor containing the indicies of points to group with Returns ------- torch....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GroupPoints: def forward(ctx, points: torch.Tensor, idx: torch.Tensor) -> torch.Tensor: """Parameters ---------- points : torch.Tensor (B, N, C) tensor of points to group idx : torch.Tensor (B, npoint, nsample) tensor containing the indicies of points to group with Returns ------- torch.Tensor (B, npo...
the_stack_v2_python_sparse
utils/pointnet2_utils.py
andrei-pokrovsky/GatechResearchF17
train
0
b632b6dc44fabf5c3300a2568631dcf9063c2aca
[ "self.config = config\ndefinitions_provider = DefinitionsProviderFactory.instantiate(config['definitions']['type'], config)\nself.definitions = definitions_provider.get_definitions()", "if lookml.filetype != 'view':\n raise Exception('Only views are supported. This is type ' + lookml.filetype)\nn = len(lookml....
<|body_start_0|> self.config = config definitions_provider = DefinitionsProviderFactory.instantiate(config['definitions']['type'], config) self.definitions = definitions_provider.get_definitions() <|end_body_0|> <|body_start_1|> if lookml.filetype != 'view': raise Exception(...
class that understands additions or modifications to be made and then delegates to filemodifier to make requested changes
LookMlModifier
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LookMlModifier: """class that understands additions or modifications to be made and then delegates to filemodifier to make requested changes""" def __init__(self, config): """initialize the LookMlModifier Args: config (JSON): the JSON configuration""" <|body_0|> def find...
stack_v2_sparse_classes_75kplus_train_005890
5,054
permissive
[ { "docstring": "initialize the LookMlModifier Args: config (JSON): the JSON configuration", "name": "__init__", "signature": "def __init__(self, config)" }, { "docstring": "get the description, if any, from this measure or dimension Args: lookml (LookML): instance of LookML header_type (str): 'm...
3
stack_v2_sparse_classes_30k_test_000225
Implement the Python class `LookMlModifier` described below. Class description: class that understands additions or modifications to be made and then delegates to filemodifier to make requested changes Method signatures and docstrings: - def __init__(self, config): initialize the LookMlModifier Args: config (JSON): t...
Implement the Python class `LookMlModifier` described below. Class description: class that understands additions or modifications to be made and then delegates to filemodifier to make requested changes Method signatures and docstrings: - def __init__(self, config): initialize the LookMlModifier Args: config (JSON): t...
cded1fd6a916cedebfd4a5b21993ce117a4a1a11
<|skeleton|> class LookMlModifier: """class that understands additions or modifications to be made and then delegates to filemodifier to make requested changes""" def __init__(self, config): """initialize the LookMlModifier Args: config (JSON): the JSON configuration""" <|body_0|> def find...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LookMlModifier: """class that understands additions or modifications to be made and then delegates to filemodifier to make requested changes""" def __init__(self, config): """initialize the LookMlModifier Args: config (JSON): the JSON configuration""" self.config = config definiti...
the_stack_v2_python_sparse
lkmltools/updater/lookml_modifier.py
mborukhava/lookml-tools
train
1
01bf75baf7cb98762e200a8204fb6955182faae5
[ "res = -1\nc = collections.Counter(arr)\nfor i in c:\n if c[i] == i:\n res = max(res, i)\nreturn res", "res = -1\ndic = collections.defaultdict(int)\nfor i in arr:\n dic[i] += 1\nfor k in dic.keys():\n if dic[k] == k and k > res:\n res = k\nreturn res", "res = -1\ndic = {}\nfor i in arr:\...
<|body_start_0|> res = -1 c = collections.Counter(arr) for i in c: if c[i] == i: res = max(res, i) return res <|end_body_0|> <|body_start_1|> res = -1 dic = collections.defaultdict(int) for i in arr: dic[i] += 1 for...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findLucky(self, arr): """:type arr: List[int] :rtype: int""" <|body_0|> def findLucky(self, arr): """:type arr: List[int] :rtype: int""" <|body_1|> def findLucky(self, arr): """:type arr: List[int] :rtype: int""" <|body_2|> ...
stack_v2_sparse_classes_75kplus_train_005891
965
no_license
[ { "docstring": ":type arr: List[int] :rtype: int", "name": "findLucky", "signature": "def findLucky(self, arr)" }, { "docstring": ":type arr: List[int] :rtype: int", "name": "findLucky", "signature": "def findLucky(self, arr)" }, { "docstring": ":type arr: List[int] :rtype: int",...
3
stack_v2_sparse_classes_30k_train_017939
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findLucky(self, arr): :type arr: List[int] :rtype: int - def findLucky(self, arr): :type arr: List[int] :rtype: int - def findLucky(self, arr): :type arr: List[int] :rtype: i...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findLucky(self, arr): :type arr: List[int] :rtype: int - def findLucky(self, arr): :type arr: List[int] :rtype: int - def findLucky(self, arr): :type arr: List[int] :rtype: i...
a509b383a42f54313970168d9faa11f088f18708
<|skeleton|> class Solution: def findLucky(self, arr): """:type arr: List[int] :rtype: int""" <|body_0|> def findLucky(self, arr): """:type arr: List[int] :rtype: int""" <|body_1|> def findLucky(self, arr): """:type arr: List[int] :rtype: int""" <|body_2|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findLucky(self, arr): """:type arr: List[int] :rtype: int""" res = -1 c = collections.Counter(arr) for i in c: if c[i] == i: res = max(res, i) return res def findLucky(self, arr): """:type arr: List[int] :rtype: int...
the_stack_v2_python_sparse
1394_Find_Lucky_Integer_in_an_Array.py
bingli8802/leetcode
train
0
b675b1a64fc89fedc36ca5187474ba5c2ef399b7
[ "super(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)\nself.gru = tf.keras.layers.GRU(units=units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)\nself.F = tf.keras.layers.Dense(units=vocab)", "batch, units = s_pre...
<|body_start_0|> super(RNNDecoder, self).__init__() self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding) self.gru = tf.keras.layers.GRU(units=units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True) self.F = tf.keras.layers.Den...
doc
RNNDecoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNNDecoder: """doc""" def __init__(self, vocab, embedding, units, batch): """doc""" <|body_0|> def call(self, x, s_prev, hidden_states): """doc""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(RNNDecoder, self).__init__() self.embed...
stack_v2_sparse_classes_75kplus_train_005892
1,304
no_license
[ { "docstring": "doc", "name": "__init__", "signature": "def __init__(self, vocab, embedding, units, batch)" }, { "docstring": "doc", "name": "call", "signature": "def call(self, x, s_prev, hidden_states)" } ]
2
stack_v2_sparse_classes_30k_train_029337
Implement the Python class `RNNDecoder` described below. Class description: doc Method signatures and docstrings: - def __init__(self, vocab, embedding, units, batch): doc - def call(self, x, s_prev, hidden_states): doc
Implement the Python class `RNNDecoder` described below. Class description: doc Method signatures and docstrings: - def __init__(self, vocab, embedding, units, batch): doc - def call(self, x, s_prev, hidden_states): doc <|skeleton|> class RNNDecoder: """doc""" def __init__(self, vocab, embedding, units, bat...
3bffd1391b3fc790f0137d0afbe90eb8e2f7d713
<|skeleton|> class RNNDecoder: """doc""" def __init__(self, vocab, embedding, units, batch): """doc""" <|body_0|> def call(self, x, s_prev, hidden_states): """doc""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RNNDecoder: """doc""" def __init__(self, vocab, embedding, units, batch): """doc""" super(RNNDecoder, self).__init__() self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding) self.gru = tf.keras.layers.GRU(units=units, recurrent_initializer='gloro...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/2-rnn_decoder.py
pafuentess/holbertonschool-machine_learning
train
0
03cc79c6bda59745752361ce520e967365a7c426
[ "super(DrainageAreaModel, self).__init__(input_file=input_file, params=params)\nself.flow_router = FlowRouter(self.grid, **self.params)\nself.lake_filler = DepressionFinderAndRouter(self.grid, **self.params)", "self.flow_router.run_one_step()\nfrom landlab.io import write_esri_ascii\nimport numpy\nwrite_esri_asci...
<|body_start_0|> super(DrainageAreaModel, self).__init__(input_file=input_file, params=params) self.flow_router = FlowRouter(self.grid, **self.params) self.lake_filler = DepressionFinderAndRouter(self.grid, **self.params) <|end_body_0|> <|body_start_1|> self.flow_router.run_one_step() ...
A DrainageAreaModel simply computes drainage area on a raster-grid DEM.
DrainageAreaModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DrainageAreaModel: """A DrainageAreaModel simply computes drainage area on a raster-grid DEM.""" def __init__(self, input_file=None, params=None): """Initialize the LinearDiffusionModel.""" <|body_0|> def run_one_step(self, dt): """Advance model for one time-step...
stack_v2_sparse_classes_75kplus_train_005893
2,284
no_license
[ { "docstring": "Initialize the LinearDiffusionModel.", "name": "__init__", "signature": "def __init__(self, input_file=None, params=None)" }, { "docstring": "Advance model for one time-step of duration dt.", "name": "run_one_step", "signature": "def run_one_step(self, dt)" } ]
2
null
Implement the Python class `DrainageAreaModel` described below. Class description: A DrainageAreaModel simply computes drainage area on a raster-grid DEM. Method signatures and docstrings: - def __init__(self, input_file=None, params=None): Initialize the LinearDiffusionModel. - def run_one_step(self, dt): Advance mo...
Implement the Python class `DrainageAreaModel` described below. Class description: A DrainageAreaModel simply computes drainage area on a raster-grid DEM. Method signatures and docstrings: - def __init__(self, input_file=None, params=None): Initialize the LinearDiffusionModel. - def run_one_step(self, dt): Advance mo...
3506ec741a7c8a170ea654d40c6119fefe1b93ba
<|skeleton|> class DrainageAreaModel: """A DrainageAreaModel simply computes drainage area on a raster-grid DEM.""" def __init__(self, input_file=None, params=None): """Initialize the LinearDiffusionModel.""" <|body_0|> def run_one_step(self, dt): """Advance model for one time-step...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DrainageAreaModel: """A DrainageAreaModel simply computes drainage area on a raster-grid DEM.""" def __init__(self, input_file=None, params=None): """Initialize the LinearDiffusionModel.""" super(DrainageAreaModel, self).__init__(input_file=input_file, params=params) self.flow_rou...
the_stack_v2_python_sparse
erosion_modeling_suite/erosion_model/single_component/drainage_area/drainage_area_model.py
kbarnhart/inverting_topography_postglacial
train
4
d0e0af05416528de6b183456529a8d3bb9775ba4
[ "try:\n user = User.objects.get(username__iexact=username)\n if user.check_password(password):\n return user\n return None\nexcept User.DoesNotExist:\n return None", "try:\n return User.objects.get(id=user_id)\nexcept User.DoesNotExist:\n return None" ]
<|body_start_0|> try: user = User.objects.get(username__iexact=username) if user.check_password(password): return user return None except User.DoesNotExist: return None <|end_body_0|> <|body_start_1|> try: return User.o...
PrklModelBackend
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrklModelBackend: def authenticate(self, username=None, password=None): """Use our derived User object but call superclass (contrib.auth) for check_password""" <|body_0|> def get_user(self, user_id): """User getter""" <|body_1|> <|end_skeleton|> <|body_star...
stack_v2_sparse_classes_75kplus_train_005894
1,543
no_license
[ { "docstring": "Use our derived User object but call superclass (contrib.auth) for check_password", "name": "authenticate", "signature": "def authenticate(self, username=None, password=None)" }, { "docstring": "User getter", "name": "get_user", "signature": "def get_user(self, user_id)" ...
2
stack_v2_sparse_classes_30k_train_042594
Implement the Python class `PrklModelBackend` described below. Class description: Implement the PrklModelBackend class. Method signatures and docstrings: - def authenticate(self, username=None, password=None): Use our derived User object but call superclass (contrib.auth) for check_password - def get_user(self, user_...
Implement the Python class `PrklModelBackend` described below. Class description: Implement the PrklModelBackend class. Method signatures and docstrings: - def authenticate(self, username=None, password=None): Use our derived User object but call superclass (contrib.auth) for check_password - def get_user(self, user_...
1c95d454c9efc180058156694b5c9900ef526ed0
<|skeleton|> class PrklModelBackend: def authenticate(self, username=None, password=None): """Use our derived User object but call superclass (contrib.auth) for check_password""" <|body_0|> def get_user(self, user_id): """User getter""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PrklModelBackend: def authenticate(self, username=None, password=None): """Use our derived User object but call superclass (contrib.auth) for check_password""" try: user = User.objects.get(username__iexact=username) if user.check_password(password): retu...
the_stack_v2_python_sparse
web/auth.py
mjtorn/prkl
train
0
a9c3ba960690756f88d22e81291e4d283be26e16
[ "self.lr = lr\nself.b1 = b1\nself.b2 = b2\nself.num_params = num_params\nself.counter = 0\nself.momentum = [0 for _ in range(num_params)]\nself.velocity = [0 for _ in range(num_params)]", "self.counter += 1\nepsilon = 1e-08\nnew_params = []\nfor i in range(self.num_params):\n self.momentum[i] = self.b1 * self....
<|body_start_0|> self.lr = lr self.b1 = b1 self.b2 = b2 self.num_params = num_params self.counter = 0 self.momentum = [0 for _ in range(num_params)] self.velocity = [0 for _ in range(num_params)] <|end_body_0|> <|body_start_1|> self.counter += 1 e...
Adamax
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Adamax: def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.99): """Initializer for Adamax optimizer Inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 b1 : The ex...
stack_v2_sparse_classes_75kplus_train_005895
10,861
no_license
[ { "docstring": "Initializer for Adamax optimizer Inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 b1 : The exponential decay rate for the first moment(integer/float), default is 0.9 b2 : Th...
2
stack_v2_sparse_classes_30k_train_053962
Implement the Python class `Adamax` described below. Class description: Implement the Adamax class. Method signatures and docstrings: - def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.99): Initializer for Adamax optimizer Inputs: num params: number of parameters which are ought to be passed lr: The learning r...
Implement the Python class `Adamax` described below. Class description: Implement the Adamax class. Method signatures and docstrings: - def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.99): Initializer for Adamax optimizer Inputs: num params: number of parameters which are ought to be passed lr: The learning r...
9406b21aef9b2d94091d570e809f88a752277e30
<|skeleton|> class Adamax: def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.99): """Initializer for Adamax optimizer Inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 b1 : The ex...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Adamax: def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.99): """Initializer for Adamax optimizer Inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 b1 : The exponential deca...
the_stack_v2_python_sparse
optimizers.py
viswambhar-yasa/AuToDiFf
train
0
629ca01c8f28979a280d98248aba28a7dc3b6ebc
[ "super().__init__(db_interface)\nself.table_name = '自合成指数'\nself.policy = index_composition_policy\nself.weight = None\nif index_composition_policy.unit_base:\n self.weight = (CompactFactor(index_composition_policy.unit_base, self.db_interface) * self.data_reader.stock_close).weight()\nself.stock_ticker_selector...
<|body_start_0|> super().__init__(db_interface) self.table_name = '自合成指数' self.policy = index_composition_policy self.weight = None if index_composition_policy.unit_base: self.weight = (CompactFactor(index_composition_policy.unit_base, self.db_interface) * self.data_r...
IndexCompositor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IndexCompositor: def __init__(self, index_composition_policy: utils.StockIndexCompositionPolicy, db_interface: DBInterface=None): """自建指数收益计算器""" <|body_0|> def update(self): """更新市场收益率""" <|body_1|> <|end_skeleton|> <|body_start_0|> super().__init_...
stack_v2_sparse_classes_75kplus_train_005896
13,646
permissive
[ { "docstring": "自建指数收益计算器", "name": "__init__", "signature": "def __init__(self, index_composition_policy: utils.StockIndexCompositionPolicy, db_interface: DBInterface=None)" }, { "docstring": "更新市场收益率", "name": "update", "signature": "def update(self)" } ]
2
stack_v2_sparse_classes_30k_train_004628
Implement the Python class `IndexCompositor` described below. Class description: Implement the IndexCompositor class. Method signatures and docstrings: - def __init__(self, index_composition_policy: utils.StockIndexCompositionPolicy, db_interface: DBInterface=None): 自建指数收益计算器 - def update(self): 更新市场收益率
Implement the Python class `IndexCompositor` described below. Class description: Implement the IndexCompositor class. Method signatures and docstrings: - def __init__(self, index_composition_policy: utils.StockIndexCompositionPolicy, db_interface: DBInterface=None): 自建指数收益计算器 - def update(self): 更新市场收益率 <|skeleton|>...
13c78602fe00a5326f421c8a8003f3889492e6dd
<|skeleton|> class IndexCompositor: def __init__(self, index_composition_policy: utils.StockIndexCompositionPolicy, db_interface: DBInterface=None): """自建指数收益计算器""" <|body_0|> def update(self): """更新市场收益率""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IndexCompositor: def __init__(self, index_composition_policy: utils.StockIndexCompositionPolicy, db_interface: DBInterface=None): """自建指数收益计算器""" super().__init__(db_interface) self.table_name = '自合成指数' self.policy = index_composition_policy self.weight = None i...
the_stack_v2_python_sparse
AShareData/factor_compositor/factor_compositor.py
ccbobt/AShareData
train
0
092cde234f7272a0e0e5a55bdb1cdc677a5ae153
[ "try:\n self.SOCK = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.SOCK.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nexcept:\n print('启动失败')\n exit(0)\nself.application = app", "self.SOCK.listen()\nwhile True:\n client_socket, client_ip = self.SOCK.accept()\n p = Process(targ...
<|body_start_0|> try: self.SOCK = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.SOCK.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except: print('启动失败') exit(0) self.application = app <|end_body_0|> <|body_start_1|> self.S...
HTTPServer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HTTPServer: def __init__(self, app: object) -> None: """初始化参数,端口 启动时监听网路数据 IP 监听的IP port 监听的端口""" <|body_0|> def start(self) -> None: """主循环等待客户端连接""" <|body_1|> def bind(self, PORT: any=8000, IP: str='127.0.0.1') -> None: """绑定端口,IP""" <...
stack_v2_sparse_classes_75kplus_train_005897
2,785
no_license
[ { "docstring": "初始化参数,端口 启动时监听网路数据 IP 监听的IP port 监听的端口", "name": "__init__", "signature": "def __init__(self, app: object) -> None" }, { "docstring": "主循环等待客户端连接", "name": "start", "signature": "def start(self) -> None" }, { "docstring": "绑定端口,IP", "name": "bind", "signat...
5
stack_v2_sparse_classes_30k_train_044891
Implement the Python class `HTTPServer` described below. Class description: Implement the HTTPServer class. Method signatures and docstrings: - def __init__(self, app: object) -> None: 初始化参数,端口 启动时监听网路数据 IP 监听的IP port 监听的端口 - def start(self) -> None: 主循环等待客户端连接 - def bind(self, PORT: any=8000, IP: str='127.0.0.1') ->...
Implement the Python class `HTTPServer` described below. Class description: Implement the HTTPServer class. Method signatures and docstrings: - def __init__(self, app: object) -> None: 初始化参数,端口 启动时监听网路数据 IP 监听的IP port 监听的端口 - def start(self) -> None: 主循环等待客户端连接 - def bind(self, PORT: any=8000, IP: str='127.0.0.1') ->...
9db454d173ef35576d1f5f453e69ad9181d76ee7
<|skeleton|> class HTTPServer: def __init__(self, app: object) -> None: """初始化参数,端口 启动时监听网路数据 IP 监听的IP port 监听的端口""" <|body_0|> def start(self) -> None: """主循环等待客户端连接""" <|body_1|> def bind(self, PORT: any=8000, IP: str='127.0.0.1') -> None: """绑定端口,IP""" <...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HTTPServer: def __init__(self, app: object) -> None: """初始化参数,端口 启动时监听网路数据 IP 监听的IP port 监听的端口""" try: self.SOCK = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.SOCK.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except: print('启动失败')...
the_stack_v2_python_sparse
HTTP_SERVER/sys_http/server.py
WillOfTree/TaoWu
train
0
941242456a627032f5e0d32e5e734e3e245ac655
[ "vis = {(0, 0)}\nfor i in range(m):\n for j in range(n):\n if ((i - 1, j) in vis or (i, j - 1) in vis) and digit_sum(i) + digit_sum(j) <= k:\n vis.add((i, j))\nreturn len(vis)", "from queue import Queue\nq = Queue()\nq.put((0, 0))\ns = set()\nwhile not q.empty():\n x, y = q.get()\n if (...
<|body_start_0|> vis = {(0, 0)} for i in range(m): for j in range(n): if ((i - 1, j) in vis or (i, j - 1) in vis) and digit_sum(i) + digit_sum(j) <= k: vis.add((i, j)) return len(vis) <|end_body_0|> <|body_start_1|> from queue import Queue...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def movingCount(self, m: int, n: int, k: int) -> int: """递推法 这里需要注意,所有的可能题解都是联通的,只需要考虑向右或者向下的情况。""" <|body_0|> def movingCount_2(self, m: int, n: int, k: int) -> int: """广度优先法""" <|body_1|> <|end_skeleton|> <|body_start_0|> vis = {(0, 0)} ...
stack_v2_sparse_classes_75kplus_train_005898
1,810
no_license
[ { "docstring": "递推法 这里需要注意,所有的可能题解都是联通的,只需要考虑向右或者向下的情况。", "name": "movingCount", "signature": "def movingCount(self, m: int, n: int, k: int) -> int" }, { "docstring": "广度优先法", "name": "movingCount_2", "signature": "def movingCount_2(self, m: int, n: int, k: int) -> int" } ]
2
stack_v2_sparse_classes_30k_train_002834
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def movingCount(self, m: int, n: int, k: int) -> int: 递推法 这里需要注意,所有的可能题解都是联通的,只需要考虑向右或者向下的情况。 - def movingCount_2(self, m: int, n: int, k: int) -> int: 广度优先法
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def movingCount(self, m: int, n: int, k: int) -> int: 递推法 这里需要注意,所有的可能题解都是联通的,只需要考虑向右或者向下的情况。 - def movingCount_2(self, m: int, n: int, k: int) -> int: 广度优先法 <|skeleton|> class ...
c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0
<|skeleton|> class Solution: def movingCount(self, m: int, n: int, k: int) -> int: """递推法 这里需要注意,所有的可能题解都是联通的,只需要考虑向右或者向下的情况。""" <|body_0|> def movingCount_2(self, m: int, n: int, k: int) -> int: """广度优先法""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def movingCount(self, m: int, n: int, k: int) -> int: """递推法 这里需要注意,所有的可能题解都是联通的,只需要考虑向右或者向下的情况。""" vis = {(0, 0)} for i in range(m): for j in range(n): if ((i - 1, j) in vis or (i, j - 1) in vis) and digit_sum(i) + digit_sum(j) <= k: ...
the_stack_v2_python_sparse
SwordOffer/SwordOffer_13.py
EachenKuang/LeetCode
train
28
7b1ee8a032873f555036c4b432c1d9e974f0498c
[ "expected_required_inputs = PIPELINE_TO_REQD_INFILES_BY_SAMPLE['testpipeline.sh'][sample_index]\nsample = proj.samples[sample_index]\nsample.set_pipeline_attributes(pipe_iface, 'testpipeline.sh')\nobserved_required_inputs = [os.path.basename(f) for f in sample.required_inputs]\nassert expected_required_inputs == ob...
<|body_start_0|> expected_required_inputs = PIPELINE_TO_REQD_INFILES_BY_SAMPLE['testpipeline.sh'][sample_index] sample = proj.samples[sample_index] sample.set_pipeline_attributes(pipe_iface, 'testpipeline.sh') observed_required_inputs = [os.path.basename(f) for f in sample.required_input...
Tests for `Sample` related to `Project` construction
SampleWrtProjectCtorTests
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SampleWrtProjectCtorTests: """Tests for `Sample` related to `Project` construction""" def test_required_inputs(self, proj, pipe_iface, sample_index): """A looper Sample's required inputs are based on pipeline.""" <|body_0|> def test_ngs_pipe_ngs_sample(self, proj, pipe_i...
stack_v2_sparse_classes_75kplus_train_005899
4,853
permissive
[ { "docstring": "A looper Sample's required inputs are based on pipeline.", "name": "test_required_inputs", "signature": "def test_required_inputs(self, proj, pipe_iface, sample_index)" }, { "docstring": "NGS pipeline with NGS input works just fine.", "name": "test_ngs_pipe_ngs_sample", "...
3
null
Implement the Python class `SampleWrtProjectCtorTests` described below. Class description: Tests for `Sample` related to `Project` construction Method signatures and docstrings: - def test_required_inputs(self, proj, pipe_iface, sample_index): A looper Sample's required inputs are based on pipeline. - def test_ngs_pi...
Implement the Python class `SampleWrtProjectCtorTests` described below. Class description: Tests for `Sample` related to `Project` construction Method signatures and docstrings: - def test_required_inputs(self, proj, pipe_iface, sample_index): A looper Sample's required inputs are based on pipeline. - def test_ngs_pi...
df535be2a0bd7257ee37148cb601d688ec557909
<|skeleton|> class SampleWrtProjectCtorTests: """Tests for `Sample` related to `Project` construction""" def test_required_inputs(self, proj, pipe_iface, sample_index): """A looper Sample's required inputs are based on pipeline.""" <|body_0|> def test_ngs_pipe_ngs_sample(self, proj, pipe_i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SampleWrtProjectCtorTests: """Tests for `Sample` related to `Project` construction""" def test_required_inputs(self, proj, pipe_iface, sample_index): """A looper Sample's required inputs are based on pipeline.""" expected_required_inputs = PIPELINE_TO_REQD_INFILES_BY_SAMPLE['testpipeline....
the_stack_v2_python_sparse
oldtests/integration/def test_project_iface_sample_interaction.py
vreuter/looper
train
1