blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0d7435c9c3f78fea8212d02288beb662458c31ff | [
"role = get_object_or_404(Role, pk=role_id)\nserializer = RoleSerializer(role)\nreturn Response(serializer.data)",
"role = get_object_or_404(Role, pk=role_id)\nserializer = RoleSerializer(role, data=request.data)\nif serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\nreturn Respo... | <|body_start_0|>
role = get_object_or_404(Role, pk=role_id)
serializer = RoleSerializer(role)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
role = get_object_or_404(Role, pk=role_id)
serializer = RoleSerializer(role, data=request.data)
if serializer.is... | RoleDetail | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleDetail:
def get(self, request, role_id, format=None):
"""Get role detail --- serializer: administrator.serializers.RoleSerializer"""
<|body_0|>
def put(self, request, role_id, format=None):
"""Edit role --- serializer: administrator.serializers.RoleSerializer"""
... | stack_v2_sparse_classes_36k_train_016100 | 30,608 | permissive | [
{
"docstring": "Get role detail --- serializer: administrator.serializers.RoleSerializer",
"name": "get",
"signature": "def get(self, request, role_id, format=None)"
},
{
"docstring": "Edit role --- serializer: administrator.serializers.RoleSerializer",
"name": "put",
"signature": "def p... | 3 | stack_v2_sparse_classes_30k_train_008841 | Implement the Python class `RoleDetail` described below.
Class description:
Implement the RoleDetail class.
Method signatures and docstrings:
- def get(self, request, role_id, format=None): Get role detail --- serializer: administrator.serializers.RoleSerializer
- def put(self, request, role_id, format=None): Edit ro... | Implement the Python class `RoleDetail` described below.
Class description:
Implement the RoleDetail class.
Method signatures and docstrings:
- def get(self, request, role_id, format=None): Get role detail --- serializer: administrator.serializers.RoleSerializer
- def put(self, request, role_id, format=None): Edit ro... | 73728463badb3bfd4413aa0f7aeb44a9606fdfea | <|skeleton|>
class RoleDetail:
def get(self, request, role_id, format=None):
"""Get role detail --- serializer: administrator.serializers.RoleSerializer"""
<|body_0|>
def put(self, request, role_id, format=None):
"""Edit role --- serializer: administrator.serializers.RoleSerializer"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleDetail:
def get(self, request, role_id, format=None):
"""Get role detail --- serializer: administrator.serializers.RoleSerializer"""
role = get_object_or_404(Role, pk=role_id)
serializer = RoleSerializer(role)
return Response(serializer.data)
def put(self, request, rol... | the_stack_v2_python_sparse | administrator/views.py | belatrix/BackendAllStars | train | 5 | |
fc5098e903f2c888d6eadfb11a5210f594600dce | [
"tempDictionary = {}\ntempDictionary['total_price'] = 0\nfor product in products:\n if not product['name'] in self.products_data:\n new_product = super(Purchase, self).__init__(product['name'], product['type'], 0, product['price'])\n product_price = product['quantity'] * product['price']\n tax = pro... | <|body_start_0|>
tempDictionary = {}
tempDictionary['total_price'] = 0
for product in products:
if not product['name'] in self.products_data:
new_product = super(Purchase, self).__init__(product['name'], product['type'], 0, product['price'])
product_price ... | This class used to store purchase of products | Purchase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Purchase:
"""This class used to store purchase of products"""
def create_purchase_order(self, products, vendor_name):
"""func :- Used to create new purchase order. params :- products' names, quantity, type and price - dictionary params :- vendor name - string returns :- Error msg if ... | stack_v2_sparse_classes_36k_train_016101 | 2,497 | no_license | [
{
"docstring": "func :- Used to create new purchase order. params :- products' names, quantity, type and price - dictionary params :- vendor name - string returns :- Error msg if more than purchase price else purchase number",
"name": "create_purchase_order",
"signature": "def create_purchase_order(self... | 2 | stack_v2_sparse_classes_30k_train_016424 | Implement the Python class `Purchase` described below.
Class description:
This class used to store purchase of products
Method signatures and docstrings:
- def create_purchase_order(self, products, vendor_name): func :- Used to create new purchase order. params :- products' names, quantity, type and price - dictionar... | Implement the Python class `Purchase` described below.
Class description:
This class used to store purchase of products
Method signatures and docstrings:
- def create_purchase_order(self, products, vendor_name): func :- Used to create new purchase order. params :- products' names, quantity, type and price - dictionar... | 08668c834bdb4aee3abafdedc9126bba7aa041b8 | <|skeleton|>
class Purchase:
"""This class used to store purchase of products"""
def create_purchase_order(self, products, vendor_name):
"""func :- Used to create new purchase order. params :- products' names, quantity, type and price - dictionary params :- vendor name - string returns :- Error msg if ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Purchase:
"""This class used to store purchase of products"""
def create_purchase_order(self, products, vendor_name):
"""func :- Used to create new purchase order. params :- products' names, quantity, type and price - dictionary params :- vendor name - string returns :- Error msg if more than pur... | the_stack_v2_python_sparse | Test1/purchase.py | maulikb-emipro/Python-Training | train | 0 |
53164e19a35cb504e347207fc5c6d28819da125e | [
"self.pitch = pitch\nself.frame_center = frame_center\nheight, width, channels = frame_shape\nself.return_circle_contours = return_circle_contours\nself.ball_tracker = BallTracker((0, width, 0, height), 0, pitch, calibration)\nself.circle_tracker = RobotTracker(['yellow', 'blue'], ['green', 'pink'], (0, width, 0, h... | <|body_start_0|>
self.pitch = pitch
self.frame_center = frame_center
height, width, channels = frame_shape
self.return_circle_contours = return_circle_contours
self.ball_tracker = BallTracker((0, width, 0, height), 0, pitch, calibration)
self.circle_tracker = RobotTracker... | Locate objects on the pitch. | Vision | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vision:
"""Locate objects on the pitch."""
def __init__(self, pitch, frame_shape, frame_center, calibration, robots, trackers_out, return_circle_contours=False, using_matlab=False):
"""Initialize the vision system. Params: [int] pitch pitch number (0 or 1) [string] color color of our... | stack_v2_sparse_classes_36k_train_016102 | 6,060 | no_license | [
{
"docstring": "Initialize the vision system. Params: [int] pitch pitch number (0 or 1) [string] color color of our robot [string] our_side our side [boolean] return_circle_contours - will return circle contours as well as calculated robot locations. Made for color calibration GUI. [boolean] using_matlab - will... | 3 | stack_v2_sparse_classes_30k_train_009006 | Implement the Python class `Vision` described below.
Class description:
Locate objects on the pitch.
Method signatures and docstrings:
- def __init__(self, pitch, frame_shape, frame_center, calibration, robots, trackers_out, return_circle_contours=False, using_matlab=False): Initialize the vision system. Params: [int... | Implement the Python class `Vision` described below.
Class description:
Locate objects on the pitch.
Method signatures and docstrings:
- def __init__(self, pitch, frame_shape, frame_center, calibration, robots, trackers_out, return_circle_contours=False, using_matlab=False): Initialize the vision system. Params: [int... | d3bf4195144240412d3696bbe9e1055e58f46c0d | <|skeleton|>
class Vision:
"""Locate objects on the pitch."""
def __init__(self, pitch, frame_shape, frame_center, calibration, robots, trackers_out, return_circle_contours=False, using_matlab=False):
"""Initialize the vision system. Params: [int] pitch pitch number (0 or 1) [string] color color of our... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vision:
"""Locate objects on the pitch."""
def __init__(self, pitch, frame_shape, frame_center, calibration, robots, trackers_out, return_circle_contours=False, using_matlab=False):
"""Initialize the vision system. Params: [int] pitch pitch number (0 or 1) [string] color color of our robot [strin... | the_stack_v2_python_sparse | vision.py | jsren/sdp-vision | train | 2 |
6e36b3fa2f3e0af60eb323ed181fc87e6bc972b5 | [
"for uri in msg.uri_list:\n while HTTP_REDIR.match(uri):\n h_redir = HTTP_REDIR.match(uri).groups()[0]\n h_dest = HTTP_REDIR.match(uri).groups()[1]\n uri = h_dest\n h_redir = urlparse(h_redir).netloc\n h_dest = urlparse(h_dest).netloc\n if h_redir != h_dest:\n ... | <|body_start_0|>
for uri in msg.uri_list:
while HTTP_REDIR.match(uri):
h_redir = HTTP_REDIR.match(uri).groups()[0]
h_dest = HTTP_REDIR.match(uri).groups()[1]
uri = h_dest
h_redir = urlparse(h_redir).netloc
h_dest = urlpa... | Implements the uri_eval rule | URIEvalPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class URIEvalPlugin:
"""Implements the uri_eval rule"""
def check_for_http_redirector(self, msg, target=None):
"""Checks if the uri has been redirected. -use HTTP_REDIR regex in order to extract the destination domain and compare it with source domain"""
<|body_0|>
def check_h... | stack_v2_sparse_classes_36k_train_016103 | 3,242 | permissive | [
{
"docstring": "Checks if the uri has been redirected. -use HTTP_REDIR regex in order to extract the destination domain and compare it with source domain",
"name": "check_for_http_redirector",
"signature": "def check_for_http_redirector(self, msg, target=None)"
},
{
"docstring": "Checks if in <a... | 4 | stack_v2_sparse_classes_30k_val_000046 | Implement the Python class `URIEvalPlugin` described below.
Class description:
Implements the uri_eval rule
Method signatures and docstrings:
- def check_for_http_redirector(self, msg, target=None): Checks if the uri has been redirected. -use HTTP_REDIR regex in order to extract the destination domain and compare it ... | Implement the Python class `URIEvalPlugin` described below.
Class description:
Implements the uri_eval rule
Method signatures and docstrings:
- def check_for_http_redirector(self, msg, target=None): Checks if the uri has been redirected. -use HTTP_REDIR regex in order to extract the destination domain and compare it ... | 86cab72a79f9d9151390a01f3efc372a2c658eef | <|skeleton|>
class URIEvalPlugin:
"""Implements the uri_eval rule"""
def check_for_http_redirector(self, msg, target=None):
"""Checks if the uri has been redirected. -use HTTP_REDIR regex in order to extract the destination domain and compare it with source domain"""
<|body_0|>
def check_h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class URIEvalPlugin:
"""Implements the uri_eval rule"""
def check_for_http_redirector(self, msg, target=None):
"""Checks if the uri has been redirected. -use HTTP_REDIR regex in order to extract the destination domain and compare it with source domain"""
for uri in msg.uri_list:
whi... | the_stack_v2_python_sparse | oa/plugins/uri_eval.py | SpamExperts/OrangeAssassin | train | 59 |
dc8908acbe8419473fc88fe51b25882824298413 | [
"if data is not None:\n data = np.transpose(np.atleast_2d(data))\n self.mean = data.mean(axis=0)\n self.std = data.std(axis=0)\n self.nobservations = data.shape[0]\n self.ndimensions = data.shape[1]\nelse:\n self.nobservations = 0",
"if self.nobservations == 0:\n self.__init__(data)\nelse:\n ... | <|body_start_0|>
if data is not None:
data = np.transpose(np.atleast_2d(data))
self.mean = data.mean(axis=0)
self.std = data.std(axis=0)
self.nobservations = data.shape[0]
self.ndimensions = data.shape[1]
else:
self.nobservations = ... | StatsRecorder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatsRecorder:
def __init__(self, data=None):
"""data: ndarray, shape (nobservations, ndimensions)"""
<|body_0|>
def update(self, data):
"""data: ndarray, shape (nobservations, ndimensions)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if data is ... | stack_v2_sparse_classes_36k_train_016104 | 13,008 | no_license | [
{
"docstring": "data: ndarray, shape (nobservations, ndimensions)",
"name": "__init__",
"signature": "def __init__(self, data=None)"
},
{
"docstring": "data: ndarray, shape (nobservations, ndimensions)",
"name": "update",
"signature": "def update(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015321 | Implement the Python class `StatsRecorder` described below.
Class description:
Implement the StatsRecorder class.
Method signatures and docstrings:
- def __init__(self, data=None): data: ndarray, shape (nobservations, ndimensions)
- def update(self, data): data: ndarray, shape (nobservations, ndimensions) | Implement the Python class `StatsRecorder` described below.
Class description:
Implement the StatsRecorder class.
Method signatures and docstrings:
- def __init__(self, data=None): data: ndarray, shape (nobservations, ndimensions)
- def update(self, data): data: ndarray, shape (nobservations, ndimensions)
<|skeleton... | 28a59f3182f0ba58ba582449377c6588af1d4cde | <|skeleton|>
class StatsRecorder:
def __init__(self, data=None):
"""data: ndarray, shape (nobservations, ndimensions)"""
<|body_0|>
def update(self, data):
"""data: ndarray, shape (nobservations, ndimensions)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatsRecorder:
def __init__(self, data=None):
"""data: ndarray, shape (nobservations, ndimensions)"""
if data is not None:
data = np.transpose(np.atleast_2d(data))
self.mean = data.mean(axis=0)
self.std = data.std(axis=0)
self.nobservations = dat... | the_stack_v2_python_sparse | ]tasks/2018.11.06.domain_baselines/dtda_gaussian_recorder.py | bohaohuang/sis | train | 2 | |
2ef601b6b82a6cd9749b697cd4c42d0d4ce7c62e | [
"vectorized = not isinstance(y0, float)\nself._t_bound = t_bound\nif rtol is None:\n rtol = 0.2 * stepsize\nif atol is None:\n atol = rtol / 800.0\nsuper(RK45, self).__init__(fun=fun, t0=t0, y0=y0, t_bound=self._t_bound, first_step=0.8 * stepsize, max_step=8.0 * stepsize, rtol=rtol, atol=atol, vectorized=vect... | <|body_start_0|>
vectorized = not isinstance(y0, float)
self._t_bound = t_bound
if rtol is None:
rtol = 0.2 * stepsize
if atol is None:
atol = rtol / 800.0
super(RK45, self).__init__(fun=fun, t0=t0, y0=y0, t_bound=self._t_bound, first_step=0.8 * stepsize, ... | This Class inherits ~scipy.integrate.RK45 Class | RK45 | [
"LicenseRef-scancode-proprietary-license",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RK45:
"""This Class inherits ~scipy.integrate.RK45 Class"""
def __init__(self, fun, t0, y0, t_bound, stepsize, rtol=None, atol=None):
"""Initialization Parameters ---------- fun : function Should accept t, y as parameters, and return same type as y t0 : float Initial t y0 : ~numpy.ar... | stack_v2_sparse_classes_36k_train_016105 | 3,387 | permissive | [
{
"docstring": "Initialization Parameters ---------- fun : function Should accept t, y as parameters, and return same type as y t0 : float Initial t y0 : ~numpy.array or float Initial y t_bound : float Boundary time - the integration won't continue beyond it. It also determines the direction of the integration.... | 2 | stack_v2_sparse_classes_30k_train_006944 | Implement the Python class `RK45` described below.
Class description:
This Class inherits ~scipy.integrate.RK45 Class
Method signatures and docstrings:
- def __init__(self, fun, t0, y0, t_bound, stepsize, rtol=None, atol=None): Initialization Parameters ---------- fun : function Should accept t, y as parameters, and ... | Implement the Python class `RK45` described below.
Class description:
This Class inherits ~scipy.integrate.RK45 Class
Method signatures and docstrings:
- def __init__(self, fun, t0, y0, t_bound, stepsize, rtol=None, atol=None): Initialization Parameters ---------- fun : function Should accept t, y as parameters, and ... | 1bd1b27e142b0a0ec2e26bf2611468dbf50d9cf8 | <|skeleton|>
class RK45:
"""This Class inherits ~scipy.integrate.RK45 Class"""
def __init__(self, fun, t0, y0, t_bound, stepsize, rtol=None, atol=None):
"""Initialization Parameters ---------- fun : function Should accept t, y as parameters, and return same type as y t0 : float Initial t y0 : ~numpy.ar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RK45:
"""This Class inherits ~scipy.integrate.RK45 Class"""
def __init__(self, fun, t0, y0, t_bound, stepsize, rtol=None, atol=None):
"""Initialization Parameters ---------- fun : function Should accept t, y as parameters, and return same type as y t0 : float Initial t y0 : ~numpy.array or float ... | the_stack_v2_python_sparse | src/einsteinpy/integrators/runge_kutta.py | einsteinpy/einsteinpy | train | 594 |
a79b236c599dd279e73918862a4bc6bd08b56819 | [
"super().__init__(headers, headers_submap, path, path_params, path_params_submap, query_params, query_params_submap)\nif messages and messages[0] is ...:\n messages = messages[1:]\n self.any_start = True\nelse:\n self.any_start = False\nif messages and messages[-1] is ...:\n messages = messages[:-1]\n ... | <|body_start_0|>
super().__init__(headers, headers_submap, path, path_params, path_params_submap, query_params, query_params_submap)
if messages and messages[0] is ...:
messages = messages[1:]
self.any_start = True
else:
self.any_start = False
if messa... | An expected websocket transcript | ExpectedWSTranscript | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpectedWSTranscript:
"""An expected websocket transcript"""
def __init__(self, messages: Sequence[Union[ellipsis, ExpectedWSMessage]]=(...,), headers: Optional[Mapping[bytes, Collection[bytes]]]=None, headers_submap: Optional[Mapping[bytes, Collection[bytes]]]=None, path: Optional[Union[str... | stack_v2_sparse_classes_36k_train_016106 | 20,254 | permissive | [
{
"docstring": "Args: messages: the expected messages in the transcript, can begin or end ellipsis to signify that any number of messages and precede or follow the messages to match. headers: If specified, expects the request to have these headers exactly headers_submap: If specified expects the request to have... | 2 | stack_v2_sparse_classes_30k_val_000624 | Implement the Python class `ExpectedWSTranscript` described below.
Class description:
An expected websocket transcript
Method signatures and docstrings:
- def __init__(self, messages: Sequence[Union[ellipsis, ExpectedWSMessage]]=(...,), headers: Optional[Mapping[bytes, Collection[bytes]]]=None, headers_submap: Option... | Implement the Python class `ExpectedWSTranscript` described below.
Class description:
An expected websocket transcript
Method signatures and docstrings:
- def __init__(self, messages: Sequence[Union[ellipsis, ExpectedWSMessage]]=(...,), headers: Optional[Mapping[bytes, Collection[bytes]]]=None, headers_submap: Option... | 1914e42f33f8758d25cc985d672aaa3855ee9261 | <|skeleton|>
class ExpectedWSTranscript:
"""An expected websocket transcript"""
def __init__(self, messages: Sequence[Union[ellipsis, ExpectedWSMessage]]=(...,), headers: Optional[Mapping[bytes, Collection[bytes]]]=None, headers_submap: Optional[Mapping[bytes, Collection[bytes]]]=None, path: Optional[Union[str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExpectedWSTranscript:
"""An expected websocket transcript"""
def __init__(self, messages: Sequence[Union[ellipsis, ExpectedWSMessage]]=(...,), headers: Optional[Mapping[bytes, Collection[bytes]]]=None, headers_submap: Optional[Mapping[bytes, Collection[bytes]]]=None, path: Optional[Union[str, Pattern[str... | the_stack_v2_python_sparse | yellowbox/extras/webserver/ws_request_capture.py | nx6110a5100/yellowbox | train | 0 |
74d1238680fb22a67c83447af0fe73406e31bc75 | [
"self.model = BBBSeg()\nif weight_path is not None:\n self.model.load_weights(weight_path)",
"if Checker.check_input_type_bool(path, 'nii'):\n image = sitk.ReadImage(path)\n self.space = image.GetSpacing()\n image = sitk.GetArrayFromImage(image).astype('float32')\nelif Checker.check_input_type_bool(pa... | <|body_start_0|>
self.model = BBBSeg()
if weight_path is not None:
self.model.load_weights(weight_path)
<|end_body_0|>
<|body_start_1|>
if Checker.check_input_type_bool(path, 'nii'):
image = sitk.ReadImage(path)
self.space = image.GetSpacing()
ima... | BlackbloodSegmentation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlackbloodSegmentation:
def __init__(self, weight_path: str=None):
"""Initialize the model with its weight. Args: (string) weight_path : model's weight path"""
<|body_0|>
def _preprocessing(self, path: str) -> np.array:
"""Preprocess the image from the path Args: (st... | stack_v2_sparse_classes_36k_train_016107 | 8,369 | permissive | [
{
"docstring": "Initialize the model with its weight. Args: (string) weight_path : model's weight path",
"name": "__init__",
"signature": "def __init__(self, weight_path: str=None)"
},
{
"docstring": "Preprocess the image from the path Args: (string) path : absolute path of image Return: (numpy ... | 3 | stack_v2_sparse_classes_30k_train_004513 | Implement the Python class `BlackbloodSegmentation` described below.
Class description:
Implement the BlackbloodSegmentation class.
Method signatures and docstrings:
- def __init__(self, weight_path: str=None): Initialize the model with its weight. Args: (string) weight_path : model's weight path
- def _preprocessing... | Implement the Python class `BlackbloodSegmentation` described below.
Class description:
Implement the BlackbloodSegmentation class.
Method signatures and docstrings:
- def __init__(self, weight_path: str=None): Initialize the model with its weight. Args: (string) weight_path : model's weight path
- def _preprocessing... | 158a74985074f95fcd6a345c310903936dd2adbe | <|skeleton|>
class BlackbloodSegmentation:
def __init__(self, weight_path: str=None):
"""Initialize the model with its weight. Args: (string) weight_path : model's weight path"""
<|body_0|>
def _preprocessing(self, path: str) -> np.array:
"""Preprocess the image from the path Args: (st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlackbloodSegmentation:
def __init__(self, weight_path: str=None):
"""Initialize the model with its weight. Args: (string) weight_path : model's weight path"""
self.model = BBBSeg()
if weight_path is not None:
self.model.load_weights(weight_path)
def _preprocessing(sel... | the_stack_v2_python_sparse | medimodule/Brain/module.py | mi2rl/MI2RLNet | train | 13 | |
bfdead9fbce97bcfe16c8f5e3a9ca8340dd64dd9 | [
"self.task = task\nself.cim = model\nif not isinstance(self.cim, ConditionalImage):\n raise RuntimeError('model type not supported: ' + str(type(self.cim)))",
"self.root = VisualSearchNode(self.task, self.cim, parent=None, action=self.cim.null_option)\nself.root.makeRoot(I)\nif draw:\n plt.figure()\nfor i i... | <|body_start_0|>
self.task = task
self.cim = model
if not isinstance(self.cim, ConditionalImage):
raise RuntimeError('model type not supported: ' + str(type(self.cim)))
<|end_body_0|>
<|body_start_1|>
self.root = VisualSearchNode(self.task, self.cim, parent=None, action=self... | Hold the tree and perform a short visual tree search. | VisualSearch | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisualSearch:
"""Hold the tree and perform a short visual tree search."""
def __init__(self, task, model, *args, **kwargs):
"""Create the conditional image model."""
<|body_0|>
def __call__(self, I, iter=10, depth=5, draw=False):
"""Take in current world observat... | stack_v2_sparse_classes_36k_train_016108 | 7,188 | permissive | [
{
"docstring": "Create the conditional image model.",
"name": "__init__",
"signature": "def __init__(self, task, model, *args, **kwargs)"
},
{
"docstring": "Take in current world observation. Create a search tree: - generate nex",
"name": "__call__",
"signature": "def __call__(self, I, i... | 2 | null | Implement the Python class `VisualSearch` described below.
Class description:
Hold the tree and perform a short visual tree search.
Method signatures and docstrings:
- def __init__(self, task, model, *args, **kwargs): Create the conditional image model.
- def __call__(self, I, iter=10, depth=5, draw=False): Take in c... | Implement the Python class `VisualSearch` described below.
Class description:
Hold the tree and perform a short visual tree search.
Method signatures and docstrings:
- def __init__(self, task, model, *args, **kwargs): Create the conditional image model.
- def __call__(self, I, iter=10, depth=5, draw=False): Take in c... | be5c12f9d0e9d7078e6a5c283d3be059e7f3d040 | <|skeleton|>
class VisualSearch:
"""Hold the tree and perform a short visual tree search."""
def __init__(self, task, model, *args, **kwargs):
"""Create the conditional image model."""
<|body_0|>
def __call__(self, I, iter=10, depth=5, draw=False):
"""Take in current world observat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VisualSearch:
"""Hold the tree and perform a short visual tree search."""
def __init__(self, task, model, *args, **kwargs):
"""Create the conditional image model."""
self.task = task
self.cim = model
if not isinstance(self.cim, ConditionalImage):
raise RuntimeE... | the_stack_v2_python_sparse | ctp_visual/python/ctp_visual/search.py | lk-greenbird/costar_plan | train | 0 |
41e0436f911674a0fb02cc7dc81b19837988742b | [
"previousSibling = self.GetPrevSibling(item)\nif previousSibling:\n return self.GetLastChildRecursively(previousSibling)\nelse:\n parent = self.GetItemParent(item)\n if parent == self.GetRootItem() and self.GetWindowStyle() & wx.TR_HIDE_ROOT:\n return previousSibling\n else:\n return paren... | <|body_start_0|>
previousSibling = self.GetPrevSibling(item)
if previousSibling:
return self.GetLastChildRecursively(previousSibling)
else:
parent = self.GetItemParent(item)
if parent == self.GetRootItem() and self.GetWindowStyle() & wx.TR_HIDE_ROOT:
... | TreeCtrl is the same as :class:`TreeCtrl`, with a few convenience methods added for easier navigation of items. | IterableTreeCtrl | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IterableTreeCtrl:
"""TreeCtrl is the same as :class:`TreeCtrl`, with a few convenience methods added for easier navigation of items."""
def GetPreviousItem(self, item):
"""Returns the item that is on the line immediately above item (as is displayed when the tree is fully expanded). T... | stack_v2_sparse_classes_36k_train_016109 | 32,868 | permissive | [
{
"docstring": "Returns the item that is on the line immediately above item (as is displayed when the tree is fully expanded). The returned item is invalid if item is the first item in the tree. :param TreeItemId `item`: a :class:`TreeItemId` :return: the :class:`TreeItemId` previous to the one passed in or an ... | 6 | stack_v2_sparse_classes_30k_train_021036 | Implement the Python class `IterableTreeCtrl` described below.
Class description:
TreeCtrl is the same as :class:`TreeCtrl`, with a few convenience methods added for easier navigation of items.
Method signatures and docstrings:
- def GetPreviousItem(self, item): Returns the item that is on the line immediately above ... | Implement the Python class `IterableTreeCtrl` described below.
Class description:
TreeCtrl is the same as :class:`TreeCtrl`, with a few convenience methods added for easier navigation of items.
Method signatures and docstrings:
- def GetPreviousItem(self, item): Returns the item that is on the line immediately above ... | c21d9abf56e1756fa8073ccc3547ec9a85d83e2a | <|skeleton|>
class IterableTreeCtrl:
"""TreeCtrl is the same as :class:`TreeCtrl`, with a few convenience methods added for easier navigation of items."""
def GetPreviousItem(self, item):
"""Returns the item that is on the line immediately above item (as is displayed when the tree is fully expanded). T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IterableTreeCtrl:
"""TreeCtrl is the same as :class:`TreeCtrl`, with a few convenience methods added for easier navigation of items."""
def GetPreviousItem(self, item):
"""Returns the item that is on the line immediately above item (as is displayed when the tree is fully expanded). The returned i... | the_stack_v2_python_sparse | venv/Lib/site-packages/wx/lib/combotreebox.py | saleguas/deskOrg | train | 3 |
ee2aed7b3678c8c22b05c04c50adf7571f4228b0 | [
"super(DumpConfiguration, self).__init__(*args, **kwargs)\nself.allow_extras = True\nreturn",
"if self._configspec_source is None:\n self._configspec_source = dump_configspec\nreturn self._configspec_source"
] | <|body_start_0|>
super(DumpConfiguration, self).__init__(*args, **kwargs)
self.allow_extras = True
return
<|end_body_0|>
<|body_start_1|>
if self._configspec_source is None:
self._configspec_source = dump_configspec
return self._configspec_source
<|end_body_1|>
| A configuration for the dump | DumpConfiguration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DumpConfiguration:
"""A configuration for the dump"""
def __init__(self, *args, **kwargs):
"""DumpConfiguration constructor (allow_extras=True)"""
<|body_0|>
def configspec_source(self):
"""string configuration specification"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_016110 | 18,096 | no_license | [
{
"docstring": "DumpConfiguration constructor (allow_extras=True)",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "string configuration specification",
"name": "configspec_source",
"signature": "def configspec_source(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007433 | Implement the Python class `DumpConfiguration` described below.
Class description:
A configuration for the dump
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): DumpConfiguration constructor (allow_extras=True)
- def configspec_source(self): string configuration specification | Implement the Python class `DumpConfiguration` described below.
Class description:
A configuration for the dump
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): DumpConfiguration constructor (allow_extras=True)
- def configspec_source(self): string configuration specification
<|skeleton|>
cla... | cd735b8c0fec06f7f9083714900ff88395c9443f | <|skeleton|>
class DumpConfiguration:
"""A configuration for the dump"""
def __init__(self, *args, **kwargs):
"""DumpConfiguration constructor (allow_extras=True)"""
<|body_0|>
def configspec_source(self):
"""string configuration specification"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DumpConfiguration:
"""A configuration for the dump"""
def __init__(self, *args, **kwargs):
"""DumpConfiguration constructor (allow_extras=True)"""
super(DumpConfiguration, self).__init__(*args, **kwargs)
self.allow_extras = True
return
def configspec_source(self):
... | the_stack_v2_python_sparse | cameraobscura/plugins/rvrplugin.py | russell-n/cameraobscura | train | 0 |
de81d8e5e85f6f355fc69c7b010d515a5abe6757 | [
"if len(point_list) < 3:\n raise ValueError('small number of points')\nself.point_list = point_list\nself.convex_hull = None",
"p_min = min(self.point_list, key=lambda p: (p.y, p.x))\nself.point_list.sort(key=lambda p: ((p - p_min).alpha(), (p - p_min) * (p - p_min)))\nm = 1\ni = 2\nwhile i < len(self.point_li... | <|body_start_0|>
if len(point_list) < 3:
raise ValueError('small number of points')
self.point_list = point_list
self.convex_hull = None
<|end_body_0|>
<|body_start_1|>
p_min = min(self.point_list, key=lambda p: (p.y, p.x))
self.point_list.sort(key=lambda p: ((p - p_... | Graham's scan algorithm for finding the convex hull of points. | GrahamScan2 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GrahamScan2:
"""Graham's scan algorithm for finding the convex hull of points."""
def __init__(self, point_list):
"""The algorithm initialization."""
<|body_0|>
def run(self):
"""Executable pseudocode."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_016111 | 2,863 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, point_list)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015874 | Implement the Python class `GrahamScan2` described below.
Class description:
Graham's scan algorithm for finding the convex hull of points.
Method signatures and docstrings:
- def __init__(self, point_list): The algorithm initialization.
- def run(self): Executable pseudocode. | Implement the Python class `GrahamScan2` described below.
Class description:
Graham's scan algorithm for finding the convex hull of points.
Method signatures and docstrings:
- def __init__(self, point_list): The algorithm initialization.
- def run(self): Executable pseudocode.
<|skeleton|>
class GrahamScan2:
"""... | 93417f2de3ec1694b5a63b1d77b96138bf8db20d | <|skeleton|>
class GrahamScan2:
"""Graham's scan algorithm for finding the convex hull of points."""
def __init__(self, point_list):
"""The algorithm initialization."""
<|body_0|>
def run(self):
"""Executable pseudocode."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GrahamScan2:
"""Graham's scan algorithm for finding the convex hull of points."""
def __init__(self, point_list):
"""The algorithm initialization."""
if len(point_list) < 3:
raise ValueError('small number of points')
self.point_list = point_list
self.convex_hul... | the_stack_v2_python_sparse | planegeometry/hulls/graham.py | ufkapano/planegeometry | train | 1 |
588e753b17e5ecf55d765295d8c2a041a78af550 | [
"modify = True\nif modify and kwargs is not None:\n for key, value in kwargs.items():\n log('%s == %s' % (key, value))\nif modify:\n config = kwargs['config']\n inputdict = kwargs['inputdict']\n inputkeydict = kwargs['inputkeydict']",
"modify = True\nif modify and kwargs is not None:\n for k... | <|body_start_0|>
modify = True
if modify and kwargs is not None:
for key, value in kwargs.items():
log('%s == %s' % (key, value))
if modify:
config = kwargs['config']
inputdict = kwargs['inputdict']
inputkeydict = kwargs['inputkeydi... | ServiceDataCustomization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceDataCustomization:
def process_service_create_data(smodelctx, sdata, dev, **kwargs):
"""Custom API to modify the inputs"""
<|body_0|>
def process_service_device_bindings(smodelctx, sdata, dev, **kwargs):
"""Custom API to modify the device bindings or Call the ... | stack_v2_sparse_classes_36k_train_016112 | 12,407 | no_license | [
{
"docstring": "Custom API to modify the inputs",
"name": "process_service_create_data",
"signature": "def process_service_create_data(smodelctx, sdata, dev, **kwargs)"
},
{
"docstring": "Custom API to modify the device bindings or Call the Business Login Handlers",
"name": "process_service_... | 4 | stack_v2_sparse_classes_30k_train_003749 | Implement the Python class `ServiceDataCustomization` described below.
Class description:
Implement the ServiceDataCustomization class.
Method signatures and docstrings:
- def process_service_create_data(smodelctx, sdata, dev, **kwargs): Custom API to modify the inputs
- def process_service_device_bindings(smodelctx,... | Implement the Python class `ServiceDataCustomization` described below.
Class description:
Implement the ServiceDataCustomization class.
Method signatures and docstrings:
- def process_service_create_data(smodelctx, sdata, dev, **kwargs): Custom API to modify the inputs
- def process_service_device_bindings(smodelctx,... | 96de3a4fd4adbbc0d443620f0c53f397823a1cad | <|skeleton|>
class ServiceDataCustomization:
def process_service_create_data(smodelctx, sdata, dev, **kwargs):
"""Custom API to modify the inputs"""
<|body_0|>
def process_service_device_bindings(smodelctx, sdata, dev, **kwargs):
"""Custom API to modify the device bindings or Call the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServiceDataCustomization:
def process_service_create_data(smodelctx, sdata, dev, **kwargs):
"""Custom API to modify the inputs"""
modify = True
if modify and kwargs is not None:
for key, value in kwargs.items():
log('%s == %s' % (key, value))
if modi... | the_stack_v2_python_sparse | scripts/managed_cpe_services/customer/wanop_services/type4_site/type4_site/wanop_secondary/routes/route/options/service_customization.py | lucabrasi83/anutacpedeployment | train | 0 | |
ae30ef96654b959357e94a65d26d48da6c244672 | [
"self.image = tf.placeholder(dtype=tf.float32, shape=dataset.shape)\nself.model = model_class(tf.expand_dims(self.image, axis=0), trainable=False, num_classes=dataset.num_classes, **params)\nself.logits = self.model.logits[0]\nself.num_classes = self.logits.shape.as_list()[0]\nself.logits_grad = jacobian(self.logit... | <|body_start_0|>
self.image = tf.placeholder(dtype=tf.float32, shape=dataset.shape)
self.model = model_class(tf.expand_dims(self.image, axis=0), trainable=False, num_classes=dataset.num_classes, **params)
self.logits = self.model.logits[0]
self.num_classes = self.logits.shape.as_list()[0... | DeepfoolOp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepfoolOp:
def __init__(self, model_class, dataset, params):
"""Creates necessary ops for deepfool in the tensorflow graph Args: model_class: The class of the model to construct. Expects subclass of BasicModel dataset: The dataset to use. Only necessary for shape and number of classes p... | stack_v2_sparse_classes_36k_train_016113 | 3,133 | permissive | [
{
"docstring": "Creates necessary ops for deepfool in the tensorflow graph Args: model_class: The class of the model to construct. Expects subclass of BasicModel dataset: The dataset to use. Only necessary for shape and number of classes params: Additional parameters to pass to the model init",
"name": "__i... | 2 | stack_v2_sparse_classes_30k_train_001592 | Implement the Python class `DeepfoolOp` described below.
Class description:
Implement the DeepfoolOp class.
Method signatures and docstrings:
- def __init__(self, model_class, dataset, params): Creates necessary ops for deepfool in the tensorflow graph Args: model_class: The class of the model to construct. Expects s... | Implement the Python class `DeepfoolOp` described below.
Class description:
Implement the DeepfoolOp class.
Method signatures and docstrings:
- def __init__(self, model_class, dataset, params): Creates necessary ops for deepfool in the tensorflow graph Args: model_class: The class of the model to construct. Expects s... | 2aea27d28746c0726c2da6be21a51c92bf120b70 | <|skeleton|>
class DeepfoolOp:
def __init__(self, model_class, dataset, params):
"""Creates necessary ops for deepfool in the tensorflow graph Args: model_class: The class of the model to construct. Expects subclass of BasicModel dataset: The dataset to use. Only necessary for shape and number of classes p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepfoolOp:
def __init__(self, model_class, dataset, params):
"""Creates necessary ops for deepfool in the tensorflow graph Args: model_class: The class of the model to construct. Expects subclass of BasicModel dataset: The dataset to use. Only necessary for shape and number of classes params: Additio... | the_stack_v2_python_sparse | code/attacks/deepfool.py | Ichbinhippo/Adversarial-Attacks-on-CapsNets | train | 0 | |
6a686bff9cb07eda65d69d24799c3d1c2154a1bd | [
"m, n = (len(mat), len(mat[0]))\nfor i in range(m):\n for j in range(n):\n if mat[i][j] and i > 0:\n mat[i][j] += mat[i - 1][j]\nans = 0\nfor i in range(m):\n stack = []\n cnt = 0\n for j in range(n):\n while stack and mat[i][stack[-1]] > mat[i][j]:\n jj = stack.pop()... | <|body_start_0|>
m, n = (len(mat), len(mat[0]))
for i in range(m):
for j in range(n):
if mat[i][j] and i > 0:
mat[i][j] += mat[i - 1][j]
ans = 0
for i in range(m):
stack = []
cnt = 0
for j in range(n):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubmat(self, mat):
""":type mat: List[List[int]] :rtype: int"""
<|body_0|>
def numSubmat2(self, mat):
""":type mat: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m, n = (len(mat), len(mat[0]))
f... | stack_v2_sparse_classes_36k_train_016114 | 3,210 | no_license | [
{
"docstring": ":type mat: List[List[int]] :rtype: int",
"name": "numSubmat",
"signature": "def numSubmat(self, mat)"
},
{
"docstring": ":type mat: List[List[int]] :rtype: int",
"name": "numSubmat2",
"signature": "def numSubmat2(self, mat)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubmat(self, mat): :type mat: List[List[int]] :rtype: int
- def numSubmat2(self, mat): :type mat: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubmat(self, mat): :type mat: List[List[int]] :rtype: int
- def numSubmat2(self, mat): :type mat: List[List[int]] :rtype: int
<|skeleton|>
class Solution:
def numSub... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def numSubmat(self, mat):
""":type mat: List[List[int]] :rtype: int"""
<|body_0|>
def numSubmat2(self, mat):
""":type mat: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSubmat(self, mat):
""":type mat: List[List[int]] :rtype: int"""
m, n = (len(mat), len(mat[0]))
for i in range(m):
for j in range(n):
if mat[i][j] and i > 0:
mat[i][j] += mat[i - 1][j]
ans = 0
for i in rang... | the_stack_v2_python_sparse | C/CountSubmatricesWithAllOnes.py | bssrdf/pyleet | train | 2 | |
11a6fa7cd70d9cad24f7486d2b5396486d69e57d | [
"try:\n clone_from_id = kwargs['clone_from']\n clone_to_id = kwargs['clone_to']\n with transaction.atomic():\n clone_from_data = TMasterModuleRoleUser.objects.filter(mmr_module_id=clone_from_id, mmr_role__cr_parent_id=0)\n clone_to_data_count = TMasterModuleRoleUser.objects.filter(mmr_module_... | <|body_start_0|>
try:
clone_from_id = kwargs['clone_from']
clone_to_id = kwargs['clone_to']
with transaction.atomic():
clone_from_data = TMasterModuleRoleUser.objects.filter(mmr_module_id=clone_from_id, mmr_role__cr_parent_id=0)
clone_to_data_c... | CloneModuleRole | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloneModuleRole:
def post(self, request, *args, **kwargs):
"""Clone Roles from given Module to given Module like as (clone_module-roles/module id ,where from clone/module id ,where to clone/) 1. Raplicate module must be blank 2. clone only Role 3.transaction is avilable 4.Thread is avila... | stack_v2_sparse_classes_36k_train_016115 | 20,616 | no_license | [
{
"docstring": "Clone Roles from given Module to given Module like as (clone_module-roles/module id ,where from clone/module id ,where to clone/) 1. Raplicate module must be blank 2. clone only Role 3.transaction is avilable 4.Thread is avilable",
"name": "post",
"signature": "def post(self, request, *a... | 3 | stack_v2_sparse_classes_30k_train_020925 | Implement the Python class `CloneModuleRole` described below.
Class description:
Implement the CloneModuleRole class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Clone Roles from given Module to given Module like as (clone_module-roles/module id ,where from clone/module id ,where to ... | Implement the Python class `CloneModuleRole` described below.
Class description:
Implement the CloneModuleRole class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Clone Roles from given Module to given Module like as (clone_module-roles/module id ,where from clone/module id ,where to ... | af36011a86376291af01a1c3a569f999bed4cb0d | <|skeleton|>
class CloneModuleRole:
def post(self, request, *args, **kwargs):
"""Clone Roles from given Module to given Module like as (clone_module-roles/module id ,where from clone/module id ,where to clone/) 1. Raplicate module must be blank 2. clone only Role 3.transaction is avilable 4.Thread is avila... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloneModuleRole:
def post(self, request, *args, **kwargs):
"""Clone Roles from given Module to given Module like as (clone_module-roles/module id ,where from clone/module id ,where to clone/) 1. Raplicate module must be blank 2. clone only Role 3.transaction is avilable 4.Thread is avilable"""
... | the_stack_v2_python_sparse | ssil_sso_ms/master/views.py | abhisek11/my_django_boiler | train | 0 | |
8ff0d16459494647e04ac06b010654e2d9e6a7cd | [
"sanitized_week_day_str = week_day_str.upper()\nif sanitized_week_day_str not in cls.__members__:\n raise AttributeError(f'Invalid Week Day passed: \"{week_day_str}\"')\nreturn cls[sanitized_week_day_str]",
"if isinstance(day, WeekDay):\n return day\nreturn cls.get_weekday_number(week_day_str=day)",
"if n... | <|body_start_0|>
sanitized_week_day_str = week_day_str.upper()
if sanitized_week_day_str not in cls.__members__:
raise AttributeError(f'Invalid Week Day passed: "{week_day_str}"')
return cls[sanitized_week_day_str]
<|end_body_0|>
<|body_start_1|>
if isinstance(day, WeekDay):... | Python Enum containing Days of the Week. | WeekDay | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeekDay:
"""Python Enum containing Days of the Week."""
def get_weekday_number(cls, week_day_str: str):
"""Return the ISO Week Day Number for a Week Day. :param week_day_str: Full Name of the Week Day. Example: "Sunday" :return: ISO Week Day Number corresponding to the provided Weekd... | stack_v2_sparse_classes_36k_train_016116 | 2,675 | permissive | [
{
"docstring": "Return the ISO Week Day Number for a Week Day. :param week_day_str: Full Name of the Week Day. Example: \"Sunday\" :return: ISO Week Day Number corresponding to the provided Weekday",
"name": "get_weekday_number",
"signature": "def get_weekday_number(cls, week_day_str: str)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_013492 | Implement the Python class `WeekDay` described below.
Class description:
Python Enum containing Days of the Week.
Method signatures and docstrings:
- def get_weekday_number(cls, week_day_str: str): Return the ISO Week Day Number for a Week Day. :param week_day_str: Full Name of the Week Day. Example: "Sunday" :return... | Implement the Python class `WeekDay` described below.
Class description:
Python Enum containing Days of the Week.
Method signatures and docstrings:
- def get_weekday_number(cls, week_day_str: str): Return the ISO Week Day Number for a Week Day. :param week_day_str: Full Name of the Week Day. Example: "Sunday" :return... | 1b122c15030e99cef9d4ff26d3781a7a9d6949bc | <|skeleton|>
class WeekDay:
"""Python Enum containing Days of the Week."""
def get_weekday_number(cls, week_day_str: str):
"""Return the ISO Week Day Number for a Week Day. :param week_day_str: Full Name of the Week Day. Example: "Sunday" :return: ISO Week Day Number corresponding to the provided Weekd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeekDay:
"""Python Enum containing Days of the Week."""
def get_weekday_number(cls, week_day_str: str):
"""Return the ISO Week Day Number for a Week Day. :param week_day_str: Full Name of the Week Day. Example: "Sunday" :return: ISO Week Day Number corresponding to the provided Weekday"""
... | the_stack_v2_python_sparse | airflow/utils/weekday.py | apache/airflow | train | 22,756 |
79b88cfb0013cfe3ff89046b6315c677f120f59b | [
"if not root:\n return ''\nres = [self.serialize(root.left), root.val, self.serialize(root.right)]\nreturn str(res)",
"if not data:\n return\nleft, cur, right = eval(data)\nroot = TreeNode(cur)\nroot.left = self.deserialize(left)\nroot.right = self.deserialize(right)\nreturn root"
] | <|body_start_0|>
if not root:
return ''
res = [self.serialize(root.left), root.val, self.serialize(root.right)]
return str(res)
<|end_body_0|>
<|body_start_1|>
if not data:
return
left, cur, right = eval(data)
root = TreeNode(cur)
root.lef... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_36k_train_016117 | 3,000 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_008135 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 6dc5b8968b6bef0186d3806e4aa35ee7b5d75ff2 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
if not root:
return ''
res = [self.serialize(root.left), root.val, self.serialize(root.right)]
return str(res)
def deserialize(self, data: str) -> TreeNode:
"""D... | the_stack_v2_python_sparse | letecode/361-480/441-460/449.py | hshrimp/letecode_for_me | train | 1 | |
fb4d255ffa4d8e1ae35f9ab463c816c518e4ddc6 | [
"feature = self.backbone(data)\ncls_score = self.head(feature)\nreturn cls_score",
"data = data_batch[0]\nlabel = data_batch[1:]\ncls_score = self.forward_net(data)\nloss_metrics = self.head.loss(cls_score, label)\nreturn loss_metrics",
"data = data_batch[0]\nlabel = data_batch[1:]\ncls_score = self.forward_net... | <|body_start_0|>
feature = self.backbone(data)
cls_score = self.head(feature)
return cls_score
<|end_body_0|>
<|body_start_1|>
data = data_batch[0]
label = data_batch[1:]
cls_score = self.forward_net(data)
loss_metrics = self.head.loss(cls_score, label)
r... | GCN Recognizer model framework. | RecognizerGCN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecognizerGCN:
"""GCN Recognizer model framework."""
def forward_net(self, data):
"""Define how the model is going to run, from input to output."""
<|body_0|>
def train_step(self, data_batch):
"""Training step."""
<|body_1|>
def val_step(self, data_b... | stack_v2_sparse_classes_36k_train_016118 | 1,962 | no_license | [
{
"docstring": "Define how the model is going to run, from input to output.",
"name": "forward_net",
"signature": "def forward_net(self, data)"
},
{
"docstring": "Training step.",
"name": "train_step",
"signature": "def train_step(self, data_batch)"
},
{
"docstring": "Validating ... | 5 | stack_v2_sparse_classes_30k_train_009559 | Implement the Python class `RecognizerGCN` described below.
Class description:
GCN Recognizer model framework.
Method signatures and docstrings:
- def forward_net(self, data): Define how the model is going to run, from input to output.
- def train_step(self, data_batch): Training step.
- def val_step(self, data_batch... | Implement the Python class `RecognizerGCN` described below.
Class description:
GCN Recognizer model framework.
Method signatures and docstrings:
- def forward_net(self, data): Define how the model is going to run, from input to output.
- def train_step(self, data_batch): Training step.
- def val_step(self, data_batch... | 703466c1ecd67afe6e97eaed598c6d8d75ea5344 | <|skeleton|>
class RecognizerGCN:
"""GCN Recognizer model framework."""
def forward_net(self, data):
"""Define how the model is going to run, from input to output."""
<|body_0|>
def train_step(self, data_batch):
"""Training step."""
<|body_1|>
def val_step(self, data_b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecognizerGCN:
"""GCN Recognizer model framework."""
def forward_net(self, data):
"""Define how the model is going to run, from input to output."""
feature = self.backbone(data)
cls_score = self.head(feature)
return cls_score
def train_step(self, data_batch):
... | the_stack_v2_python_sparse | work/XtSe/paddlevideo/modeling/framework/recognizers/recognizer_gcn.py | tonylin52/2021CCF_BDCI_NAIR | train | 8 |
6a3450cba10962c35a0546862f425d87c02469fd | [
"out = self.item\nitem = self.next()\nif isletter(out, isatletter):\n while self.uplegal() and isletter(item, isatletter):\n out += item\n item = self.next()\nreturn out",
"comment = ''\nwhile self.uplegal() and '\\n' != self.item:\n comment += self.item\n self.next()\nwhile self.uplegal() ... | <|body_start_0|>
out = self.item
item = self.next()
if isletter(out, isatletter):
while self.uplegal() and isletter(item, isatletter):
out += item
item = self.next()
return out
<|end_body_0|>
<|body_start_1|>
comment = ''
while... | Char_stream | [
"BSL-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Char_stream:
def scan_escape_token(self, isatletter=False):
"""Starts after the escape sign, assumes that it is scanning a symbol. Returns a token-string."""
<|body_0|>
def scan_comment_token(self):
"""Starts at the comment sign %, assumes that it is scanning a comme... | stack_v2_sparse_classes_36k_train_016119 | 35,480 | permissive | [
{
"docstring": "Starts after the escape sign, assumes that it is scanning a symbol. Returns a token-string.",
"name": "scan_escape_token",
"signature": "def scan_escape_token(self, isatletter=False)"
},
{
"docstring": "Starts at the comment sign %, assumes that it is scanning a comment. Returns ... | 4 | stack_v2_sparse_classes_30k_train_011379 | Implement the Python class `Char_stream` described below.
Class description:
Implement the Char_stream class.
Method signatures and docstrings:
- def scan_escape_token(self, isatletter=False): Starts after the escape sign, assumes that it is scanning a symbol. Returns a token-string.
- def scan_comment_token(self): S... | Implement the Python class `Char_stream` described below.
Class description:
Implement the Char_stream class.
Method signatures and docstrings:
- def scan_escape_token(self, isatletter=False): Starts after the escape sign, assumes that it is scanning a symbol. Returns a token-string.
- def scan_comment_token(self): S... | 47045aaf7054bc8efe657d1e9e070e6b27652c64 | <|skeleton|>
class Char_stream:
def scan_escape_token(self, isatletter=False):
"""Starts after the escape sign, assumes that it is scanning a symbol. Returns a token-string."""
<|body_0|>
def scan_comment_token(self):
"""Starts at the comment sign %, assumes that it is scanning a comme... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Char_stream:
def scan_escape_token(self, isatletter=False):
"""Starts after the escape sign, assumes that it is scanning a symbol. Returns a token-string."""
out = self.item
item = self.next()
if isletter(out, isatletter):
while self.uplegal() and isletter(item, isa... | the_stack_v2_python_sparse | py-scripts/de-macro | vEnhance/dotfiles | train | 119 | |
d05983623662d8d6065188dda19c26ec61ad0cd0 | [
"keyboard = ['qwertyuiopQWERTYUIOP', 'asdfghjklASDFGHJKL', 'zxcvbnmZXCVBNM']\nres = []\nfor word in words:\n pos = []\n for w in word:\n for index, key in enumerate(keyboard):\n if w in key:\n pos.append(index)\n break\n if len(set(pos)) == 1:\n res.ap... | <|body_start_0|>
keyboard = ['qwertyuiopQWERTYUIOP', 'asdfghjklASDFGHJKL', 'zxcvbnmZXCVBNM']
res = []
for word in words:
pos = []
for w in word:
for index, key in enumerate(keyboard):
if w in key:
pos.append(inde... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findWords(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_0|>
def _findWords(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
keyboard = ['qwertyuiopQWERTYUIO... | stack_v2_sparse_classes_36k_train_016120 | 1,800 | permissive | [
{
"docstring": ":type words: List[str] :rtype: List[str]",
"name": "findWords",
"signature": "def findWords(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: List[str]",
"name": "_findWords",
"signature": "def _findWords(self, words)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016298 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findWords(self, words): :type words: List[str] :rtype: List[str]
- def _findWords(self, words): :type words: List[str] :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findWords(self, words): :type words: List[str] :rtype: List[str]
- def _findWords(self, words): :type words: List[str] :rtype: List[str]
<|skeleton|>
class Solution:
de... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def findWords(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_0|>
def _findWords(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findWords(self, words):
""":type words: List[str] :rtype: List[str]"""
keyboard = ['qwertyuiopQWERTYUIOP', 'asdfghjklASDFGHJKL', 'zxcvbnmZXCVBNM']
res = []
for word in words:
pos = []
for w in word:
for index, key in enumera... | the_stack_v2_python_sparse | 500.keyboard-row.py | windard/leeeeee | train | 0 | |
a5df710216898b36bd489aec2be984a72a5188e3 | [
"try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\ntry:\n dep = dependencias.read(id)\nexcept psycopg2.Error as err:\n ns.abort(400, message=get_msg_pgerror(err))\nexcept EmptySetError:\n ns.abort(404, message=self.dep_not_found)\nexcept Exception as err:\n ... | <|body_start_0|>
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
try:
dep = dependencias.read(id)
except psycopg2.Error as err:
ns.abort(400, message=get_msg_pgerror(err))
except EmptySetError:... | Dependencia | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dependencia:
def get(self, id):
"""Recuperar una dependencia"""
<|body_0|>
def put(self, id):
"""Actualizar una dependencia"""
<|body_1|>
def delete(self, id):
"""Eliminar una dependencia"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_016121 | 6,772 | no_license | [
{
"docstring": "Recuperar una dependencia",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Actualizar una dependencia",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "Eliminar una dependencia",
"name": "delete",
"signature": "def de... | 3 | stack_v2_sparse_classes_30k_train_002100 | Implement the Python class `Dependencia` described below.
Class description:
Implement the Dependencia class.
Method signatures and docstrings:
- def get(self, id): Recuperar una dependencia
- def put(self, id): Actualizar una dependencia
- def delete(self, id): Eliminar una dependencia | Implement the Python class `Dependencia` described below.
Class description:
Implement the Dependencia class.
Method signatures and docstrings:
- def get(self, id): Recuperar una dependencia
- def put(self, id): Actualizar una dependencia
- def delete(self, id): Eliminar una dependencia
<|skeleton|>
class Dependenci... | e00610fac26ef3ca078fd037c0649b70fa0e9a09 | <|skeleton|>
class Dependencia:
def get(self, id):
"""Recuperar una dependencia"""
<|body_0|>
def put(self, id):
"""Actualizar una dependencia"""
<|body_1|>
def delete(self, id):
"""Eliminar una dependencia"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dependencia:
def get(self, id):
"""Recuperar una dependencia"""
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
try:
dep = dependencias.read(id)
except psycopg2.Error as err:
ns.abort... | the_stack_v2_python_sparse | DOS/soa/service/genl/endpoints/dependencias.py | Telematica/knight-rider | train | 1 | |
2ed50d8ed0d3a3130c8d78802ec8676923107d79 | [
"response: UserOutputData | list[UserOutputData] | None\nif id:\n response = self.__find_user_by_id(id)\nelse:\n response = self.__find_users()\nreturn response",
"data = self.repository.find_users()\nresponse = []\nfor d in data:\n response.append(parse_obj_as(UserOutputData, d))\nreturn response",
"u... | <|body_start_0|>
response: UserOutputData | list[UserOutputData] | None
if id:
response = self.__find_user_by_id(id)
else:
response = self.__find_users()
return response
<|end_body_0|>
<|body_start_1|>
data = self.repository.find_users()
response ... | UserGetInteractorImpl | UserGetInteractorImpl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserGetInteractorImpl:
"""UserGetInteractorImpl"""
def handle(self, id: int=0) -> UserOutputData | list[UserOutputData] | None:
"""handle"""
<|body_0|>
def __find_users(self) -> list[UserOutputData] | None:
"""__find_users"""
<|body_1|>
def __find_us... | stack_v2_sparse_classes_36k_train_016122 | 1,563 | no_license | [
{
"docstring": "handle",
"name": "handle",
"signature": "def handle(self, id: int=0) -> UserOutputData | list[UserOutputData] | None"
},
{
"docstring": "__find_users",
"name": "__find_users",
"signature": "def __find_users(self) -> list[UserOutputData] | None"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_005656 | Implement the Python class `UserGetInteractorImpl` described below.
Class description:
UserGetInteractorImpl
Method signatures and docstrings:
- def handle(self, id: int=0) -> UserOutputData | list[UserOutputData] | None: handle
- def __find_users(self) -> list[UserOutputData] | None: __find_users
- def __find_user_b... | Implement the Python class `UserGetInteractorImpl` described below.
Class description:
UserGetInteractorImpl
Method signatures and docstrings:
- def handle(self, id: int=0) -> UserOutputData | list[UserOutputData] | None: handle
- def __find_users(self) -> list[UserOutputData] | None: __find_users
- def __find_user_b... | b2740384608b7724238a2b426ec79f6ced057e9d | <|skeleton|>
class UserGetInteractorImpl:
"""UserGetInteractorImpl"""
def handle(self, id: int=0) -> UserOutputData | list[UserOutputData] | None:
"""handle"""
<|body_0|>
def __find_users(self) -> list[UserOutputData] | None:
"""__find_users"""
<|body_1|>
def __find_us... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserGetInteractorImpl:
"""UserGetInteractorImpl"""
def handle(self, id: int=0) -> UserOutputData | list[UserOutputData] | None:
"""handle"""
response: UserOutputData | list[UserOutputData] | None
if id:
response = self.__find_user_by_id(id)
else:
re... | the_stack_v2_python_sparse | app/usecases/users/user_get_usercase.py | massa423/clean-architecture-fastapi | train | 6 |
07aaab1862077c0edbec886152b7e1f3cb76dc8c | [
"air = InsufficientOutsideAir()\nif isinstance(air, InsufficientOutsideAir):\n assert True\nelse:\n assert False",
"air = InsufficientOutsideAir()\ndata_window = td(minutes=1)\nresults = []\nair.set_class_values('test', results, data_window, 1, 10.0)\nassert air.data_window == td(minutes=1)\nassert air.no_r... | <|body_start_0|>
air = InsufficientOutsideAir()
if isinstance(air, InsufficientOutsideAir):
assert True
else:
assert False
<|end_body_0|>
<|body_start_1|>
air = InsufficientOutsideAir()
data_window = td(minutes=1)
results = []
air.set_clas... | Contains all the tests for Insufficient Outside Air Diagnostic | TestDiagnosticsInsufficientOutsideAir | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDiagnosticsInsufficientOutsideAir:
"""Contains all the tests for Insufficient Outside Air Diagnostic"""
def test_insufficient_outside_air_creation(self):
"""test the creation of excess_outside_air diagnostic class"""
<|body_0|>
def test_insufficient_ouside_air_set_va... | stack_v2_sparse_classes_36k_train_016123 | 42,174 | permissive | [
{
"docstring": "test the creation of excess_outside_air diagnostic class",
"name": "test_insufficient_outside_air_creation",
"signature": "def test_insufficient_outside_air_creation(self)"
},
{
"docstring": "test the Insufficient_outside_air set values method",
"name": "test_insufficient_ous... | 6 | null | Implement the Python class `TestDiagnosticsInsufficientOutsideAir` described below.
Class description:
Contains all the tests for Insufficient Outside Air Diagnostic
Method signatures and docstrings:
- def test_insufficient_outside_air_creation(self): test the creation of excess_outside_air diagnostic class
- def tes... | Implement the Python class `TestDiagnosticsInsufficientOutsideAir` described below.
Class description:
Contains all the tests for Insufficient Outside Air Diagnostic
Method signatures and docstrings:
- def test_insufficient_outside_air_creation(self): test the creation of excess_outside_air diagnostic class
- def tes... | 24d50729aef8d91036cc13b0f5c03be76f3237ed | <|skeleton|>
class TestDiagnosticsInsufficientOutsideAir:
"""Contains all the tests for Insufficient Outside Air Diagnostic"""
def test_insufficient_outside_air_creation(self):
"""test the creation of excess_outside_air diagnostic class"""
<|body_0|>
def test_insufficient_ouside_air_set_va... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDiagnosticsInsufficientOutsideAir:
"""Contains all the tests for Insufficient Outside Air Diagnostic"""
def test_insufficient_outside_air_creation(self):
"""test the creation of excess_outside_air diagnostic class"""
air = InsufficientOutsideAir()
if isinstance(air, Insufficie... | the_stack_v2_python_sparse | EnergyEfficiency/EconomizerRCxAgent/economizer/test.py | shwethanidd/volttron-pnnl-applications-2 | train | 0 |
d6f06dfa0aaf9a05a28434ec6d1be871c6690a2a | [
"if sport not in self.sports.keys():\n err_msg = 'update sports.game_status.GameStatus for sport: %s' % sport\n raise self.InvalidSportException(err_msg)\nself.status_map = self.sports.get(sport)",
"if status not in self.status_map.keys():\n err_msg = '%s does not exist and therefore cant have a primary ... | <|body_start_0|>
if sport not in self.sports.keys():
err_msg = 'update sports.game_status.GameStatus for sport: %s' % sport
raise self.InvalidSportException(err_msg)
self.status_map = self.sports.get(sport)
<|end_body_0|>
<|body_start_1|>
if status not in self.status_map... | for discrepencies with the values returned by this class, please refer to the source extended documentation found on the SportRadar website: https://developer.sportradar.us/ this object is in charge of making sense of granular boxscore game statuses. given an MLB boxscore game status like 'odelay', the method get_prima... | GameStatus | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameStatus:
"""for discrepencies with the values returned by this class, please refer to the source extended documentation found on the SportRadar website: https://developer.sportradar.us/ this object is in charge of making sense of granular boxscore game statuses. given an MLB boxscore game stat... | stack_v2_sparse_classes_36k_train_016124 | 6,302 | no_license | [
{
"docstring": ":param sport: string name of the sport you want to use the GameStatus object for. :raise InvalidSportException: if the 'sport' arg not found among top-level keys in the status map",
"name": "__init__",
"signature": "def __init__(self, sport)"
},
{
"docstring": "given a granular b... | 2 | stack_v2_sparse_classes_30k_train_018198 | Implement the Python class `GameStatus` described below.
Class description:
for discrepencies with the values returned by this class, please refer to the source extended documentation found on the SportRadar website: https://developer.sportradar.us/ this object is in charge of making sense of granular boxscore game st... | Implement the Python class `GameStatus` described below.
Class description:
for discrepencies with the values returned by this class, please refer to the source extended documentation found on the SportRadar website: https://developer.sportradar.us/ this object is in charge of making sense of granular boxscore game st... | 4796fa9d88b56f80def011e2b043ce595bfce8c4 | <|skeleton|>
class GameStatus:
"""for discrepencies with the values returned by this class, please refer to the source extended documentation found on the SportRadar website: https://developer.sportradar.us/ this object is in charge of making sense of granular boxscore game statuses. given an MLB boxscore game stat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameStatus:
"""for discrepencies with the values returned by this class, please refer to the source extended documentation found on the SportRadar website: https://developer.sportradar.us/ this object is in charge of making sense of granular boxscore game statuses. given an MLB boxscore game status like 'odel... | the_stack_v2_python_sparse | sports/game_status.py | nakamotohideyoshi/draftboard-web | train | 0 |
d95af573eb1d328b9a2c77c89fd94a8c3e4189b9 | [
"token_url = current_app.config.get('ACCOUNT_SVC_AUTH_URL')\nclient_id = current_app.config.get('ACCOUNT_SVC_CLIENT_ID')\nclient_secret = current_app.config.get('ACCOUNT_SVC_CLIENT_SECRET')\ndata = 'grant_type=client_credentials'\nres = requests.post(url=token_url, data=data, headers={'content-type': 'application/x... | <|body_start_0|>
token_url = current_app.config.get('ACCOUNT_SVC_AUTH_URL')
client_id = current_app.config.get('ACCOUNT_SVC_CLIENT_ID')
client_secret = current_app.config.get('ACCOUNT_SVC_CLIENT_SECRET')
data = 'grant_type=client_credentials'
res = requests.post(url=token_url, da... | Wrapper to call Authentication Services. @TODO Cache and refresh / retry token as needed to reduce calls. | AccountService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountService:
"""Wrapper to call Authentication Services. @TODO Cache and refresh / retry token as needed to reduce calls."""
def get_bearer_token(cls):
"""Get a valid Bearer token for the service to use."""
<|body_0|>
def create_affiliation(cls, account: int, business... | stack_v2_sparse_classes_36k_train_016125 | 10,376 | permissive | [
{
"docstring": "Get a valid Bearer token for the service to use.",
"name": "get_bearer_token",
"signature": "def get_bearer_token(cls)"
},
{
"docstring": "Affiliate a business to an account.",
"name": "create_affiliation",
"signature": "def create_affiliation(cls, account: int, business_... | 5 | null | Implement the Python class `AccountService` described below.
Class description:
Wrapper to call Authentication Services. @TODO Cache and refresh / retry token as needed to reduce calls.
Method signatures and docstrings:
- def get_bearer_token(cls): Get a valid Bearer token for the service to use.
- def create_affilia... | Implement the Python class `AccountService` described below.
Class description:
Wrapper to call Authentication Services. @TODO Cache and refresh / retry token as needed to reduce calls.
Method signatures and docstrings:
- def get_bearer_token(cls): Get a valid Bearer token for the service to use.
- def create_affilia... | d90f11a7b14411b02c07fe97d2c1fc31cd4a9b32 | <|skeleton|>
class AccountService:
"""Wrapper to call Authentication Services. @TODO Cache and refresh / retry token as needed to reduce calls."""
def get_bearer_token(cls):
"""Get a valid Bearer token for the service to use."""
<|body_0|>
def create_affiliation(cls, account: int, business... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountService:
"""Wrapper to call Authentication Services. @TODO Cache and refresh / retry token as needed to reduce calls."""
def get_bearer_token(cls):
"""Get a valid Bearer token for the service to use."""
token_url = current_app.config.get('ACCOUNT_SVC_AUTH_URL')
client_id = ... | the_stack_v2_python_sparse | legal-api/src/legal_api/services/bootstrap.py | bcgov/lear | train | 13 |
2029c92856d61ef5f30e356e76cd1a66d6d5dd08 | [
"super(OneLayerNet, self).__init__()\nself.linear1 = torch.nn.Linear(D_in, H)\nself.linear2 = torch.nn.Linear(H, D_out)",
"x = F.relu(self.linear1(x))\nx = F.sigmoid(self.linear2(x))\nreturn x"
] | <|body_start_0|>
super(OneLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
<|end_body_0|>
<|body_start_1|>
x = F.relu(self.linear1(x))
x = F.sigmoid(self.linear2(x))
return x
<|end_body_1|>
| OneLayerNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OneLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Tensor of input data and we must return a Tenso... | stack_v2_sparse_classes_36k_train_016126 | 2,558 | no_license | [
{
"docstring": "In the constructor we instantiate two nn.Linear modules and assign them as member variables.",
"name": "__init__",
"signature": "def __init__(self, D_in, H, D_out)"
},
{
"docstring": "In the forward function we accept a Tensor of input data and we must return a Tensor of output d... | 2 | null | Implement the Python class `OneLayerNet` described below.
Class description:
Implement the OneLayerNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x): In the forward func... | Implement the Python class `OneLayerNet` described below.
Class description:
Implement the OneLayerNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x): In the forward func... | 05ae9ddb0aad2f7601cde3339505890e095c26d4 | <|skeleton|>
class OneLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Tensor of input data and we must return a Tenso... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OneLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
super(OneLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
def forw... | the_stack_v2_python_sparse | akuna/torch.py | ChuhanXu/LeetCode | train | 0 | |
63c56da208c8a3bfe9fe98d7679dd5cd0e400b18 | [
"if urlconf_modules is None:\n urlconf_modules = [settings.ROOT_URLCONF]\n if self.URLCONF_MODULES is not None:\n urlconf_modules.extend(self.URLCONF_MODULES)\nfor urlconf in urlconf_modules:\n if urlconf in sys.modules:\n reload(sys.modules[urlconf])\nclear_url_caches()\nresolve('/')",
"su... | <|body_start_0|>
if urlconf_modules is None:
urlconf_modules = [settings.ROOT_URLCONF]
if self.URLCONF_MODULES is not None:
urlconf_modules.extend(self.URLCONF_MODULES)
for urlconf in urlconf_modules:
if urlconf in sys.modules:
reload(s... | Mixin to reset urls.py before and after a test Django memoizes the function that reads the urls module (whatever module urlconf names). The module itself is also stored by python in sys.modules. To fully reload it, we need to reload the python module, and also clear django's cache of the parsed urls. However, the order... | UrlResetMixin | [
"MIT",
"AGPL-3.0-only",
"AGPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UrlResetMixin:
"""Mixin to reset urls.py before and after a test Django memoizes the function that reads the urls module (whatever module urlconf names). The module itself is also stored by python in sys.modules. To fully reload it, we need to reload the python module, and also clear django's cac... | stack_v2_sparse_classes_36k_train_016127 | 5,815 | permissive | [
{
"docstring": "Reset `urls.py` for a set of Django apps.",
"name": "reset_urls",
"signature": "def reset_urls(self, urlconf_modules=None)"
},
{
"docstring": "Reset Django urls before tests and after tests If you need to reset `urls.py` from a particular Django app (or apps), specify these modul... | 2 | null | Implement the Python class `UrlResetMixin` described below.
Class description:
Mixin to reset urls.py before and after a test Django memoizes the function that reads the urls module (whatever module urlconf names). The module itself is also stored by python in sys.modules. To fully reload it, we need to reload the pyt... | Implement the Python class `UrlResetMixin` described below.
Class description:
Mixin to reset urls.py before and after a test Django memoizes the function that reads the urls module (whatever module urlconf names). The module itself is also stored by python in sys.modules. To fully reload it, we need to reload the pyt... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class UrlResetMixin:
"""Mixin to reset urls.py before and after a test Django memoizes the function that reads the urls module (whatever module urlconf names). The module itself is also stored by python in sys.modules. To fully reload it, we need to reload the python module, and also clear django's cac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UrlResetMixin:
"""Mixin to reset urls.py before and after a test Django memoizes the function that reads the urls module (whatever module urlconf names). The module itself is also stored by python in sys.modules. To fully reload it, we need to reload the python module, and also clear django's cache of the par... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/djangoapps/util/testing.py | luque/better-ways-of-thinking-about-software | train | 3 |
627923ca1ac3413fff27cb3a8265d6c8440509f4 | [
"segments = list(track.get_segments())[-(NUM_PLAYLIST_SEGMENTS + 1):]\nif segments[-1].complete:\n segments = segments[-NUM_PLAYLIST_SEGMENTS:]\nfirst_segment = segments[0]\nplaylist = ['#EXTM3U', '#EXT-X-VERSION:6', '#EXT-X-INDEPENDENT-SEGMENTS', '#EXT-X-MAP:URI=\"init.mp4\"', f'#EXT-X-TARGETDURATION:{track.tar... | <|body_start_0|>
segments = list(track.get_segments())[-(NUM_PLAYLIST_SEGMENTS + 1):]
if segments[-1].complete:
segments = segments[-NUM_PLAYLIST_SEGMENTS:]
first_segment = segments[0]
playlist = ['#EXTM3U', '#EXT-X-VERSION:6', '#EXT-X-INDEPENDENT-SEGMENTS', '#EXT-X-MAP:URI="... | Stream view to serve a M3U8 stream. | HlsPlaylistView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HlsPlaylistView:
"""Stream view to serve a M3U8 stream."""
def render(track: StreamOutput) -> str:
"""Render playlist."""
<|body_0|>
async def handle(self, request: web.Request, stream: Stream, sequence: str) -> web.Response:
"""Return m3u8 playlist."""
<... | stack_v2_sparse_classes_36k_train_016128 | 7,890 | permissive | [
{
"docstring": "Render playlist.",
"name": "render",
"signature": "def render(track: StreamOutput) -> str"
},
{
"docstring": "Return m3u8 playlist.",
"name": "handle",
"signature": "async def handle(self, request: web.Request, stream: Stream, sequence: str) -> web.Response"
}
] | 2 | null | Implement the Python class `HlsPlaylistView` described below.
Class description:
Stream view to serve a M3U8 stream.
Method signatures and docstrings:
- def render(track: StreamOutput) -> str: Render playlist.
- async def handle(self, request: web.Request, stream: Stream, sequence: str) -> web.Response: Return m3u8 p... | Implement the Python class `HlsPlaylistView` described below.
Class description:
Stream view to serve a M3U8 stream.
Method signatures and docstrings:
- def render(track: StreamOutput) -> str: Render playlist.
- async def handle(self, request: web.Request, stream: Stream, sequence: str) -> web.Response: Return m3u8 p... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class HlsPlaylistView:
"""Stream view to serve a M3U8 stream."""
def render(track: StreamOutput) -> str:
"""Render playlist."""
<|body_0|>
async def handle(self, request: web.Request, stream: Stream, sequence: str) -> web.Response:
"""Return m3u8 playlist."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HlsPlaylistView:
"""Stream view to serve a M3U8 stream."""
def render(track: StreamOutput) -> str:
"""Render playlist."""
segments = list(track.get_segments())[-(NUM_PLAYLIST_SEGMENTS + 1):]
if segments[-1].complete:
segments = segments[-NUM_PLAYLIST_SEGMENTS:]
... | the_stack_v2_python_sparse | homeassistant/components/stream/hls.py | BenWoodford/home-assistant | train | 11 |
b0c966dff277a10aea78a9a9491dc19206387314 | [
"if isinstance(other, TheCloud):\n return self is other\nreturn NotImplemented",
"if isinstance(other, TheCloud):\n return TheCloud()\nreturn NotImplemented",
"if isinstance(other, TheCloud):\n return self is other\nreturn NotImplemented"
] | <|body_start_0|>
if isinstance(other, TheCloud):
return self is other
return NotImplemented
<|end_body_0|>
<|body_start_1|>
if isinstance(other, TheCloud):
return TheCloud()
return NotImplemented
<|end_body_1|>
<|body_start_2|>
if isinstance(other, TheCl... | Arbitrary class declaring a method exercising this test. | TheCloud | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TheCloud:
"""Arbitrary class declaring a method exercising this test."""
def __eq__(self, other: object) -> bool:
"""Arbitrary binary dunder method correctly returning the ``NotImplemented`` singleton."""
<|body_0|>
def __add__(self, other: object) -> 'TheCloud':
... | stack_v2_sparse_classes_36k_train_016129 | 6,036 | permissive | [
{
"docstring": "Arbitrary binary dunder method correctly returning the ``NotImplemented`` singleton.",
"name": "__eq__",
"signature": "def __eq__(self, other: object) -> bool"
},
{
"docstring": "Another arbitrary binary dunder method correctly returning the ``NotImplemented`` singleton.",
"n... | 3 | null | Implement the Python class `TheCloud` described below.
Class description:
Arbitrary class declaring a method exercising this test.
Method signatures and docstrings:
- def __eq__(self, other: object) -> bool: Arbitrary binary dunder method correctly returning the ``NotImplemented`` singleton.
- def __add__(self, other... | Implement the Python class `TheCloud` described below.
Class description:
Arbitrary class declaring a method exercising this test.
Method signatures and docstrings:
- def __eq__(self, other: object) -> bool: Arbitrary binary dunder method correctly returning the ``NotImplemented`` singleton.
- def __add__(self, other... | 0cfd53391eb4de2f8297a4632aa5895b8d82a5b7 | <|skeleton|>
class TheCloud:
"""Arbitrary class declaring a method exercising this test."""
def __eq__(self, other: object) -> bool:
"""Arbitrary binary dunder method correctly returning the ``NotImplemented`` singleton."""
<|body_0|>
def __add__(self, other: object) -> 'TheCloud':
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TheCloud:
"""Arbitrary class declaring a method exercising this test."""
def __eq__(self, other: object) -> bool:
"""Arbitrary binary dunder method correctly returning the ``NotImplemented`` singleton."""
if isinstance(other, TheCloud):
return self is other
return NotI... | the_stack_v2_python_sparse | beartype_test/a00_unit/a70_decor/a40_code/a00_mod/test_decor_mypy.py | beartype/beartype | train | 1,992 |
5b3c725a77620e02b2a245debdbf176a1a8a52a9 | [
"QtGui.QWidget.__init__(self, parent)\nself.OK = QtGui.QToolButton(parent)\nself.OK.setAutoRaise(True)\nself.OK.setIcon(QtGui.QIcon(Qt4_Icons.load('button_ok_small')))\nself.Cancel = QtGui.QToolButton(parent)\nself.Cancel.setAutoRaise(True)\nself.Cancel.setIcon(QtGui.QIcon(Qt4_Icons.load('button_cancel_small')))\ns... | <|body_start_0|>
QtGui.QWidget.__init__(self, parent)
self.OK = QtGui.QToolButton(parent)
self.OK.setAutoRaise(True)
self.OK.setIcon(QtGui.QIcon(Qt4_Icons.load('button_ok_small')))
self.Cancel = QtGui.QToolButton(parent)
self.Cancel.setAutoRaise(True)
self.Cancel.... | Descript. : | ValidationTableItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidationTableItem:
"""Descript. :"""
def __init__(self, parent=None):
"""Descript. : parent (QTreeWidget) : Item's QTreeWidget parent."""
<|body_0|>
def setEnabled(self, enabled):
"""Descript. :"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_016130 | 15,558 | no_license | [
{
"docstring": "Descript. : parent (QTreeWidget) : Item's QTreeWidget parent.",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Descript. :",
"name": "setEnabled",
"signature": "def setEnabled(self, enabled)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000020 | Implement the Python class `ValidationTableItem` described below.
Class description:
Descript. :
Method signatures and docstrings:
- def __init__(self, parent=None): Descript. : parent (QTreeWidget) : Item's QTreeWidget parent.
- def setEnabled(self, enabled): Descript. : | Implement the Python class `ValidationTableItem` described below.
Class description:
Descript. :
Method signatures and docstrings:
- def __init__(self, parent=None): Descript. : parent (QTreeWidget) : Item's QTreeWidget parent.
- def setEnabled(self, enabled): Descript. :
<|skeleton|>
class ValidationTableItem:
... | 11486d6c91fc0077e967cb2321743466a7c1aa8b | <|skeleton|>
class ValidationTableItem:
"""Descript. :"""
def __init__(self, parent=None):
"""Descript. : parent (QTreeWidget) : Item's QTreeWidget parent."""
<|body_0|>
def setEnabled(self, enabled):
"""Descript. :"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidationTableItem:
"""Descript. :"""
def __init__(self, parent=None):
"""Descript. : parent (QTreeWidget) : Item's QTreeWidget parent."""
QtGui.QWidget.__init__(self, parent)
self.OK = QtGui.QToolButton(parent)
self.OK.setAutoRaise(True)
self.OK.setIcon(QtGui.QIc... | the_stack_v2_python_sparse | Utils/Qt4_PropertyEditor.py | douglasbeniz/BlissFramework | train | 0 |
154fe6a28d95f4a93a28fdf88cb379a2c4d23454 | [
"from vmware.vapi.bindings.datetime_helper import DateTimeConverter\nif isinstance(datetime_arg, six.string_types):\n datetime_arg = DateTimeConverter.convert_to_datetime(datetime_arg)\nif not isinstance(datetime_arg, datetime):\n raise TypeError('Argument is not a datetime')\nreturn datetime_arg.strftime(loc... | <|body_start_0|>
from vmware.vapi.bindings.datetime_helper import DateTimeConverter
if isinstance(datetime_arg, six.string_types):
datetime_arg = DateTimeConverter.convert_to_datetime(datetime_arg)
if not isinstance(datetime_arg, datetime):
raise TypeError('Argument is no... | Format the string | StringFormatter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringFormatter:
"""Format the string"""
def _localize_datetime(cls, datetime_arg):
"""Localize a datetime object :type datetime_arg: :class:`datetime.datetime` :param datetime_arg: Datetime object :rtype: :class:`str` :return: Localized datetime string"""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_016131 | 5,766 | no_license | [
{
"docstring": "Localize a datetime object :type datetime_arg: :class:`datetime.datetime` :param datetime_arg: Datetime object :rtype: :class:`str` :return: Localized datetime string",
"name": "_localize_datetime",
"signature": "def _localize_datetime(cls, datetime_arg)"
},
{
"docstring": "Local... | 4 | null | Implement the Python class `StringFormatter` described below.
Class description:
Format the string
Method signatures and docstrings:
- def _localize_datetime(cls, datetime_arg): Localize a datetime object :type datetime_arg: :class:`datetime.datetime` :param datetime_arg: Datetime object :rtype: :class:`str` :return:... | Implement the Python class `StringFormatter` described below.
Class description:
Format the string
Method signatures and docstrings:
- def _localize_datetime(cls, datetime_arg): Localize a datetime object :type datetime_arg: :class:`datetime.datetime` :param datetime_arg: Datetime object :rtype: :class:`str` :return:... | 5d395700ab3d0d1d45b497e48beab8c366fca9f5 | <|skeleton|>
class StringFormatter:
"""Format the string"""
def _localize_datetime(cls, datetime_arg):
"""Localize a datetime object :type datetime_arg: :class:`datetime.datetime` :param datetime_arg: Datetime object :rtype: :class:`str` :return: Localized datetime string"""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringFormatter:
"""Format the string"""
def _localize_datetime(cls, datetime_arg):
"""Localize a datetime object :type datetime_arg: :class:`datetime.datetime` :param datetime_arg: Datetime object :rtype: :class:`str` :return: Localized datetime string"""
from vmware.vapi.bindings.dateti... | the_stack_v2_python_sparse | alexa-program.bak/vmware/vapi/l10n/formatter.py | taromurata/TDP2018_VMCAPI | train | 1 |
e34c0cd4f84f2328e88b1394b8940f5c8bba5448 | [
"self.copyMatrix = matrix\nself.sumMatrix = []\nif matrix != []:\n row = len(matrix)\n col = len(matrix[0])\n for i in range(0, row):\n temp = []\n for j in range(0, col):\n temp.append(0)\n self.sumMatrix.append(temp)\n rowSum = 0\n for c in range(0, col):\n ro... | <|body_start_0|>
self.copyMatrix = matrix
self.sumMatrix = []
if matrix != []:
row = len(matrix)
col = len(matrix[0])
for i in range(0, row):
temp = []
for j in range(0, col):
temp.append(0)
s... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_36k_train_016132 | 2,054 | no_license | [
{
"docstring": "initialize your data structure here. :type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtyp... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | 0a2e0e4a5176c02910d7718c42903d10a6c47a5f | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
self.copyMatrix = matrix
self.sumMatrix = []
if matrix != []:
row = len(matrix)
col = len(matrix[0])
for i in range(0, row):
... | the_stack_v2_python_sparse | Range_Sum_Query2D_Immutable.py | baichuan/Leetcode | train | 0 | |
b1bd9176ed8c7004b2fe625b5ced7b081418164c | [
"self.sigmoid_layers = []\nself.rbm_layers = []\nself.params = []\nself.n_layers = len(hidden_layers_sizes)\nassert self.n_layers > 0\nif not theano_rng:\n theano_rng = MRG_RandomStreams(numpy_rng.randint(2 ** 30))\nself.x = T.matrix('x')\nself.y = T.ivector('y')\nfor i in range(self.n_layers):\n if i == 0:\n... | <|body_start_0|>
self.sigmoid_layers = []
self.rbm_layers = []
self.params = []
self.n_layers = len(hidden_layers_sizes)
assert self.n_layers > 0
if not theano_rng:
theano_rng = MRG_RandomStreams(numpy_rng.randint(2 ** 30))
self.x = T.matrix('x')
... | Deep Belief Network | DBN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBN:
"""Deep Belief Network"""
def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10):
"""This class is made to support a variable number of layers. numpy_rng is the random state number. numpy_rng is the generator to draw initial weights.... | stack_v2_sparse_classes_36k_train_016133 | 9,191 | no_license | [
{
"docstring": "This class is made to support a variable number of layers. numpy_rng is the random state number. numpy_rng is the generator to draw initial weights. theano_rng is for tensor's theano rng. n_ins is an integer of the input dimension. hidden_layer_sizes is the intermediate layers size. n_outs is ou... | 3 | stack_v2_sparse_classes_30k_train_012158 | Implement the Python class `DBN` described below.
Class description:
Deep Belief Network
Method signatures and docstrings:
- def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10): This class is made to support a variable number of layers. numpy_rng is the random state nu... | Implement the Python class `DBN` described below.
Class description:
Deep Belief Network
Method signatures and docstrings:
- def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10): This class is made to support a variable number of layers. numpy_rng is the random state nu... | 6849cc891bbb9ac69cb20dfb13fe6bb5bd77d8c5 | <|skeleton|>
class DBN:
"""Deep Belief Network"""
def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10):
"""This class is made to support a variable number of layers. numpy_rng is the random state number. numpy_rng is the generator to draw initial weights.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DBN:
"""Deep Belief Network"""
def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10):
"""This class is made to support a variable number of layers. numpy_rng is the random state number. numpy_rng is the generator to draw initial weights. theano_rng i... | the_stack_v2_python_sparse | algebra/linear/deepbeliefnetwork.py | HussainAther/mathematics | train | 2 |
573dc4ca5ea195faee224c90d9bd4ccaaa4e3e93 | [
"is_unprivileged = self.is_unprivileged_query(request, identifier)\nif is_unprivileged:\n if not getattr(settings, 'ALLOW_UNPRIVILEGED_SSO_PROVIDER_QUERY', False):\n return Response(status=status.HTTP_403_FORBIDDEN)\ntry:\n user = User.objects.get(**{identifier.kind: identifier.value})\nexcept User.Doe... | <|body_start_0|>
is_unprivileged = self.is_unprivileged_query(request, identifier)
if is_unprivileged:
if not getattr(settings, 'ALLOW_UNPRIVILEGED_SSO_PROVIDER_QUERY', False):
return Response(status=status.HTTP_403_FORBIDDEN)
try:
user = User.objects.get(... | Common core of UserView and UserViewV2 | BaseUserView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseUserView:
"""Common core of UserView and UserViewV2"""
def do_get(self, request, identifier):
"""Fulfill the request, now that the identifier has been specified."""
<|body_0|>
def get_provider_data(self, assoc, is_unprivileged):
"""Return the data for the spe... | stack_v2_sparse_classes_36k_train_016134 | 16,815 | permissive | [
{
"docstring": "Fulfill the request, now that the identifier has been specified.",
"name": "do_get",
"signature": "def do_get(self, request, identifier)"
},
{
"docstring": "Return the data for the specified provider. If the request is unprivileged, do not return the remote ID of the user.",
... | 3 | stack_v2_sparse_classes_30k_train_013278 | Implement the Python class `BaseUserView` described below.
Class description:
Common core of UserView and UserViewV2
Method signatures and docstrings:
- def do_get(self, request, identifier): Fulfill the request, now that the identifier has been specified.
- def get_provider_data(self, assoc, is_unprivileged): Return... | Implement the Python class `BaseUserView` described below.
Class description:
Common core of UserView and UserViewV2
Method signatures and docstrings:
- def do_get(self, request, identifier): Fulfill the request, now that the identifier has been specified.
- def get_provider_data(self, assoc, is_unprivileged): Return... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class BaseUserView:
"""Common core of UserView and UserViewV2"""
def do_get(self, request, identifier):
"""Fulfill the request, now that the identifier has been specified."""
<|body_0|>
def get_provider_data(self, assoc, is_unprivileged):
"""Return the data for the spe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseUserView:
"""Common core of UserView and UserViewV2"""
def do_get(self, request, identifier):
"""Fulfill the request, now that the identifier has been specified."""
is_unprivileged = self.is_unprivileged_query(request, identifier)
if is_unprivileged:
if not getattr... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/djangoapps/third_party_auth/api/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
6a2cd9ef9f68da6c10c51e02a85ffa9cc3ad979e | [
"super().__init__()\nself._instruction_names = {instruction_name} if isinstance(instruction_name, str) else set(instruction_name)\nself._recurse = recurse",
"names = dag.count_ops(recurse=self._recurse)\nfor name in self._instruction_names:\n self.property_set[f'contains_{name}'] = name in names"
] | <|body_start_0|>
super().__init__()
self._instruction_names = {instruction_name} if isinstance(instruction_name, str) else set(instruction_name)
self._recurse = recurse
<|end_body_0|>
<|body_start_1|>
names = dag.count_ops(recurse=self._recurse)
for name in self._instruction_nam... | An analysis pass to detect if the DAG contains a specific instruction. This pass takes in a single instruction name for example ``'delay'`` and will set the property set ``contains_delay`` to ``True`` if the DAG contains that instruction and ``False`` if it does not. | ContainsInstruction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContainsInstruction:
"""An analysis pass to detect if the DAG contains a specific instruction. This pass takes in a single instruction name for example ``'delay'`` and will set the property set ``contains_delay`` to ``True`` if the DAG contains that instruction and ``False`` if it does not."""
... | stack_v2_sparse_classes_36k_train_016135 | 1,834 | permissive | [
{
"docstring": "ContainsInstruction initializer. Args: instruction_name (str | Iterable[str]): The instruction or instructions to check are in the DAG. The output in the property set is set to ``contains_`` prefixed on each value for this parameter. recurse (bool): if ``True`` (default), then recurse into contr... | 2 | stack_v2_sparse_classes_30k_train_001081 | Implement the Python class `ContainsInstruction` described below.
Class description:
An analysis pass to detect if the DAG contains a specific instruction. This pass takes in a single instruction name for example ``'delay'`` and will set the property set ``contains_delay`` to ``True`` if the DAG contains that instruct... | Implement the Python class `ContainsInstruction` described below.
Class description:
An analysis pass to detect if the DAG contains a specific instruction. This pass takes in a single instruction name for example ``'delay'`` and will set the property set ``contains_delay`` to ``True`` if the DAG contains that instruct... | 0b51250e219ca303654fc28a318c21366584ccd3 | <|skeleton|>
class ContainsInstruction:
"""An analysis pass to detect if the DAG contains a specific instruction. This pass takes in a single instruction name for example ``'delay'`` and will set the property set ``contains_delay`` to ``True`` if the DAG contains that instruction and ``False`` if it does not."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContainsInstruction:
"""An analysis pass to detect if the DAG contains a specific instruction. This pass takes in a single instruction name for example ``'delay'`` and will set the property set ``contains_delay`` to ``True`` if the DAG contains that instruction and ``False`` if it does not."""
def __init... | the_stack_v2_python_sparse | qiskit/transpiler/passes/utils/contains_instruction.py | 1ucian0/qiskit-terra | train | 6 |
12902aac3f09bed3547f4be6c5aef26623f1117b | [
"self.face_net = cv.dnn.readNet('FaceNet.prototxt', 'FaceNet.caffemodel')\nself.mask_net = load_model('mask_detector.model')\nself.confidence = confidence",
"h, w = frame.shape[:2]\nblob = cv.dnn.blobFromImage(frame, 1.0, (235, 350))\nself.face_net.setInput(blob)\ndetections = self.face_net.forward()\nfaces = []\... | <|body_start_0|>
self.face_net = cv.dnn.readNet('FaceNet.prototxt', 'FaceNet.caffemodel')
self.mask_net = load_model('mask_detector.model')
self.confidence = confidence
<|end_body_0|>
<|body_start_1|>
h, w = frame.shape[:2]
blob = cv.dnn.blobFromImage(frame, 1.0, (235, 350))
... | Class that encapsulates the functionality of the face and mask detector and it's used to get the predictions of the network. | FaceAndMaskDetector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceAndMaskDetector:
"""Class that encapsulates the functionality of the face and mask detector and it's used to get the predictions of the network."""
def __init__(self, confidence: float):
"""Loads the face and mask models and sets the confidence level."""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_016136 | 3,436 | no_license | [
{
"docstring": "Loads the face and mask models and sets the confidence level.",
"name": "__init__",
"signature": "def __init__(self, confidence: float)"
},
{
"docstring": "Gets the current frame and returns the predictions and their corresponding locations.",
"name": "detect_and_predict",
... | 2 | stack_v2_sparse_classes_30k_train_017748 | Implement the Python class `FaceAndMaskDetector` described below.
Class description:
Class that encapsulates the functionality of the face and mask detector and it's used to get the predictions of the network.
Method signatures and docstrings:
- def __init__(self, confidence: float): Loads the face and mask models an... | Implement the Python class `FaceAndMaskDetector` described below.
Class description:
Class that encapsulates the functionality of the face and mask detector and it's used to get the predictions of the network.
Method signatures and docstrings:
- def __init__(self, confidence: float): Loads the face and mask models an... | 8ca1d270d2d382c48c138bb78e0ea7f8e04cffee | <|skeleton|>
class FaceAndMaskDetector:
"""Class that encapsulates the functionality of the face and mask detector and it's used to get the predictions of the network."""
def __init__(self, confidence: float):
"""Loads the face and mask models and sets the confidence level."""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FaceAndMaskDetector:
"""Class that encapsulates the functionality of the face and mask detector and it's used to get the predictions of the network."""
def __init__(self, confidence: float):
"""Loads the face and mask models and sets the confidence level."""
self.face_net = cv.dnn.readNet... | the_stack_v2_python_sparse | utils/face_and_mask_detector.py | rajatrawal/tiago-mask-checker | train | 0 |
f0aef98815ce8ea181f036f4118513281cc3bf1c | [
"size = len(primes)\nindex = [0 for i in range(size)]\nvals = [0 for i in range(size)]\nres = [1]\nfor i in range(1, n):\n for j in range(size):\n vals[j] = res[index[j]] * primes[j]\n res.append(min(vals))\n for j in range(size):\n if vals[j] == res[i]:\n index[j] += 1\nreturn res... | <|body_start_0|>
size = len(primes)
index = [0 for i in range(size)]
vals = [0 for i in range(size)]
res = [1]
for i in range(1, n):
for j in range(size):
vals[j] = res[index[j]] * primes[j]
res.append(min(vals))
for j in range(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
<|body_0|>
def nthSuperUglyNumber1(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_016137 | 1,130 | no_license | [
{
"docstring": ":type n: int :type primes: List[int] :rtype: int",
"name": "nthSuperUglyNumber",
"signature": "def nthSuperUglyNumber(self, n, primes)"
},
{
"docstring": ":type n: int :type primes: List[int] :rtype: int",
"name": "nthSuperUglyNumber1",
"signature": "def nthSuperUglyNumbe... | 2 | stack_v2_sparse_classes_30k_train_013756 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthSuperUglyNumber(self, n, primes): :type n: int :type primes: List[int] :rtype: int
- def nthSuperUglyNumber1(self, n, primes): :type n: int :type primes: List[int] :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthSuperUglyNumber(self, n, primes): :type n: int :type primes: List[int] :rtype: int
- def nthSuperUglyNumber1(self, n, primes): :type n: int :type primes: List[int] :rtype:... | a62f5518113392126a08b1bdb94b94685f618c72 | <|skeleton|>
class Solution:
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
<|body_0|>
def nthSuperUglyNumber1(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
size = len(primes)
index = [0 for i in range(size)]
vals = [0 for i in range(size)]
res = [1]
for i in range(1, n):
for j in range(size):
... | the_stack_v2_python_sparse | Super Ugly Number.py | MartinTrojans/Leetcode-Python | train | 0 | |
644781938c21fa8c8499ed5c29233f0c1c1c0046 | [
"self.df = df\nkeys_list = ['train_dir', 'test_dir', 'train_out', 'test_out', 'masks_out']\nfor key in keys_list:\n setattr(self, key, None)\nfor key in paths_dict.keys():\n setattr(self, key, paths_dict[key])\nif self.train_dir is not None:\n assert os.path.isdir(self.train_dir), 'Please make sure train_d... | <|body_start_0|>
self.df = df
keys_list = ['train_dir', 'test_dir', 'train_out', 'test_out', 'masks_out']
for key in keys_list:
setattr(self, key, None)
for key in paths_dict.keys():
setattr(self, key, paths_dict[key])
if self.train_dir is not None:
... | Preprocessor class. Attributes: df: dataframe with cols ["Image_Label", "EncodedPixels"]; the first dataframe from running `setup_train_and_sub_df(...)` train_dir (str / None): test_dir (str / None): train_out (str / None): test_out (str / None): masks_out (str / None): Leave as None, if not using a specific route. out... | Preprocessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preprocessor:
"""Preprocessor class. Attributes: df: dataframe with cols ["Image_Label", "EncodedPixels"]; the first dataframe from running `setup_train_and_sub_df(...)` train_dir (str / None): test_dir (str / None): train_out (str / None): test_out (str / None): masks_out (str / None): Leave as ... | stack_v2_sparse_classes_36k_train_016138 | 7,254 | permissive | [
{
"docstring": "Args: df: dataframe with cols [\"Image_Label\", \"EncodedPixels\"]; the first dataframe from running `setup_train_and_sub_df(...)` paths_dict (dict): for all of the paths to the input and output directories and files. Keys: - train_dir - test_dir - train_out: path to the output training images z... | 4 | stack_v2_sparse_classes_30k_train_006234 | Implement the Python class `Preprocessor` described below.
Class description:
Preprocessor class. Attributes: df: dataframe with cols ["Image_Label", "EncodedPixels"]; the first dataframe from running `setup_train_and_sub_df(...)` train_dir (str / None): test_dir (str / None): train_out (str / None): test_out (str / N... | Implement the Python class `Preprocessor` described below.
Class description:
Preprocessor class. Attributes: df: dataframe with cols ["Image_Label", "EncodedPixels"]; the first dataframe from running `setup_train_and_sub_df(...)` train_dir (str / None): test_dir (str / None): train_out (str / None): test_out (str / N... | 25571f53efd48f68735d7fe2991e3ad783cbd4b1 | <|skeleton|>
class Preprocessor:
"""Preprocessor class. Attributes: df: dataframe with cols ["Image_Label", "EncodedPixels"]; the first dataframe from running `setup_train_and_sub_df(...)` train_dir (str / None): test_dir (str / None): train_out (str / None): test_out (str / None): masks_out (str / None): Leave as ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Preprocessor:
"""Preprocessor class. Attributes: df: dataframe with cols ["Image_Label", "EncodedPixels"]; the first dataframe from running `setup_train_and_sub_df(...)` train_dir (str / None): test_dir (str / None): train_out (str / None): test_out (str / None): masks_out (str / None): Leave as None, if not ... | the_stack_v2_python_sparse | clouds/preprocess.py | jchen42703/reproducing-cloud-3rd-place | train | 1 |
21d480d25e85340fe1f8bbeee8201ea4831e1dd6 | [
"id = request.query_params.get('id')\nif id:\n queryset = queryset.filter(id=id)\nname = request.query_params.get('name')\nif name:\n queryset = queryset.filter(name__icontains=name)\nphone = request.query_params.get('phone')\nif phone:\n queryset = queryset.filter(phone__icontains=phone)\nemail = request.... | <|body_start_0|>
id = request.query_params.get('id')
if id:
queryset = queryset.filter(id=id)
name = request.query_params.get('name')
if name:
queryset = queryset.filter(name__icontains=name)
phone = request.query_params.get('phone')
if phone:
... | Service to filter admin panel table data | FilterService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterService:
"""Service to filter admin panel table data"""
def filter_user(cls, request=None, queryset=None):
"""filter user based on query params"""
<|body_0|>
def filter_resource(cls, request=None, queryset=None):
"""filter user resource based on query param... | stack_v2_sparse_classes_36k_train_016139 | 2,683 | no_license | [
{
"docstring": "filter user based on query params",
"name": "filter_user",
"signature": "def filter_user(cls, request=None, queryset=None)"
},
{
"docstring": "filter user resource based on query params",
"name": "filter_resource",
"signature": "def filter_resource(cls, request=None, quer... | 2 | stack_v2_sparse_classes_30k_train_011822 | Implement the Python class `FilterService` described below.
Class description:
Service to filter admin panel table data
Method signatures and docstrings:
- def filter_user(cls, request=None, queryset=None): filter user based on query params
- def filter_resource(cls, request=None, queryset=None): filter user resource... | Implement the Python class `FilterService` described below.
Class description:
Service to filter admin panel table data
Method signatures and docstrings:
- def filter_user(cls, request=None, queryset=None): filter user based on query params
- def filter_resource(cls, request=None, queryset=None): filter user resource... | 672f7dd7740d37706606879a4d9b83f3aa5e8dfd | <|skeleton|>
class FilterService:
"""Service to filter admin panel table data"""
def filter_user(cls, request=None, queryset=None):
"""filter user based on query params"""
<|body_0|>
def filter_resource(cls, request=None, queryset=None):
"""filter user resource based on query param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterService:
"""Service to filter admin panel table data"""
def filter_user(cls, request=None, queryset=None):
"""filter user based on query params"""
id = request.query_params.get('id')
if id:
queryset = queryset.filter(id=id)
name = request.query_params.get... | the_stack_v2_python_sparse | user/services/filter_service.py | chauhanajay4u/resource-project | train | 0 |
1f4264f0bdf99b3b1df879ca6dcbcab7b483eefc | [
"ret = list(s)\nwhile 1:\n n = len(ret)\n tmp = list()\n i = 0\n is_last_removed = False\n while i < n - 1:\n if ret[i] == ret[i + 1].swapcase():\n i += 2\n if i == n:\n is_last_removed = True\n else:\n tmp.append(ret[i])\n i +=... | <|body_start_0|>
ret = list(s)
while 1:
n = len(ret)
tmp = list()
i = 0
is_last_removed = False
while i < n - 1:
if ret[i] == ret[i + 1].swapcase():
i += 2
if i == n:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def makeGood2(self, s):
""":type s: str :rtype: str thought: keep removing adjacent 2 chars until the length does not change. easy - medium 20 - 30 min. corner case of how to handle the last char. 04/03/2022 11:41 Accepted 46 ms 13.6 MB python use stack is much easier code."""
... | stack_v2_sparse_classes_36k_train_016140 | 2,621 | no_license | [
{
"docstring": ":type s: str :rtype: str thought: keep removing adjacent 2 chars until the length does not change. easy - medium 20 - 30 min. corner case of how to handle the last char. 04/03/2022 11:41 Accepted 46 ms 13.6 MB python use stack is much easier code.",
"name": "makeGood2",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_005733 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def makeGood2(self, s): :type s: str :rtype: str thought: keep removing adjacent 2 chars until the length does not change. easy - medium 20 - 30 min. corner case of how to handle... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def makeGood2(self, s): :type s: str :rtype: str thought: keep removing adjacent 2 chars until the length does not change. easy - medium 20 - 30 min. corner case of how to handle... | 02726da394971ef02616a038dadc126c6ff260de | <|skeleton|>
class Solution:
def makeGood2(self, s):
""":type s: str :rtype: str thought: keep removing adjacent 2 chars until the length does not change. easy - medium 20 - 30 min. corner case of how to handle the last char. 04/03/2022 11:41 Accepted 46 ms 13.6 MB python use stack is much easier code."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def makeGood2(self, s):
""":type s: str :rtype: str thought: keep removing adjacent 2 chars until the length does not change. easy - medium 20 - 30 min. corner case of how to handle the last char. 04/03/2022 11:41 Accepted 46 ms 13.6 MB python use stack is much easier code."""
ret = ... | the_stack_v2_python_sparse | N1544_MakeTheStringGreat.py | zerghua/leetcode-python | train | 2 | |
1e12abe768d49dc83d9be7a54e613fd872dbd4dd | [
"idx: Dict[int, Dict[str, Union[int, List[int]]]] = {}\nfor i, v in enumerate(numbers):\n if v not in idx:\n idx[v] = {'count': 1, 'index': [i]}\n else:\n idx[v]['count'] += 1\n idx[v]['index'].append(i)\nindex1, index2 = (0, 0)\nfor k in idx.keys():\n dif = target - k\n if dif in i... | <|body_start_0|>
idx: Dict[int, Dict[str, Union[int, List[int]]]] = {}
for i, v in enumerate(numbers):
if v not in idx:
idx[v] = {'count': 1, 'index': [i]}
else:
idx[v]['count'] += 1
idx[v]['index'].append(i)
index1, index2 ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
"""哈希表。"""
<|body_0|>
def twoSum2(self, numbers: List[int], target: int) -> List[int]:
"""二分查找。"""
<|body_1|>
def twoSum3(self, numbers: List[int], target: int) -> List[int]:
... | stack_v2_sparse_classes_36k_train_016141 | 4,429 | no_license | [
{
"docstring": "哈希表。",
"name": "twoSum",
"signature": "def twoSum(self, numbers: List[int], target: int) -> List[int]"
},
{
"docstring": "二分查找。",
"name": "twoSum2",
"signature": "def twoSum2(self, numbers: List[int], target: int) -> List[int]"
},
{
"docstring": "双指针。",
"name"... | 3 | stack_v2_sparse_classes_30k_train_016478 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers: List[int], target: int) -> List[int]: 哈希表。
- def twoSum2(self, numbers: List[int], target: int) -> List[int]: 二分查找。
- def twoSum3(self, numbers: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers: List[int], target: int) -> List[int]: 哈希表。
- def twoSum2(self, numbers: List[int], target: int) -> List[int]: 二分查找。
- def twoSum3(self, numbers: List[in... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
"""哈希表。"""
<|body_0|>
def twoSum2(self, numbers: List[int], target: int) -> List[int]:
"""二分查找。"""
<|body_1|>
def twoSum3(self, numbers: List[int], target: int) -> List[int]:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
"""哈希表。"""
idx: Dict[int, Dict[str, Union[int, List[int]]]] = {}
for i, v in enumerate(numbers):
if v not in idx:
idx[v] = {'count': 1, 'index': [i]}
else:
... | the_stack_v2_python_sparse | 0167_two-sum-ii-input-array-is-sorted.py | Nigirimeshi/leetcode | train | 0 | |
a71a2356d354be9c11656064c7cf37b8d04f690a | [
"if not FIXCLING:\n self.assertTrue(hasattr(PyTest, '_S_single'))\n self.assertTrue(hasattr(PyTest, '__default_lock_policy'))",
"nullptr = ROOT.nullptr\nself.assertNotEqual(nullptr, 0)\nif os.environ.get('LEGACY_PYROOT') == 'True':\n self.assertRaises(TypeError, TGraphErrors, 0, 0, 0)\ng = TGraphErrors(0... | <|body_start_0|>
if not FIXCLING:
self.assertTrue(hasattr(PyTest, '_S_single'))
self.assertTrue(hasattr(PyTest, '__default_lock_policy'))
<|end_body_0|>
<|body_start_1|>
nullptr = ROOT.nullptr
self.assertNotEqual(nullptr, 0)
if os.environ.get('LEGACY_PYROOT') == ... | Cpp2Cpp11LanguageConstructsTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cpp2Cpp11LanguageConstructsTestCase:
def test01StaticEnum(self):
"""Test usage and access of a const static enum defined in header"""
<|body_0|>
def test02NULLPtrPassing(self):
"""Allow the programmer to pass NULL in certain cases"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_016142 | 2,590 | no_license | [
{
"docstring": "Test usage and access of a const static enum defined in header",
"name": "test01StaticEnum",
"signature": "def test01StaticEnum(self)"
},
{
"docstring": "Allow the programmer to pass NULL in certain cases",
"name": "test02NULLPtrPassing",
"signature": "def test02NULLPtrPa... | 2 | null | Implement the Python class `Cpp2Cpp11LanguageConstructsTestCase` described below.
Class description:
Implement the Cpp2Cpp11LanguageConstructsTestCase class.
Method signatures and docstrings:
- def test01StaticEnum(self): Test usage and access of a const static enum defined in header
- def test02NULLPtrPassing(self):... | Implement the Python class `Cpp2Cpp11LanguageConstructsTestCase` described below.
Class description:
Implement the Cpp2Cpp11LanguageConstructsTestCase class.
Method signatures and docstrings:
- def test01StaticEnum(self): Test usage and access of a const static enum defined in header
- def test02NULLPtrPassing(self):... | 134508460915282a5d82d6cbbb6e6afa14653413 | <|skeleton|>
class Cpp2Cpp11LanguageConstructsTestCase:
def test01StaticEnum(self):
"""Test usage and access of a const static enum defined in header"""
<|body_0|>
def test02NULLPtrPassing(self):
"""Allow the programmer to pass NULL in certain cases"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cpp2Cpp11LanguageConstructsTestCase:
def test01StaticEnum(self):
"""Test usage and access of a const static enum defined in header"""
if not FIXCLING:
self.assertTrue(hasattr(PyTest, '_S_single'))
self.assertTrue(hasattr(PyTest, '__default_lock_policy'))
def test02... | the_stack_v2_python_sparse | python/cpp/PyROOT_cpp11tests.py | root-project/roottest | train | 41 | |
6a35afabc54c0dc6cb20ba1a1e82031652e913eb | [
"self.text_name = kwargs.pop('text_name', 'text')\nself.identity_name = kwargs.pop('identity_name', 'identity')\nsuper(GenericHttpForm, self).__init__(*args, **kwargs)\nself.fields[self.text_name] = forms.CharField()\nself.fields[self.identity_name] = forms.CharField()",
"identity = self.cleaned_data[self.identit... | <|body_start_0|>
self.text_name = kwargs.pop('text_name', 'text')
self.identity_name = kwargs.pop('identity_name', 'identity')
super(GenericHttpForm, self).__init__(*args, **kwargs)
self.fields[self.text_name] = forms.CharField()
self.fields[self.identity_name] = forms.CharField(... | GenericHttpForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericHttpForm:
def __init__(self, *args, **kwargs):
"""Saves the identify (phone number) and text field names on self, calls super(), and then adds the required fields."""
<|body_0|>
def get_incoming_data(self):
"""Returns the connection and text for this message, ... | stack_v2_sparse_classes_36k_train_016143 | 1,876 | permissive | [
{
"docstring": "Saves the identify (phone number) and text field names on self, calls super(), and then adds the required fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Returns the connection and text for this message, based on the field names... | 2 | stack_v2_sparse_classes_30k_train_013875 | Implement the Python class `GenericHttpForm` described below.
Class description:
Implement the GenericHttpForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Saves the identify (phone number) and text field names on self, calls super(), and then adds the required fields.
- def get_inc... | Implement the Python class `GenericHttpForm` described below.
Class description:
Implement the GenericHttpForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Saves the identify (phone number) and text field names on self, calls super(), and then adds the required fields.
- def get_inc... | aaa2ddab68e19d979525c3823c3ec0e646e92c83 | <|skeleton|>
class GenericHttpForm:
def __init__(self, *args, **kwargs):
"""Saves the identify (phone number) and text field names on self, calls super(), and then adds the required fields."""
<|body_0|>
def get_incoming_data(self):
"""Returns the connection and text for this message, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenericHttpForm:
def __init__(self, *args, **kwargs):
"""Saves the identify (phone number) and text field names on self, calls super(), and then adds the required fields."""
self.text_name = kwargs.pop('text_name', 'text')
self.identity_name = kwargs.pop('identity_name', 'identity')
... | the_stack_v2_python_sparse | rapidsms/backends/http/forms.py | rapidsms/rapidsms | train | 409 | |
3e3a4940cc200e8131278c06a78be96538d41e7d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn InvitationParticipantInfo()",
"from .identity_set import IdentitySet\nfrom .identity_set import IdentitySet\nfields: Dict[str, Callable[[Any], None]] = {'hidden': lambda n: setattr(self, 'hidden', n.get_bool_value()), 'identity': lambd... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return InvitationParticipantInfo()
<|end_body_0|>
<|body_start_1|>
from .identity_set import IdentitySet
from .identity_set import IdentitySet
fields: Dict[str, Callable[[Any], None]] =... | InvitationParticipantInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvitationParticipantInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitationParticipantInfo:
"""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 c... | stack_v2_sparse_classes_36k_train_016144 | 3,902 | 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: InvitationParticipantInfo",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrim... | 3 | null | Implement the Python class `InvitationParticipantInfo` described below.
Class description:
Implement the InvitationParticipantInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitationParticipantInfo: Creates a new instance of the appropriat... | Implement the Python class `InvitationParticipantInfo` described below.
Class description:
Implement the InvitationParticipantInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitationParticipantInfo: Creates a new instance of the appropriat... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class InvitationParticipantInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitationParticipantInfo:
"""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 c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InvitationParticipantInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> InvitationParticipantInfo:
"""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 obje... | the_stack_v2_python_sparse | msgraph/generated/models/invitation_participant_info.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
042db8150433131b2b5f55d64201442cf0794dcf | [
"if not a:\n return None\nl = 0\nr = len(a)\nreturn self.convert_arr(a, l, r)",
"if l == r:\n return None\nm = l + (r - l) // 2\np = TreeNode(a[m])\np.cl = self.convert_arr(a, l, m)\np.cr = self.convert_arr(a, m + 1, r)\nreturn p"
] | <|body_start_0|>
if not a:
return None
l = 0
r = len(a)
return self.convert_arr(a, l, r)
<|end_body_0|>
<|body_start_1|>
if l == r:
return None
m = l + (r - l) // 2
p = TreeNode(a[m])
p.cl = self.convert_arr(a, l, m)
p.cr =... | Binary traversal and breadth-first search of sorted array. Time complexity: O(n) - Traverse all nodes Space complexity: O(n) - Create TreeNode objects for each element in sorted list | Solution | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Binary traversal and breadth-first search of sorted array. Time complexity: O(n) - Traverse all nodes Space complexity: O(n) - Create TreeNode objects for each element in sorted list"""
def sorted_arr_to_bst(self, a):
"""Creates binary search tree from input sorted list.... | stack_v2_sparse_classes_36k_train_016145 | 4,204 | permissive | [
{
"docstring": "Creates binary search tree from input sorted list. :param list[int] a: sorted array of integers :return: binary search tree representing input sorted array :rtype: TreeNode",
"name": "sorted_arr_to_bst",
"signature": "def sorted_arr_to_bst(self, a)"
},
{
"docstring": "Recursively... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Binary traversal and breadth-first search of sorted array. Time complexity: O(n) - Traverse all nodes Space complexity: O(n) - Create TreeNode objects for each element in sorted list
Method signatures and docstrings:
- def sorted_arr_to_bst(sel... | Implement the Python class `Solution` described below.
Class description:
Binary traversal and breadth-first search of sorted array. Time complexity: O(n) - Traverse all nodes Space complexity: O(n) - Create TreeNode objects for each element in sorted list
Method signatures and docstrings:
- def sorted_arr_to_bst(sel... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution:
"""Binary traversal and breadth-first search of sorted array. Time complexity: O(n) - Traverse all nodes Space complexity: O(n) - Create TreeNode objects for each element in sorted list"""
def sorted_arr_to_bst(self, a):
"""Creates binary search tree from input sorted list.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Binary traversal and breadth-first search of sorted array. Time complexity: O(n) - Traverse all nodes Space complexity: O(n) - Create TreeNode objects for each element in sorted list"""
def sorted_arr_to_bst(self, a):
"""Creates binary search tree from input sorted list. :param list[... | the_stack_v2_python_sparse | 0108_convert_sorted_array_binary_search_tree/python_source.py | arthurdysart/LeetCode | train | 0 |
e3a2d212506b59b37efd258df0b7355e43697319 | [
"_query_builder = Configuration.get_base_uri()\n_query_builder += '/information/businessregistry'\n_query_url = APIHelper.clean_url(_query_builder)\n_headers = {'accept': 'application/json'}\n_request = self.http_client.get(_query_url, headers=_headers)\nOAuth2.apply(_request)\n_context = self.execute_request(_requ... | <|body_start_0|>
_query_builder = Configuration.get_base_uri()
_query_builder += '/information/businessregistry'
_query_url = APIHelper.clean_url(_query_builder)
_headers = {'accept': 'application/json'}
_request = self.http_client.get(_query_url, headers=_headers)
OAuth2... | A Controller to access Endpoints in the idfy_rest_client API. | BusinessRegistryController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BusinessRegistryController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def list_registration_authorities(self):
"""Does a GET request to /information/businessregistry. Retrieves a list of business registration authorities globally Returns: mixed: Response fro... | stack_v2_sparse_classes_36k_train_016146 | 3,352 | permissive | [
{
"docstring": "Does a GET request to /information/businessregistry. Retrieves a list of business registration authorities globally Returns: mixed: Response from the API. OK Raises: APIException: When an error occurs while fetching the data from the remote API. This exception includes the HTTP Response code, an... | 2 | stack_v2_sparse_classes_30k_train_021477 | Implement the Python class `BusinessRegistryController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def list_registration_authorities(self): Does a GET request to /information/businessregistry. Retrieves a list of business regis... | Implement the Python class `BusinessRegistryController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def list_registration_authorities(self): Does a GET request to /information/businessregistry. Retrieves a list of business regis... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class BusinessRegistryController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def list_registration_authorities(self):
"""Does a GET request to /information/businessregistry. Retrieves a list of business registration authorities globally Returns: mixed: Response fro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BusinessRegistryController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def list_registration_authorities(self):
"""Does a GET request to /information/businessregistry. Retrieves a list of business registration authorities globally Returns: mixed: Response from the API. OK... | the_stack_v2_python_sparse | idfy_rest_client/controllers/business_registry_controller.py | dealflowteam/Idfy | train | 0 |
ff8c898672da529c3c6791353f891404bc48dcfc | [
"if span_context.trace_id is None or span_context.span_id is None:\n log.debug('tried to inject invalid context %r', span_context)\n return\nif PROPAGATION_STYLE_DATADOG in config._propagation_style_inject:\n _DatadogMultiHeader._inject(span_context, headers)\nif PROPAGATION_STYLE_B3 in config._propagation... | <|body_start_0|>
if span_context.trace_id is None or span_context.span_id is None:
log.debug('tried to inject invalid context %r', span_context)
return
if PROPAGATION_STYLE_DATADOG in config._propagation_style_inject:
_DatadogMultiHeader._inject(span_context, headers)... | A HTTP Propagator using HTTP headers as carrier. | HTTPPropagator | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTTPPropagator:
"""A HTTP Propagator using HTTP headers as carrier."""
def inject(span_context, headers):
"""Inject Context attributes that have to be propagated as HTTP headers. Here is an example using `requests`:: import requests from ddtrace.propagation.http import HTTPPropagator... | stack_v2_sparse_classes_36k_train_016147 | 35,485 | permissive | [
{
"docstring": "Inject Context attributes that have to be propagated as HTTP headers. Here is an example using `requests`:: import requests from ddtrace.propagation.http import HTTPPropagator def parent_call(): with tracer.trace('parent_span') as span: headers = {} HTTPPropagator.inject(span.context, headers) u... | 2 | null | Implement the Python class `HTTPPropagator` described below.
Class description:
A HTTP Propagator using HTTP headers as carrier.
Method signatures and docstrings:
- def inject(span_context, headers): Inject Context attributes that have to be propagated as HTTP headers. Here is an example using `requests`:: import req... | Implement the Python class `HTTPPropagator` described below.
Class description:
A HTTP Propagator using HTTP headers as carrier.
Method signatures and docstrings:
- def inject(span_context, headers): Inject Context attributes that have to be propagated as HTTP headers. Here is an example using `requests`:: import req... | 1e3bd6d4edef5cda5a0831a6a7ec8e4046659d17 | <|skeleton|>
class HTTPPropagator:
"""A HTTP Propagator using HTTP headers as carrier."""
def inject(span_context, headers):
"""Inject Context attributes that have to be propagated as HTTP headers. Here is an example using `requests`:: import requests from ddtrace.propagation.http import HTTPPropagator... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HTTPPropagator:
"""A HTTP Propagator using HTTP headers as carrier."""
def inject(span_context, headers):
"""Inject Context attributes that have to be propagated as HTTP headers. Here is an example using `requests`:: import requests from ddtrace.propagation.http import HTTPPropagator def parent_c... | the_stack_v2_python_sparse | ddtrace/propagation/http.py | DataDog/dd-trace-py | train | 461 |
1abe9da6a20bb1086c0837faf9fd4e7af63f03e8 | [
"self._payment_dates = payment_dates\nself._payment_steps = payment_steps\nself._maturity = payment_dates[len(payment_dates) - 1]\nself._steps = payment_steps[len(payment_steps) - 1]\nself._bond_tree = {}",
"if not hw_tree._is_built:\n hw_tree.hw_prob()\n hw_tree.calibrate()",
"self.build_hw_tree(hw_tree)... | <|body_start_0|>
self._payment_dates = payment_dates
self._payment_steps = payment_steps
self._maturity = payment_dates[len(payment_dates) - 1]
self._steps = payment_steps[len(payment_steps) - 1]
self._bond_tree = {}
<|end_body_0|>
<|body_start_1|>
if not hw_tree._is_bui... | Representation of a Zero Coupon Bond | ZCBond | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZCBond:
"""Representation of a Zero Coupon Bond"""
def __init__(self, payment_dates, payment_steps):
"""Initialize a Zero Coupon Bond object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment dates payment_steps : array_like of shape (1, ) with inte... | stack_v2_sparse_classes_36k_train_016148 | 6,090 | no_license | [
{
"docstring": "Initialize a Zero Coupon Bond object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment dates payment_steps : array_like of shape (1, ) with integer payment steps that corresponds to the tree coupon_rates : scalar or array_like of shape (1, ) with the coupon ra... | 3 | stack_v2_sparse_classes_30k_train_013762 | Implement the Python class `ZCBond` described below.
Class description:
Representation of a Zero Coupon Bond
Method signatures and docstrings:
- def __init__(self, payment_dates, payment_steps): Initialize a Zero Coupon Bond object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment ... | Implement the Python class `ZCBond` described below.
Class description:
Representation of a Zero Coupon Bond
Method signatures and docstrings:
- def __init__(self, payment_dates, payment_steps): Initialize a Zero Coupon Bond object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment ... | 9f710a8de56fb9b4456c6f98be91f4b22ef5ede5 | <|skeleton|>
class ZCBond:
"""Representation of a Zero Coupon Bond"""
def __init__(self, payment_dates, payment_steps):
"""Initialize a Zero Coupon Bond object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment dates payment_steps : array_like of shape (1, ) with inte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZCBond:
"""Representation of a Zero Coupon Bond"""
def __init__(self, payment_dates, payment_steps):
"""Initialize a Zero Coupon Bond object Parameters ---------- payment_dates : array_like of shape (1, ) with datetime payment dates payment_steps : array_like of shape (1, ) with integer payment s... | the_stack_v2_python_sparse | Hull-White Model/simple_bond.py | jesusmramirez/Term-Structure-Models | train | 1 |
282d3c3437b5daec2537fc9abdff3643fbebbf7f | [
"request_command = self.parser_invoker.get_maintenance_date_time_command_bytes(self.sequence_id, self.product_id)\nresponse_command_content = self.connectObj.send_receive_command(request_command)\nreturn response_command_content",
"request_command = self.parser_invoker.get_maintenance_period_command_bytes(self.se... | <|body_start_0|>
request_command = self.parser_invoker.get_maintenance_date_time_command_bytes(self.sequence_id, self.product_id)
response_command_content = self.connectObj.send_receive_command(request_command)
return response_command_content
<|end_body_0|>
<|body_start_1|>
request_comm... | This class is used to define all related methods with device report. | DeviceReport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceReport:
"""This class is used to define all related methods with device report."""
def get_maintenance_date_time(self):
"""This method is used to get maintenance date time. :return: date time"""
<|body_0|>
def get_maintenance_period(self):
"""This method is... | stack_v2_sparse_classes_36k_train_016149 | 2,642 | permissive | [
{
"docstring": "This method is used to get maintenance date time. :return: date time",
"name": "get_maintenance_date_time",
"signature": "def get_maintenance_date_time(self)"
},
{
"docstring": "This method is used to get maintenance period. :return: maintenance period(unit:month)",
"name": "... | 5 | stack_v2_sparse_classes_30k_train_000280 | Implement the Python class `DeviceReport` described below.
Class description:
This class is used to define all related methods with device report.
Method signatures and docstrings:
- def get_maintenance_date_time(self): This method is used to get maintenance date time. :return: date time
- def get_maintenance_period(... | Implement the Python class `DeviceReport` described below.
Class description:
This class is used to define all related methods with device report.
Method signatures and docstrings:
- def get_maintenance_date_time(self): This method is used to get maintenance date time. :return: date time
- def get_maintenance_period(... | c2a4884a36f4c6c6552fa942143ae5d21c120b41 | <|skeleton|>
class DeviceReport:
"""This class is used to define all related methods with device report."""
def get_maintenance_date_time(self):
"""This method is used to get maintenance date time. :return: date time"""
<|body_0|>
def get_maintenance_period(self):
"""This method is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeviceReport:
"""This class is used to define all related methods with device report."""
def get_maintenance_date_time(self):
"""This method is used to get maintenance date time. :return: date time"""
request_command = self.parser_invoker.get_maintenance_date_time_command_bytes(self.seque... | the_stack_v2_python_sparse | Keywords/MenuSettings/device_report.py | cassie01/PumpLibrary | train | 0 |
498d53a6768480a7186f5d0917fadda2b020d05d | [
"if as_datetime and 'detect_types' not in kwargs:\n kwargs['detect_types'] = sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES\nsuper(ConnectionsTable, self).__init__(database, **kwargs)\nself.execute(f'CREATE TABLE IF NOT EXISTS {self.NAME} (pid INTEGER PRIMARY KEY AUTOINCREMENT, datetime DATETIME NOT NULL, ip_a... | <|body_start_0|>
if as_datetime and 'detect_types' not in kwargs:
kwargs['detect_types'] = sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES
super(ConnectionsTable, self).__init__(database, **kwargs)
self.execute(f'CREATE TABLE IF NOT EXISTS {self.NAME} (pid INTEGER PRIMARY KEY AUTOIN... | ConnectionsTable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectionsTable:
def __init__(self, *, database=None, as_datetime=False, **kwargs):
"""The database table for devices that have connected to the Network :class:`~msl.network.manager.Manager`. Parameters ---------- database : :class:`str`, optional The path to the database file, or ``':m... | stack_v2_sparse_classes_36k_train_016150 | 20,753 | permissive | [
{
"docstring": "The database table for devices that have connected to the Network :class:`~msl.network.manager.Manager`. Parameters ---------- database : :class:`str`, optional The path to the database file, or ``':memory:'`` to open a connection to a database that resides in RAM instead of on disk. If :data:`N... | 3 | stack_v2_sparse_classes_30k_train_002110 | Implement the Python class `ConnectionsTable` described below.
Class description:
Implement the ConnectionsTable class.
Method signatures and docstrings:
- def __init__(self, *, database=None, as_datetime=False, **kwargs): The database table for devices that have connected to the Network :class:`~msl.network.manager.... | Implement the Python class `ConnectionsTable` described below.
Class description:
Implement the ConnectionsTable class.
Method signatures and docstrings:
- def __init__(self, *, database=None, as_datetime=False, **kwargs): The database table for devices that have connected to the Network :class:`~msl.network.manager.... | 700f003b2f27cada274ec8bfaccaf1bfa6acb0f0 | <|skeleton|>
class ConnectionsTable:
def __init__(self, *, database=None, as_datetime=False, **kwargs):
"""The database table for devices that have connected to the Network :class:`~msl.network.manager.Manager`. Parameters ---------- database : :class:`str`, optional The path to the database file, or ``':m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConnectionsTable:
def __init__(self, *, database=None, as_datetime=False, **kwargs):
"""The database table for devices that have connected to the Network :class:`~msl.network.manager.Manager`. Parameters ---------- database : :class:`str`, optional The path to the database file, or ``':memory:'`` to o... | the_stack_v2_python_sparse | msl/network/database.py | MSLNZ/msl-network | train | 0 | |
10b976bbbe35096eb28886df89f563697ed23780 | [
"cls.testDir = os.path.join(originalPath, 'rmg', 'test_data', 'restartTest')\ncls.outputDir = os.path.join(cls.testDir, 'output_no_filters')\ncls.databaseDirectory = settings['database.directory']\nos.mkdir(cls.outputDir)\ninitialize_log(logging.INFO, os.path.join(cls.outputDir, 'RMG.log'))\ncls.rmg = RMG(input_fil... | <|body_start_0|>
cls.testDir = os.path.join(originalPath, 'rmg', 'test_data', 'restartTest')
cls.outputDir = os.path.join(cls.testDir, 'output_no_filters')
cls.databaseDirectory = settings['database.directory']
os.mkdir(cls.outputDir)
initialize_log(logging.INFO, os.path.join(cls... | TestRestartNoFilters | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRestartNoFilters:
def setUpClass(cls):
"""A function that is run ONCE before all unit tests in this class."""
<|body_0|>
def test_restart_no_filters(self):
"""Test that the RMG restart job with no filters included completed without problems"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_016151 | 15,751 | permissive | [
{
"docstring": "A function that is run ONCE before all unit tests in this class.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Test that the RMG restart job with no filters included completed without problems",
"name": "test_restart_no_filters",
"signature... | 3 | null | Implement the Python class `TestRestartNoFilters` described below.
Class description:
Implement the TestRestartNoFilters class.
Method signatures and docstrings:
- def setUpClass(cls): A function that is run ONCE before all unit tests in this class.
- def test_restart_no_filters(self): Test that the RMG restart job w... | Implement the Python class `TestRestartNoFilters` described below.
Class description:
Implement the TestRestartNoFilters class.
Method signatures and docstrings:
- def setUpClass(cls): A function that is run ONCE before all unit tests in this class.
- def test_restart_no_filters(self): Test that the RMG restart job w... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TestRestartNoFilters:
def setUpClass(cls):
"""A function that is run ONCE before all unit tests in this class."""
<|body_0|>
def test_restart_no_filters(self):
"""Test that the RMG restart job with no filters included completed without problems"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestRestartNoFilters:
def setUpClass(cls):
"""A function that is run ONCE before all unit tests in this class."""
cls.testDir = os.path.join(originalPath, 'rmg', 'test_data', 'restartTest')
cls.outputDir = os.path.join(cls.testDir, 'output_no_filters')
cls.databaseDirectory = s... | the_stack_v2_python_sparse | rmgpy/rmg/mainTest.py | CanePan-cc/CanePanWorkshop | train | 2 | |
3255ee09722cf2e7a86a2b6b0373e85e4e4dc7da | [
"super(StatusBarWidget, self).__init__(parent)\nself.value = None\nself._icon = icon\nself._pixmap = icon.pixmap(QSize(16, 16)) if icon is not None else None\nself.label_icon = QLabel() if icon is not None else None\nself.label_value = QLabel()\nif icon is not None:\n self.label_icon.setPixmap(self._pixmap)\nsel... | <|body_start_0|>
super(StatusBarWidget, self).__init__(parent)
self.value = None
self._icon = icon
self._pixmap = icon.pixmap(QSize(16, 16)) if icon is not None else None
self.label_icon = QLabel() if icon is not None else None
self.label_value = QLabel()
if icon ... | Status bar widget base. | StatusBarWidget | [
"LGPL-3.0-only",
"LGPL-2.1-only",
"Python-2.0",
"LGPL-2.1-or-later",
"LGPL-2.0-or-later",
"CC-BY-2.5",
"OFL-1.1",
"LGPL-3.0-or-later",
"GPL-1.0-or-later",
"GPL-2.0-only",
"Apache-2.0",
"CC-BY-3.0",
"MIT",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatusBarWidget:
"""Status bar widget base."""
def __init__(self, parent, statusbar, icon=None):
"""Status bar widget base."""
<|body_0|>
def set_value(self, value):
"""Set formatted text value."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
su... | stack_v2_sparse_classes_36k_train_016152 | 5,934 | permissive | [
{
"docstring": "Status bar widget base.",
"name": "__init__",
"signature": "def __init__(self, parent, statusbar, icon=None)"
},
{
"docstring": "Set formatted text value.",
"name": "set_value",
"signature": "def set_value(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021257 | Implement the Python class `StatusBarWidget` described below.
Class description:
Status bar widget base.
Method signatures and docstrings:
- def __init__(self, parent, statusbar, icon=None): Status bar widget base.
- def set_value(self, value): Set formatted text value. | Implement the Python class `StatusBarWidget` described below.
Class description:
Status bar widget base.
Method signatures and docstrings:
- def __init__(self, parent, statusbar, icon=None): Status bar widget base.
- def set_value(self, value): Set formatted text value.
<|skeleton|>
class StatusBarWidget:
"""Sta... | be98b086f95968fccc4e8dbe3f1140154c94a412 | <|skeleton|>
class StatusBarWidget:
"""Status bar widget base."""
def __init__(self, parent, statusbar, icon=None):
"""Status bar widget base."""
<|body_0|>
def set_value(self, value):
"""Set formatted text value."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatusBarWidget:
"""Status bar widget base."""
def __init__(self, parent, statusbar, icon=None):
"""Status bar widget base."""
super(StatusBarWidget, self).__init__(parent)
self.value = None
self._icon = icon
self._pixmap = icon.pixmap(QSize(16, 16)) if icon is not... | the_stack_v2_python_sparse | spyder/widgets/status.py | zrlzwd/spyder | train | 2 |
9f5482183e5d970ff3668db236e709f569ed2f91 | [
"cloned_head = Node(head.val)\nclone_iterator = new_head\noriginal_iterator = head\nwhile original_iterator.next:\n clone_iterator.next = Node(original_iterator.next.val)\n clone_iterator = clone_iterator.next\n original_iterator = original_iterator.next\nnew_head = cloned_head\nold_head = head\nwhile new_... | <|body_start_0|>
cloned_head = Node(head.val)
clone_iterator = new_head
original_iterator = head
while original_iterator.next:
clone_iterator.next = Node(original_iterator.next.val)
clone_iterator = clone_iterator.next
original_iterator = original_iter... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def copyRandomList(self, head):
""":type head: Node :rtype: Node"""
<|body_0|>
def copy_random_list(self, head):
"""Deep copies the linked list"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cloned_head = Node(head.val)
clone_iter... | stack_v2_sparse_classes_36k_train_016153 | 3,684 | permissive | [
{
"docstring": ":type head: Node :rtype: Node",
"name": "copyRandomList",
"signature": "def copyRandomList(self, head)"
},
{
"docstring": "Deep copies the linked list",
"name": "copy_random_list",
"signature": "def copy_random_list(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def copyRandomList(self, head): :type head: Node :rtype: Node
- def copy_random_list(self, head): Deep copies the linked list | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def copyRandomList(self, head): :type head: Node :rtype: Node
- def copy_random_list(self, head): Deep copies the linked list
<|skeleton|>
class Solution:
def copyRandomLis... | 547c200b627c774535bc22880b16d5390183aeba | <|skeleton|>
class Solution:
def copyRandomList(self, head):
""":type head: Node :rtype: Node"""
<|body_0|>
def copy_random_list(self, head):
"""Deep copies the linked list"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def copyRandomList(self, head):
""":type head: Node :rtype: Node"""
cloned_head = Node(head.val)
clone_iterator = new_head
original_iterator = head
while original_iterator.next:
clone_iterator.next = Node(original_iterator.next.val)
clo... | the_stack_v2_python_sparse | medium/138_copy_list_with_random_pointer.py | Sukhrobjon/leetcode | train | 0 | |
6cdde7771e6511bf5fd38c2372b662742ac627d0 | [
"from app import send_email\nmail = send_email()\nsender = Config()\nsubject = 'Registration'\nmsg = Message(subject, sender=sender.SENDER, recipients=[email])\nmsg.body = 'You have registred with sendit courier services' + '\\n\\n\\n\\nKind Regards,\\nSendIT Courier Services'\nmail.send(msg)",
"from app import s... | <|body_start_0|>
from app import send_email
mail = send_email()
sender = Config()
subject = 'Registration'
msg = Message(subject, sender=sender.SENDER, recipients=[email])
msg.body = 'You have registred with sendit courier services' + '\n\n\n\nKind Regards,\nSendIT Courie... | Class to handle app emails | Emails | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Emails:
"""Class to handle app emails"""
def user_registration(self, email):
"""Method to return email after successiful registration"""
<|body_0|>
def change_status(self, email, order, user_by_id):
"""Method to return email after successiful change of parcel ord... | stack_v2_sparse_classes_36k_train_016154 | 2,257 | no_license | [
{
"docstring": "Method to return email after successiful registration",
"name": "user_registration",
"signature": "def user_registration(self, email)"
},
{
"docstring": "Method to return email after successiful change of parcel order status",
"name": "change_status",
"signature": "def ch... | 4 | stack_v2_sparse_classes_30k_train_020348 | Implement the Python class `Emails` described below.
Class description:
Class to handle app emails
Method signatures and docstrings:
- def user_registration(self, email): Method to return email after successiful registration
- def change_status(self, email, order, user_by_id): Method to return email after successiful... | Implement the Python class `Emails` described below.
Class description:
Class to handle app emails
Method signatures and docstrings:
- def user_registration(self, email): Method to return email after successiful registration
- def change_status(self, email, order, user_by_id): Method to return email after successiful... | b6508fa6e296a4c9bd3d9c67be79a76ca942ac00 | <|skeleton|>
class Emails:
"""Class to handle app emails"""
def user_registration(self, email):
"""Method to return email after successiful registration"""
<|body_0|>
def change_status(self, email, order, user_by_id):
"""Method to return email after successiful change of parcel ord... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Emails:
"""Class to handle app emails"""
def user_registration(self, email):
"""Method to return email after successiful registration"""
from app import send_email
mail = send_email()
sender = Config()
subject = 'Registration'
msg = Message(subject, sender=... | the_stack_v2_python_sparse | app/api/v2/views/email.py | RachelleMaina/SendIT-API | train | 0 |
a053dfd9b79ea130d44a86de2ce4cd30f8c7eb31 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn PrinterDefaults()",
"from .print_color_mode import PrintColorMode\nfrom .print_duplex_mode import PrintDuplexMode\nfrom .print_finishing import PrintFinishing\nfrom .print_multipage_layout import PrintMultipageLayout\nfrom .print_orien... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return PrinterDefaults()
<|end_body_0|>
<|body_start_1|>
from .print_color_mode import PrintColorMode
from .print_duplex_mode import PrintDuplexMode
from .print_finishing import PrintFi... | PrinterDefaults | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrinterDefaults:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterDefaults:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_36k_train_016155 | 8,504 | 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: PrinterDefaults",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | null | Implement the Python class `PrinterDefaults` described below.
Class description:
Implement the PrinterDefaults class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterDefaults: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `PrinterDefaults` described below.
Class description:
Implement the PrinterDefaults class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterDefaults: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class PrinterDefaults:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterDefaults:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrinterDefaults:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterDefaults:
"""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: PrinterD... | the_stack_v2_python_sparse | msgraph/generated/models/printer_defaults.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b70bf32f0bd39773c1acafbd78de998ece30f31f | [
"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. | PointWiseFeedForward | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointWiseFeedForward:
"""PointWise forward Module."""
def __init__(self, hidden_units, dropout_rate):
"""Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate."""
<|body_0|>
def forward(self, inputs):
"""Forwa... | stack_v2_sparse_classes_36k_train_016156 | 9,120 | 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 functioin. Args: inputs ([type]): [description] Returns: [ty... | 2 | null | Implement the Python class `PointWiseFeedForward` described below.
Class description:
PointWise forward Module.
Method signatures and docstrings:
- def __init__(self, hidden_units, dropout_rate): Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate.
- def forward... | Implement the Python class `PointWiseFeedForward` described below.
Class description:
PointWise forward Module.
Method signatures and docstrings:
- def __init__(self, hidden_units, dropout_rate): Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate.
- def forward... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class PointWiseFeedForward:
"""PointWise forward Module."""
def __init__(self, hidden_units, dropout_rate):
"""Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate."""
<|body_0|>
def forward(self, inputs):
"""Forwa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PointWiseFeedForward:
"""PointWise forward Module."""
def __init__(self, hidden_units, dropout_rate):
"""Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate."""
super(PointWiseFeedForward, self).__init__()
self.conv1 = torch.... | the_stack_v2_python_sparse | beta_rec/models/sasrec.py | beta-team/beta-recsys | train | 156 |
280c03b2e401efc21f6cbdeba9f4afbd65484a80 | [
"result = []\nqueue = deque([root])\n\ndef helper(q, arr):\n if len(q) <= 0:\n return\n node = q.popleft()\n if node is None:\n arr.append(None)\n else:\n arr.append(node.val)\n q.append(node.left)\n q.append(node.right)\n helper(q, arr)\nhelper(queue, result)\nif l... | <|body_start_0|>
result = []
queue = deque([root])
def helper(q, arr):
if len(q) <= 0:
return
node = q.popleft()
if node is None:
arr.append(None)
else:
arr.append(node.val)
q.append(... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_016157 | 2,228 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | a0ab59ba0a1a11a06b7086aa8f791293ec9c7139 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
result = []
queue = deque([root])
def helper(q, arr):
if len(q) <= 0:
return
node = q.popleft()
if node is None:
... | the_stack_v2_python_sparse | leetCodePython2020/297.serialize-and-deserialize-binary-tree.py | HOZH/leetCode | train | 2 | |
c841186b2cdaefe63ba121340e77da1308c1308b | [
"SHA1_RE = re.compile('^[a-f0-9]{40}$')\ninstance = None\nif SHA1_RE.search(activation_key):\n try:\n instance = self.get(refuser=user, activation_key=activation_key)\n except (self.model.DoesNotExist, TypeError):\n return None\n return instance\nelse:\n return None",
"SHA1_RE = re.compi... | <|body_start_0|>
SHA1_RE = re.compile('^[a-f0-9]{40}$')
instance = None
if SHA1_RE.search(activation_key):
try:
instance = self.get(refuser=user, activation_key=activation_key)
except (self.model.DoesNotExist, TypeError):
return None
... | Access to ChangeEmail in a safe manner | ChangeEmailManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeEmailManager:
"""Access to ChangeEmail in a safe manner"""
def get_instance(self, user, activation_key):
"""Get the given instance (should be unique under activation_key). The user lookup is excessive but provided to avoid errors in use @return is either None or a valid instanc... | stack_v2_sparse_classes_36k_train_016158 | 5,619 | no_license | [
{
"docstring": "Get the given instance (should be unique under activation_key). The user lookup is excessive but provided to avoid errors in use @return is either None or a valid instance.",
"name": "get_instance",
"signature": "def get_instance(self, user, activation_key)"
},
{
"docstring": "Ge... | 2 | stack_v2_sparse_classes_30k_train_010894 | Implement the Python class `ChangeEmailManager` described below.
Class description:
Access to ChangeEmail in a safe manner
Method signatures and docstrings:
- def get_instance(self, user, activation_key): Get the given instance (should be unique under activation_key). The user lookup is excessive but provided to avoi... | Implement the Python class `ChangeEmailManager` described below.
Class description:
Access to ChangeEmail in a safe manner
Method signatures and docstrings:
- def get_instance(self, user, activation_key): Get the given instance (should be unique under activation_key). The user lookup is excessive but provided to avoi... | f2415fd82551ddaacba42eac9e2f2a1a3bc6fb88 | <|skeleton|>
class ChangeEmailManager:
"""Access to ChangeEmail in a safe manner"""
def get_instance(self, user, activation_key):
"""Get the given instance (should be unique under activation_key). The user lookup is excessive but provided to avoid errors in use @return is either None or a valid instanc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChangeEmailManager:
"""Access to ChangeEmail in a safe manner"""
def get_instance(self, user, activation_key):
"""Get the given instance (should be unique under activation_key). The user lookup is excessive but provided to avoid errors in use @return is either None or a valid instance."""
... | the_stack_v2_python_sparse | wsgi/openshift/changeemail/models.py | idi-konkurranser/IDIOpen | train | 0 |
b19f22e532f77f77ab5cf5d38a4012e3cc854230 | [
"pos, angle = controller.odometry(10, 10, Vector2(0, 0), 0)\nassert pos == Vector2(0, 0)\nassert angle == 0",
"pos, angle = controller.odometry(20, 20, Vector2(0, 0), 0)\nassert pos == Vector2(2 * math.pi * WHEEL_RADIUS * 10 / TICK_PER_REVOLUTION, 0)\nassert angle == 0\npos, angle = controller.odometry(10, 10, Ve... | <|body_start_0|>
pos, angle = controller.odometry(10, 10, Vector2(0, 0), 0)
assert pos == Vector2(0, 0)
assert angle == 0
<|end_body_0|>
<|body_start_1|>
pos, angle = controller.odometry(20, 20, Vector2(0, 0), 0)
assert pos == Vector2(2 * math.pi * WHEEL_RADIUS * 10 / TICK_PER_R... | Test the odometry function. | TestOdometry | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestOdometry:
"""Test the odometry function."""
def test_did_not_move(controller):
"""Robot did not move."""
<|body_0|>
def test_move_straight(controller):
"""Robot moved in a straight line."""
<|body_1|>
def test_rotate_without_moving(controller):
... | stack_v2_sparse_classes_36k_train_016159 | 3,622 | permissive | [
{
"docstring": "Robot did not move.",
"name": "test_did_not_move",
"signature": "def test_did_not_move(controller)"
},
{
"docstring": "Robot moved in a straight line.",
"name": "test_move_straight",
"signature": "def test_move_straight(controller)"
},
{
"docstring": "Robot rotate... | 5 | stack_v2_sparse_classes_30k_train_009444 | Implement the Python class `TestOdometry` described below.
Class description:
Test the odometry function.
Method signatures and docstrings:
- def test_did_not_move(controller): Robot did not move.
- def test_move_straight(controller): Robot moved in a straight line.
- def test_rotate_without_moving(controller): Robot... | Implement the Python class `TestOdometry` described below.
Class description:
Test the odometry function.
Method signatures and docstrings:
- def test_did_not_move(controller): Robot did not move.
- def test_move_straight(controller): Robot moved in a straight line.
- def test_rotate_without_moving(controller): Robot... | b55d1ce6143ee7ef248fa7a9d6675c693b727d91 | <|skeleton|>
class TestOdometry:
"""Test the odometry function."""
def test_did_not_move(controller):
"""Robot did not move."""
<|body_0|>
def test_move_straight(controller):
"""Robot moved in a straight line."""
<|body_1|>
def test_rotate_without_moving(controller):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestOdometry:
"""Test the odometry function."""
def test_did_not_move(controller):
"""Robot did not move."""
pos, angle = controller.odometry(10, 10, Vector2(0, 0), 0)
assert pos == Vector2(0, 0)
assert angle == 0
def test_move_straight(controller):
"""Robot m... | the_stack_v2_python_sparse | highlevel/robot/controller/motion/odometry_test.py | outech-robotic/hl-flowing-clean-arch | train | 2 |
e90faba1719dc1d56f83bb6a9c9764298a6b8067 | [
"ObjectManager.__init__(self)\nself.getters.update({'description': 'get_general', 'name': 'get_general', 'post': 'get_foreign_key'})\nself.setters.update({'description': 'set_general', 'name': 'set_general', 'post': 'set_foreign_key'})\nself.my_django_model = facade.models.ForumPostAttachment\nself.setter = facade.... | <|body_start_0|>
ObjectManager.__init__(self)
self.getters.update({'description': 'get_general', 'name': 'get_general', 'post': 'get_foreign_key'})
self.setters.update({'description': 'set_general', 'name': 'set_general', 'post': 'set_foreign_key'})
self.my_django_model = facade.models.F... | Manage Attachments in the Power Reg Forum system | ForumPostAttachmentManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForumPostAttachmentManager:
"""Manage Attachments in the Power Reg Forum system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name, post, optional_attributes=None):
"""Create a new Attachment @param name name of the Attachment @... | stack_v2_sparse_classes_36k_train_016160 | 1,653 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new Attachment @param name name of the Attachment @type name string @param post post FK @type post int @return a reference to the newly created Attachment",
"name": "create",
"... | 2 | null | Implement the Python class `ForumPostAttachmentManager` described below.
Class description:
Manage Attachments in the Power Reg Forum system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name, post, optional_attributes=None): Create a new Attachment @param name nam... | Implement the Python class `ForumPostAttachmentManager` described below.
Class description:
Manage Attachments in the Power Reg Forum system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name, post, optional_attributes=None): Create a new Attachment @param name nam... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class ForumPostAttachmentManager:
"""Manage Attachments in the Power Reg Forum system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name, post, optional_attributes=None):
"""Create a new Attachment @param name name of the Attachment @... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ForumPostAttachmentManager:
"""Manage Attachments in the Power Reg Forum system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.getters.update({'description': 'get_general', 'name': 'get_general', 'post': 'get_foreign_key'})
self.setters.update({... | the_stack_v2_python_sparse | forum/managers/post_attachment.py | ninemoreminutes/openassign-server | train | 0 |
14b728c4baa159b55147938f59723fa64fa3e63a | [
"keys = [' ' + key + '=', ' ' + key + ' ', ' ' + key + '\\n']\nret = []\nfor k in keys:\n pos = str_content.rfind(k)\n if pos != -1:\n pos += 1\n ret.append(pos)\nreturn max(ret)",
"with open('/proc/cmdline', 'r') as file:\n active_cmd = file.read()\nkeypos = Utils.get_keypos(active_cmd, key)\n... | <|body_start_0|>
keys = [' ' + key + '=', ' ' + key + ' ', ' ' + key + '\n']
ret = []
for k in keys:
pos = str_content.rfind(k)
if pos != -1:
pos += 1
ret.append(pos)
return max(ret)
<|end_body_0|>
<|body_start_1|>
with open('/... | Utils class | Utils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Utils:
"""Utils class"""
def get_keypos(str_content, key):
"""get key position"""
<|body_0|>
def get_value(key):
"""get value according to key"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
keys = [' ' + key + '=', ' ' + key + ' ', ' ' + key + ... | stack_v2_sparse_classes_36k_train_016161 | 1,408 | no_license | [
{
"docstring": "get key position",
"name": "get_keypos",
"signature": "def get_keypos(str_content, key)"
},
{
"docstring": "get value according to key",
"name": "get_value",
"signature": "def get_value(key)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014087 | Implement the Python class `Utils` described below.
Class description:
Utils class
Method signatures and docstrings:
- def get_keypos(str_content, key): get key position
- def get_value(key): get value according to key | Implement the Python class `Utils` described below.
Class description:
Utils class
Method signatures and docstrings:
- def get_keypos(str_content, key): get key position
- def get_value(key): get value according to key
<|skeleton|>
class Utils:
"""Utils class"""
def get_keypos(str_content, key):
"""... | e4f257d00305849b9a52a033651da09412436785 | <|skeleton|>
class Utils:
"""Utils class"""
def get_keypos(str_content, key):
"""get key position"""
<|body_0|>
def get_value(key):
"""get value according to key"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Utils:
"""Utils class"""
def get_keypos(str_content, key):
"""get key position"""
keys = [' ' + key + '=', ' ' + key + ' ', ' ' + key + '\n']
ret = []
for k in keys:
pos = str_content.rfind(k)
if pos != -1:
pos += 1
ret.a... | the_stack_v2_python_sparse | analysis/plugin/configurator/bootloader/bootutils.py | hanxinke/A-Tune | train | 0 |
89dcbe0a1e14c94a93fab6bb500551d70b2fabfe | [
"if self.user:\n self.render('add_blog.html', user=self.user)\nelse:\n cookie_error = 'Your session has expired please login again to continue!'\n self.render('login.html', error=cookie_error)",
"title = self.request.get('title')\ncontent = self.request.get('content')\nif self.user:\n if title and con... | <|body_start_0|>
if self.user:
self.render('add_blog.html', user=self.user)
else:
cookie_error = 'Your session has expired please login again to continue!'
self.render('login.html', error=cookie_error)
<|end_body_0|>
<|body_start_1|>
title = self.request.get(... | To create a new blog post | AddBlog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddBlog:
"""To create a new blog post"""
def get(self):
"""Renders the form for adding post"""
<|body_0|>
def post(self):
"""To process ans store blog post information into database"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.user:
... | stack_v2_sparse_classes_36k_train_016162 | 4,859 | no_license | [
{
"docstring": "Renders the form for adding post",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "To process ans store blog post information into database",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005523 | Implement the Python class `AddBlog` described below.
Class description:
To create a new blog post
Method signatures and docstrings:
- def get(self): Renders the form for adding post
- def post(self): To process ans store blog post information into database | Implement the Python class `AddBlog` described below.
Class description:
To create a new blog post
Method signatures and docstrings:
- def get(self): Renders the form for adding post
- def post(self): To process ans store blog post information into database
<|skeleton|>
class AddBlog:
"""To create a new blog pos... | 74c6e821c2fdb4198de8be2e83c64164e23f9992 | <|skeleton|>
class AddBlog:
"""To create a new blog post"""
def get(self):
"""Renders the form for adding post"""
<|body_0|>
def post(self):
"""To process ans store blog post information into database"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddBlog:
"""To create a new blog post"""
def get(self):
"""Renders the form for adding post"""
if self.user:
self.render('add_blog.html', user=self.user)
else:
cookie_error = 'Your session has expired please login again to continue!'
self.render... | the_stack_v2_python_sparse | Multi User Blog/Multi User Blog/handlers/blog.py | mascot6699/udacity-full-stack | train | 8 |
62698644a9c83f32aa05e8b3c146af2b974449cb | [
"v_axis_item = Render2DNeuronIdentityLinesMixin._setup_custom_neuron_ticks(plot_widget, n_cells)\nv_axis_item = Render2DNeuronIdentityLinesMixin._add_lines(plot_widget)\nreturn v_axis_item",
"neuron_id_ticks = [[(float(i), '') for i in np.arange(n_cells + 1)]]\nv_axis_item = plot_widget.axes['left']['item']\nv_ax... | <|body_start_0|>
v_axis_item = Render2DNeuronIdentityLinesMixin._setup_custom_neuron_ticks(plot_widget, n_cells)
v_axis_item = Render2DNeuronIdentityLinesMixin._add_lines(plot_widget)
return v_axis_item
<|end_body_0|>
<|body_start_1|>
neuron_id_ticks = [[(float(i), '') for i in np.arang... | renders the horizontal lines separating the neurons on the 2D raster plots Review 2022-08-30 - Confirmed working as implemented! (Actually, the correct spacing/grid layout of the lines wasn't validated and doesn't look perfect, but the whole thing works. TODO: This is not really a mixin, need to figure out how I want t... | Render2DNeuronIdentityLinesMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Render2DNeuronIdentityLinesMixin:
"""renders the horizontal lines separating the neurons on the 2D raster plots Review 2022-08-30 - Confirmed working as implemented! (Actually, the correct spacing/grid layout of the lines wasn't validated and doesn't look perfect, but the whole thing works. TODO:... | stack_v2_sparse_classes_36k_train_016163 | 3,487 | permissive | [
{
"docstring": "Completely sets up the custom 2D neuron identity axis vertical/y-axis) by adding one minor tick per neuron and displaying the horizontal grid.",
"name": "setup_custom_neuron_identity_axis",
"signature": "def setup_custom_neuron_identity_axis(plot_widget, n_cells)"
},
{
"docstring... | 3 | stack_v2_sparse_classes_30k_test_000910 | Implement the Python class `Render2DNeuronIdentityLinesMixin` described below.
Class description:
renders the horizontal lines separating the neurons on the 2D raster plots Review 2022-08-30 - Confirmed working as implemented! (Actually, the correct spacing/grid layout of the lines wasn't validated and doesn't look pe... | Implement the Python class `Render2DNeuronIdentityLinesMixin` described below.
Class description:
renders the horizontal lines separating the neurons on the 2D raster plots Review 2022-08-30 - Confirmed working as implemented! (Actually, the correct spacing/grid layout of the lines wasn't validated and doesn't look pe... | 212399d826284b394fce8894ff1a93133aef783f | <|skeleton|>
class Render2DNeuronIdentityLinesMixin:
"""renders the horizontal lines separating the neurons on the 2D raster plots Review 2022-08-30 - Confirmed working as implemented! (Actually, the correct spacing/grid layout of the lines wasn't validated and doesn't look perfect, but the whole thing works. TODO:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Render2DNeuronIdentityLinesMixin:
"""renders the horizontal lines separating the neurons on the 2D raster plots Review 2022-08-30 - Confirmed working as implemented! (Actually, the correct spacing/grid layout of the lines wasn't validated and doesn't look perfect, but the whole thing works. TODO: This is not ... | the_stack_v2_python_sparse | src/pyphoplacecellanalysis/GUI/PyQtPlot/Widgets/Mixins/Render2DNeuronIdentityLinesMixin.py | CommanderPho/pyPhoPlaceCellAnalysis | train | 1 |
9be1e23c6c24af6fd14e2478b3c7cb9c6b07b552 | [
"self.max_depth = max_depth\nself.save_images = save_images\nself.clock = time.time()\nself.t_buffer = t_buffer\nself.output_dir = output_dir\nself.data_dir = path.join(self.output_dir, '{}'.format(time.strftime('%d_%b_%Y_%H:%M', time.localtime())))\nif self.save_images:\n ensureDir(self.data_dir)\npass\nnp.warn... | <|body_start_0|>
self.max_depth = max_depth
self.save_images = save_images
self.clock = time.time()
self.t_buffer = t_buffer
self.output_dir = output_dir
self.data_dir = path.join(self.output_dir, '{}'.format(time.strftime('%d_%b_%Y_%H:%M', time.localtime())))
if ... | Object to get data from R200 | Camera | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Camera:
"""Object to get data from R200"""
def __init__(self, max_depth=4.0, save_images=False, t_buffer=5, output_dir='./Trials/'):
"""Intitalizes Camera object"""
<|body_0|>
def connect(self):
"""Establishes connection to R200 camera"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_016164 | 6,258 | permissive | [
{
"docstring": "Intitalizes Camera object",
"name": "__init__",
"signature": "def __init__(self, max_depth=4.0, save_images=False, t_buffer=5, output_dir='./Trials/')"
},
{
"docstring": "Establishes connection to R200 camera",
"name": "connect",
"signature": "def connect(self)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_002303 | Implement the Python class `Camera` described below.
Class description:
Object to get data from R200
Method signatures and docstrings:
- def __init__(self, max_depth=4.0, save_images=False, t_buffer=5, output_dir='./Trials/'): Intitalizes Camera object
- def connect(self): Establishes connection to R200 camera
- def ... | Implement the Python class `Camera` described below.
Class description:
Object to get data from R200
Method signatures and docstrings:
- def __init__(self, max_depth=4.0, save_images=False, t_buffer=5, output_dir='./Trials/'): Intitalizes Camera object
- def connect(self): Establishes connection to R200 camera
- def ... | 08fe54fe37df89ffc7e6378125bb14ad5bead421 | <|skeleton|>
class Camera:
"""Object to get data from R200"""
def __init__(self, max_depth=4.0, save_images=False, t_buffer=5, output_dir='./Trials/'):
"""Intitalizes Camera object"""
<|body_0|>
def connect(self):
"""Establishes connection to R200 camera"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Camera:
"""Object to get data from R200"""
def __init__(self, max_depth=4.0, save_images=False, t_buffer=5, output_dir='./Trials/'):
"""Intitalizes Camera object"""
self.max_depth = max_depth
self.save_images = save_images
self.clock = time.time()
self.t_buffer = t... | the_stack_v2_python_sparse | Camera/camera.py | marioliu/AutonomousQuadblade | train | 0 |
5ebf4579df60cb28b252bdd239314a217f9477df | [
"self.locations_hltv_starting_ = config[sC.BUCKET_LOCATIONS][sC.HLTV_STARTING]\nself.score_starting_ = config[sC.BUCKET_LOCATIONS][sC.SCORE_STARTING]\nself.logs_starting_ = config[sC.BUCKET_LOCATIONS][sC.LOGS_STARTING]\nself.temp = config[sC.FOLDER_LOCATIONS][sC.TEMP_APP_ENGINE_FOLDER]\nself.results_ = config[sC.FO... | <|body_start_0|>
self.locations_hltv_starting_ = config[sC.BUCKET_LOCATIONS][sC.HLTV_STARTING]
self.score_starting_ = config[sC.BUCKET_LOCATIONS][sC.SCORE_STARTING]
self.logs_starting_ = config[sC.BUCKET_LOCATIONS][sC.LOGS_STARTING]
self.temp = config[sC.FOLDER_LOCATIONS][sC.TEMP_APP_ENG... | FTPHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FTPHelper:
def __init__(self, config):
"""Initialize the FTP Helper This Class contains FTP related Functions :param config: Config Object"""
<|body_0|>
def get_hltv_demos_from_ftp(self, date, server_id, folder):
"""Download Match HLTV demos from instance :param date... | stack_v2_sparse_classes_36k_train_016165 | 3,170 | no_license | [
{
"docstring": "Initialize the FTP Helper This Class contains FTP related Functions :param config: Config Object",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Download Match HLTV demos from instance :param date: date for which the demos will be downloaded :pa... | 3 | stack_v2_sparse_classes_30k_train_016499 | Implement the Python class `FTPHelper` described below.
Class description:
Implement the FTPHelper class.
Method signatures and docstrings:
- def __init__(self, config): Initialize the FTP Helper This Class contains FTP related Functions :param config: Config Object
- def get_hltv_demos_from_ftp(self, date, server_id... | Implement the Python class `FTPHelper` described below.
Class description:
Implement the FTPHelper class.
Method signatures and docstrings:
- def __init__(self, config): Initialize the FTP Helper This Class contains FTP related Functions :param config: Config Object
- def get_hltv_demos_from_ftp(self, date, server_id... | e282063def8f8424143fc5e1ae1d2e495ddb3313 | <|skeleton|>
class FTPHelper:
def __init__(self, config):
"""Initialize the FTP Helper This Class contains FTP related Functions :param config: Config Object"""
<|body_0|>
def get_hltv_demos_from_ftp(self, date, server_id, folder):
"""Download Match HLTV demos from instance :param date... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FTPHelper:
def __init__(self, config):
"""Initialize the FTP Helper This Class contains FTP related Functions :param config: Config Object"""
self.locations_hltv_starting_ = config[sC.BUCKET_LOCATIONS][sC.HLTV_STARTING]
self.score_starting_ = config[sC.BUCKET_LOCATIONS][sC.SCORE_STARTI... | the_stack_v2_python_sparse | helpers/FTPHelper.py | SanketRevankar/TournamentManagementPy | train | 1 | |
01bd47e91421af891503f948b611260c8594cc53 | [
"root = TreeNode(preorder[0])\nif len(preorder) == 1:\n return root\nindex = inorder.index(root.value)\nleftlist, rightlist = ([], [])\nfor n in preorder:\n if n in inorder[:index]:\n leftlist.append(n)\n elif n in inorder[index + 1:]:\n rightlist.append(n)\nroot.lchild = self.buildTree(leftl... | <|body_start_0|>
root = TreeNode(preorder[0])
if len(preorder) == 1:
return root
index = inorder.index(root.value)
leftlist, rightlist = ([], [])
for n in preorder:
if n in inorder[:index]:
leftlist.append(n)
elif n in inorder[i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
""":param preorder: list[int] :param inorder: list[int] :return: TreeNode"""
<|body_0|>
def buildTree2(self, preorder, inorder):
""":param preorder: list[int] :param inorder: list[int] :return: TreeNode"""
<|b... | stack_v2_sparse_classes_36k_train_016166 | 1,819 | no_license | [
{
"docstring": ":param preorder: list[int] :param inorder: list[int] :return: TreeNode",
"name": "buildTree",
"signature": "def buildTree(self, preorder, inorder)"
},
{
"docstring": ":param preorder: list[int] :param inorder: list[int] :return: TreeNode",
"name": "buildTree2",
"signature... | 2 | stack_v2_sparse_classes_30k_train_010245 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): :param preorder: list[int] :param inorder: list[int] :return: TreeNode
- def buildTree2(self, preorder, inorder): :param preorder: list[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): :param preorder: list[int] :param inorder: list[int] :return: TreeNode
- def buildTree2(self, preorder, inorder): :param preorder: list[in... | 4f2802d4773eddd2a2e06e61c51463056886b730 | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
""":param preorder: list[int] :param inorder: list[int] :return: TreeNode"""
<|body_0|>
def buildTree2(self, preorder, inorder):
""":param preorder: list[int] :param inorder: list[int] :return: TreeNode"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def buildTree(self, preorder, inorder):
""":param preorder: list[int] :param inorder: list[int] :return: TreeNode"""
root = TreeNode(preorder[0])
if len(preorder) == 1:
return root
index = inorder.index(root.value)
leftlist, rightlist = ([], [])
... | the_stack_v2_python_sparse | leetcode2/62_buildTree.py | Yara7L/python_algorithm | train | 0 | |
f15f3adb7320f791c345b4ba5dc9de997d6194b4 | [
"super().__init__(preprocess, postprocess, allow_none)\nself._dtype = dtype\nself._shape = shape\nself._order = order",
"typed_and_ordered = np.array(arr, dtype=self._dtype, order=self._order)\nif len(typed_and_ordered.shape) != len(self._shape):\n raise ValueError(f'Expected array of {len(self._shape)} dimens... | <|body_start_0|>
super().__init__(preprocess, postprocess, allow_none)
self._dtype = dtype
self._shape = shape
self._order = order
<|end_body_0|>
<|body_start_1|>
typed_and_ordered = np.array(arr, dtype=self._dtype, order=self._order)
if len(typed_and_ordered.shape) != l... | Validates array and array-like structures. Args: dtype (numpy.dtype): The type of individual items in the array. shape (`tuple` [`int`, ...], optional): The shape of the array. The number of dimensions is specified by the length of the tuple and the length of a dimension is specified by the value. A value of ``None`` i... | NDArrayValidator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NDArrayValidator:
"""Validates array and array-like structures. Args: dtype (numpy.dtype): The type of individual items in the array. shape (`tuple` [`int`, ...], optional): The shape of the array. The number of dimensions is specified by the length of the tuple and the length of a dimension is s... | stack_v2_sparse_classes_36k_train_016167 | 20,632 | permissive | [
{
"docstring": "Create a NDArrayValidator object.",
"name": "__init__",
"signature": "def __init__(self, dtype, shape=(None,), order='K', preprocess=None, postprocess=None, allow_none=False)"
},
{
"docstring": "Validate an array or array-like object.",
"name": "_validate",
"signature": "... | 2 | null | Implement the Python class `NDArrayValidator` described below.
Class description:
Validates array and array-like structures. Args: dtype (numpy.dtype): The type of individual items in the array. shape (`tuple` [`int`, ...], optional): The shape of the array. The number of dimensions is specified by the length of the t... | Implement the Python class `NDArrayValidator` described below.
Class description:
Validates array and array-like structures. Args: dtype (numpy.dtype): The type of individual items in the array. shape (`tuple` [`int`, ...], optional): The shape of the array. The number of dimensions is specified by the length of the t... | abdd76bc854358426e4cf055badd27f80df6ec85 | <|skeleton|>
class NDArrayValidator:
"""Validates array and array-like structures. Args: dtype (numpy.dtype): The type of individual items in the array. shape (`tuple` [`int`, ...], optional): The shape of the array. The number of dimensions is specified by the length of the tuple and the length of a dimension is s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NDArrayValidator:
"""Validates array and array-like structures. Args: dtype (numpy.dtype): The type of individual items in the array. shape (`tuple` [`int`, ...], optional): The shape of the array. The number of dimensions is specified by the length of the tuple and the length of a dimension is specified by t... | the_stack_v2_python_sparse | hoomd/data/typeconverter.py | glotzerlab/hoomd-blue | train | 287 |
68313708978cc5db86d8d2cd819e6da388645e55 | [
"self.object_attribute_parameters = object_attribute_parameters\nself.object_parameters = object_parameters\nself.mtype = mtype",
"if dictionary is None:\n return None\nobject_attribute_parameters = cohesity_management_sdk.models.ad_object_attribute_parameters.AdObjectAttributeParameters.from_dictionary(dictio... | <|body_start_0|>
self.object_attribute_parameters = object_attribute_parameters
self.object_parameters = object_parameters
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
object_attribute_parameters = cohesity_management_sdk.mode... | Implementation of the 'AdRestoreOptions' model. AdRestoreOptions are the AD specific options for the restore task being updated Attributes: object_attribute_parameters (AdObjectAttributeParameters): Specifies the object attributes restore parameters with the list of attributes to be restored. This is set only when type... | AdRestoreOptions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdRestoreOptions:
"""Implementation of the 'AdRestoreOptions' model. AdRestoreOptions are the AD specific options for the restore task being updated Attributes: object_attribute_parameters (AdObjectAttributeParameters): Specifies the object attributes restore parameters with the list of attribute... | stack_v2_sparse_classes_36k_train_016168 | 3,153 | permissive | [
{
"docstring": "Constructor for the AdRestoreOptions class",
"name": "__init__",
"signature": "def __init__(self, object_attribute_parameters=None, object_parameters=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A diction... | 2 | stack_v2_sparse_classes_30k_train_011190 | Implement the Python class `AdRestoreOptions` described below.
Class description:
Implementation of the 'AdRestoreOptions' model. AdRestoreOptions are the AD specific options for the restore task being updated Attributes: object_attribute_parameters (AdObjectAttributeParameters): Specifies the object attributes restor... | Implement the Python class `AdRestoreOptions` described below.
Class description:
Implementation of the 'AdRestoreOptions' model. AdRestoreOptions are the AD specific options for the restore task being updated Attributes: object_attribute_parameters (AdObjectAttributeParameters): Specifies the object attributes restor... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AdRestoreOptions:
"""Implementation of the 'AdRestoreOptions' model. AdRestoreOptions are the AD specific options for the restore task being updated Attributes: object_attribute_parameters (AdObjectAttributeParameters): Specifies the object attributes restore parameters with the list of attribute... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdRestoreOptions:
"""Implementation of the 'AdRestoreOptions' model. AdRestoreOptions are the AD specific options for the restore task being updated Attributes: object_attribute_parameters (AdObjectAttributeParameters): Specifies the object attributes restore parameters with the list of attributes to be resto... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ad_restore_options.py | cohesity/management-sdk-python | train | 24 |
10e9ecfce73f8972e5e37b13d4aa66c5a2a8077a | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RequiredResourceAccess()",
"from .resource_access import ResourceAccess\nfrom .resource_access import ResourceAccess\nfields: Dict[str, Callable[[Any], None]] = {'@odata.type': lambda n: setattr(self, 'odata_type', n.get_str_value()), ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return RequiredResourceAccess()
<|end_body_0|>
<|body_start_1|>
from .resource_access import ResourceAccess
from .resource_access import ResourceAccess
fields: Dict[str, Callable[[Any],... | RequiredResourceAccess | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequiredResourceAccess:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RequiredResourceAccess:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create ... | stack_v2_sparse_classes_36k_train_016169 | 3,200 | 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: RequiredResourceAccess",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | stack_v2_sparse_classes_30k_train_018046 | Implement the Python class `RequiredResourceAccess` described below.
Class description:
Implement the RequiredResourceAccess class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RequiredResourceAccess: Creates a new instance of the appropriate class b... | Implement the Python class `RequiredResourceAccess` described below.
Class description:
Implement the RequiredResourceAccess class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RequiredResourceAccess: Creates a new instance of the appropriate class b... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class RequiredResourceAccess:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RequiredResourceAccess:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequiredResourceAccess:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RequiredResourceAccess:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | the_stack_v2_python_sparse | msgraph/generated/models/required_resource_access.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
912b6eb073c8bb0b49a0df46e7999a3f8716df9f | [
"eps_space = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nd_space = [100, 1000, 10000]\nfor eps in eps_space:\n for d in d_space:\n gamma, _ = privunit.find_best_gamma(d, eps)\n self.assertLessEqual(0, gamma)\n self.assertLessEqual(gamma, 1)\n if gamma <= np.sqrt(np.pi / (2 * (d - 1))) * (np.exp(... | <|body_start_0|>
eps_space = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
d_space = [100, 1000, 10000]
for eps in eps_space:
for d in d_space:
gamma, _ = privunit.find_best_gamma(d, eps)
self.assertLessEqual(0, gamma)
self.assertLessEqual(gamma, 1)
... | PrivunitTest | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrivunitTest:
def test_gamma_is_in_range(self):
"""Test whether gamma adheres to (16a) or (16b) in the original paper."""
<|body_0|>
def test_c2_is_less_equal_c1(self):
"""Tests if c2 is less than or equal to c1."""
<|body_1|>
def test_m_is_less_equal_on... | stack_v2_sparse_classes_36k_train_016170 | 3,348 | permissive | [
{
"docstring": "Test whether gamma adheres to (16a) or (16b) in the original paper.",
"name": "test_gamma_is_in_range",
"signature": "def test_gamma_is_in_range(self)"
},
{
"docstring": "Tests if c2 is less than or equal to c1.",
"name": "test_c2_is_less_equal_c1",
"signature": "def test... | 4 | stack_v2_sparse_classes_30k_train_020005 | Implement the Python class `PrivunitTest` described below.
Class description:
Implement the PrivunitTest class.
Method signatures and docstrings:
- def test_gamma_is_in_range(self): Test whether gamma adheres to (16a) or (16b) in the original paper.
- def test_c2_is_less_equal_c1(self): Tests if c2 is less than or eq... | Implement the Python class `PrivunitTest` described below.
Class description:
Implement the PrivunitTest class.
Method signatures and docstrings:
- def test_gamma_is_in_range(self): Test whether gamma adheres to (16a) or (16b) in the original paper.
- def test_c2_is_less_equal_c1(self): Tests if c2 is less than or eq... | 329e60fa56b87f691303638ceb9dfa1fc5083953 | <|skeleton|>
class PrivunitTest:
def test_gamma_is_in_range(self):
"""Test whether gamma adheres to (16a) or (16b) in the original paper."""
<|body_0|>
def test_c2_is_less_equal_c1(self):
"""Tests if c2 is less than or equal to c1."""
<|body_1|>
def test_m_is_less_equal_on... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrivunitTest:
def test_gamma_is_in_range(self):
"""Test whether gamma adheres to (16a) or (16b) in the original paper."""
eps_space = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
d_space = [100, 1000, 10000]
for eps in eps_space:
for d in d_space:
gamma, _ = priv... | the_stack_v2_python_sparse | rcc_dp/mean_estimation/privunit_test.py | google-research/federated | train | 595 | |
a63c45a738b5bb3da4d07aee135641ca2129c883 | [
"logger.info('用例编号:116-1---多单持仓成功,下限价多单50倍杠杆委托,下限价空单成交,验证余额,委托状态')\nrange_num = 5\nbuy_num = 100000000\nsell_num = buy_num * range_num\nlever = 50\nstock_price_dict = market_info_get(user=self.buyer, session=self.session, sda_id=sda_id)\nnow_stock_price = stock_price_dict['stockPrice']\ndeal_price = int(int(now_sto... | <|body_start_0|>
logger.info('用例编号:116-1---多单持仓成功,下限价多单50倍杠杆委托,下限价空单成交,验证余额,委托状态')
range_num = 5
buy_num = 100000000
sell_num = buy_num * range_num
lever = 50
stock_price_dict = market_info_get(user=self.buyer, session=self.session, sda_id=sda_id)
now_stock_price ... | 持仓成功状态,继续下委托。 | TestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCase:
"""持仓成功状态,继续下委托。"""
def test_01(self):
"""限价多单持仓成功,下限价多单委托,验证余额,委托状态"""
<|body_0|>
def test_02(self):
"""限价空单持仓成功,下空单委托"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
logger.info('用例编号:116-1---多单持仓成功,下限价多单50倍杠杆委托,下限价空单成交,验证余额,委托状态')
... | stack_v2_sparse_classes_36k_train_016171 | 7,045 | no_license | [
{
"docstring": "限价多单持仓成功,下限价多单委托,验证余额,委托状态",
"name": "test_01",
"signature": "def test_01(self)"
},
{
"docstring": "限价空单持仓成功,下空单委托",
"name": "test_02",
"signature": "def test_02(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000372 | Implement the Python class `TestCase` described below.
Class description:
持仓成功状态,继续下委托。
Method signatures and docstrings:
- def test_01(self): 限价多单持仓成功,下限价多单委托,验证余额,委托状态
- def test_02(self): 限价空单持仓成功,下空单委托 | Implement the Python class `TestCase` described below.
Class description:
持仓成功状态,继续下委托。
Method signatures and docstrings:
- def test_01(self): 限价多单持仓成功,下限价多单委托,验证余额,委托状态
- def test_02(self): 限价空单持仓成功,下空单委托
<|skeleton|>
class TestCase:
"""持仓成功状态,继续下委托。"""
def test_01(self):
"""限价多单持仓成功,下限价多单委托,验证余额,委... | 29f04fc05d4c1d8c950d726861b1884892cfbf58 | <|skeleton|>
class TestCase:
"""持仓成功状态,继续下委托。"""
def test_01(self):
"""限价多单持仓成功,下限价多单委托,验证余额,委托状态"""
<|body_0|>
def test_02(self):
"""限价空单持仓成功,下空单委托"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCase:
"""持仓成功状态,继续下委托。"""
def test_01(self):
"""限价多单持仓成功,下限价多单委托,验证余额,委托状态"""
logger.info('用例编号:116-1---多单持仓成功,下限价多单50倍杠杆委托,下限价空单成交,验证余额,委托状态')
range_num = 5
buy_num = 100000000
sell_num = buy_num * range_num
lever = 50
stock_price_dict = market... | the_stack_v2_python_sparse | case/SDA/test_116.py | xiaoxiangLiu/test | train | 0 |
fdab026b6fefb55587b2d4ee233ee93fe24cf5bd | [
"if pts is None or len(pts) == 0:\n return 0\nsorted_pts = sorted(pts, key=lambda pt: pt.x)\nx_sums = self.mht_sum(sorted_pts, True)\nsorted_pts = sorted(pts, key=lambda pt: pt.y)\ny_sums = self.mht_sum(sorted_pts, True)\nret = (1 << 31) - 1\nfor i in range(0, len(pts)):\n ret = min(ret, x_sums[pts[i].x, pts[... | <|body_start_0|>
if pts is None or len(pts) == 0:
return 0
sorted_pts = sorted(pts, key=lambda pt: pt.x)
x_sums = self.mht_sum(sorted_pts, True)
sorted_pts = sorted(pts, key=lambda pt: pt.y)
y_sums = self.mht_sum(sorted_pts, True)
ret = (1 << 31) - 1
f... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def min_mht_dis(self, pts):
""":param pts: List[Point] :return: int"""
<|body_0|>
def mht_sum(self, pts, is_x):
""":param pts: List[Point] :param is_x: Boolean :return: Dict{(int, int): int}"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_016172 | 2,860 | no_license | [
{
"docstring": ":param pts: List[Point] :return: int",
"name": "min_mht_dis",
"signature": "def min_mht_dis(self, pts)"
},
{
"docstring": ":param pts: List[Point] :param is_x: Boolean :return: Dict{(int, int): int}",
"name": "mht_sum",
"signature": "def mht_sum(self, pts, is_x)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def min_mht_dis(self, pts): :param pts: List[Point] :return: int
- def mht_sum(self, pts, is_x): :param pts: List[Point] :param is_x: Boolean :return: Dict{(int, int): int} | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def min_mht_dis(self, pts): :param pts: List[Point] :return: int
- def mht_sum(self, pts, is_x): :param pts: List[Point] :param is_x: Boolean :return: Dict{(int, int): int}
<|sk... | e41f4ac9e99b9272ed4718680f4d12fd7443db03 | <|skeleton|>
class Solution:
def min_mht_dis(self, pts):
""":param pts: List[Point] :return: int"""
<|body_0|>
def mht_sum(self, pts, is_x):
""":param pts: List[Point] :param is_x: Boolean :return: Dict{(int, int): int}"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def min_mht_dis(self, pts):
""":param pts: List[Point] :return: int"""
if pts is None or len(pts) == 0:
return 0
sorted_pts = sorted(pts, key=lambda pt: pt.x)
x_sums = self.mht_sum(sorted_pts, True)
sorted_pts = sorted(pts, key=lambda pt: pt.y)
... | the_stack_v2_python_sparse | tags/sort/min_sum_of_manhattan_distance.py | jied314/IQs | train | 0 | |
153f267eaedd42cb199f155c8c0ddb694ae1f4a3 | [
"logger.debug('Start clean data in ResetPasswordForm.')\nemail = self.cleaned_data.get('email')\nself.validator_all(email)\nlogger.debug('Exit clean data in ResetPasswordForm.')\nreturn super(ResetPasswordForm, self).clean(*args, **kwargs)",
"logger.debug('Start validations in ResetPasswordForm.')\nvalidator = Us... | <|body_start_0|>
logger.debug('Start clean data in ResetPasswordForm.')
email = self.cleaned_data.get('email')
self.validator_all(email)
logger.debug('Exit clean data in ResetPasswordForm.')
return super(ResetPasswordForm, self).clean(*args, **kwargs)
<|end_body_0|>
<|body_start... | Form to reset password User | ResetPasswordForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetPasswordForm:
"""Form to reset password User"""
def clean(self, *args, **kwargs):
"""Get patient fields."""
<|body_0|>
def validator_all(self, email):
"""Checks validator in all fields."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
logger... | stack_v2_sparse_classes_36k_train_016173 | 1,291 | permissive | [
{
"docstring": "Get patient fields.",
"name": "clean",
"signature": "def clean(self, *args, **kwargs)"
},
{
"docstring": "Checks validator in all fields.",
"name": "validator_all",
"signature": "def validator_all(self, email)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001476 | Implement the Python class `ResetPasswordForm` described below.
Class description:
Form to reset password User
Method signatures and docstrings:
- def clean(self, *args, **kwargs): Get patient fields.
- def validator_all(self, email): Checks validator in all fields. | Implement the Python class `ResetPasswordForm` described below.
Class description:
Form to reset password User
Method signatures and docstrings:
- def clean(self, *args, **kwargs): Get patient fields.
- def validator_all(self, email): Checks validator in all fields.
<|skeleton|>
class ResetPasswordForm:
"""Form ... | 5387eb80dfb354e948abe64f7d8bbe087fc4f136 | <|skeleton|>
class ResetPasswordForm:
"""Form to reset password User"""
def clean(self, *args, **kwargs):
"""Get patient fields."""
<|body_0|>
def validator_all(self, email):
"""Checks validator in all fields."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResetPasswordForm:
"""Form to reset password User"""
def clean(self, *args, **kwargs):
"""Get patient fields."""
logger.debug('Start clean data in ResetPasswordForm.')
email = self.cleaned_data.get('email')
self.validator_all(email)
logger.debug('Exit clean data in... | the_stack_v2_python_sparse | medical_prescription/user/forms/resetpasswordform.py | ristovao/2017.2-Receituario-Medico | train | 0 |
472f04d47d5578cc55fa7fd848b0688250e4e2eb | [
"self._input = input_file\nself._spill = BufferedStream()\nself._zlib = zlib.compressobj(level=1, method=zlib.DEFLATED, wbits=-zlib.MAX_WBITS)\nself._crc = zlib.crc32(b'')\nself._read_size = 0\nif not mtime:\n mtime = time.time()\nself._spill.write(pack('<3sBL2s', b'\\x1f\\x8b\\x08', 8 if filename else 0, int(mt... | <|body_start_0|>
self._input = input_file
self._spill = BufferedStream()
self._zlib = zlib.compressobj(level=1, method=zlib.DEFLATED, wbits=-zlib.MAX_WBITS)
self._crc = zlib.crc32(b'')
self._read_size = 0
if not mtime:
mtime = time.time()
self._spill.w... | Gzip-compressed stream from a readable stream | GzipStreamWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GzipStreamWrapper:
"""Gzip-compressed stream from a readable stream"""
def __init__(self, input_file, mtime=None, filename: str=None):
"""Initialize the stream"""
<|body_0|>
def read(self, size=-1):
"""Read data from input and compress it"""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_016174 | 4,086 | permissive | [
{
"docstring": "Initialize the stream",
"name": "__init__",
"signature": "def __init__(self, input_file, mtime=None, filename: str=None)"
},
{
"docstring": "Read data from input and compress it",
"name": "read",
"signature": "def read(self, size=-1)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001645 | Implement the Python class `GzipStreamWrapper` described below.
Class description:
Gzip-compressed stream from a readable stream
Method signatures and docstrings:
- def __init__(self, input_file, mtime=None, filename: str=None): Initialize the stream
- def read(self, size=-1): Read data from input and compress it | Implement the Python class `GzipStreamWrapper` described below.
Class description:
Gzip-compressed stream from a readable stream
Method signatures and docstrings:
- def __init__(self, input_file, mtime=None, filename: str=None): Initialize the stream
- def read(self, size=-1): Read data from input and compress it
<|... | 9c9040f6a173af5c495f5447889e9349fa56f234 | <|skeleton|>
class GzipStreamWrapper:
"""Gzip-compressed stream from a readable stream"""
def __init__(self, input_file, mtime=None, filename: str=None):
"""Initialize the stream"""
<|body_0|>
def read(self, size=-1):
"""Read data from input and compress it"""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GzipStreamWrapper:
"""Gzip-compressed stream from a readable stream"""
def __init__(self, input_file, mtime=None, filename: str=None):
"""Initialize the stream"""
self._input = input_file
self._spill = BufferedStream()
self._zlib = zlib.compressobj(level=1, method=zlib.DEF... | the_stack_v2_python_sparse | tessia/server/lib/compression.py | tessia-project/tessia | train | 10 |
81e7a1ac52704e8601e93aafdf7e0cdc579385b3 | [
"LoginPage(browser).login(data['user'], data['pwd'])\nmsg = LoginPage(browser).erro_msg()\nassert data['msg'] == msg",
"LoginPage(browser).login(ld.ID_1['user'], ld.ID_1['pwd'])\nmsg = HomePage(browser).is_user_link_exists()\nassert msg == True",
"HomePage(browser).logout()\nmsg = HomePage(browser).is_user_link... | <|body_start_0|>
LoginPage(browser).login(data['user'], data['pwd'])
msg = LoginPage(browser).erro_msg()
assert data['msg'] == msg
<|end_body_0|>
<|body_start_1|>
LoginPage(browser).login(ld.ID_1['user'], ld.ID_1['pwd'])
msg = HomePage(browser).is_user_link_exists()
asse... | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
def test_login_1_error(self, data, browser):
"""名称:使用错误的账号密码信息登录 步骤: 1、打开浏览器 2、输入账号密码 3、点击登录按钮 检查点: * 检查页面弹出的提示信息。"""
<|body_0|>
def test_login_2_sucess(self, browser):
"""名称:使用正确的账号密码信息登录 步骤: 1、打开浏览器 2、输入正确账号密码 3、点击登录按钮 检查点: * 检查页面右侧的账户名是否存在。"""
<... | stack_v2_sparse_classes_36k_train_016175 | 1,787 | no_license | [
{
"docstring": "名称:使用错误的账号密码信息登录 步骤: 1、打开浏览器 2、输入账号密码 3、点击登录按钮 检查点: * 检查页面弹出的提示信息。",
"name": "test_login_1_error",
"signature": "def test_login_1_error(self, data, browser)"
},
{
"docstring": "名称:使用正确的账号密码信息登录 步骤: 1、打开浏览器 2、输入正确账号密码 3、点击登录按钮 检查点: * 检查页面右侧的账户名是否存在。",
"name": "test_login_2_suc... | 3 | stack_v2_sparse_classes_30k_train_002885 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login_1_error(self, data, browser): 名称:使用错误的账号密码信息登录 步骤: 1、打开浏览器 2、输入账号密码 3、点击登录按钮 检查点: * 检查页面弹出的提示信息。
- def test_login_2_sucess(self, browser): 名称:使用正确的账号密码信息登录 步骤: 1... | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login_1_error(self, data, browser): 名称:使用错误的账号密码信息登录 步骤: 1、打开浏览器 2、输入账号密码 3、点击登录按钮 检查点: * 检查页面弹出的提示信息。
- def test_login_2_sucess(self, browser): 名称:使用正确的账号密码信息登录 步骤: 1... | e10910b4317f8effacedb3f861ede88d252d828f | <|skeleton|>
class TestLogin:
def test_login_1_error(self, data, browser):
"""名称:使用错误的账号密码信息登录 步骤: 1、打开浏览器 2、输入账号密码 3、点击登录按钮 检查点: * 检查页面弹出的提示信息。"""
<|body_0|>
def test_login_2_sucess(self, browser):
"""名称:使用正确的账号密码信息登录 步骤: 1、打开浏览器 2、输入正确账号密码 3、点击登录按钮 检查点: * 检查页面右侧的账户名是否存在。"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLogin:
def test_login_1_error(self, data, browser):
"""名称:使用错误的账号密码信息登录 步骤: 1、打开浏览器 2、输入账号密码 3、点击登录按钮 检查点: * 检查页面弹出的提示信息。"""
LoginPage(browser).login(data['user'], data['pwd'])
msg = LoginPage(browser).erro_msg()
assert data['msg'] == msg
def test_login_2_sucess(self, ... | the_stack_v2_python_sparse | TestCases/login/test_1_login.py | liqi629/yy_echo | train | 0 | |
adee28b65fc41db2414026f42a549c2495195562 | [
"self.res = []\nself.getPaths(root, '')\nreturn self.res",
"if root == None:\n return\nif path == '':\n path = path + str(root.val)\nelse:\n path = path + '->' + str(root.val)\nif root.left == None and root.right == None:\n self.res.append(path)\nelse:\n self.getPaths(root.left, path)\n self.get... | <|body_start_0|>
self.res = []
self.getPaths(root, '')
return self.res
<|end_body_0|>
<|body_start_1|>
if root == None:
return
if path == '':
path = path + str(root.val)
else:
path = path + '->' + str(root.val)
if root.left == ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str]"""
<|body_0|>
def getPaths(self, root, path):
""":type root: TreeNode :rtype: None"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.res = []
self.getPat... | stack_v2_sparse_classes_36k_train_016176 | 1,625 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[str]",
"name": "binaryTreePaths",
"signature": "def binaryTreePaths(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: None",
"name": "getPaths",
"signature": "def getPaths(self, root, path)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004621 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binaryTreePaths(self, root): :type root: TreeNode :rtype: List[str]
- def getPaths(self, root, path): :type root: TreeNode :rtype: None | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binaryTreePaths(self, root): :type root: TreeNode :rtype: List[str]
- def getPaths(self, root, path): :type root: TreeNode :rtype: None
<|skeleton|>
class Solution:
def... | 8cda0518440488992d7e2c70cb8555ec7b34083f | <|skeleton|>
class Solution:
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str]"""
<|body_0|>
def getPaths(self, root, path):
""":type root: TreeNode :rtype: None"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str]"""
self.res = []
self.getPaths(root, '')
return self.res
def getPaths(self, root, path):
""":type root: TreeNode :rtype: None"""
if root == None:
return
... | the_stack_v2_python_sparse | 257/main.py | szhongren/leetcode | train | 0 | |
766ce05099a1e5082c298c2dded4178b4c11a6fd | [
"parameters = dict()\nparameters['page'] = GraphQLParam(page, 'PageInput', False)\nparameters['filter'] = GraphQLParam(dc_filter, 'DataCenterFilter', False)\nparameters['sort'] = GraphQLParam(sort, 'DataCenterSort', False)\nresponse = self._query(name='getDataCenters', params=parameters, fields=DataCenterList.field... | <|body_start_0|>
parameters = dict()
parameters['page'] = GraphQLParam(page, 'PageInput', False)
parameters['filter'] = GraphQLParam(dc_filter, 'DataCenterFilter', False)
parameters['sort'] = GraphQLParam(sort, 'DataCenterSort', False)
response = self._query(name='getDataCenters'... | Mixin to add datacenter related methods to the GraphQL client | DatacentersMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatacentersMixin:
"""Mixin to add datacenter related methods to the GraphQL client"""
def get_datacenters(self, page: PageInput=None, dc_filter: DataCenterFilter=None, sort: DataCenterSort=None) -> DataCenterList:
"""Retrieves a list of datacenter objects :param page: The requested p... | stack_v2_sparse_classes_36k_train_016177 | 30,254 | permissive | [
{
"docstring": "Retrieves a list of datacenter objects :param page: The requested page from the server. This is an optional argument and if omitted the server will default to returning the first page with a maximum of ``100`` items. :type page: PageInput, optional :param dc_filter: A filter object to filter the... | 4 | stack_v2_sparse_classes_30k_train_016466 | Implement the Python class `DatacentersMixin` described below.
Class description:
Mixin to add datacenter related methods to the GraphQL client
Method signatures and docstrings:
- def get_datacenters(self, page: PageInput=None, dc_filter: DataCenterFilter=None, sort: DataCenterSort=None) -> DataCenterList: Retrieves ... | Implement the Python class `DatacentersMixin` described below.
Class description:
Mixin to add datacenter related methods to the GraphQL client
Method signatures and docstrings:
- def get_datacenters(self, page: PageInput=None, dc_filter: DataCenterFilter=None, sort: DataCenterSort=None) -> DataCenterList: Retrieves ... | 8ea044096bd18aaccbfb81eca4e26ec29895a18c | <|skeleton|>
class DatacentersMixin:
"""Mixin to add datacenter related methods to the GraphQL client"""
def get_datacenters(self, page: PageInput=None, dc_filter: DataCenterFilter=None, sort: DataCenterSort=None) -> DataCenterList:
"""Retrieves a list of datacenter objects :param page: The requested p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatacentersMixin:
"""Mixin to add datacenter related methods to the GraphQL client"""
def get_datacenters(self, page: PageInput=None, dc_filter: DataCenterFilter=None, sort: DataCenterSort=None) -> DataCenterList:
"""Retrieves a list of datacenter objects :param page: The requested page from the ... | the_stack_v2_python_sparse | nebpyclient/api/datacenters.py | firefly707/nebpyclient | train | 0 |
d7abfe5ff429b3d5fd8ffcbbb3960273d88b767f | [
"form = FormService.get_by_id(form_id=form_id)\nif form is None:\n raise BadRequest('No such form')\nif form.owner_id != current_user.id:\n raise Forbidden(\"Can't view fields of the form that doesn't belong to you\")\nform_fields = FormFieldService.filter(form_id=form.id)\nform_fields_json = []\nfor form_fie... | <|body_start_0|>
form = FormService.get_by_id(form_id=form_id)
if form is None:
raise BadRequest('No such form')
if form.owner_id != current_user.id:
raise Forbidden("Can't view fields of the form that doesn't belong to you")
form_fields = FormFieldService.filter(... | FormFields API url: 'forms/{form_id}/fields/' methods: get, post | FormFieldsAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormFieldsAPI:
"""FormFields API url: 'forms/{form_id}/fields/' methods: get, post"""
def get(self, form_id):
"""Get all fields that are contained within a form :param form_id: ID of the form that contains fields"""
<|body_0|>
def post(self, form_id):
"""Add fiel... | stack_v2_sparse_classes_36k_train_016178 | 10,042 | no_license | [
{
"docstring": "Get all fields that are contained within a form :param form_id: ID of the form that contains fields",
"name": "get",
"signature": "def get(self, form_id)"
},
{
"docstring": "Add field to a form :param form_id: ID of the form to which the field will be inserted",
"name": "post... | 2 | stack_v2_sparse_classes_30k_train_012523 | Implement the Python class `FormFieldsAPI` described below.
Class description:
FormFields API url: 'forms/{form_id}/fields/' methods: get, post
Method signatures and docstrings:
- def get(self, form_id): Get all fields that are contained within a form :param form_id: ID of the form that contains fields
- def post(sel... | Implement the Python class `FormFieldsAPI` described below.
Class description:
FormFields API url: 'forms/{form_id}/fields/' methods: get, post
Method signatures and docstrings:
- def get(self, form_id): Get all fields that are contained within a form :param form_id: ID of the form that contains fields
- def post(sel... | 7344e4bd1cc977781b35a2ad1b38ff0d270163b7 | <|skeleton|>
class FormFieldsAPI:
"""FormFields API url: 'forms/{form_id}/fields/' methods: get, post"""
def get(self, form_id):
"""Get all fields that are contained within a form :param form_id: ID of the form that contains fields"""
<|body_0|>
def post(self, form_id):
"""Add fiel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FormFieldsAPI:
"""FormFields API url: 'forms/{form_id}/fields/' methods: get, post"""
def get(self, form_id):
"""Get all fields that are contained within a form :param form_id: ID of the form that contains fields"""
form = FormService.get_by_id(form_id=form_id)
if form is None:
... | the_stack_v2_python_sparse | src/app/routers/form_field.py | Lv-474-Python/ngfg | train | 0 |
bfdfbd37aa19e6eae8425030c406b35e3f4a33e0 | [
"assert query_params is None or isinstance(query_params, APIQueryParams)\nassert queries_params is None or isinstance(queries_params, dict)\nif queries_params is not None:\n assert all((isinstance(query, APIQueryParams) for query in queries_params.values()))\nassert not (query_params is None and queries_params i... | <|body_start_0|>
assert query_params is None or isinstance(query_params, APIQueryParams)
assert queries_params is None or isinstance(queries_params, dict)
if queries_params is not None:
assert all((isinstance(query, APIQueryParams) for query in queries_params.values()))
asser... | SDAPIQuery | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SDAPIQuery:
def submit_query(cls, query_params: Optional[APIQueryParams]=None, queries_params: Optional[Dict[str, APIQueryParams]]=None, timeout: Optional[float]=None, headers: Optional[Dict[str, str]]=None) -> Union[T_DF, Dict[str, T_DF]]:
"""Determines the proper method to use and pass... | stack_v2_sparse_classes_36k_train_016179 | 17,212 | permissive | [
{
"docstring": "Determines the proper method to use and passes values along for request submission Parameters ---------- query_params: Optional[APIQueryParams] = None A single query params object to submit as part of the request queries_params: Optional[Dict[str, APIQueryParams]] = None A list of dicts, with qu... | 4 | stack_v2_sparse_classes_30k_test_001095 | Implement the Python class `SDAPIQuery` described below.
Class description:
Implement the SDAPIQuery class.
Method signatures and docstrings:
- def submit_query(cls, query_params: Optional[APIQueryParams]=None, queries_params: Optional[Dict[str, APIQueryParams]]=None, timeout: Optional[float]=None, headers: Optional[... | Implement the Python class `SDAPIQuery` described below.
Class description:
Implement the SDAPIQuery class.
Method signatures and docstrings:
- def submit_query(cls, query_params: Optional[APIQueryParams]=None, queries_params: Optional[Dict[str, APIQueryParams]]=None, timeout: Optional[float]=None, headers: Optional[... | 392413cd821c05b8db0e385a7f5ad629b5b04759 | <|skeleton|>
class SDAPIQuery:
def submit_query(cls, query_params: Optional[APIQueryParams]=None, queries_params: Optional[Dict[str, APIQueryParams]]=None, timeout: Optional[float]=None, headers: Optional[Dict[str, str]]=None) -> Union[T_DF, Dict[str, T_DF]]:
"""Determines the proper method to use and pass... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SDAPIQuery:
def submit_query(cls, query_params: Optional[APIQueryParams]=None, queries_params: Optional[Dict[str, APIQueryParams]]=None, timeout: Optional[float]=None, headers: Optional[Dict[str, str]]=None) -> Union[T_DF, Dict[str, T_DF]]:
"""Determines the proper method to use and passes values alon... | the_stack_v2_python_sparse | strato_query/api_query.py | StratoDem/strato-query | train | 1 | |
c328af232c8df9e8f62f371186f51fd772838d23 | [
"config = super().default_configs()\nconfig.update({'max_char_length': None, 'entry_type': 'ft.onto.base_ontology.Token'})\nreturn config",
"word: Annotation\nif self.config is None:\n raise ProcessorConfigError('Configuration for the extractor not found.')\nfor word in pack.get(self.config.entry_type, context... | <|body_start_0|>
config = super().default_configs()
config.update({'max_char_length': None, 'entry_type': 'ft.onto.base_ontology.Token'})
return config
<|end_body_0|>
<|body_start_1|>
word: Annotation
if self.config is None:
raise ProcessorConfigError('Configuration ... | CharExtractor extracts feature from the text of entry. Text will be split into characters. | CharExtractor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CharExtractor:
"""CharExtractor extracts feature from the text of entry. Text will be split into characters."""
def default_configs(cls):
"""Returns a dictionary of default configuration parameters. Here: - "max_char_length": int The maximum number of characters for one token in the ... | stack_v2_sparse_classes_36k_train_016180 | 4,511 | permissive | [
{
"docstring": "Returns a dictionary of default configuration parameters. Here: - \"max_char_length\": int The maximum number of characters for one token in the text, default is None, which means no limit will be set. - \"entry_type\": str The fully qualified name of an annotation type entry. Characters will be... | 3 | stack_v2_sparse_classes_30k_train_001697 | Implement the Python class `CharExtractor` described below.
Class description:
CharExtractor extracts feature from the text of entry. Text will be split into characters.
Method signatures and docstrings:
- def default_configs(cls): Returns a dictionary of default configuration parameters. Here: - "max_char_length": i... | Implement the Python class `CharExtractor` described below.
Class description:
CharExtractor extracts feature from the text of entry. Text will be split into characters.
Method signatures and docstrings:
- def default_configs(cls): Returns a dictionary of default configuration parameters. Here: - "max_char_length": i... | 13e50aebe2afd79a7a8b3c01f0bb2568addea54f | <|skeleton|>
class CharExtractor:
"""CharExtractor extracts feature from the text of entry. Text will be split into characters."""
def default_configs(cls):
"""Returns a dictionary of default configuration parameters. Here: - "max_char_length": int The maximum number of characters for one token in the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CharExtractor:
"""CharExtractor extracts feature from the text of entry. Text will be split into characters."""
def default_configs(cls):
"""Returns a dictionary of default configuration parameters. Here: - "max_char_length": int The maximum number of characters for one token in the text, default... | the_stack_v2_python_sparse | forte/data/extractors/char_extractor.py | asyml/forte | train | 233 |
6c3b0896585a2b834791b7db54084116cb9587fc | [
"self.ide = identity_element\nself.lide = lazy_ide\nself.func = segfunc\nn = len(ls)\nself.num = 2 ** (n - 1).bit_length()\nself.tree = [self.ide] * (2 * self.num)\nself.lazy = [self.lide] * (2 * self.num)\nfor i, l in enumerate(ls):\n self.tree[i + self.num - 1] = l\nfor i in range(self.num - 2, -1, -1):\n s... | <|body_start_0|>
self.ide = identity_element
self.lide = lazy_ide
self.func = segfunc
n = len(ls)
self.num = 2 ** (n - 1).bit_length()
self.tree = [self.ide] * (2 * self.num)
self.lazy = [self.lide] * (2 * self.num)
for i, l in enumerate(ls):
s... | LazySegmentTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LazySegmentTree:
def __init__(self, ls: list, segfunc, identity_element, lazy_ide=None):
"""セグ木 pypyじゃないとTLEなるかも 一次元のリストlsを受け取り初期化する。O(len(ls)) 区間のルールはsegfuncによって定義される identity elementは単位元。e.g., 最小値を求めたい→inf, 和→0, 積→1, gcd→0 [単位元](https://ja.wikipedia.org/wiki/%E5%8D%98%E4%BD%8D%E5%85%83... | stack_v2_sparse_classes_36k_train_016181 | 23,273 | no_license | [
{
"docstring": "セグ木 pypyじゃないとTLEなるかも 一次元のリストlsを受け取り初期化する。O(len(ls)) 区間のルールはsegfuncによって定義される identity elementは単位元。e.g., 最小値を求めたい→inf, 和→0, 積→1, gcd→0 [単位元](https://ja.wikipedia.org/wiki/%E5%8D%98%E4%BD%8D%E5%85%83)",
"name": "__init__",
"signature": "def __init__(self, ls: list, segfunc, identity_element... | 4 | null | Implement the Python class `LazySegmentTree` described below.
Class description:
Implement the LazySegmentTree class.
Method signatures and docstrings:
- def __init__(self, ls: list, segfunc, identity_element, lazy_ide=None): セグ木 pypyじゃないとTLEなるかも 一次元のリストlsを受け取り初期化する。O(len(ls)) 区間のルールはsegfuncによって定義される identity element... | Implement the Python class `LazySegmentTree` described below.
Class description:
Implement the LazySegmentTree class.
Method signatures and docstrings:
- def __init__(self, ls: list, segfunc, identity_element, lazy_ide=None): セグ木 pypyじゃないとTLEなるかも 一次元のリストlsを受け取り初期化する。O(len(ls)) 区間のルールはsegfuncによって定義される identity element... | 74915a40ac157f89fe400e3f98e9bf3c10012cd7 | <|skeleton|>
class LazySegmentTree:
def __init__(self, ls: list, segfunc, identity_element, lazy_ide=None):
"""セグ木 pypyじゃないとTLEなるかも 一次元のリストlsを受け取り初期化する。O(len(ls)) 区間のルールはsegfuncによって定義される identity elementは単位元。e.g., 最小値を求めたい→inf, 和→0, 積→1, gcd→0 [単位元](https://ja.wikipedia.org/wiki/%E5%8D%98%E4%BD%8D%E5%85%83... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LazySegmentTree:
def __init__(self, ls: list, segfunc, identity_element, lazy_ide=None):
"""セグ木 pypyじゃないとTLEなるかも 一次元のリストlsを受け取り初期化する。O(len(ls)) 区間のルールはsegfuncによって定義される identity elementは単位元。e.g., 最小値を求めたい→inf, 和→0, 積→1, gcd→0 [単位元](https://ja.wikipedia.org/wiki/%E5%8D%98%E4%BD%8D%E5%85%83)"""
s... | the_stack_v2_python_sparse | algorithm/SegmentTree.py | masakiaota/kyoupuro | train | 1 | |
4df996da07e870ae1e974007c28aaab3c395768f | [
"if args:\n super(Application, self).__init__(args)\nelse:\n super(Application, self).__init__()\nself.window = MainWindow(self, state, screenFps, fixedFps)",
"self.window.start()\nself.window.show()\nself.exec_()"
] | <|body_start_0|>
if args:
super(Application, self).__init__(args)
else:
super(Application, self).__init__()
self.window = MainWindow(self, state, screenFps, fixedFps)
<|end_body_0|>
<|body_start_1|>
self.window.start()
self.window.show()
self.exec... | This is the core class of an AggiEngine application. | Application | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""This is the core class of an AggiEngine application."""
def __init__(self, state: State, screenFps: Optional[float]=120, fixedFps: Optional[float]=60, args: Optional[list]=None) -> None:
"""Creates and initializes QWidgets for the application to start. ``state:`` The ... | stack_v2_sparse_classes_36k_train_016182 | 1,055 | permissive | [
{
"docstring": "Creates and initializes QWidgets for the application to start. ``state:`` The initial state to launch the Application with ``args:`` System arguments passed in ``config:`` Set application parameters",
"name": "__init__",
"signature": "def __init__(self, state: State, screenFps: Optional[... | 2 | stack_v2_sparse_classes_30k_train_012724 | Implement the Python class `Application` described below.
Class description:
This is the core class of an AggiEngine application.
Method signatures and docstrings:
- def __init__(self, state: State, screenFps: Optional[float]=120, fixedFps: Optional[float]=60, args: Optional[list]=None) -> None: Creates and initializ... | Implement the Python class `Application` described below.
Class description:
This is the core class of an AggiEngine application.
Method signatures and docstrings:
- def __init__(self, state: State, screenFps: Optional[float]=120, fixedFps: Optional[float]=60, args: Optional[list]=None) -> None: Creates and initializ... | d06b9fd71b2559c73b33395cc79d7f8cbd457bbf | <|skeleton|>
class Application:
"""This is the core class of an AggiEngine application."""
def __init__(self, state: State, screenFps: Optional[float]=120, fixedFps: Optional[float]=60, args: Optional[list]=None) -> None:
"""Creates and initializes QWidgets for the application to start. ``state:`` The ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Application:
"""This is the core class of an AggiEngine application."""
def __init__(self, state: State, screenFps: Optional[float]=120, fixedFps: Optional[float]=60, args: Optional[list]=None) -> None:
"""Creates and initializes QWidgets for the application to start. ``state:`` The initial state... | the_stack_v2_python_sparse | AggiEngine/application.py | aggie-coding-club/AggiEngine | train | 9 |
be3fa87baca44878c8a8332feb16348baa301526 | [
"self.assertEqual(99, highScore.playerHighScore('Dr Teeth', 99))\nself.assertEqual(99, highScore.playerHighScore('Dr Teeth', 91))\nself.assertEqual(108, highScore.playerHighScore('Dr Teeth', 108))\nself.assertEqual(0, highScore.playerHighScore('Animal', 0))\nself.assertEqual(0, highScore.playerHighScore('Animal', -... | <|body_start_0|>
self.assertEqual(99, highScore.playerHighScore('Dr Teeth', 99))
self.assertEqual(99, highScore.playerHighScore('Dr Teeth', 91))
self.assertEqual(108, highScore.playerHighScore('Dr Teeth', 108))
self.assertEqual(0, highScore.playerHighScore('Animal', 0))
self.asse... | TestHighScore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHighScore:
def testScores(self):
"""Test out some scores - expected vs observed (shelf previous best)"""
<|body_0|>
def tearDown(self):
"""Remove the .shelve.* files"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.assertEqual(99, highScore.... | stack_v2_sparse_classes_36k_train_016183 | 1,228 | no_license | [
{
"docstring": "Test out some scores - expected vs observed (shelf previous best)",
"name": "testScores",
"signature": "def testScores(self)"
},
{
"docstring": "Remove the .shelve.* files",
"name": "tearDown",
"signature": "def tearDown(self)"
}
] | 2 | null | Implement the Python class `TestHighScore` described below.
Class description:
Implement the TestHighScore class.
Method signatures and docstrings:
- def testScores(self): Test out some scores - expected vs observed (shelf previous best)
- def tearDown(self): Remove the .shelve.* files | Implement the Python class `TestHighScore` described below.
Class description:
Implement the TestHighScore class.
Method signatures and docstrings:
- def testScores(self): Test out some scores - expected vs observed (shelf previous best)
- def tearDown(self): Remove the .shelve.* files
<|skeleton|>
class TestHighSco... | 049c654ed626e97d7fe2f8dc61d84c60f10d7558 | <|skeleton|>
class TestHighScore:
def testScores(self):
"""Test out some scores - expected vs observed (shelf previous best)"""
<|body_0|>
def tearDown(self):
"""Remove the .shelve.* files"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestHighScore:
def testScores(self):
"""Test out some scores - expected vs observed (shelf previous best)"""
self.assertEqual(99, highScore.playerHighScore('Dr Teeth', 99))
self.assertEqual(99, highScore.playerHighScore('Dr Teeth', 91))
self.assertEqual(108, highScore.playerHig... | the_stack_v2_python_sparse | python2/HighScore_Homework/src/test_highScore.py | paulrefalo/Python-2---4 | train | 0 | |
f319631fec656a0124af5226cfea8bc7388d7682 | [
"m = len(nums1)\nn = len(nums2)\nnums = []\nk = m + n\ni = 0\nj = 0\nwhile i < m and j < n:\n if nums1[i] < nums2[j]:\n nums.append(nums1[i])\n i += 1\n else:\n nums.append(nums2[j])\n j += 1\nif i == m:\n while j < n:\n nums.append(nums2[j])\n j += 1\nelif j == n:... | <|body_start_0|>
m = len(nums1)
n = len(nums2)
nums = []
k = m + n
i = 0
j = 0
while i < m and j < n:
if nums1[i] < nums2[j]:
nums.append(nums1[i])
i += 1
else:
nums.append(nums2[j])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def findMedianSortedArrays0(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_1|... | stack_v2_sparse_classes_36k_train_016184 | 1,204 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays",
"signature": "def findMedianSortedArrays(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays0",
... | 2 | stack_v2_sparse_classes_30k_train_013291 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def findMedianSortedArrays0(self, nums1, nums2): :type nums1: List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def findMedianSortedArrays0(self, nums1, nums2): :type nums1: List[i... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def findMedianSortedArrays0(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
m = len(nums1)
n = len(nums2)
nums = []
k = m + n
i = 0
j = 0
while i < m and j < n:
if nums1[i] < nums2[j]:
... | the_stack_v2_python_sparse | PythonCode/src/0004_Median_of_Two_Sorted_Arrays.py | oneyuan/CodeforFun | train | 0 | |
d4e65a56479f777f51287bd420d01f3268674805 | [
"QgsMapLayerRenderer.__init__(self, layer.id())\nself.context = context\nself.controller = ImajnetOpenlayersController(None, context, webPage, layerType)\nself.loop = None",
"debug('[WORKER THREAD] Calling request() asynchronously', 3)\nQMetaObject.invokeMethod(self.controller, 'request')\ntimer = QTimer()\ntimer... | <|body_start_0|>
QgsMapLayerRenderer.__init__(self, layer.id())
self.context = context
self.controller = ImajnetOpenlayersController(None, context, webPage, layerType)
self.loop = None
<|end_body_0|>
<|body_start_1|>
debug('[WORKER THREAD] Calling request() asynchronously', 3)
... | ImajnetOpenlayersRenderer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImajnetOpenlayersRenderer:
def __init__(self, layer, context, webPage, layerType):
"""Initialize the object. This function is still run in the GUI thread. Should refrain from doing any heavy work."""
<|body_0|>
def render(self):
"""do the rendering. This function is ... | stack_v2_sparse_classes_36k_train_016185 | 18,957 | no_license | [
{
"docstring": "Initialize the object. This function is still run in the GUI thread. Should refrain from doing any heavy work.",
"name": "__init__",
"signature": "def __init__(self, layer, context, webPage, layerType)"
},
{
"docstring": "do the rendering. This function is called in the worker th... | 3 | stack_v2_sparse_classes_30k_train_010897 | Implement the Python class `ImajnetOpenlayersRenderer` described below.
Class description:
Implement the ImajnetOpenlayersRenderer class.
Method signatures and docstrings:
- def __init__(self, layer, context, webPage, layerType): Initialize the object. This function is still run in the GUI thread. Should refrain from... | Implement the Python class `ImajnetOpenlayersRenderer` described below.
Class description:
Implement the ImajnetOpenlayersRenderer class.
Method signatures and docstrings:
- def __init__(self, layer, context, webPage, layerType): Initialize the object. This function is still run in the GUI thread. Should refrain from... | bc44d2e6ce840fe67da83e9b11c2a63119b6d99d | <|skeleton|>
class ImajnetOpenlayersRenderer:
def __init__(self, layer, context, webPage, layerType):
"""Initialize the object. This function is still run in the GUI thread. Should refrain from doing any heavy work."""
<|body_0|>
def render(self):
"""do the rendering. This function is ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImajnetOpenlayersRenderer:
def __init__(self, layer, context, webPage, layerType):
"""Initialize the object. This function is still run in the GUI thread. Should refrain from doing any heavy work."""
QgsMapLayerRenderer.__init__(self, layer.id())
self.context = context
self.con... | the_stack_v2_python_sparse | openlayers/openlayers_layer.py | imajing/imajnet-qgis-plugin | train | 1 | |
6b76bd1cd1a9b94de22650905143d43a38582306 | [
"super().vet()\nif 'rdx' not in self.config.keys() or 'spectrograph' not in self.config['rdx'].keys():\n msgs.error(f'Missing spectrograph in the Parameter block of your .coadd2d file. Add it!')\nmsgs.info('.cube file successfully vetted.')",
"opts = dict(scale_corr=None, skysub_frame=None)\nscale_corr = self... | <|body_start_0|>
super().vet()
if 'rdx' not in self.config.keys() or 'spectrograph' not in self.config['rdx'].keys():
msgs.error(f'Missing spectrograph in the Parameter block of your .coadd2d file. Add it!')
msgs.info('.cube file successfully vetted.')
<|end_body_0|>
<|body_start_1... | Child class for coadding spec2d files into datacubes | Coadd3DFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Coadd3DFile:
"""Child class for coadding spec2d files into datacubes"""
def vet(self):
"""Check for required bits and pieces of the .coadd2d file besides the input objects themselves"""
<|body_0|>
def options(self):
"""Parse the options associated with a cube blo... | stack_v2_sparse_classes_36k_train_016186 | 31,807 | permissive | [
{
"docstring": "Check for required bits and pieces of the .coadd2d file besides the input objects themselves",
"name": "vet",
"signature": "def vet(self)"
},
{
"docstring": "Parse the options associated with a cube block. Here is a description of the available options: - ``scale_corr``: The name... | 2 | null | Implement the Python class `Coadd3DFile` described below.
Class description:
Child class for coadding spec2d files into datacubes
Method signatures and docstrings:
- def vet(self): Check for required bits and pieces of the .coadd2d file besides the input objects themselves
- def options(self): Parse the options assoc... | Implement the Python class `Coadd3DFile` described below.
Class description:
Child class for coadding spec2d files into datacubes
Method signatures and docstrings:
- def vet(self): Check for required bits and pieces of the .coadd2d file besides the input objects themselves
- def options(self): Parse the options assoc... | 0d2e2196afc6904050b1af4d572f5c643bb07e38 | <|skeleton|>
class Coadd3DFile:
"""Child class for coadding spec2d files into datacubes"""
def vet(self):
"""Check for required bits and pieces of the .coadd2d file besides the input objects themselves"""
<|body_0|>
def options(self):
"""Parse the options associated with a cube blo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Coadd3DFile:
"""Child class for coadding spec2d files into datacubes"""
def vet(self):
"""Check for required bits and pieces of the .coadd2d file besides the input objects themselves"""
super().vet()
if 'rdx' not in self.config.keys() or 'spectrograph' not in self.config['rdx'].ke... | the_stack_v2_python_sparse | pypeit/inputfiles.py | pypeit/PypeIt | train | 136 |
2f6668ca25d618767878ed8759bb638bf4ee5690 | [
"if len(digits) == 0:\n return []\nres = []\nself.__dfs(digits, 0, '', res)\nreturn res",
"if index == len(digits):\n res.append(pre)\n return\ns = self.digits_array[int(digits[index])]\nfor alpha in s:\n self.__dfs(digits, index + 1, pre + alpha, res)"
] | <|body_start_0|>
if len(digits) == 0:
return []
res = []
self.__dfs(digits, 0, '', res)
return res
<|end_body_0|>
<|body_start_1|>
if index == len(digits):
res.append(pre)
return
s = self.digits_array[int(digits[index])]
for al... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def __dfs(self, digits, index, pre, res):
""":param digits: 字母表,全局 :param index: 当前看第几个数字 :param pre: 已经得到的字符串 :param res: 保存最终结果 :return:"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_016187 | 1,113 | permissive | [
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits)"
},
{
"docstring": ":param digits: 字母表,全局 :param index: 当前看第几个数字 :param pre: 已经得到的字符串 :param res: 保存最终结果 :return:",
"name": "__dfs",
"signature": "def __... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def __dfs(self, digits, index, pre, res): :param digits: 字母表,全局 :param index: 当前看第几个数字 :param pre: 已经得... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def __dfs(self, digits, index, pre, res): :param digits: 字母表,全局 :param index: 当前看第几个数字 :param pre: 已经得... | b484ae4c4e9f9186232e31f2de11720aebb42968 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def __dfs(self, digits, index, pre, res):
""":param digits: 字母表,全局 :param index: 当前看第几个数字 :param pre: 已经得到的字符串 :param res: 保存最终结果 :return:"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
if len(digits) == 0:
return []
res = []
self.__dfs(digits, 0, '', res)
return res
def __dfs(self, digits, index, pre, res):
""":param digits: 字母表,全局 :param... | the_stack_v2_python_sparse | 08-递归和回溯法/0017-电话号码的字母组合.py | Sytx74/LeetCode-Solution-Python | train | 0 | |
5279be123f7f6bc9cea2641601a62070ae56e064 | [
"self.net = net\nself.data = data\nself.optimizer = optimizer\nself.loss = loss\nself.step = step\nself.seed = 33",
"paddle.enable_static()\npaddle.disable_static()\npaddle.seed(self.seed)\nnp.random.seed(self.seed)",
"reset(self.seed)\nnet = self.net.get_layer()\nnet.train()\nopt = self.optimizer.get_opt(net=n... | <|body_start_0|>
self.net = net
self.data = data
self.optimizer = optimizer
self.loss = loss
self.step = step
self.seed = 33
<|end_body_0|>
<|body_start_1|>
paddle.enable_static()
paddle.disable_static()
paddle.seed(self.seed)
np.random.se... | 构建Layer训练的通用类 | LayerTrain | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerTrain:
"""构建Layer训练的通用类"""
def __init__(self, net, data, optimizer, loss, step):
"""初始化"""
<|body_0|>
def reset(self):
"""重置模型图 :return:"""
<|body_1|>
def dy_train(self):
"""dygraph train"""
<|body_2|>
def dy_train_dl(self):... | stack_v2_sparse_classes_36k_train_016188 | 4,955 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self, net, data, optimizer, loss, step)"
},
{
"docstring": "重置模型图 :return:",
"name": "reset",
"signature": "def reset(self)"
},
{
"docstring": "dygraph train",
"name": "dy_train",
"signature": "def dy_tr... | 6 | stack_v2_sparse_classes_30k_train_020993 | Implement the Python class `LayerTrain` described below.
Class description:
构建Layer训练的通用类
Method signatures and docstrings:
- def __init__(self, net, data, optimizer, loss, step): 初始化
- def reset(self): 重置模型图 :return:
- def dy_train(self): dygraph train
- def dy_train_dl(self): dygraph train with dataloader
- def dy2... | Implement the Python class `LayerTrain` described below.
Class description:
构建Layer训练的通用类
Method signatures and docstrings:
- def __init__(self, net, data, optimizer, loss, step): 初始化
- def reset(self): 重置模型图 :return:
- def dy_train(self): dygraph train
- def dy_train_dl(self): dygraph train with dataloader
- def dy2... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class LayerTrain:
"""构建Layer训练的通用类"""
def __init__(self, net, data, optimizer, loss, step):
"""初始化"""
<|body_0|>
def reset(self):
"""重置模型图 :return:"""
<|body_1|>
def dy_train(self):
"""dygraph train"""
<|body_2|>
def dy_train_dl(self):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LayerTrain:
"""构建Layer训练的通用类"""
def __init__(self, net, data, optimizer, loss, step):
"""初始化"""
self.net = net
self.data = data
self.optimizer = optimizer
self.loss = loss
self.step = step
self.seed = 33
def reset(self):
"""重置模型图 :retur... | the_stack_v2_python_sparse | framework/e2e/paddleLT/donotuse/train_origin.py | PaddlePaddle/PaddleTest | train | 42 |
1780b5328a560e63ce923341386ebb153a00d772 | [
"try:\n timestamp = self._ReadStructureFromByteStream(registry_value, 0, self._GetDataTypeMap('filetime'))\nexcept (ValueError, errors.ParseError) as exception:\n raise errors.ParseError('Unable to parse timestamp with error: {0!s}'.format(exception))\nreturn timestamp",
"for sid_key in registry_key.GetSubk... | <|body_start_0|>
try:
timestamp = self._ReadStructureFromByteStream(registry_value, 0, self._GetDataTypeMap('filetime'))
except (ValueError, errors.ParseError) as exception:
raise errors.ParseError('Unable to parse timestamp with error: {0!s}'.format(exception))
return ti... | Background Activity Moderator data Windows Registry plugin. | BackgroundActivityModeratorWindowsRegistryPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackgroundActivityModeratorWindowsRegistryPlugin:
"""Background Activity Moderator data Windows Registry plugin."""
def _ParseValue(self, registry_value):
"""Parses the registry value. Args: registry_value (bytes): value data. Returns: int: timestamp. Raises: ParseError: if the value... | stack_v2_sparse_classes_36k_train_016189 | 3,301 | permissive | [
{
"docstring": "Parses the registry value. Args: registry_value (bytes): value data. Returns: int: timestamp. Raises: ParseError: if the value data could not be parsed.",
"name": "_ParseValue",
"signature": "def _ParseValue(self, registry_value)"
},
{
"docstring": "Extracts events from a Windows... | 2 | null | Implement the Python class `BackgroundActivityModeratorWindowsRegistryPlugin` described below.
Class description:
Background Activity Moderator data Windows Registry plugin.
Method signatures and docstrings:
- def _ParseValue(self, registry_value): Parses the registry value. Args: registry_value (bytes): value data. ... | Implement the Python class `BackgroundActivityModeratorWindowsRegistryPlugin` described below.
Class description:
Background Activity Moderator data Windows Registry plugin.
Method signatures and docstrings:
- def _ParseValue(self, registry_value): Parses the registry value. Args: registry_value (bytes): value data. ... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class BackgroundActivityModeratorWindowsRegistryPlugin:
"""Background Activity Moderator data Windows Registry plugin."""
def _ParseValue(self, registry_value):
"""Parses the registry value. Args: registry_value (bytes): value data. Returns: int: timestamp. Raises: ParseError: if the value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BackgroundActivityModeratorWindowsRegistryPlugin:
"""Background Activity Moderator data Windows Registry plugin."""
def _ParseValue(self, registry_value):
"""Parses the registry value. Args: registry_value (bytes): value data. Returns: int: timestamp. Raises: ParseError: if the value data could n... | the_stack_v2_python_sparse | plaso/parsers/winreg_plugins/bam.py | log2timeline/plaso | train | 1,506 |
a7b7a313e91f7871bafbd35258aeaecce20a4700 | [
"def preorder(node):\n if node:\n return f'{node.val}' + ',' + preorder(node.left) + ',' + preorder(node.right)\n else:\n return 'None'\nreturn preorder(root)",
"def preorder():\n val = data.pop()\n if val == 'None':\n return None\n node = TreeNode(int(val))\n node.left = pr... | <|body_start_0|>
def preorder(node):
if node:
return f'{node.val}' + ',' + preorder(node.left) + ',' + preorder(node.right)
else:
return 'None'
return preorder(root)
<|end_body_0|>
<|body_start_1|>
def preorder():
val = data.po... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_016190 | 1,549 | 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_018213 | 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:... | 1903829812e2fb72ca3941c906db408b6ab56a54 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def preorder(node):
if node:
return f'{node.val}' + ',' + preorder(node.left) + ',' + preorder(node.right)
else:
return 'None'
... | the_stack_v2_python_sparse | blind_75_leetcode/python/s0297_serialize_and_deserialize_binary_tree.py | livexia/algorithm | train | 2 | |
b973f7bf6c3e559bda63e1e7ccd02b8350b21eb3 | [
"self.ex = ex\nself.lc = lightcurve\nif self.lc is not None:\n for p1 in self.lc:\n for p2 in self.lc:\n if p1.index == p2.index and p1 is not p2:\n raise ValueError('Two lightcurve points supplied for sameimage index.')",
"if self.lc is None:\n return self.ex\nelse:\n fo... | <|body_start_0|>
self.ex = ex
self.lc = lightcurve
if self.lc is not None:
for p1 in self.lc:
for p2 in self.lc:
if p1.index == p2.index and p1 is not p2:
raise ValueError('Two lightcurve points supplied for sameimage index.... | Defines a MockSource for generating mock source lists. (These can be used to test the database routines.) When initialised with a transient lightcurve (a list of MockLCPoint tuples), the source lists can be populated with non-detections (zero measurements) at the images for which the lightcurve is not defined. When the... | MockSource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MockSource:
"""Defines a MockSource for generating mock source lists. (These can be used to test the database routines.) When initialised with a transient lightcurve (a list of MockLCPoint tuples), the source lists can be populated with non-detections (zero measurements) at the images for which t... | stack_v2_sparse_classes_36k_train_016191 | 15,221 | no_license | [
{
"docstring": "*Args* `ex`: template `extractedsource`, Defines the position, etc. If no lightcurve is supplied, then these details are used to model a fixed source. `lightcurve`: A list of `MockLightcurvePoint`s, defining a transient lightcurve.",
"name": "__init__",
"signature": "def __init__(self, e... | 3 | stack_v2_sparse_classes_30k_train_000219 | Implement the Python class `MockSource` described below.
Class description:
Defines a MockSource for generating mock source lists. (These can be used to test the database routines.) When initialised with a transient lightcurve (a list of MockLCPoint tuples), the source lists can be populated with non-detections (zero ... | Implement the Python class `MockSource` described below.
Class description:
Defines a MockSource for generating mock source lists. (These can be used to test the database routines.) When initialised with a transient lightcurve (a list of MockLCPoint tuples), the source lists can be populated with non-detections (zero ... | 8c3a91c9dd2338bf88c1e13b7c8332223aaec508 | <|skeleton|>
class MockSource:
"""Defines a MockSource for generating mock source lists. (These can be used to test the database routines.) When initialised with a transient lightcurve (a list of MockLCPoint tuples), the source lists can be populated with non-detections (zero measurements) at the images for which t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MockSource:
"""Defines a MockSource for generating mock source lists. (These can be used to test the database routines.) When initialised with a transient lightcurve (a list of MockLCPoint tuples), the source lists can be populated with non-detections (zero measurements) at the images for which the lightcurve... | the_stack_v2_python_sparse | tkp/testutil/db_subs.py | hughbg/tkp | train | 2 |
1f129b32690030aa5b21e971a5a0c7864e8f7cb5 | [
"assert hasattr(obj, 'ssh_targets'), f'{obj.__class__.__name__} objects do not have the .ssh_targets attribute'\nassert hasattr(obj, 'running_tasks'), f'{obj.__class__.__name__} objects do not have the .running_tasks attribute'\ntarget = None\ncontainer_name = None\nif choose:\n running_tasks = sorted(obj.runnin... | <|body_start_0|>
assert hasattr(obj, 'ssh_targets'), f'{obj.__class__.__name__} objects do not have the .ssh_targets attribute'
assert hasattr(obj, 'running_tasks'), f'{obj.__class__.__name__} objects do not have the .running_tasks attribute'
target = None
container_name = None
i... | ObjectDockerExecController | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectDockerExecController:
def get_ssh_exec_target(self, obj: SupportsService, choose: bool=False) -> Tuple[Optional[Instance], Optional[str]]:
"""Return an (instance, container_name) tuple suitable for using to exec into a particular container on a particular instance. .. note:: This i... | stack_v2_sparse_classes_36k_train_016192 | 13,998 | permissive | [
{
"docstring": "Return an (instance, container_name) tuple suitable for using to exec into a particular container on a particular instance. .. note:: This is for EC2 backed services only. For FARGATE services, use ``self.get_ecs_exec_target()``. If ``choose`` is ``False``, return (None, None). If ``choose`` is ... | 3 | stack_v2_sparse_classes_30k_train_008784 | Implement the Python class `ObjectDockerExecController` described below.
Class description:
Implement the ObjectDockerExecController class.
Method signatures and docstrings:
- def get_ssh_exec_target(self, obj: SupportsService, choose: bool=False) -> Tuple[Optional[Instance], Optional[str]]: Return an (instance, cont... | Implement the Python class `ObjectDockerExecController` described below.
Class description:
Implement the ObjectDockerExecController class.
Method signatures and docstrings:
- def get_ssh_exec_target(self, obj: SupportsService, choose: bool=False) -> Tuple[Optional[Instance], Optional[str]]: Return an (instance, cont... | caa4698da812f5291a47366f307c1abebb4a989c | <|skeleton|>
class ObjectDockerExecController:
def get_ssh_exec_target(self, obj: SupportsService, choose: bool=False) -> Tuple[Optional[Instance], Optional[str]]:
"""Return an (instance, container_name) tuple suitable for using to exec into a particular container on a particular instance. .. note:: This i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectDockerExecController:
def get_ssh_exec_target(self, obj: SupportsService, choose: bool=False) -> Tuple[Optional[Instance], Optional[str]]:
"""Return an (instance, container_name) tuple suitable for using to exec into a particular container on a particular instance. .. note:: This is for EC2 back... | the_stack_v2_python_sparse | deployfish/controllers/network.py | caltechads/deployfish | train | 98 | |
34d044002269d8927a730fb717cd768e0e0445e5 | [
"inf = sys.maxsize\ngraph = [[inf for _ in range(n)] for _ in range(n)]\nfor i in range(n):\n graph[i][i] = 0\nfor u, v, w in edges:\n graph[u][v] = w\n graph[v][u] = w\nfor k in range(n):\n for i in range(n):\n for j in range(n):\n graph[i][j] = min(graph[i][j], graph[i][k] + graph[k]... | <|body_start_0|>
inf = sys.maxsize
graph = [[inf for _ in range(n)] for _ in range(n)]
for i in range(n):
graph[i][i] = 0
for u, v, w in edges:
graph[u][v] = w
graph[v][u] = w
for k in range(n):
for i in range(n):
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTheCityFloyd(self, n, edges, distanceThreshold):
""":type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int"""
<|body_0|>
def findTheCity(self, n, edges, distanceThreshold):
""":type n: int :type edges: List[List[int]] :ty... | stack_v2_sparse_classes_36k_train_016193 | 4,208 | no_license | [
{
"docstring": ":type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int",
"name": "findTheCityFloyd",
"signature": "def findTheCityFloyd(self, n, edges, distanceThreshold)"
},
{
"docstring": ":type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype... | 2 | stack_v2_sparse_classes_30k_train_003414 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTheCityFloyd(self, n, edges, distanceThreshold): :type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int
- def findTheCity(self, n, edges, dist... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTheCityFloyd(self, n, edges, distanceThreshold): :type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int
- def findTheCity(self, n, edges, dist... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def findTheCityFloyd(self, n, edges, distanceThreshold):
""":type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int"""
<|body_0|>
def findTheCity(self, n, edges, distanceThreshold):
""":type n: int :type edges: List[List[int]] :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findTheCityFloyd(self, n, edges, distanceThreshold):
""":type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int"""
inf = sys.maxsize
graph = [[inf for _ in range(n)] for _ in range(n)]
for i in range(n):
graph[i][i] = 0
... | the_stack_v2_python_sparse | F/FindTheCityWithTheSmallestNumberOfNeighborsAtAThresholdDistance.py | bssrdf/pyleet | train | 2 | |
b0feb00089da238d21232a3ad6165f89379a1c29 | [
"self.kind = kind\nif not axes:\n _, self.ax = plt.subplots(1, 1)\nelse:\n self.ax = axes\nself.ax.set_xscale('log')\nif self.kind == TisserandKind.APSIS:\n self.ax.set_yscale('log')",
"body_rv = get_mean_elements(body).to_vectors()\nR_body, V_body = (norm(body_rv.r), norm(body_rv.v))\nvinf_array = np.li... | <|body_start_0|>
self.kind = kind
if not axes:
_, self.ax = plt.subplots(1, 1)
else:
self.ax = axes
self.ax.set_xscale('log')
if self.kind == TisserandKind.APSIS:
self.ax.set_yscale('log')
<|end_body_0|>
<|body_start_1|>
body_rv = get_... | Generates Tisserand figures. | TisserandPlotter | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TisserandPlotter:
"""Generates Tisserand figures."""
def __init__(self, kind=TisserandKind.APSIS, axes=None):
"""Object initializer. Parameters ---------- kind : TisserandKind Nature for the Tisserand axes : ~matplotlib.pyplot.axes Axes for the figure"""
<|body_0|>
def _... | stack_v2_sparse_classes_36k_train_016194 | 6,084 | permissive | [
{
"docstring": "Object initializer. Parameters ---------- kind : TisserandKind Nature for the Tisserand axes : ~matplotlib.pyplot.axes Axes for the figure",
"name": "__init__",
"signature": "def __init__(self, kind=TisserandKind.APSIS, axes=None)"
},
{
"docstring": "Solves all possible Tisserand... | 5 | null | Implement the Python class `TisserandPlotter` described below.
Class description:
Generates Tisserand figures.
Method signatures and docstrings:
- def __init__(self, kind=TisserandKind.APSIS, axes=None): Object initializer. Parameters ---------- kind : TisserandKind Nature for the Tisserand axes : ~matplotlib.pyplot.... | Implement the Python class `TisserandPlotter` described below.
Class description:
Generates Tisserand figures.
Method signatures and docstrings:
- def __init__(self, kind=TisserandKind.APSIS, axes=None): Object initializer. Parameters ---------- kind : TisserandKind Nature for the Tisserand axes : ~matplotlib.pyplot.... | 55e96432b27301c5dffb4ef6b4f383d970c6e9c0 | <|skeleton|>
class TisserandPlotter:
"""Generates Tisserand figures."""
def __init__(self, kind=TisserandKind.APSIS, axes=None):
"""Object initializer. Parameters ---------- kind : TisserandKind Nature for the Tisserand axes : ~matplotlib.pyplot.axes Axes for the figure"""
<|body_0|>
def _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TisserandPlotter:
"""Generates Tisserand figures."""
def __init__(self, kind=TisserandKind.APSIS, axes=None):
"""Object initializer. Parameters ---------- kind : TisserandKind Nature for the Tisserand axes : ~matplotlib.pyplot.axes Axes for the figure"""
self.kind = kind
if not ax... | the_stack_v2_python_sparse | src/poliastro/plotting/tisserand.py | poliastro/poliastro | train | 814 |
6cec8e4c35586191b17329054091208f79726bb9 | [
"if years[0] is None:\n raise ValueError('Person has no birth year.')\nif years[1] is not None and years[1] < years[0]:\n raise ValueError('Birth year must be before death year.')\nself.birth_year = years[0]\nself.death_year = years[1]",
"if self.death_year is None:\n return True\nreturn year >= self.bir... | <|body_start_0|>
if years[0] is None:
raise ValueError('Person has no birth year.')
if years[1] is not None and years[1] < years[0]:
raise ValueError('Birth year must be before death year.')
self.birth_year = years[0]
self.death_year = years[1]
<|end_body_0|>
<|b... | Class simulates a person's lifespan. Attributes: birth_year: An int. death_year: An int. | Person | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Person:
"""Class simulates a person's lifespan. Attributes: birth_year: An int. death_year: An int."""
def __init__(self, years):
"""Inits a valid Person instance when input tuple is valid, and raises a ValueError otherwise."""
<|body_0|>
def was_alive(self, year):
... | stack_v2_sparse_classes_36k_train_016195 | 8,147 | no_license | [
{
"docstring": "Inits a valid Person instance when input tuple is valid, and raises a ValueError otherwise.",
"name": "__init__",
"signature": "def __init__(self, years)"
},
{
"docstring": "Returns whether or not a person was alive at year.",
"name": "was_alive",
"signature": "def was_al... | 2 | stack_v2_sparse_classes_30k_train_018308 | Implement the Python class `Person` described below.
Class description:
Class simulates a person's lifespan. Attributes: birth_year: An int. death_year: An int.
Method signatures and docstrings:
- def __init__(self, years): Inits a valid Person instance when input tuple is valid, and raises a ValueError otherwise.
- ... | Implement the Python class `Person` described below.
Class description:
Class simulates a person's lifespan. Attributes: birth_year: An int. death_year: An int.
Method signatures and docstrings:
- def __init__(self, years): Inits a valid Person instance when input tuple is valid, and raises a ValueError otherwise.
- ... | 1afd046e6f88ddf10c7411b0bc7a594d627ea66b | <|skeleton|>
class Person:
"""Class simulates a person's lifespan. Attributes: birth_year: An int. death_year: An int."""
def __init__(self, years):
"""Inits a valid Person instance when input tuple is valid, and raises a ValueError otherwise."""
<|body_0|>
def was_alive(self, year):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Person:
"""Class simulates a person's lifespan. Attributes: birth_year: An int. death_year: An int."""
def __init__(self, years):
"""Inits a valid Person instance when input tuple is valid, and raises a ValueError otherwise."""
if years[0] is None:
raise ValueError('Person has... | the_stack_v2_python_sparse | c16/c16p10.py | jake-albert/py-algs | train | 1 |
bb57c4f644e73890c91153f87777fe72c7adcdcc | [
"if self.layout:\n return self.layout.template_name\nreturn self.fallback_template",
"content_type = ContentType.objects.get_for_model(self)\nresult = False\nif self.layout:\n for data in self.layout.get_placeholder_data():\n placeholder, created = Placeholder.objects.update_or_create(parent_type=con... | <|body_start_0|>
if self.layout:
return self.layout.template_name
return self.fallback_template
<|end_body_0|>
<|body_start_1|>
content_type = ContentType.objects.get_for_model(self)
result = False
if self.layout:
for data in self.layout.get_placeholder_d... | Add ``layout`` field to models that already have ``contentitem_set`` and ``placeholder_set`` fields. | LayoutFieldMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayoutFieldMixin:
"""Add ``layout`` field to models that already have ``contentitem_set`` and ``placeholder_set`` fields."""
def get_layout_template_name(self):
"""Return ``layout.template_name`` or `fallback_template``."""
<|body_0|>
def add_missing_placeholders(self):
... | stack_v2_sparse_classes_36k_train_016196 | 15,510 | permissive | [
{
"docstring": "Return ``layout.template_name`` or `fallback_template``.",
"name": "get_layout_template_name",
"signature": "def get_layout_template_name(self)"
},
{
"docstring": "Add missing placeholders from templates. Return `True` if any missing placeholders were created.",
"name": "add_... | 2 | null | Implement the Python class `LayoutFieldMixin` described below.
Class description:
Add ``layout`` field to models that already have ``contentitem_set`` and ``placeholder_set`` fields.
Method signatures and docstrings:
- def get_layout_template_name(self): Return ``layout.template_name`` or `fallback_template``.
- def ... | Implement the Python class `LayoutFieldMixin` described below.
Class description:
Add ``layout`` field to models that already have ``contentitem_set`` and ``placeholder_set`` fields.
Method signatures and docstrings:
- def get_layout_template_name(self): Return ``layout.template_name`` or `fallback_template``.
- def ... | c507ea5b1864303732c53ad7c5800571fca5fa94 | <|skeleton|>
class LayoutFieldMixin:
"""Add ``layout`` field to models that already have ``contentitem_set`` and ``placeholder_set`` fields."""
def get_layout_template_name(self):
"""Return ``layout.template_name`` or `fallback_template``."""
<|body_0|>
def add_missing_placeholders(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LayoutFieldMixin:
"""Add ``layout`` field to models that already have ``contentitem_set`` and ``placeholder_set`` fields."""
def get_layout_template_name(self):
"""Return ``layout.template_name`` or `fallback_template``."""
if self.layout:
return self.layout.template_name
... | the_stack_v2_python_sparse | icekit/mixins.py | ic-labs/django-icekit | train | 53 |
6ca7afc0b45203b1b5fd53ad4a0b91c1e7cf6886 | [
"EasyFrame.__init__(self, title='Canvas Demo 2')\nself.colors = ('blue', 'green', 'red', 'yellow')\nself.shapes = list()\nself.canvas = self.addCanvas(row=0, column=0, columnspan=2, width=300, height=150, background='gray')\nself.addButton(text='Draw oval', row=1, column=0, command=self.drawOval)\nself.addButton(te... | <|body_start_0|>
EasyFrame.__init__(self, title='Canvas Demo 2')
self.colors = ('blue', 'green', 'red', 'yellow')
self.shapes = list()
self.canvas = self.addCanvas(row=0, column=0, columnspan=2, width=300, height=150, background='gray')
self.addButton(text='Draw oval', row=1, col... | Draws filled ovals on a canvas, and allows the user to erase them all. | CanvasDemo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanvasDemo:
"""Draws filled ovals on a canvas, and allows the user to erase them all."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def drawOval(self):
"""Draws a filled oval at a random position."""
<|body_1|>
def eraseAll(... | stack_v2_sparse_classes_36k_train_016197 | 1,550 | no_license | [
{
"docstring": "Sets up the window and widgets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Draws a filled oval at a random position.",
"name": "drawOval",
"signature": "def drawOval(self)"
},
{
"docstring": "Deletes all ovals from the canvas.",
... | 3 | stack_v2_sparse_classes_30k_train_003153 | Implement the Python class `CanvasDemo` described below.
Class description:
Draws filled ovals on a canvas, and allows the user to erase them all.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def drawOval(self): Draws a filled oval at a random position.
- def eraseAll(self... | Implement the Python class `CanvasDemo` described below.
Class description:
Draws filled ovals on a canvas, and allows the user to erase them all.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def drawOval(self): Draws a filled oval at a random position.
- def eraseAll(self... | eca69d000dc77681a30734b073b2383c97ccc02e | <|skeleton|>
class CanvasDemo:
"""Draws filled ovals on a canvas, and allows the user to erase them all."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def drawOval(self):
"""Draws a filled oval at a random position."""
<|body_1|>
def eraseAll(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CanvasDemo:
"""Draws filled ovals on a canvas, and allows the user to erase them all."""
def __init__(self):
"""Sets up the window and widgets."""
EasyFrame.__init__(self, title='Canvas Demo 2')
self.colors = ('blue', 'green', 'red', 'yellow')
self.shapes = list()
... | the_stack_v2_python_sparse | gui/breezy/canvasdemo2.py | lforet/robomow | train | 11 |
8517d9e912d5303ef3859e8458739acdb2b43c4a | [
"self.plugin_package = plugin_package\nself.reload_plugins()\nself._disable = False",
"self.plugins = []\nself.seen_paths = []\nlogger.info(f'Looking for plugins under package {self.plugin_package}')\nself.walk_package(self.plugin_package)",
"if not isinstance(disable, bool):\n logger.warning('Disable must b... | <|body_start_0|>
self.plugin_package = plugin_package
self.reload_plugins()
self._disable = False
<|end_body_0|>
<|body_start_1|>
self.plugins = []
self.seen_paths = []
logger.info(f'Looking for plugins under package {self.plugin_package}')
self.walk_package(self... | Upon creation, this class will read the plugins package for modules that contain a class definition that is inheriting from the Plugin class | PluginCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PluginCollection:
"""Upon creation, this class will read the plugins package for modules that contain a class definition that is inheriting from the Plugin class"""
def __init__(self, plugin_package):
"""Constructor that initiates the reading of all available plugins when an instance... | stack_v2_sparse_classes_36k_train_016198 | 4,543 | no_license | [
{
"docstring": "Constructor that initiates the reading of all available plugins when an instance of the PluginCollection object is created",
"name": "__init__",
"signature": "def __init__(self, plugin_package)"
},
{
"docstring": "Reset the list of all plugins and initiate the walk over the main ... | 5 | stack_v2_sparse_classes_30k_train_009369 | Implement the Python class `PluginCollection` described below.
Class description:
Upon creation, this class will read the plugins package for modules that contain a class definition that is inheriting from the Plugin class
Method signatures and docstrings:
- def __init__(self, plugin_package): Constructor that initia... | Implement the Python class `PluginCollection` described below.
Class description:
Upon creation, this class will read the plugins package for modules that contain a class definition that is inheriting from the Plugin class
Method signatures and docstrings:
- def __init__(self, plugin_package): Constructor that initia... | 2d4b3c76ea817880485f6ac3bb26a9ca2c035037 | <|skeleton|>
class PluginCollection:
"""Upon creation, this class will read the plugins package for modules that contain a class definition that is inheriting from the Plugin class"""
def __init__(self, plugin_package):
"""Constructor that initiates the reading of all available plugins when an instance... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PluginCollection:
"""Upon creation, this class will read the plugins package for modules that contain a class definition that is inheriting from the Plugin class"""
def __init__(self, plugin_package):
"""Constructor that initiates the reading of all available plugins when an instance of the Plugi... | the_stack_v2_python_sparse | libs/plugin_collection.py | AlexLaur/py-encoder | train | 0 |
646a4472c7b7854f7b7535e3468135850692b274 | [
"Polynomial.__init__(self, coefficients)\nif self.getDegree() != 2:\n raise PolynomialError('Not a quadratic polynomial.')",
"a, b, c = (self.getCoefficients()[2], self.getCoefficients()[1], self.getCoefficients()[0])\ndelta = b ** 2 - 4 * a * c\nif delta >= 0:\n roots = sorted([(-b - math.sqrt(delta)) / (2... | <|body_start_0|>
Polynomial.__init__(self, coefficients)
if self.getDegree() != 2:
raise PolynomialError('Not a quadratic polynomial.')
<|end_body_0|>
<|body_start_1|>
a, b, c = (self.getCoefficients()[2], self.getCoefficients()[1], self.getCoefficients()[0])
delta = b ** 2 ... | QuadraticPolynomial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuadraticPolynomial:
def __init__(self, coefficients):
"""Exercise 10"""
<|body_0|>
def getRoots(self):
"""Exercise 11 Get roots of a quadratic polynomial"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Polynomial.__init__(self, coefficients)
... | stack_v2_sparse_classes_36k_train_016199 | 12,688 | no_license | [
{
"docstring": "Exercise 10",
"name": "__init__",
"signature": "def __init__(self, coefficients)"
},
{
"docstring": "Exercise 11 Get roots of a quadratic polynomial",
"name": "getRoots",
"signature": "def getRoots(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004810 | Implement the Python class `QuadraticPolynomial` described below.
Class description:
Implement the QuadraticPolynomial class.
Method signatures and docstrings:
- def __init__(self, coefficients): Exercise 10
- def getRoots(self): Exercise 11 Get roots of a quadratic polynomial | Implement the Python class `QuadraticPolynomial` described below.
Class description:
Implement the QuadraticPolynomial class.
Method signatures and docstrings:
- def __init__(self, coefficients): Exercise 10
- def getRoots(self): Exercise 11 Get roots of a quadratic polynomial
<|skeleton|>
class QuadraticPolynomial:... | a47c529a7085233ba7d7f484316d1cdd3b542df4 | <|skeleton|>
class QuadraticPolynomial:
def __init__(self, coefficients):
"""Exercise 10"""
<|body_0|>
def getRoots(self):
"""Exercise 11 Get roots of a quadratic polynomial"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuadraticPolynomial:
def __init__(self, coefficients):
"""Exercise 10"""
Polynomial.__init__(self, coefficients)
if self.getDegree() != 2:
raise PolynomialError('Not a quadratic polynomial.')
def getRoots(self):
"""Exercise 11 Get roots of a quadratic polynomia... | the_stack_v2_python_sparse | Lesson2/TD/Polynomial_Solutions.py | riduan91/DSC101 | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.