blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b7ae12437727c5f89d006f643674c018db505e04 | [
"audio = np.empty((1,))\nsecs_loaded = 0\nfiles_loaded = 0\nfiles = glob.glob(path + '*.wav')\nfor file in files:\n sr, samples = wavfile.read(file)\n audio = np.concatenate((audio, samples))\n dur = len(samples) / sr\n secs_loaded = secs_loaded + dur\n files_loaded = files_loaded + 1\n if secs_lo... | <|body_start_0|>
audio = np.empty((1,))
secs_loaded = 0
files_loaded = 0
files = glob.glob(path + '*.wav')
for file in files:
sr, samples = wavfile.read(file)
audio = np.concatenate((audio, samples))
dur = len(samples) / sr
secs_loa... | Spectrogram data from the Vox Celeb Dataset. | VoxCeleb | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VoxCeleb:
"""Spectrogram data from the Vox Celeb Dataset."""
def __init__(self, secs, path, concat=True):
"""Create a VoxCeleb dataset object. Parameters ---------- secs : int Number of seconds of the dataset to be generated. Multiple .wav files will be combined if necessary. path : ... | stack_v2_sparse_classes_75kplus_train_067100 | 3,492 | no_license | [
{
"docstring": "Create a VoxCeleb dataset object. Parameters ---------- secs : int Number of seconds of the dataset to be generated. Multiple .wav files will be combined if necessary. path : string Path to folder containing .wav file(s) concat : bool Whether or not to concatenate multiple files. If false, only ... | 2 | stack_v2_sparse_classes_30k_train_000947 | Implement the Python class `VoxCeleb` described below.
Class description:
Spectrogram data from the Vox Celeb Dataset.
Method signatures and docstrings:
- def __init__(self, secs, path, concat=True): Create a VoxCeleb dataset object. Parameters ---------- secs : int Number of seconds of the dataset to be generated. M... | Implement the Python class `VoxCeleb` described below.
Class description:
Spectrogram data from the Vox Celeb Dataset.
Method signatures and docstrings:
- def __init__(self, secs, path, concat=True): Create a VoxCeleb dataset object. Parameters ---------- secs : int Number of seconds of the dataset to be generated. M... | eabdb6ca44cb8f44f0cfb2d94561c9d4de9bb413 | <|skeleton|>
class VoxCeleb:
"""Spectrogram data from the Vox Celeb Dataset."""
def __init__(self, secs, path, concat=True):
"""Create a VoxCeleb dataset object. Parameters ---------- secs : int Number of seconds of the dataset to be generated. Multiple .wav files will be combined if necessary. path : ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VoxCeleb:
"""Spectrogram data from the Vox Celeb Dataset."""
def __init__(self, secs, path, concat=True):
"""Create a VoxCeleb dataset object. Parameters ---------- secs : int Number of seconds of the dataset to be generated. Multiple .wav files will be combined if necessary. path : string Path t... | the_stack_v2_python_sparse | cmfpy/datasets/vox_celeb.py | degleris1/cmfpy | train | 1 |
e5b98006f2d47e4b0183060427ccf1be69609c21 | [
"self.error = ftol\nself.iterationMax = iterations_max\nself.trials = trials\nself.correct_factor = correct_factor",
"iteration = state['iteration']\nold_value = state['old_value']\nnew_value = state['new_value']\nold_parameters = state['old_parameters']\nnew_parameters = state['new_parameters']\nif not 'trial' i... | <|body_start_0|>
self.error = ftol
self.iterationMax = iterations_max
self.trials = trials
self.correct_factor = correct_factor
<|end_body_0|>
<|body_start_1|>
iteration = state['iteration']
old_value = state['old_value']
new_value = state['new_value']
ol... | The Akaike information criterion with several trials authorized | ModifiedAICCriterion | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModifiedAICCriterion:
"""The Akaike information criterion with several trials authorized"""
def __init__(self, ftol, iterations_max, correct_factor=1.0, trials=5):
"""Initializes the criterion with a max number of iterations and an error fraction for the monotony test - ftol is the r... | stack_v2_sparse_classes_75kplus_train_067101 | 2,400 | permissive | [
{
"docstring": "Initializes the criterion with a max number of iterations and an error fraction for the monotony test - ftol is the relative tolerance of the AIC criterion - trials indicates how many time the criterion will return false when in fact the criterion was true - correct_factor is the modifiying fact... | 2 | stack_v2_sparse_classes_30k_train_034875 | Implement the Python class `ModifiedAICCriterion` described below.
Class description:
The Akaike information criterion with several trials authorized
Method signatures and docstrings:
- def __init__(self, ftol, iterations_max, correct_factor=1.0, trials=5): Initializes the criterion with a max number of iterations an... | Implement the Python class `ModifiedAICCriterion` described below.
Class description:
The Akaike information criterion with several trials authorized
Method signatures and docstrings:
- def __init__(self, ftol, iterations_max, correct_factor=1.0, trials=5): Initializes the criterion with a max number of iterations an... | 3d298e908ff55340cd3612078508be0c791f63a8 | <|skeleton|>
class ModifiedAICCriterion:
"""The Akaike information criterion with several trials authorized"""
def __init__(self, ftol, iterations_max, correct_factor=1.0, trials=5):
"""Initializes the criterion with a max number of iterations and an error fraction for the monotony test - ftol is the r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModifiedAICCriterion:
"""The Akaike information criterion with several trials authorized"""
def __init__(self, ftol, iterations_max, correct_factor=1.0, trials=5):
"""Initializes the criterion with a max number of iterations and an error fraction for the monotony test - ftol is the relative toler... | the_stack_v2_python_sparse | PyDSTool/Toolbox/optimizers/criterion/information_criteria.py | mdlama/pydstool | train | 2 |
c50665eaba2bea1a104d7e7cb27c2909f1c9cb61 | [
"if self is self.STREAMING:\n return 'StreamEncoder'\nif self is self.MEMORY:\n return 'MemoryEncoder'\nraise ValueError('Unknown encoder type')",
"if self is self.STREAMING:\n return 'StreamEncoder'\nif self is self.MEMORY:\n return 'MemoryEncoder'\nraise ValueError('Unknown encoder type')"
] | <|body_start_0|>
if self is self.STREAMING:
return 'StreamEncoder'
if self is self.MEMORY:
return 'MemoryEncoder'
raise ValueError('Unknown encoder type')
<|end_body_0|>
<|body_start_1|>
if self is self.STREAMING:
return 'StreamEncoder'
if sel... | EncoderType | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderType:
def base_class_name(self) -> str:
"""Returns the base class used by this encoder type."""
<|body_0|>
def codegen_class_name(self) -> str:
"""Returns the base class used by this encoder type."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_067102 | 24,939 | permissive | [
{
"docstring": "Returns the base class used by this encoder type.",
"name": "base_class_name",
"signature": "def base_class_name(self) -> str"
},
{
"docstring": "Returns the base class used by this encoder type.",
"name": "codegen_class_name",
"signature": "def codegen_class_name(self) -... | 2 | stack_v2_sparse_classes_30k_train_008002 | Implement the Python class `EncoderType` described below.
Class description:
Implement the EncoderType class.
Method signatures and docstrings:
- def base_class_name(self) -> str: Returns the base class used by this encoder type.
- def codegen_class_name(self) -> str: Returns the base class used by this encoder type. | Implement the Python class `EncoderType` described below.
Class description:
Implement the EncoderType class.
Method signatures and docstrings:
- def base_class_name(self) -> str: Returns the base class used by this encoder type.
- def codegen_class_name(self) -> str: Returns the base class used by this encoder type.... | 7f3590b58e8398aad68c1e59702c459d2f8ca38e | <|skeleton|>
class EncoderType:
def base_class_name(self) -> str:
"""Returns the base class used by this encoder type."""
<|body_0|>
def codegen_class_name(self) -> str:
"""Returns the base class used by this encoder type."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EncoderType:
def base_class_name(self) -> str:
"""Returns the base class used by this encoder type."""
if self is self.STREAMING:
return 'StreamEncoder'
if self is self.MEMORY:
return 'MemoryEncoder'
raise ValueError('Unknown encoder type')
def code... | the_stack_v2_python_sparse | pw_protobuf/py/pw_protobuf/codegen_pwpb.py | waelbarakat/pigweed | train | 0 | |
2b0888883f3afb4ecbbfccec9032c136cda72694 | [
"self._bidders = bidders\nself._auctioneer = Auctioneer()\nfor bidder in bidders:\n self._auctioneer.register_bidder(bidder)",
"print(f'Auctioning {item} starting at {start_price}!')\nself._auctioneer.accept_bid(start_price, 'Starting Bid')\nsummary = {bidder.name: bidder.highest_bid for bidder in self._bidder... | <|body_start_0|>
self._bidders = bidders
self._auctioneer = Auctioneer()
for bidder in bidders:
self._auctioneer.register_bidder(bidder)
<|end_body_0|>
<|body_start_1|>
print(f'Auctioning {item} starting at {start_price}!')
self._auctioneer.accept_bid(start_price, 'S... | Simulates an auction. Is responsible for driving the auctioneer and the bidders. | Auction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Auction:
"""Simulates an auction. Is responsible for driving the auctioneer and the bidders."""
def __init__(self, bidders):
"""Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder"""
... | stack_v2_sparse_classes_75kplus_train_067103 | 6,353 | no_license | [
{
"docstring": "Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder",
"name": "__init__",
"signature": "def __init__(self, bidders)"
},
{
"docstring": "Starts the auction for the given item at the g... | 2 | stack_v2_sparse_classes_30k_train_001246 | Implement the Python class `Auction` described below.
Class description:
Simulates an auction. Is responsible for driving the auctioneer and the bidders.
Method signatures and docstrings:
- def __init__(self, bidders): Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :para... | Implement the Python class `Auction` described below.
Class description:
Simulates an auction. Is responsible for driving the auctioneer and the bidders.
Method signatures and docstrings:
- def __init__(self, bidders): Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :para... | 6e2347b70c07cfc3ca83af29c2bd5c4696c55bb6 | <|skeleton|>
class Auction:
"""Simulates an auction. Is responsible for driving the auctioneer and the bidders."""
def __init__(self, bidders):
"""Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Auction:
"""Simulates an auction. Is responsible for driving the auctioneer and the bidders."""
def __init__(self, bidders):
"""Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder"""
self._bi... | the_stack_v2_python_sparse | Lab/Lab6/auction_simulator.py | kwokwill/comp3522-object-oriented-programming | train | 0 |
a71dc3de2f560d8fc10e9a77e02967ac0aba6e83 | [
"base_cmd = ['ceph', 'orch']\nif config.get('base_cmd_args'):\n base_cmd_args_str = config_dict_to_string(config.get('base_cmd_args'))\n base_cmd.append(base_cmd_args_str)\nbase_cmd.extend(['device', 'zap'])\npos_args = config['pos_args']\nnode = pos_args[0]\nhost_id = get_node_by_id(self.cluster, node)\nhost... | <|body_start_0|>
base_cmd = ['ceph', 'orch']
if config.get('base_cmd_args'):
base_cmd_args_str = config_dict_to_string(config.get('base_cmd_args'))
base_cmd.append(base_cmd_args_str)
base_cmd.extend(['device', 'zap'])
pos_args = config['pos_args']
node = p... | Device | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Device:
def zap(self, config: Dict) -> None:
"""Zap particular device Args: config (Dict): Zap configs Returns: output (Str), error (Str) returned by the command. Example:: command: zap base_cmd_args: verbose: true pos_args: - "node1" - "/dev/vdb" args: force: true"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_067104 | 2,556 | permissive | [
{
"docstring": "Zap particular device Args: config (Dict): Zap configs Returns: output (Str), error (Str) returned by the command. Example:: command: zap base_cmd_args: verbose: true pos_args: - \"node1\" - \"/dev/vdb\" args: force: true",
"name": "zap",
"signature": "def zap(self, config: Dict) -> None... | 2 | stack_v2_sparse_classes_30k_train_013213 | Implement the Python class `Device` described below.
Class description:
Implement the Device class.
Method signatures and docstrings:
- def zap(self, config: Dict) -> None: Zap particular device Args: config (Dict): Zap configs Returns: output (Str), error (Str) returned by the command. Example:: command: zap base_cm... | Implement the Python class `Device` described below.
Class description:
Implement the Device class.
Method signatures and docstrings:
- def zap(self, config: Dict) -> None: Zap particular device Args: config (Dict): Zap configs Returns: output (Str), error (Str) returned by the command. Example:: command: zap base_cm... | 0691fbaf8fca2a9cd051c5049c83758c65301654 | <|skeleton|>
class Device:
def zap(self, config: Dict) -> None:
"""Zap particular device Args: config (Dict): Zap configs Returns: output (Str), error (Str) returned by the command. Example:: command: zap base_cmd_args: verbose: true pos_args: - "node1" - "/dev/vdb" args: force: true"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Device:
def zap(self, config: Dict) -> None:
"""Zap particular device Args: config (Dict): Zap configs Returns: output (Str), error (Str) returned by the command. Example:: command: zap base_cmd_args: verbose: true pos_args: - "node1" - "/dev/vdb" args: force: true"""
base_cmd = ['ceph', 'orch... | the_stack_v2_python_sparse | ceph/ceph_admin/device.py | red-hat-storage/cephci | train | 28 | |
e722af39bccbfbd035933fee4f4170f8f2d76da7 | [
"if len(nums) == len(temp_result):\n result.append(temp_result.copy())\n return\nelse:\n for num in nums:\n if num in temp_result:\n continue\n temp_result.append(num)\n self.dfs(result, nums, temp_result)\n temp_result.pop()",
"result = []\nself.dfs(result, nums, [... | <|body_start_0|>
if len(nums) == len(temp_result):
result.append(temp_result.copy())
return
else:
for num in nums:
if num in temp_result:
continue
temp_result.append(num)
self.dfs(result, nums, temp_r... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dfs(self, result, nums, temp_result):
"""@param result List(List()) @param nums"""
<|body_0|>
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == len... | stack_v2_sparse_classes_75kplus_train_067105 | 999 | permissive | [
{
"docstring": "@param result List(List()) @param nums",
"name": "dfs",
"signature": "def dfs(self, result, nums, temp_result)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permute",
"signature": "def permute(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, result, nums, temp_result): @param result List(List()) @param nums
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, result, nums, temp_result): @param result List(List()) @param nums
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solu... | 1ed22267156fb968671731c2e983b0e65f670750 | <|skeleton|>
class Solution:
def dfs(self, result, nums, temp_result):
"""@param result List(List()) @param nums"""
<|body_0|>
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def dfs(self, result, nums, temp_result):
"""@param result List(List()) @param nums"""
if len(nums) == len(temp_result):
result.append(temp_result.copy())
return
else:
for num in nums:
if num in temp_result:
... | the_stack_v2_python_sparse | leetcode/46.py | pingrunhuang/CodeChallenge | train | 0 | |
54889c21b75cbe4b3ce4ed40d41d21c85f5c0faf | [
"if not hasattr(self, '_MockEstimatorMixin__log'):\n return []\nelse:\n return self._MockEstimatorMixin__log",
"if not hasattr(self, '_MockEstimatorMixin__log'):\n self._MockEstimatorMixin__log = [value]\nelse:\n self._MockEstimatorMixin__log = self._MockEstimatorMixin__log + [value]"
] | <|body_start_0|>
if not hasattr(self, '_MockEstimatorMixin__log'):
return []
else:
return self._MockEstimatorMixin__log
<|end_body_0|>
<|body_start_1|>
if not hasattr(self, '_MockEstimatorMixin__log'):
self._MockEstimatorMixin__log = [value]
else:
... | Mixin class for constructing Mock estimators. | _MockEstimatorMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _MockEstimatorMixin:
"""Mixin class for constructing Mock estimators."""
def log(self):
"""Log of the methods called and the parameters passed in each method."""
<|body_0|>
def add_log_item(self, value):
"""Append an item to the log. State change: self.log - `val... | stack_v2_sparse_classes_75kplus_train_067106 | 3,695 | permissive | [
{
"docstring": "Log of the methods called and the parameters passed in each method.",
"name": "log",
"signature": "def log(self)"
},
{
"docstring": "Append an item to the log. State change: self.log - `value` is appended to the list self.log Parameters ---------- value : any object",
"name":... | 2 | null | Implement the Python class `_MockEstimatorMixin` described below.
Class description:
Mixin class for constructing Mock estimators.
Method signatures and docstrings:
- def log(self): Log of the methods called and the parameters passed in each method.
- def add_log_item(self, value): Append an item to the log. State ch... | Implement the Python class `_MockEstimatorMixin` described below.
Class description:
Mixin class for constructing Mock estimators.
Method signatures and docstrings:
- def log(self): Log of the methods called and the parameters passed in each method.
- def add_log_item(self, value): Append an item to the log. State ch... | 70b2bfaaa597eb31bc3a1032366dcc0e1f4c8a9f | <|skeleton|>
class _MockEstimatorMixin:
"""Mixin class for constructing Mock estimators."""
def log(self):
"""Log of the methods called and the parameters passed in each method."""
<|body_0|>
def add_log_item(self, value):
"""Append an item to the log. State change: self.log - `val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _MockEstimatorMixin:
"""Mixin class for constructing Mock estimators."""
def log(self):
"""Log of the methods called and the parameters passed in each method."""
if not hasattr(self, '_MockEstimatorMixin__log'):
return []
else:
return self._MockEstimatorMix... | the_stack_v2_python_sparse | sktime/utils/estimators/_base.py | sktime/sktime | train | 1,117 |
dc6a83d18c5c60421734ac7f51a40111f8f84da1 | [
"self.host = 'http://' + str(host) + ':' + str(port) + '/'\nself.api_root = self.host + 'api/v1/'\nself.config_root = self.api_root + 'config/'\nself.realtime_root = self.api_root + 'realtime'",
"viewBytes = restEncodeImage(image)\nipAndPort = my_ip + ':' + str(my_port)\nscreenSpacePoints = []\nworldSpacePoints =... | <|body_start_0|>
self.host = 'http://' + str(host) + ':' + str(port) + '/'
self.api_root = self.host + 'api/v1/'
self.config_root = self.api_root + 'config/'
self.realtime_root = self.api_root + 'realtime'
<|end_body_0|>
<|body_start_1|>
viewBytes = restEncodeImage(image)
... | Stubs for REST Endpoints of Analytics Engine Server | APIAccess | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIAccess:
"""Stubs for REST Endpoints of Analytics Engine Server"""
def __init__(self, host, port):
"""Initialize :param host: Server host :param port: Server port"""
<|body_0|>
def postCameraView(self, camera_id, image, my_ip, my_port, w, h, markers=None, map_markers=N... | stack_v2_sparse_classes_75kplus_train_067107 | 3,032 | permissive | [
{
"docstring": "Initialize :param host: Server host :param port: Server port",
"name": "__init__",
"signature": "def __init__(self, host, port)"
},
{
"docstring": "Send camera captured image to analytics engine :param camera_id: camera_id :param image: image :param my_ip: camera_ip :param my_por... | 4 | stack_v2_sparse_classes_30k_train_030773 | Implement the Python class `APIAccess` described below.
Class description:
Stubs for REST Endpoints of Analytics Engine Server
Method signatures and docstrings:
- def __init__(self, host, port): Initialize :param host: Server host :param port: Server port
- def postCameraView(self, camera_id, image, my_ip, my_port, w... | Implement the Python class `APIAccess` described below.
Class description:
Stubs for REST Endpoints of Analytics Engine Server
Method signatures and docstrings:
- def __init__(self, host, port): Initialize :param host: Server host :param port: Server port
- def postCameraView(self, camera_id, image, my_ip, my_port, w... | 7b5941b7149b2a576789722db6e54b7d20216c2e | <|skeleton|>
class APIAccess:
"""Stubs for REST Endpoints of Analytics Engine Server"""
def __init__(self, host, port):
"""Initialize :param host: Server host :param port: Server port"""
<|body_0|>
def postCameraView(self, camera_id, image, my_ip, my_port, w, h, markers=None, map_markers=N... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class APIAccess:
"""Stubs for REST Endpoints of Analytics Engine Server"""
def __init__(self, host, port):
"""Initialize :param host: Server host :param port: Server port"""
self.host = 'http://' + str(host) + ':' + str(port) + '/'
self.api_root = self.host + 'api/v1/'
self.conf... | the_stack_v2_python_sparse | sense/communication/APIAccess.py | eduze/AugurSense | train | 2 |
1c7c87933bedf08dc09a537f6a924dbf3907205c | [
"self.max_size = max_size\nself.num_nodes = 0\nself.front = None\nself.rear = None",
"new_node = Node(key)\nif self.num_nodes == self.max_size:\n print('Queue overflow')\nelif self.rear is None:\n self.front = new_node\n self.rear = new_node\n self.num_nodes += 1\nelse:\n self.rear.next = new_node\... | <|body_start_0|>
self.max_size = max_size
self.num_nodes = 0
self.front = None
self.rear = None
<|end_body_0|>
<|body_start_1|>
new_node = Node(key)
if self.num_nodes == self.max_size:
print('Queue overflow')
elif self.rear is None:
self.f... | Queue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Queue:
def __init__(self, max_size=sys.maxsize):
"""Initialize a Queue Parameters: max_size: max number of nodes in the queue num_nodes: number of nodes in the queue front: points the first item of queue rear: points to last item of queue"""
<|body_0|>
def queue(self, key):
... | stack_v2_sparse_classes_75kplus_train_067108 | 1,651 | no_license | [
{
"docstring": "Initialize a Queue Parameters: max_size: max number of nodes in the queue num_nodes: number of nodes in the queue front: points the first item of queue rear: points to last item of queue",
"name": "__init__",
"signature": "def __init__(self, max_size=sys.maxsize)"
},
{
"docstring... | 3 | stack_v2_sparse_classes_30k_train_003888 | Implement the Python class `Queue` described below.
Class description:
Implement the Queue class.
Method signatures and docstrings:
- def __init__(self, max_size=sys.maxsize): Initialize a Queue Parameters: max_size: max number of nodes in the queue num_nodes: number of nodes in the queue front: points the first item... | Implement the Python class `Queue` described below.
Class description:
Implement the Queue class.
Method signatures and docstrings:
- def __init__(self, max_size=sys.maxsize): Initialize a Queue Parameters: max_size: max number of nodes in the queue num_nodes: number of nodes in the queue front: points the first item... | 7a03314d101c37f2c6a096188689ac8518461895 | <|skeleton|>
class Queue:
def __init__(self, max_size=sys.maxsize):
"""Initialize a Queue Parameters: max_size: max number of nodes in the queue num_nodes: number of nodes in the queue front: points the first item of queue rear: points to last item of queue"""
<|body_0|>
def queue(self, key):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Queue:
def __init__(self, max_size=sys.maxsize):
"""Initialize a Queue Parameters: max_size: max number of nodes in the queue num_nodes: number of nodes in the queue front: points the first item of queue rear: points to last item of queue"""
self.max_size = max_size
self.num_nodes = 0
... | the_stack_v2_python_sparse | stack_queue_heap/queue.py | ntrang086/python_snippets | train | 0 | |
3e77dba78b8c96953c968bc77dbf1f1f30b17019 | [
"include_archived = request.args.get('includeArchived') == 'true'\ncategories = MappingIssueCategoryService.get_all_mapping_issue_categories(include_archived)\nreturn (categories.to_primitive(), 200)",
"try:\n category_dto = MappingIssueCategoryDTO(request.get_json())\n category_dto.validate()\nexcept DataE... | <|body_start_0|>
include_archived = request.args.get('includeArchived') == 'true'
categories = MappingIssueCategoryService.get_all_mapping_issue_categories(include_archived)
return (categories.to_primitive(), 200)
<|end_body_0|>
<|body_start_1|>
try:
category_dto = MappingIs... | IssuesAllAPI | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IssuesAllAPI:
def get(self):
"""Gets all mapping issue categories --- tags: - issues produces: - application/json parameters: - in: query name: includeArchived description: Optional filter to include archived categories type: boolean default: false responses: 200: description: Mapping is... | stack_v2_sparse_classes_75kplus_train_067109 | 7,229 | permissive | [
{
"docstring": "Gets all mapping issue categories --- tags: - issues produces: - application/json parameters: - in: query name: includeArchived description: Optional filter to include archived categories type: boolean default: false responses: 200: description: Mapping issue categories 500: description: Interna... | 2 | stack_v2_sparse_classes_30k_train_044846 | Implement the Python class `IssuesAllAPI` described below.
Class description:
Implement the IssuesAllAPI class.
Method signatures and docstrings:
- def get(self): Gets all mapping issue categories --- tags: - issues produces: - application/json parameters: - in: query name: includeArchived description: Optional filte... | Implement the Python class `IssuesAllAPI` described below.
Class description:
Implement the IssuesAllAPI class.
Method signatures and docstrings:
- def get(self): Gets all mapping issue categories --- tags: - issues produces: - application/json parameters: - in: query name: includeArchived description: Optional filte... | 45bf3937c74902226096aee5b49e7abea62df524 | <|skeleton|>
class IssuesAllAPI:
def get(self):
"""Gets all mapping issue categories --- tags: - issues produces: - application/json parameters: - in: query name: includeArchived description: Optional filter to include archived categories type: boolean default: false responses: 200: description: Mapping is... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IssuesAllAPI:
def get(self):
"""Gets all mapping issue categories --- tags: - issues produces: - application/json parameters: - in: query name: includeArchived description: Optional filter to include archived categories type: boolean default: false responses: 200: description: Mapping issue categories... | the_stack_v2_python_sparse | backend/api/issues/resources.py | hotosm/tasking-manager | train | 526 | |
ec5a771bc1d61f6a57e61a3f6f42877c24167a32 | [
"self.guendongtiaocaozuo_jianyiban(EFL.hotel_management_loc, '滚动右侧一级菜单酒店管理')\nself.click_element(EFL.hotel_query_loc, '点击右侧二级菜单_酒店查询')\nself.click_element(EFL.hotel_list_excel_loc, '点击_在售商品导出excel')\ntime.sleep(4)\nnow = time.strftime('%Y-%m-%d %H-%M-%S')\nself.export_file(f'E:\\\\WebWebpageTest\\\\酒店商品销售明细表_{now}.... | <|body_start_0|>
self.guendongtiaocaozuo_jianyiban(EFL.hotel_management_loc, '滚动右侧一级菜单酒店管理')
self.click_element(EFL.hotel_query_loc, '点击右侧二级菜单_酒店查询')
self.click_element(EFL.hotel_list_excel_loc, '点击_在售商品导出excel')
time.sleep(4)
now = time.strftime('%Y-%m-%d %H-%M-%S')
self... | 下载平台后台excel表格 | ExportFilePage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExportFilePage:
"""下载平台后台excel表格"""
def hotel_list_excel(self):
"""下载 酒店管理列表 - excel表格 :return:"""
<|body_0|>
def sales_detail_excel(self):
"""订单列表 - 销售明细导出excel :return:"""
<|body_1|>
def order_detail_excel(self):
"""订单管理 - 订单明细导出excel :retu... | stack_v2_sparse_classes_75kplus_train_067110 | 3,368 | no_license | [
{
"docstring": "下载 酒店管理列表 - excel表格 :return:",
"name": "hotel_list_excel",
"signature": "def hotel_list_excel(self)"
},
{
"docstring": "订单列表 - 销售明细导出excel :return:",
"name": "sales_detail_excel",
"signature": "def sales_detail_excel(self)"
},
{
"docstring": "订单管理 - 订单明细导出excel :r... | 3 | stack_v2_sparse_classes_30k_train_008423 | Implement the Python class `ExportFilePage` described below.
Class description:
下载平台后台excel表格
Method signatures and docstrings:
- def hotel_list_excel(self): 下载 酒店管理列表 - excel表格 :return:
- def sales_detail_excel(self): 订单列表 - 销售明细导出excel :return:
- def order_detail_excel(self): 订单管理 - 订单明细导出excel :return: | Implement the Python class `ExportFilePage` described below.
Class description:
下载平台后台excel表格
Method signatures and docstrings:
- def hotel_list_excel(self): 下载 酒店管理列表 - excel表格 :return:
- def sales_detail_excel(self): 订单列表 - 销售明细导出excel :return:
- def order_detail_excel(self): 订单管理 - 订单明细导出excel :return:
<|skeleton... | cfadd3132c2c7c518c784589e0dab6510a662a6c | <|skeleton|>
class ExportFilePage:
"""下载平台后台excel表格"""
def hotel_list_excel(self):
"""下载 酒店管理列表 - excel表格 :return:"""
<|body_0|>
def sales_detail_excel(self):
"""订单列表 - 销售明细导出excel :return:"""
<|body_1|>
def order_detail_excel(self):
"""订单管理 - 订单明细导出excel :retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExportFilePage:
"""下载平台后台excel表格"""
def hotel_list_excel(self):
"""下载 酒店管理列表 - excel表格 :return:"""
self.guendongtiaocaozuo_jianyiban(EFL.hotel_management_loc, '滚动右侧一级菜单酒店管理')
self.click_element(EFL.hotel_query_loc, '点击右侧二级菜单_酒店查询')
self.click_element(EFL.hotel_list_excel_l... | the_stack_v2_python_sparse | lemon/Python_practice/tebiemiao_web/PageObjects/export_file_page.py | songyongzhuang/PythonCode_office | train | 0 |
e3d9b938b7eacaf010f68ec0c4f2db07213a706b | [
"workspaces = Workspace.objects.filter(id__in=workspace_ids)\nresults = {}\nfor workspace in workspaces:\n results[workspace.id] = workspace.is_active\nreturn results",
"workspace_ids = data_files.keys()\nworkspaces = Workspace.objects.filter(id__in=workspace_ids)\nresults = {}\nremote_path = self._calculate_r... | <|body_start_0|>
workspaces = Workspace.objects.filter(id__in=workspace_ids)
results = {}
for workspace in workspaces:
results[workspace.id] = workspace.is_active
return results
<|end_body_0|>
<|body_start_1|>
workspace_ids = data_files.keys()
workspaces = Wo... | Implements the data file store class to provide a way to validate product file output configuration and store product data files. | ProductDataFileStore | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductDataFileStore:
"""Implements the data file store class to provide a way to validate product file output configuration and store product data files."""
def get_workspaces(self, workspace_ids):
"""See :meth:`job.configuration.data.data_file.AbstractDataFileStore.get_workspaces`"... | stack_v2_sparse_classes_75kplus_train_067111 | 4,906 | permissive | [
{
"docstring": "See :meth:`job.configuration.data.data_file.AbstractDataFileStore.get_workspaces`",
"name": "get_workspaces",
"signature": "def get_workspaces(self, workspace_ids)"
},
{
"docstring": "See :meth:`job.configuration.data.data_file.AbstractDataFileStore.store_files`",
"name": "st... | 3 | stack_v2_sparse_classes_30k_train_036275 | Implement the Python class `ProductDataFileStore` described below.
Class description:
Implements the data file store class to provide a way to validate product file output configuration and store product data files.
Method signatures and docstrings:
- def get_workspaces(self, workspace_ids): See :meth:`job.configurat... | Implement the Python class `ProductDataFileStore` described below.
Class description:
Implements the data file store class to provide a way to validate product file output configuration and store product data files.
Method signatures and docstrings:
- def get_workspaces(self, workspace_ids): See :meth:`job.configurat... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class ProductDataFileStore:
"""Implements the data file store class to provide a way to validate product file output configuration and store product data files."""
def get_workspaces(self, workspace_ids):
"""See :meth:`job.configuration.data.data_file.AbstractDataFileStore.get_workspaces`"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductDataFileStore:
"""Implements the data file store class to provide a way to validate product file output configuration and store product data files."""
def get_workspaces(self, workspace_ids):
"""See :meth:`job.configuration.data.data_file.AbstractDataFileStore.get_workspaces`"""
wo... | the_stack_v2_python_sparse | scale/product/configuration/product_data_file.py | kfconsultant/scale | train | 0 |
c6013f131a6b3e35cb594c75e7cd391dcc7d983f | [
"save_btn = True\nactive_page = 'code'\ncode_snippet = None\ncode_snippets = ()\npage_title = _('Code snippets')\nif slug:\n code_snippet = get_object_or_404(Code, slug=slug)\n active_page = f'code/{code_snippet.title}'\n page_title = code_snippet.title\n try:\n self.get_user(request, username)\n... | <|body_start_0|>
save_btn = True
active_page = 'code'
code_snippet = None
code_snippets = ()
page_title = _('Code snippets')
if slug:
code_snippet = get_object_or_404(Code, slug=slug)
active_page = f'code/{code_snippet.title}'
page_titl... | CodeView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodeView:
def get(self, request, slug=None, username=None):
"""Get list of user code snippets or user snippet."""
<|body_0|>
def post(self, request, slug=None, username=None):
"""Save or create code snippet."""
<|body_1|>
def delete(self, request, slug, ... | stack_v2_sparse_classes_75kplus_train_067112 | 30,576 | permissive | [
{
"docstring": "Get list of user code snippets or user snippet.",
"name": "get",
"signature": "def get(self, request, slug=None, username=None)"
},
{
"docstring": "Save or create code snippet.",
"name": "post",
"signature": "def post(self, request, slug=None, username=None)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_016342 | Implement the Python class `CodeView` described below.
Class description:
Implement the CodeView class.
Method signatures and docstrings:
- def get(self, request, slug=None, username=None): Get list of user code snippets or user snippet.
- def post(self, request, slug=None, username=None): Save or create code snippet... | Implement the Python class `CodeView` described below.
Class description:
Implement the CodeView class.
Method signatures and docstrings:
- def get(self, request, slug=None, username=None): Get list of user code snippets or user snippet.
- def post(self, request, slug=None, username=None): Save or create code snippet... | 51a2ae2b29ae5c91a3cf7171f89edf225cc8a6f0 | <|skeleton|>
class CodeView:
def get(self, request, slug=None, username=None):
"""Get list of user code snippets or user snippet."""
<|body_0|>
def post(self, request, slug=None, username=None):
"""Save or create code snippet."""
<|body_1|>
def delete(self, request, slug, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CodeView:
def get(self, request, slug=None, username=None):
"""Get list of user code snippets or user snippet."""
save_btn = True
active_page = 'code'
code_snippet = None
code_snippets = ()
page_title = _('Code snippets')
if slug:
code_snippe... | the_stack_v2_python_sparse | tool/views/views.py | mikekeda/tools | train | 0 | |
bedb3a468de70144573245effe3655bfa5a896b2 | [
"super(EncDecModel, self).__init__()\nself._config = config\nself._model_version = model_version\nassert model_version in ('v2',), 'model_version only support v2'\nself.encoder = encoder_v2.Text2SQLEncoderV2(config)\nself.decoder = decoder_v2.Text2SQLDecoder(label_encoder, dropout=0.2, desc_attn='mha', use_align_ma... | <|body_start_0|>
super(EncDecModel, self).__init__()
self._config = config
self._model_version = model_version
assert model_version in ('v2',), 'model_version only support v2'
self.encoder = encoder_v2.Text2SQLEncoderV2(config)
self.decoder = decoder_v2.Text2SQLDecoder(la... | Dygraph version of BoomUp Model | EncDecModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncDecModel:
"""Dygraph version of BoomUp Model"""
def __init__(self, config, label_encoder, model_version='v2'):
"""init of class Args: model_configs (TYPE): NULL"""
<|body_0|>
def forward(self, inputs, labels=None, db=None, is_train=True):
"""Args: inputs (TYPE... | stack_v2_sparse_classes_75kplus_train_067113 | 3,369 | permissive | [
{
"docstring": "init of class Args: model_configs (TYPE): NULL",
"name": "__init__",
"signature": "def __init__(self, config, label_encoder, model_version='v2')"
},
{
"docstring": "Args: inputs (TYPE): NULL labels (TYPE) Returns: TODO",
"name": "forward",
"signature": "def forward(self, ... | 4 | stack_v2_sparse_classes_30k_train_049509 | Implement the Python class `EncDecModel` described below.
Class description:
Dygraph version of BoomUp Model
Method signatures and docstrings:
- def __init__(self, config, label_encoder, model_version='v2'): init of class Args: model_configs (TYPE): NULL
- def forward(self, inputs, labels=None, db=None, is_train=True... | Implement the Python class `EncDecModel` described below.
Class description:
Dygraph version of BoomUp Model
Method signatures and docstrings:
- def __init__(self, config, label_encoder, model_version='v2'): init of class Args: model_configs (TYPE): NULL
- def forward(self, inputs, labels=None, db=None, is_train=True... | b8ec015fa9e16c0a879c619ee1f2aab8a393c7bd | <|skeleton|>
class EncDecModel:
"""Dygraph version of BoomUp Model"""
def __init__(self, config, label_encoder, model_version='v2'):
"""init of class Args: model_configs (TYPE): NULL"""
<|body_0|>
def forward(self, inputs, labels=None, db=None, is_train=True):
"""Args: inputs (TYPE... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EncDecModel:
"""Dygraph version of BoomUp Model"""
def __init__(self, config, label_encoder, model_version='v2'):
"""init of class Args: model_configs (TYPE): NULL"""
super(EncDecModel, self).__init__()
self._config = config
self._model_version = model_version
asse... | the_stack_v2_python_sparse | NLP/Text2SQL-BASELINE/text2sql/models/enc_dec.py | sserdoubleh/Research | train | 10 |
a419e420c425fba344dca7a214370097f1094233 | [
"config = data.config.ai.tasks[task_id]\ntask_type = config.type\nbase_task_parameter = BaseTaskParameter()\nbase_task_parameter.type = task_type\nbase_task_parameter.prev_task = prev_task\nbase_task_parameter.entity = prev_task.entity if prev_task else entity\nbase_task_parameter.input = config.input\nbase_task_pa... | <|body_start_0|>
config = data.config.ai.tasks[task_id]
task_type = config.type
base_task_parameter = BaseTaskParameter()
base_task_parameter.type = task_type
base_task_parameter.prev_task = prev_task
base_task_parameter.entity = prev_task.entity if prev_task else entity
... | Factory for task parsers. Member: _from_id -- Mapping of id to task for from_id(). Only for tasks without special parameter (dict). _from_task -- Mapping of id to task for from_task() (dict). | Factory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Factory:
"""Factory for task parsers. Member: _from_id -- Mapping of id to task for from_id(). Only for tasks without special parameter (dict). _from_task -- Mapping of id to task for from_task() (dict)."""
def from_id(task_id, prev_task, data, pipeline=None, entity=None):
"""Find th... | stack_v2_sparse_classes_75kplus_train_067114 | 4,153 | no_license | [
{
"docstring": "Find the parser for the given task id and initialize.",
"name": "from_id",
"signature": "def from_id(task_id, prev_task, data, pipeline=None, entity=None)"
},
{
"docstring": "Finds the parser for the given task.",
"name": "from_task",
"signature": "def from_task(task)"
... | 2 | null | Implement the Python class `Factory` described below.
Class description:
Factory for task parsers. Member: _from_id -- Mapping of id to task for from_id(). Only for tasks without special parameter (dict). _from_task -- Mapping of id to task for from_task() (dict).
Method signatures and docstrings:
- def from_id(task_... | Implement the Python class `Factory` described below.
Class description:
Factory for task parsers. Member: _from_id -- Mapping of id to task for from_id(). Only for tasks without special parameter (dict). _from_task -- Mapping of id to task for from_task() (dict).
Method signatures and docstrings:
- def from_id(task_... | c38b43edb7ec54f18768564c42859195bc2477e4 | <|skeleton|>
class Factory:
"""Factory for task parsers. Member: _from_id -- Mapping of id to task for from_id(). Only for tasks without special parameter (dict). _from_task -- Mapping of id to task for from_task() (dict)."""
def from_id(task_id, prev_task, data, pipeline=None, entity=None):
"""Find th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Factory:
"""Factory for task parsers. Member: _from_id -- Mapping of id to task for from_id(). Only for tasks without special parameter (dict). _from_task -- Mapping of id to task for from_task() (dict)."""
def from_id(task_id, prev_task, data, pipeline=None, entity=None):
"""Find the parser for ... | the_stack_v2_python_sparse | python-prototype/ai/task/factory.py | tea2code/fantasy-rts | train | 0 |
9083c15a4c1dd6180edcff8b9e90df0d753e1c4c | [
"method = VectorsFactory.method(config)\nif method == 'external':\n return ExternalVectors(config, scoring)\nif method == 'words':\n if not WORDS:\n raise ImportError('Word vector models are not available - install \"similarity\" extra to enable. Otherwise, specify ' + 'method=\"transformers\" to use t... | <|body_start_0|>
method = VectorsFactory.method(config)
if method == 'external':
return ExternalVectors(config, scoring)
if method == 'words':
if not WORDS:
raise ImportError('Word vector models are not available - install "similarity" extra to enable. Oth... | Methods to create Vectors models. | VectorsFactory | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VectorsFactory:
"""Methods to create Vectors models."""
def create(config, scoring):
"""Create a Vectors model instance. Args: config: vector configuration scoring: scoring instance Returns: Vectors"""
<|body_0|>
def method(config):
"""Get or derive the vector me... | stack_v2_sparse_classes_75kplus_train_067115 | 1,870 | permissive | [
{
"docstring": "Create a Vectors model instance. Args: config: vector configuration scoring: scoring instance Returns: Vectors",
"name": "create",
"signature": "def create(config, scoring)"
},
{
"docstring": "Get or derive the vector method. Args: config: vector configuration Returns: vector met... | 2 | stack_v2_sparse_classes_30k_train_038420 | Implement the Python class `VectorsFactory` described below.
Class description:
Methods to create Vectors models.
Method signatures and docstrings:
- def create(config, scoring): Create a Vectors model instance. Args: config: vector configuration scoring: scoring instance Returns: Vectors
- def method(config): Get or... | Implement the Python class `VectorsFactory` described below.
Class description:
Methods to create Vectors models.
Method signatures and docstrings:
- def create(config, scoring): Create a Vectors model instance. Args: config: vector configuration scoring: scoring instance Returns: Vectors
- def method(config): Get or... | 789a4555cb60ee9cdfa69afae5a5236d197e2b07 | <|skeleton|>
class VectorsFactory:
"""Methods to create Vectors models."""
def create(config, scoring):
"""Create a Vectors model instance. Args: config: vector configuration scoring: scoring instance Returns: Vectors"""
<|body_0|>
def method(config):
"""Get or derive the vector me... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VectorsFactory:
"""Methods to create Vectors models."""
def create(config, scoring):
"""Create a Vectors model instance. Args: config: vector configuration scoring: scoring instance Returns: Vectors"""
method = VectorsFactory.method(config)
if method == 'external':
ret... | the_stack_v2_python_sparse | src/python/txtai/vectors/factory.py | neuml/txtai | train | 4,804 |
fb591825d1409527dccd192e8c8c40a8c5cfbcd6 | [
"if not s or not wordDict or (not self.breakable(s, wordDict)):\n return []\nword_len, start = (max(map(len, wordDict)), min(map(len, wordDict)) - 1)\ndp = [[] for i in xrange(len(s) + 1)]\ndp[0].append('')\nfor i in xrange(start, len(s)):\n for j in xrange(start + 1, 1 + min(word_len, i + 1)):\n if s[... | <|body_start_0|>
if not s or not wordDict or (not self.breakable(s, wordDict)):
return []
word_len, start = (max(map(len, wordDict)), min(map(len, wordDict)) - 1)
dp = [[] for i in xrange(len(s) + 1)]
dp[0].append('')
for i in xrange(start, len(s)):
for j ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: Set[str] :rtype: List[str]"""
<|body_0|>
def breakable(self, s, wordDict):
""":type s: str :type wordDict: Set[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_067116 | 1,459 | no_license | [
{
"docstring": ":type s: str :type wordDict: Set[str] :rtype: List[str]",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: Set[str] :rtype: bool",
"name": "breakable",
"signature": "def breakable(self, s, wordDict)"
}
... | 2 | stack_v2_sparse_classes_30k_train_010460 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: Set[str] :rtype: List[str]
- def breakable(self, s, wordDict): :type s: str :type wordDict: Set[str] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: Set[str] :rtype: List[str]
- def breakable(self, s, wordDict): :type s: str :type wordDict: Set[str] :rtype: bool
... | 591e1b91927e9f9218083c30c4299c89c2aa96a0 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: Set[str] :rtype: List[str]"""
<|body_0|>
def breakable(self, s, wordDict):
""":type s: str :type wordDict: Set[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: Set[str] :rtype: List[str]"""
if not s or not wordDict or (not self.breakable(s, wordDict)):
return []
word_len, start = (max(map(len, wordDict)), min(map(len, wordDict)) - 1)
dp = [[] for i... | the_stack_v2_python_sparse | Dynamic Programming/Word Break II/Solution.py | smallt-TAO/LeetCode-On-The-Way | train | 0 | |
25cbdc721ad785f78883ff0d86e13cf478854311 | [
"if self.vat_product == 'nonvat':\n self.taxes_id = False\nelse:\n pass",
"if vals.get('taxes_id'):\n if len(vals.get('taxes_id')[0][2]) > 1:\n raise UserError('A product can only have one tax')\nreturn super(ProductTemplateInherit, self).create(vals)",
"if vals.get('taxes_id'):\n if len(vals... | <|body_start_0|>
if self.vat_product == 'nonvat':
self.taxes_id = False
else:
pass
<|end_body_0|>
<|body_start_1|>
if vals.get('taxes_id'):
if len(vals.get('taxes_id')[0][2]) > 1:
raise UserError('A product can only have one tax')
retu... | ProductTemplateInherit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductTemplateInherit:
def value_clear_validation(self):
"""This method consist of the modifications done to the non vat item. New field is added as vat status which contains values vat items and non vat items when a non vat item is selected the values in the VAT field is erased"""
... | stack_v2_sparse_classes_75kplus_train_067117 | 3,308 | no_license | [
{
"docstring": "This method consist of the modifications done to the non vat item. New field is added as vat status which contains values vat items and non vat items when a non vat item is selected the values in the VAT field is erased",
"name": "value_clear_validation",
"signature": "def value_clear_va... | 3 | stack_v2_sparse_classes_30k_train_021774 | Implement the Python class `ProductTemplateInherit` described below.
Class description:
Implement the ProductTemplateInherit class.
Method signatures and docstrings:
- def value_clear_validation(self): This method consist of the modifications done to the non vat item. New field is added as vat status which contains v... | Implement the Python class `ProductTemplateInherit` described below.
Class description:
Implement the ProductTemplateInherit class.
Method signatures and docstrings:
- def value_clear_validation(self): This method consist of the modifications done to the non vat item. New field is added as vat status which contains v... | 9de7a2ce6a17d43107ee08085c9f83a525382798 | <|skeleton|>
class ProductTemplateInherit:
def value_clear_validation(self):
"""This method consist of the modifications done to the non vat item. New field is added as vat status which contains values vat items and non vat items when a non vat item is selected the values in the VAT field is erased"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductTemplateInherit:
def value_clear_validation(self):
"""This method consist of the modifications done to the non vat item. New field is added as vat status which contains values vat items and non vat items when a non vat item is selected the values in the VAT field is erased"""
if self.va... | the_stack_v2_python_sparse | custom_taxes/models/custom_product.py | EshangAllion/cenmetrix_v12 | train | 0 | |
58e288eea32120f3ad86bde20590f1007af23b96 | [
"n = len(nums)\nINF = sys.maxint\nf = [INF for i in xrange(n)]\nfor i, ai in enumerate(nums):\n left, right = (0, i + 1)\n pos = left\n while left <= right:\n mid = left + right >> 1\n if f[mid] >= ai:\n right = mid - 1\n pos = mid\n else:\n left = mid ... | <|body_start_0|>
n = len(nums)
INF = sys.maxint
f = [INF for i in xrange(n)]
for i, ai in enumerate(nums):
left, right = (0, i + 1)
pos = left
while left <= right:
mid = left + right >> 1
if f[mid] >= ai:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS_DP(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
INF = sys.maxint
... | stack_v2_sparse_classes_75kplus_train_067118 | 1,693 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS_DP",
"signature": "def lengthOfLIS_DP(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014312 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS_DP(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS_DP(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def lengthOf... | 0a7aa09a2b95e4caca5b5123fb735ceb5c01e992 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS_DP(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
n = len(nums)
INF = sys.maxint
f = [INF for i in xrange(n)]
for i, ai in enumerate(nums):
left, right = (0, i + 1)
pos = left
while left <= right:
... | the_stack_v2_python_sparse | longest-increasing-subsequence.py | onestarshang/leetcode | train | 0 | |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\nproject_type_list = adm.get_all_project_types()\nreturn project_type_list",
"adm = ProjectAdministration()\nproposal = ProjectType.from_dict(api.payload)\nif proposal is not None:\n 'Wir verwenden Name und project_type_id des Proposals für die Erzeugung eines ProjectType-Objekte... | <|body_start_0|>
adm = ProjectAdministration()
project_type_list = adm.get_all_project_types()
return project_type_list
<|end_body_0|>
<|body_start_1|>
adm = ProjectAdministration()
proposal = ProjectType.from_dict(api.payload)
if proposal is not None:
'Wir v... | ProjectTypeListOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectTypeListOperations:
def get(self):
"""Auslesen aller ProjectType-Objekte"""
<|body_0|>
def post(self):
"""Anlegen eines neuen ProjectType-Objekts"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
adm = ProjectAdministration()
project_ty... | stack_v2_sparse_classes_75kplus_train_067119 | 44,493 | no_license | [
{
"docstring": "Auslesen aller ProjectType-Objekte",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Anlegen eines neuen ProjectType-Objekts",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_003003 | Implement the Python class `ProjectTypeListOperations` described below.
Class description:
Implement the ProjectTypeListOperations class.
Method signatures and docstrings:
- def get(self): Auslesen aller ProjectType-Objekte
- def post(self): Anlegen eines neuen ProjectType-Objekts | Implement the Python class `ProjectTypeListOperations` described below.
Class description:
Implement the ProjectTypeListOperations class.
Method signatures and docstrings:
- def get(self): Auslesen aller ProjectType-Objekte
- def post(self): Anlegen eines neuen ProjectType-Objekts
<|skeleton|>
class ProjectTypeListO... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class ProjectTypeListOperations:
def get(self):
"""Auslesen aller ProjectType-Objekte"""
<|body_0|>
def post(self):
"""Anlegen eines neuen ProjectType-Objekts"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectTypeListOperations:
def get(self):
"""Auslesen aller ProjectType-Objekte"""
adm = ProjectAdministration()
project_type_list = adm.get_all_project_types()
return project_type_list
def post(self):
"""Anlegen eines neuen ProjectType-Objekts"""
adm = Pro... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
3283bac26a2c5c6bd9ccf333976614344c3b026c | [
"self.month = month\nself.day = day\nself.year = year",
"months = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\noutput = months[self.month] + ' '\noutput += str(self.day) + ', '\noutput += str(self.year)\nreturn output",
"daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, ... | <|body_start_0|>
self.month = month
self.day = day
self.year = year
<|end_body_0|>
<|body_start_1|>
months = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
output = months[self.month] + ' '
output += str(self.day) + ', '
... | class to represent a date | Date | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Date:
"""class to represent a date"""
def __init__(self, month, day, year):
"""Date(month,day,year) -> Date"""
<|body_0|>
def __str__(self):
"""str(Date) -> str returns date in readable format"""
<|body_1|>
def go_to_next_day(self):
"""Date.g... | stack_v2_sparse_classes_75kplus_train_067120 | 1,747 | no_license | [
{
"docstring": "Date(month,day,year) -> Date",
"name": "__init__",
"signature": "def __init__(self, month, day, year)"
},
{
"docstring": "str(Date) -> str returns date in readable format",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "Date.go_to_next_day(... | 3 | stack_v2_sparse_classes_30k_train_053581 | Implement the Python class `Date` described below.
Class description:
class to represent a date
Method signatures and docstrings:
- def __init__(self, month, day, year): Date(month,day,year) -> Date
- def __str__(self): str(Date) -> str returns date in readable format
- def go_to_next_day(self): Date.go_to_next_day()... | Implement the Python class `Date` described below.
Class description:
class to represent a date
Method signatures and docstrings:
- def __init__(self, month, day, year): Date(month,day,year) -> Date
- def __str__(self): str(Date) -> str returns date in readable format
- def go_to_next_day(self): Date.go_to_next_day()... | 3c7f67fea02d44f63152825950bec79e587f684a | <|skeleton|>
class Date:
"""class to represent a date"""
def __init__(self, month, day, year):
"""Date(month,day,year) -> Date"""
<|body_0|>
def __str__(self):
"""str(Date) -> str returns date in readable format"""
<|body_1|>
def go_to_next_day(self):
"""Date.g... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Date:
"""class to represent a date"""
def __init__(self, month, day, year):
"""Date(month,day,year) -> Date"""
self.month = month
self.day = day
self.year = year
def __str__(self):
"""str(Date) -> str returns date in readable format"""
months = ['', 'J... | the_stack_v2_python_sparse | dates.py | Mercrist/Intermediate-Python-Solutions | train | 1 |
5568c53b8e8f44243969ce8850a1e295688c95c5 | [
"queue = [root]\nres = []\nwhile queue:\n node = queue.pop(0)\n if node:\n res.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\n else:\n res.append('#')\nreturn ','.join(res)",
"vals = data.split(',')\nroot_val = vals.pop(0)\nif root_val == '#':\n ... | <|body_start_0|>
queue = [root]
res = []
while queue:
node = queue.pop(0)
if node:
res.append(str(node.val))
queue.append(node.left)
queue.append(node.right)
else:
res.append('#')
return '... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_067121 | 1,507 | 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_033993 | 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:... | dca40686c6a280bd394feb8e6e78d40eecf854b9 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
queue = [root]
res = []
while queue:
node = queue.pop(0)
if node:
res.append(str(node.val))
queue.append(node.left... | the_stack_v2_python_sparse | src/amazon/297. Serialize and Deserialize Binary Tree.py | 1325052669/leetcode | train | 0 | |
2820b73150010fec08f228eeb5b1092ba3969494 | [
"res = ''\nif root:\n q = [root]\n while q:\n nq = []\n while q:\n node = q.pop(0)\n if node:\n res += str(node.val) + ' '\n nq.append(node.left)\n nq.append(node.right)\n else:\n res += 'none '\n ... | <|body_start_0|>
res = ''
if root:
q = [root]
while q:
nq = []
while q:
node = q.pop(0)
if node:
res += str(node.val) + ' '
nq.append(node.left)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_067122 | 2,958 | 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_025150 | 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:... | 80e78b153ad2bdfb52070ba75b166a4237847d75 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = ''
if root:
q = [root]
while q:
nq = []
while q:
node = q.pop(0)
if node:
... | the_stack_v2_python_sparse | 297-serializeTree.py | MarshalLeeeeee/myLeetCodes | train | 0 | |
7d274fd9633f0c1f97853f71014378afe8e5c053 | [
"dummy = ListNode(0)\ntail = dummy\nwhile l1 and l2:\n '\\n Use tail to keep track of new linked list using the original space in l1 and l2.\\n After one list finished merging, we only need to set next node of the tail to the head of remaining\\n not empty list.\\n '\n... | <|body_start_0|>
dummy = ListNode(0)
tail = dummy
while l1 and l2:
'\n Use tail to keep track of new linked list using the original space in l1 and l2.\n After one list finished merging, we only need to set next node of the tail to the head of remaining\n ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeKLists(self, lists):
""":type lists: list[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dummy = ... | stack_v2_sparse_classes_75kplus_train_067123 | 1,412 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
},
{
"docstring": ":type lists: list[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023950 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeKLists(self, lists): :type lists: list[ListNode] :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeKLists(self, lists): :type lists: list[ListNode] :rtype: ListNode
<|skeleton|>... | 7b5c5eca6426ef50d0f2bad4f6df2c8fb0357155 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeKLists(self, lists):
""":type lists: list[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
dummy = ListNode(0)
tail = dummy
while l1 and l2:
'\n Use tail to keep track of new linked list using the original space in l1 and l2.\n Aft... | the_stack_v2_python_sparse | com/hxdavid/leetcode/23MergeKSortedLists.py | hxssgaa/pyleetcode | train | 0 | |
aae353e64c9e6239a9a68f2939285c6bf8cdded8 | [
"self.name = obja['name']\nself.attractiveness = int(obja['attractiveness'])\nself.intelligence = int(obja['intelligence'])\nself.maintainance = int(obja['maintainance'])\nself.is_committed = obja['is_committed']\nself.choose_type = obja['choose_type']\nself.gift_received = {'gift_luxury': [], 'gift_essential': [],... | <|body_start_0|>
self.name = obja['name']
self.attractiveness = int(obja['attractiveness'])
self.intelligence = int(obja['intelligence'])
self.maintainance = int(obja['maintainance'])
self.is_committed = obja['is_committed']
self.choose_type = obja['choose_type']
... | Class of a desperate girl attributes: name, attractiveness, intelligence, maintainance, is_commited, to_commited, happiness, choose_type, gifts_recieved | GDesperate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GDesperate:
"""Class of a desperate girl attributes: name, attractiveness, intelligence, maintainance, is_commited, to_commited, happiness, choose_type, gifts_recieved"""
def __init__(self, obja):
"""Initializes a Girl of type Desperate"""
<|body_0|>
def calc_happiness(s... | stack_v2_sparse_classes_75kplus_train_067124 | 8,687 | no_license | [
{
"docstring": "Initializes a Girl of type Desperate",
"name": "__init__",
"signature": "def __init__(self, obja)"
},
{
"docstring": "Calculates and sets happiness of girl using appropriate logic",
"name": "calc_happiness",
"signature": "def calc_happiness(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007730 | Implement the Python class `GDesperate` described below.
Class description:
Class of a desperate girl attributes: name, attractiveness, intelligence, maintainance, is_commited, to_commited, happiness, choose_type, gifts_recieved
Method signatures and docstrings:
- def __init__(self, obja): Initializes a Girl of type ... | Implement the Python class `GDesperate` described below.
Class description:
Class of a desperate girl attributes: name, attractiveness, intelligence, maintainance, is_commited, to_commited, happiness, choose_type, gifts_recieved
Method signatures and docstrings:
- def __init__(self, obja): Initializes a Girl of type ... | c6e96a7ca5251837281d8d2b8c2123c787ad00de | <|skeleton|>
class GDesperate:
"""Class of a desperate girl attributes: name, attractiveness, intelligence, maintainance, is_commited, to_commited, happiness, choose_type, gifts_recieved"""
def __init__(self, obja):
"""Initializes a Girl of type Desperate"""
<|body_0|>
def calc_happiness(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GDesperate:
"""Class of a desperate girl attributes: name, attractiveness, intelligence, maintainance, is_commited, to_commited, happiness, choose_type, gifts_recieved"""
def __init__(self, obja):
"""Initializes a Girl of type Desperate"""
self.name = obja['name']
self.attractiven... | the_stack_v2_python_sparse | part1/helper/all_boys_girls.py | PPL-IIITA/ppl-assignment-dewana-dewan | train | 0 |
a3a4620b1b7ab47ea60d38e549fa3a9529a6707a | [
"self.OFDMObj = OFDM(ofdm_type, mapped_info, pilot_value, n_carriers, n_pilots, n_cp)\nself.ofdm_type = self.OFDMObj.ofdm_type\nself.mapped_info = self.OFDMObj.mapped_info\nself.pilot_value = self.OFDMObj.pilot_value\nself.number_of_carriers = self.OFDMObj.number_of_carriers\nself.number_of_pilots = self.OFDMObj.nu... | <|body_start_0|>
self.OFDMObj = OFDM(ofdm_type, mapped_info, pilot_value, n_carriers, n_pilots, n_cp)
self.ofdm_type = self.OFDMObj.ofdm_type
self.mapped_info = self.OFDMObj.mapped_info
self.pilot_value = self.OFDMObj.pilot_value
self.number_of_carriers = self.OFDMObj.number_of_c... | TestOFDMTypes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestOFDMTypes:
def setUp(self):
"""Setup function TestTypes for class OFDM"""
<|body_0|>
def test_types(self):
"""Function to test data types for class OFDM"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.OFDMObj = OFDM(ofdm_type, mapped_info, ... | stack_v2_sparse_classes_75kplus_train_067125 | 2,661 | permissive | [
{
"docstring": "Setup function TestTypes for class OFDM",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Function to test data types for class OFDM",
"name": "test_types",
"signature": "def test_types(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026337 | Implement the Python class `TestOFDMTypes` described below.
Class description:
Implement the TestOFDMTypes class.
Method signatures and docstrings:
- def setUp(self): Setup function TestTypes for class OFDM
- def test_types(self): Function to test data types for class OFDM | Implement the Python class `TestOFDMTypes` described below.
Class description:
Implement the TestOFDMTypes class.
Method signatures and docstrings:
- def setUp(self): Setup function TestTypes for class OFDM
- def test_types(self): Function to test data types for class OFDM
<|skeleton|>
class TestOFDMTypes:
def ... | 825a0eab64be709efe161b9a48eb54c4bc5c1bef | <|skeleton|>
class TestOFDMTypes:
def setUp(self):
"""Setup function TestTypes for class OFDM"""
<|body_0|>
def test_types(self):
"""Function to test data types for class OFDM"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestOFDMTypes:
def setUp(self):
"""Setup function TestTypes for class OFDM"""
self.OFDMObj = OFDM(ofdm_type, mapped_info, pilot_value, n_carriers, n_pilots, n_cp)
self.ofdm_type = self.OFDMObj.ofdm_type
self.mapped_info = self.OFDMObj.mapped_info
self.pilot_value = self... | the_stack_v2_python_sparse | VLC_devel/class_structure/__auto_gen__/test_OFDM.py | wenh81/vlc_simulator | train | 0 | |
efee257ca15193f95673f1d5d97d2225691dedfb | [
"from django.contrib.auth.models import User\nu = User.objects.create(username='test', password='test')\nself.failUnless(u.get_profile())",
"from django.contrib.auth.models import User\nr = self.client.post('/account/register/', {'first_name': 'Test', 'last_name': 'Example', 'username': 'test', 'email': 'test.use... | <|body_start_0|>
from django.contrib.auth.models import User
u = User.objects.create(username='test', password='test')
self.failUnless(u.get_profile())
<|end_body_0|>
<|body_start_1|>
from django.contrib.auth.models import User
r = self.client.post('/account/register/', {'first_... | UserTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserTest:
def test_profile_created(self):
"""Tests that a new user gets a default profile"""
<|body_0|>
def test_profile_filled(self):
"""Test that registration profile values are populated in the Profile."""
<|body_1|>
def test_first_last_name(self):
... | stack_v2_sparse_classes_75kplus_train_067126 | 2,523 | permissive | [
{
"docstring": "Tests that a new user gets a default profile",
"name": "test_profile_created",
"signature": "def test_profile_created(self)"
},
{
"docstring": "Test that registration profile values are populated in the Profile.",
"name": "test_profile_filled",
"signature": "def test_prof... | 4 | stack_v2_sparse_classes_30k_train_024331 | Implement the Python class `UserTest` described below.
Class description:
Implement the UserTest class.
Method signatures and docstrings:
- def test_profile_created(self): Tests that a new user gets a default profile
- def test_profile_filled(self): Test that registration profile values are populated in the Profile.
... | Implement the Python class `UserTest` described below.
Class description:
Implement the UserTest class.
Method signatures and docstrings:
- def test_profile_created(self): Tests that a new user gets a default profile
- def test_profile_filled(self): Test that registration profile values are populated in the Profile.
... | 651da880a3d4295243205bdae4de88504edc91de | <|skeleton|>
class UserTest:
def test_profile_created(self):
"""Tests that a new user gets a default profile"""
<|body_0|>
def test_profile_filled(self):
"""Test that registration profile values are populated in the Profile."""
<|body_1|>
def test_first_last_name(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserTest:
def test_profile_created(self):
"""Tests that a new user gets a default profile"""
from django.contrib.auth.models import User
u = User.objects.create(username='test', password='test')
self.failUnless(u.get_profile())
def test_profile_filled(self):
"""Tes... | the_stack_v2_python_sparse | communityprofiles/account/tests.py | 216software/Profiles | train | 3 | |
241ef0f5d59ff12b9faee262aa85915498c394a6 | [
"denvec = self[self['frame'] == frame]['coef'].values\nsquare = pd.DataFrame(density_as_square(denvec))\nsquare.index.name = 'chi0'\nsquare.columns.name = 'chi1'\nreturn square",
"cmat = momatrix.square(column=mocoefs).values\nchi0, chi1, dens, frame = density_from_momatrix(cmat, occvec)\nreturn cls.from_dict({'c... | <|body_start_0|>
denvec = self[self['frame'] == frame]['coef'].values
square = pd.DataFrame(density_as_square(denvec))
square.index.name = 'chi0'
square.columns.name = 'chi1'
return square
<|end_body_0|>
<|body_start_1|>
cmat = momatrix.square(column=mocoefs).values
... | The density matrix in a contracted basis set. As it is square symmetric, only n_basis_functions * (n_basis_functions + 1) / 2 rows are stored. +-------------------+----------+-------------------------------------------+ | Column | Type | Description | +===================+==========+====================================... | DensityMatrix | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DensityMatrix:
"""The density matrix in a contracted basis set. As it is square symmetric, only n_basis_functions * (n_basis_functions + 1) / 2 rows are stored. +-------------------+----------+-------------------------------------------+ | Column | Type | Description | +===================+======... | stack_v2_sparse_classes_75kplus_train_067127 | 21,790 | permissive | [
{
"docstring": "Returns a square dataframe of the density matrix.",
"name": "square",
"signature": "def square(self, frame=0)"
},
{
"docstring": "A density matrix can be constructed from an MOMatrix by: .. math:: D_{uv} = \\\\sum_{i}^{N} C_{ui} C_{vi} n_{i} Args: momatrix (:class:`~exatomic.orbi... | 3 | stack_v2_sparse_classes_30k_train_027862 | Implement the Python class `DensityMatrix` described below.
Class description:
The density matrix in a contracted basis set. As it is square symmetric, only n_basis_functions * (n_basis_functions + 1) / 2 rows are stored. +-------------------+----------+-------------------------------------------+ | Column | Type | De... | Implement the Python class `DensityMatrix` described below.
Class description:
The density matrix in a contracted basis set. As it is square symmetric, only n_basis_functions * (n_basis_functions + 1) / 2 rows are stored. +-------------------+----------+-------------------------------------------+ | Column | Type | De... | 2e87bae3e043e6958129fc823c83ab0b46add8b5 | <|skeleton|>
class DensityMatrix:
"""The density matrix in a contracted basis set. As it is square symmetric, only n_basis_functions * (n_basis_functions + 1) / 2 rows are stored. +-------------------+----------+-------------------------------------------+ | Column | Type | Description | +===================+======... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DensityMatrix:
"""The density matrix in a contracted basis set. As it is square symmetric, only n_basis_functions * (n_basis_functions + 1) / 2 rows are stored. +-------------------+----------+-------------------------------------------+ | Column | Type | Description | +===================+==========+========... | the_stack_v2_python_sparse | exatomic/core/orbital.py | exa-analytics/exatomic | train | 15 |
9c67bc9edab270e6aaeab0b8d73402a9ce67568e | [
"if not type(lst) == list:\n exit('The argument given was not a list.')\nif datatype:\n for elem in lst:\n if not type(elem) == datatype:\n exit('The list is not fill with the good datatype')\nreturn numpy.asarray(lst)",
"if not type(tpl) == tuple:\n exit('The argument given was not a t... | <|body_start_0|>
if not type(lst) == list:
exit('The argument given was not a list.')
if datatype:
for elem in lst:
if not type(elem) == datatype:
exit('The list is not fill with the good datatype')
return numpy.asarray(lst)
<|end_body_... | NumPyCreator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumPyCreator:
def from_list(lst, datatype=False):
"""takes in a list and returns its corresponding NumPy array."""
<|body_0|>
def from_tuple(tpl, datatype=False):
"""takes in a tuple and returns its corresponding NumPy array."""
<|body_1|>
def from_itera... | stack_v2_sparse_classes_75kplus_train_067128 | 3,686 | no_license | [
{
"docstring": "takes in a list and returns its corresponding NumPy array.",
"name": "from_list",
"signature": "def from_list(lst, datatype=False)"
},
{
"docstring": "takes in a tuple and returns its corresponding NumPy array.",
"name": "from_tuple",
"signature": "def from_tuple(tpl, dat... | 6 | stack_v2_sparse_classes_30k_test_001263 | Implement the Python class `NumPyCreator` described below.
Class description:
Implement the NumPyCreator class.
Method signatures and docstrings:
- def from_list(lst, datatype=False): takes in a list and returns its corresponding NumPy array.
- def from_tuple(tpl, datatype=False): takes in a tuple and returns its cor... | Implement the Python class `NumPyCreator` described below.
Class description:
Implement the NumPyCreator class.
Method signatures and docstrings:
- def from_list(lst, datatype=False): takes in a list and returns its corresponding NumPy array.
- def from_tuple(tpl, datatype=False): takes in a tuple and returns its cor... | a9aa648e1ef4daaf1942e5ae4d8afdd0904b5dbe | <|skeleton|>
class NumPyCreator:
def from_list(lst, datatype=False):
"""takes in a list and returns its corresponding NumPy array."""
<|body_0|>
def from_tuple(tpl, datatype=False):
"""takes in a tuple and returns its corresponding NumPy array."""
<|body_1|>
def from_itera... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumPyCreator:
def from_list(lst, datatype=False):
"""takes in a list and returns its corresponding NumPy array."""
if not type(lst) == list:
exit('The argument given was not a list.')
if datatype:
for elem in lst:
if not type(elem) == datatype:
... | the_stack_v2_python_sparse | day03/ex00/NumPyCreator.py | roduquen/42-AI_Bootcamp-Machine-Learning | train | 0 | |
26cd529ef6f5aba1c50d26fc9c546b0324f43abd | [
"table_object = Storage.query.get_or_404(int_id)\nform = StorageForm(obj=table_object)\ntemplate_return = flask.render_template('edit.html', form=form)\nif flask_login.current_user.id != table_object.user_id:\n flask.abort(403)\nreturn flask.Response(template_return, mimetype='text/html')",
"table_object = Sto... | <|body_start_0|>
table_object = Storage.query.get_or_404(int_id)
form = StorageForm(obj=table_object)
template_return = flask.render_template('edit.html', form=form)
if flask_login.current_user.id != table_object.user_id:
flask.abort(403)
return flask.Response(templat... | EditStorageResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditStorageResource:
def get(self, int_id):
"""Args: int_id: Returns:"""
<|body_0|>
def post(self, int_id):
"""Args: int_id: Returns:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
table_object = Storage.query.get_or_404(int_id)
form = Stor... | stack_v2_sparse_classes_75kplus_train_067129 | 4,506 | no_license | [
{
"docstring": "Args: int_id: Returns:",
"name": "get",
"signature": "def get(self, int_id)"
},
{
"docstring": "Args: int_id: Returns:",
"name": "post",
"signature": "def post(self, int_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014449 | Implement the Python class `EditStorageResource` described below.
Class description:
Implement the EditStorageResource class.
Method signatures and docstrings:
- def get(self, int_id): Args: int_id: Returns:
- def post(self, int_id): Args: int_id: Returns: | Implement the Python class `EditStorageResource` described below.
Class description:
Implement the EditStorageResource class.
Method signatures and docstrings:
- def get(self, int_id): Args: int_id: Returns:
- def post(self, int_id): Args: int_id: Returns:
<|skeleton|>
class EditStorageResource:
def get(self, i... | 865403e3b1717226b25c9d64aeb4c35c7220e7e3 | <|skeleton|>
class EditStorageResource:
def get(self, int_id):
"""Args: int_id: Returns:"""
<|body_0|>
def post(self, int_id):
"""Args: int_id: Returns:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EditStorageResource:
def get(self, int_id):
"""Args: int_id: Returns:"""
table_object = Storage.query.get_or_404(int_id)
form = StorageForm(obj=table_object)
template_return = flask.render_template('edit.html', form=form)
if flask_login.current_user.id != table_object.u... | the_stack_v2_python_sparse | things_organizer/web_app/storages/resources.py | yeyeto2788/Things-Organizer | train | 11 | |
225d5f33a0a8d75a74c248bcee99c805607f2fe7 | [
"if not points:\n return None\npoint = random.choice(points)\npoints.remove(point)\nreturn point",
"if location_type == LocationType.BaseAirDefense:\n return self._random_from(self.base_air_defense)\nif location_type == LocationType.Coastal:\n return self._random_from(self.coastal_defenses)\nif location_... | <|body_start_0|>
if not points:
return None
point = random.choice(points)
points.remove(point)
return point
<|end_body_0|>
<|body_start_1|>
if location_type == LocationType.BaseAirDefense:
return self._random_from(self.base_air_defense)
if locatio... | Defines the preset locations loaded from the campaign mission file. | PresetLocations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PresetLocations:
"""Defines the preset locations loaded from the campaign mission file."""
def _random_from(points: List[Point]) -> Optional[Point]:
"""Finds, removes, and returns a random position from the given list."""
<|body_0|>
def random_for(self, location_type: Lo... | stack_v2_sparse_classes_75kplus_train_067130 | 24,312 | no_license | [
{
"docstring": "Finds, removes, and returns a random position from the given list.",
"name": "_random_from",
"signature": "def _random_from(points: List[Point]) -> Optional[Point]"
},
{
"docstring": "Returns a position suitable for the given location type. The location, if found, will be claimed... | 2 | null | Implement the Python class `PresetLocations` described below.
Class description:
Defines the preset locations loaded from the campaign mission file.
Method signatures and docstrings:
- def _random_from(points: List[Point]) -> Optional[Point]: Finds, removes, and returns a random position from the given list.
- def ra... | Implement the Python class `PresetLocations` described below.
Class description:
Defines the preset locations loaded from the campaign mission file.
Method signatures and docstrings:
- def _random_from(points: List[Point]) -> Optional[Point]: Finds, removes, and returns a random position from the given list.
- def ra... | 068f9e42d759b94b8bd72e496c0e2793536fd45e | <|skeleton|>
class PresetLocations:
"""Defines the preset locations loaded from the campaign mission file."""
def _random_from(points: List[Point]) -> Optional[Point]:
"""Finds, removes, and returns a random position from the given list."""
<|body_0|>
def random_for(self, location_type: Lo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PresetLocations:
"""Defines the preset locations loaded from the campaign mission file."""
def _random_from(points: List[Point]) -> Optional[Point]:
"""Finds, removes, and returns a random position from the given list."""
if not points:
return None
point = random.choic... | the_stack_v2_python_sparse | game/theater/controlpoint.py | Pricesswg/dcs_liberation | train | 0 |
b5a33f6450019fff4535086ce66fb17a23707776 | [
"context = context or {}\nids = isinstance(ids, (int, long)) and [ids] or ids\ncr_date = time.strftime('%Y-%m-%d')\nsp_brw = self.browse(cur, uid, ids[0], context=context)\nif not sp_brw.date_contract_expiry or (sp_brw.date_contract_expiry and cr_date <= sp_brw.date_contract_expiry) or context.get('force_expiry_pic... | <|body_start_0|>
context = context or {}
ids = isinstance(ids, (int, long)) and [ids] or ids
cr_date = time.strftime('%Y-%m-%d')
sp_brw = self.browse(cur, uid, ids[0], context=context)
if not sp_brw.date_contract_expiry or (sp_brw.date_contract_expiry and cr_date <= sp_brw.date_c... | StockPickingOut | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StockPickingOut:
def action_process(self, cur, uid, ids, context=None):
"""overwrite the method to add a verification of the contract due date before process the stock picking out."""
<|body_0|>
def copy(self, default=None):
"""Ovwerwrite the copy method to also copy... | stack_v2_sparse_classes_75kplus_train_067131 | 5,912 | no_license | [
{
"docstring": "overwrite the method to add a verification of the contract due date before process the stock picking out.",
"name": "action_process",
"signature": "def action_process(self, cur, uid, ids, context=None)"
},
{
"docstring": "Ovwerwrite the copy method to also copy the date_contract_... | 2 | stack_v2_sparse_classes_30k_train_023853 | Implement the Python class `StockPickingOut` described below.
Class description:
Implement the StockPickingOut class.
Method signatures and docstrings:
- def action_process(self, cur, uid, ids, context=None): overwrite the method to add a verification of the contract due date before process the stock picking out.
- d... | Implement the Python class `StockPickingOut` described below.
Class description:
Implement the StockPickingOut class.
Method signatures and docstrings:
- def action_process(self, cur, uid, ids, context=None): overwrite the method to add a verification of the contract due date before process the stock picking out.
- d... | 511dc410b4eba1f8ea939c6af02a5adea5122c92 | <|skeleton|>
class StockPickingOut:
def action_process(self, cur, uid, ids, context=None):
"""overwrite the method to add a verification of the contract due date before process the stock picking out."""
<|body_0|>
def copy(self, default=None):
"""Ovwerwrite the copy method to also copy... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StockPickingOut:
def action_process(self, cur, uid, ids, context=None):
"""overwrite the method to add a verification of the contract due date before process the stock picking out."""
context = context or {}
ids = isinstance(ids, (int, long)) and [ids] or ids
cr_date = time.str... | the_stack_v2_python_sparse | stock_purchase_expiry/model/stock.py | yelizariev/addons-vauxoo | train | 3 | |
01e229d56676a0cbbdc65efc3656b57d03a66cc8 | [
"fm = FirewallManger()\npanic_mode = fm.get_firewall_panic_mode()\nreturn Response(panic_mode, status=status.HTTP_200_OK)",
"fm = FirewallManger()\nmode = request.DATA.get('panic_mode')\nmode_struct = ['on', 'off']\nif mode not in mode_struct:\n return Response('Arguments is not invalid!')\nelse:\n result =... | <|body_start_0|>
fm = FirewallManger()
panic_mode = fm.get_firewall_panic_mode()
return Response(panic_mode, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
fm = FirewallManger()
mode = request.DATA.get('panic_mode')
mode_struct = ['on', 'off']
if mode... | Dynamic firewall configuration: runtime and permanent | FirewalldPnaicMode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirewalldPnaicMode:
"""Dynamic firewall configuration: runtime and permanent"""
def get(self, request, format=None):
"""query the system firewall panic mode"""
<|body_0|>
def put(self, request, format=None):
"""config the firewall panic mode:on or off"""
... | stack_v2_sparse_classes_75kplus_train_067132 | 21,597 | no_license | [
{
"docstring": "query the system firewall panic mode",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "config the firewall panic mode:on or off",
"name": "put",
"signature": "def put(self, request, format=None)"
}
] | 2 | null | Implement the Python class `FirewalldPnaicMode` described below.
Class description:
Dynamic firewall configuration: runtime and permanent
Method signatures and docstrings:
- def get(self, request, format=None): query the system firewall panic mode
- def put(self, request, format=None): config the firewall panic mode:... | Implement the Python class `FirewalldPnaicMode` described below.
Class description:
Dynamic firewall configuration: runtime and permanent
Method signatures and docstrings:
- def get(self, request, format=None): query the system firewall panic mode
- def put(self, request, format=None): config the firewall panic mode:... | 7f801a569a396a27371d0831752595877c224a6b | <|skeleton|>
class FirewalldPnaicMode:
"""Dynamic firewall configuration: runtime and permanent"""
def get(self, request, format=None):
"""query the system firewall panic mode"""
<|body_0|>
def put(self, request, format=None):
"""config the firewall panic mode:on or off"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FirewalldPnaicMode:
"""Dynamic firewall configuration: runtime and permanent"""
def get(self, request, format=None):
"""query the system firewall panic mode"""
fm = FirewallManger()
panic_mode = fm.get_firewall_panic_mode()
return Response(panic_mode, status=status.HTTP_20... | the_stack_v2_python_sparse | Python_projects/flask_projects/unicorn_project/firewall/views.py | sdtimothy8/Coding | train | 0 |
456fd808fbd7ccc57d50d31d301f88d3a81fb23a | [
"if not isinstance(string, str):\n raise ValueError('This indexer works only with strings. ')\nour_dict = {}\nfor obj in t.Tokenizer().iter_tokenize(string):\n if obj.kind == 'alpha' or obj.kind == 'digit':\n l = our_dict.setdefault(obj.word, [])\n l.append(Basic_Position(obj.start, obj.end))\nr... | <|body_start_0|>
if not isinstance(string, str):
raise ValueError('This indexer works only with strings. ')
our_dict = {}
for obj in t.Tokenizer().iter_tokenize(string):
if obj.kind == 'alpha' or obj.kind == 'digit':
l = our_dict.setdefault(obj.word, [])
... | A class for creating an index. Contains three methods for creating an index from different inputs: one method creates an index from a string and two - from a file, they differ in structures of a result dict. Contains also a method to add an index from a file to a database. | Indexer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Indexer:
"""A class for creating an index. Contains three methods for creating an index from different inputs: one method creates an index from a string and two - from a file, they differ in structures of a result dict. Contains also a method to add an index from a file to a database."""
def... | stack_v2_sparse_classes_75kplus_train_067133 | 7,636 | no_license | [
{
"docstring": "Takes a string as an argument and creates a dictionary, which contains words or digits as keys and a list of their 'basic' positions in the string as values.",
"name": "create_index_from_string",
"signature": "def create_index_from_string(self, string)"
},
{
"docstring": "The met... | 4 | stack_v2_sparse_classes_30k_train_025954 | Implement the Python class `Indexer` described below.
Class description:
A class for creating an index. Contains three methods for creating an index from different inputs: one method creates an index from a string and two - from a file, they differ in structures of a result dict. Contains also a method to add an index... | Implement the Python class `Indexer` described below.
Class description:
A class for creating an index. Contains three methods for creating an index from different inputs: one method creates an index from a string and two - from a file, they differ in structures of a result dict. Contains also a method to add an index... | 61af7ae245a512ba5a713d005f23889984cccd96 | <|skeleton|>
class Indexer:
"""A class for creating an index. Contains three methods for creating an index from different inputs: one method creates an index from a string and two - from a file, they differ in structures of a result dict. Contains also a method to add an index from a file to a database."""
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Indexer:
"""A class for creating an index. Contains three methods for creating an index from different inputs: one method creates an index from a string and two - from a file, they differ in structures of a result dict. Contains also a method to add an index from a file to a database."""
def create_index... | the_stack_v2_python_sparse | my_indexer_combined.py | kr-ann/search_engine | train | 0 |
64877d873a49b85ea640dd476677996118098e97 | [
"args = self.args\nif args and (not args[0] in [\"'\", ',', ':']):\n args = ' %s' % args.strip()\nself.args = args",
"caller = self.caller\nif self.args[0] != ':':\n if not self.args:\n msg = 'What do you want to do?'\n self.caller.msg(msg)\n else:\n msg = '%s%s' % (self.caller.name,... | <|body_start_0|>
args = self.args
if args and (not args[0] in ["'", ',', ':']):
args = ' %s' % args.strip()
self.args = args
<|end_body_0|>
<|body_start_1|>
caller = self.caller
if self.args[0] != ':':
if not self.args:
msg = 'What do you ... | Strike a pose. Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name. | CmdEmote | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CmdEmote:
"""Strike a pose. Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name."""
def parse(self):
... | stack_v2_sparse_classes_75kplus_train_067134 | 8,061 | no_license | [
{
"docstring": "Custom parse the cases where the emote starts with some special letter, such as 's, at which we don't want to separate the caller's name and the emote with a space.",
"name": "parse",
"signature": "def parse(self)"
},
{
"docstring": "Hook function",
"name": "func",
"signa... | 2 | stack_v2_sparse_classes_30k_train_017607 | Implement the Python class `CmdEmote` described below.
Class description:
Strike a pose. Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your ... | Implement the Python class `CmdEmote` described below.
Class description:
Strike a pose. Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your ... | f0406066f1416d823c0dce8ef11035e46f37b7aa | <|skeleton|>
class CmdEmote:
"""Strike a pose. Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name."""
def parse(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CmdEmote:
"""Strike a pose. Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name."""
def parse(self):
"""Custom par... | the_stack_v2_python_sparse | commands/emotecommands.py | madamdata/polytopemud | train | 0 |
0f912392171b8374ab4803c0145ba81ee3c02dd7 | [
"self.disable_network = disable_network\nself.preserve_mac_address_on_new_network = preserve_mac_address_on_new_network\nself.source_network_entity = source_network_entity\nself.target_network_entity = target_network_entity",
"if dictionary is None:\n return None\ndisable_network = dictionary.get('disableNetwo... | <|body_start_0|>
self.disable_network = disable_network
self.preserve_mac_address_on_new_network = preserve_mac_address_on_new_network
self.source_network_entity = source_network_entity
self.target_network_entity = target_network_entity
<|end_body_0|>
<|body_start_1|>
if diction... | Implementation of the 'NetworkMappingProto' model. TODO: type description here. Attributes: disable_network (bool): This can be set to true to indicate that the attached network should be left in disabled state. This value takes priority over the value in RestoredObjectNetworkConfigProto. preserve_mac_address_on_new_ne... | NetworkMappingProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkMappingProto:
"""Implementation of the 'NetworkMappingProto' model. TODO: type description here. Attributes: disable_network (bool): This can be set to true to indicate that the attached network should be left in disabled state. This value takes priority over the value in RestoredObjectNet... | stack_v2_sparse_classes_75kplus_train_067135 | 3,391 | permissive | [
{
"docstring": "Constructor for the NetworkMappingProto class",
"name": "__init__",
"signature": "def __init__(self, disable_network=None, preserve_mac_address_on_new_network=None, source_network_entity=None, target_network_entity=None)"
},
{
"docstring": "Creates an instance of this model from ... | 2 | stack_v2_sparse_classes_30k_train_024431 | Implement the Python class `NetworkMappingProto` described below.
Class description:
Implementation of the 'NetworkMappingProto' model. TODO: type description here. Attributes: disable_network (bool): This can be set to true to indicate that the attached network should be left in disabled state. This value takes prior... | Implement the Python class `NetworkMappingProto` described below.
Class description:
Implementation of the 'NetworkMappingProto' model. TODO: type description here. Attributes: disable_network (bool): This can be set to true to indicate that the attached network should be left in disabled state. This value takes prior... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NetworkMappingProto:
"""Implementation of the 'NetworkMappingProto' model. TODO: type description here. Attributes: disable_network (bool): This can be set to true to indicate that the attached network should be left in disabled state. This value takes priority over the value in RestoredObjectNet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NetworkMappingProto:
"""Implementation of the 'NetworkMappingProto' model. TODO: type description here. Attributes: disable_network (bool): This can be set to true to indicate that the attached network should be left in disabled state. This value takes priority over the value in RestoredObjectNetworkConfigPro... | the_stack_v2_python_sparse | cohesity_management_sdk/models/network_mapping_proto.py | cohesity/management-sdk-python | train | 24 |
81151641791bbf4c62f625eb49c5b1bf9ff61073 | [
"exploration = FakeExploration()\nUSER_ID = 'user_id'\nexploration.state_ids = []\nwith self.assertRaisesRegexp(utils.ValidationError, 'exploration has no states'):\n exp_services.save_exploration(USER_ID, exploration)\nexploration.state_ids = ['A string']\nwith self.assertRaisesRegexp(utils.ValidationError, 'In... | <|body_start_0|>
exploration = FakeExploration()
USER_ID = 'user_id'
exploration.state_ids = []
with self.assertRaisesRegexp(utils.ValidationError, 'exploration has no states'):
exp_services.save_exploration(USER_ID, exploration)
exploration.state_ids = ['A string']
... | Test the exploration domain object. | ExplorationDomainUnitTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExplorationDomainUnitTests:
"""Test the exploration domain object."""
def test_validation(self):
"""Test validation of explorations."""
<|body_0|>
def test_init_state_property(self):
"""Test the init_state property."""
<|body_1|>
def test_is_demo_pro... | stack_v2_sparse_classes_75kplus_train_067136 | 5,716 | permissive | [
{
"docstring": "Test validation of explorations.",
"name": "test_validation",
"signature": "def test_validation(self)"
},
{
"docstring": "Test the init_state property.",
"name": "test_init_state_property",
"signature": "def test_init_state_property(self)"
},
{
"docstring": "Test ... | 5 | stack_v2_sparse_classes_30k_train_049106 | Implement the Python class `ExplorationDomainUnitTests` described below.
Class description:
Test the exploration domain object.
Method signatures and docstrings:
- def test_validation(self): Test validation of explorations.
- def test_init_state_property(self): Test the init_state property.
- def test_is_demo_propert... | Implement the Python class `ExplorationDomainUnitTests` described below.
Class description:
Test the exploration domain object.
Method signatures and docstrings:
- def test_validation(self): Test validation of explorations.
- def test_init_state_property(self): Test the init_state property.
- def test_is_demo_propert... | 3d97903a5155ec67f135b1aa2c02f3bb39eb02e7 | <|skeleton|>
class ExplorationDomainUnitTests:
"""Test the exploration domain object."""
def test_validation(self):
"""Test validation of explorations."""
<|body_0|>
def test_init_state_property(self):
"""Test the init_state property."""
<|body_1|>
def test_is_demo_pro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExplorationDomainUnitTests:
"""Test the exploration domain object."""
def test_validation(self):
"""Test validation of explorations."""
exploration = FakeExploration()
USER_ID = 'user_id'
exploration.state_ids = []
with self.assertRaisesRegexp(utils.ValidationError... | the_stack_v2_python_sparse | core/domain/exp_domain_test.py | willingc/oh-missions-oppia-beta | train | 0 |
e5e329d57dbeb8ac57ee4ec9596b2a58b0d9a60e | [
"from collections import Counter\nc = Counter(arr1)\nhashmap = dict(c)\nres = []\nfor i in arr2:\n for j in range(hashmap.get(i)):\n res.append(i)\ndiff = [item for item in arr1 if item not in arr2]\nreturn res + sorted(diff)",
"from collections import defaultdict\ndic = defaultdict(int)\nfor k, v in en... | <|body_start_0|>
from collections import Counter
c = Counter(arr1)
hashmap = dict(c)
res = []
for i in arr2:
for j in range(hashmap.get(i)):
res.append(i)
diff = [item for item in arr1 if item not in arr2]
return res + sorted(diff)
<|en... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def relativeSortArray(self, arr1, arr2):
""":type arr1: List[int] :type arr2: List[int] :rtype: List[int]"""
<|body_0|>
def relativeSortArray(self, arr1, arr2):
""":type arr1: List[int] :type arr2: List[int] :rtype: List[int]"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus_train_067137 | 1,587 | no_license | [
{
"docstring": ":type arr1: List[int] :type arr2: List[int] :rtype: List[int]",
"name": "relativeSortArray",
"signature": "def relativeSortArray(self, arr1, arr2)"
},
{
"docstring": ":type arr1: List[int] :type arr2: List[int] :rtype: List[int]",
"name": "relativeSortArray",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_023121 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def relativeSortArray(self, arr1, arr2): :type arr1: List[int] :type arr2: List[int] :rtype: List[int]
- def relativeSortArray(self, arr1, arr2): :type arr1: List[int] :type arr2... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def relativeSortArray(self, arr1, arr2): :type arr1: List[int] :type arr2: List[int] :rtype: List[int]
- def relativeSortArray(self, arr1, arr2): :type arr1: List[int] :type arr2... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def relativeSortArray(self, arr1, arr2):
""":type arr1: List[int] :type arr2: List[int] :rtype: List[int]"""
<|body_0|>
def relativeSortArray(self, arr1, arr2):
""":type arr1: List[int] :type arr2: List[int] :rtype: List[int]"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def relativeSortArray(self, arr1, arr2):
""":type arr1: List[int] :type arr2: List[int] :rtype: List[int]"""
from collections import Counter
c = Counter(arr1)
hashmap = dict(c)
res = []
for i in arr2:
for j in range(hashmap.get(i)):
... | the_stack_v2_python_sparse | 1122_Relative_Sort_Array.py | bingli8802/leetcode | train | 0 | |
30993c72838d6c0a57d2aa581df01e9aedc58dcd | [
"self.tcp_target = tcp_target\nself.tcp_port = tcp_port\nself.verbosity = verbosity\nself.peer = '{}:{}'.format(self.tcp_target, self.tcp_port)\nif is_ipv4(self.tcp_target):\n self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nelif is_ipv6(self.tcp_target):\n self.tcp_client = socket.socket(... | <|body_start_0|>
self.tcp_target = tcp_target
self.tcp_port = tcp_port
self.verbosity = verbosity
self.peer = '{}:{}'.format(self.tcp_target, self.tcp_port)
if is_ipv4(self.tcp_target):
self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
elif i... | TCP Client provides methods to handle communication with TCP server | TCPCli | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TCPCli:
"""TCP Client provides methods to handle communication with TCP server"""
def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False) -> None:
"""TCP client constructor :param str tcp_target: target TCP server ip address :param int tcp_port: target TCP server po... | stack_v2_sparse_classes_75kplus_train_067138 | 4,620 | permissive | [
{
"docstring": "TCP client constructor :param str tcp_target: target TCP server ip address :param int tcp_port: target TCP server port :param bool verbosity: display verbose output :return None:",
"name": "__init__",
"signature": "def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False)... | 6 | stack_v2_sparse_classes_30k_train_022365 | Implement the Python class `TCPCli` described below.
Class description:
TCP Client provides methods to handle communication with TCP server
Method signatures and docstrings:
- def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False) -> None: TCP client constructor :param str tcp_target: target TCP se... | Implement the Python class `TCPCli` described below.
Class description:
TCP Client provides methods to handle communication with TCP server
Method signatures and docstrings:
- def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False) -> None: TCP client constructor :param str tcp_target: target TCP se... | 56ae6325c08bcedd22c57b9fe11b58f1b38314ca | <|skeleton|>
class TCPCli:
"""TCP Client provides methods to handle communication with TCP server"""
def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False) -> None:
"""TCP client constructor :param str tcp_target: target TCP server ip address :param int tcp_port: target TCP server po... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TCPCli:
"""TCP Client provides methods to handle communication with TCP server"""
def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False) -> None:
"""TCP client constructor :param str tcp_target: target TCP server ip address :param int tcp_port: target TCP server port :param boo... | the_stack_v2_python_sparse | maza/core/tcp/tcp_client.py | ArturSpirin/maza | train | 2 |
b6937dda356e0fe1337b1bd553934351cdb5b5e5 | [
"Resource.__init__(self)\nself.policy = Policy.UNIQUE\nself.register_name('Arm')\nself.i2c = busio.I2C(board.SCL, board.SDA)\nself.servo = adafruit_pca9685.PCA9685(self.i2c)\nself.kit = ServoKit(channels=16)\ngripper_pin = cfg.motor_config.get_pin('Arm', 'Gripper')\nservo1_pin = cfg.motor_config.get_pin('Arm', 'Ser... | <|body_start_0|>
Resource.__init__(self)
self.policy = Policy.UNIQUE
self.register_name('Arm')
self.i2c = busio.I2C(board.SCL, board.SDA)
self.servo = adafruit_pca9685.PCA9685(self.i2c)
self.kit = ServoKit(channels=16)
gripper_pin = cfg.motor_config.get_pin('Arm',... | ArmMotors | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArmMotors:
def __init__(self):
"""Call set_values to set angles ofs servos. Will need to callibrate for limits"""
<|body_0|>
def set_values(self, values):
"""Receives value as -135 to 135 so there is an offset put into place."""
<|body_1|>
def _set_angle... | stack_v2_sparse_classes_75kplus_train_067139 | 9,340 | no_license | [
{
"docstring": "Call set_values to set angles ofs servos. Will need to callibrate for limits",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Receives value as -135 to 135 so there is an offset put into place.",
"name": "set_values",
"signature": "def set_values... | 3 | stack_v2_sparse_classes_30k_val_001721 | Implement the Python class `ArmMotors` described below.
Class description:
Implement the ArmMotors class.
Method signatures and docstrings:
- def __init__(self): Call set_values to set angles ofs servos. Will need to callibrate for limits
- def set_values(self, values): Receives value as -135 to 135 so there is an of... | Implement the Python class `ArmMotors` described below.
Class description:
Implement the ArmMotors class.
Method signatures and docstrings:
- def __init__(self): Call set_values to set angles ofs servos. Will need to callibrate for limits
- def set_values(self, values): Receives value as -135 to 135 so there is an of... | 98dce5ce80b5bba60c09407c1ff4b4d5c9007d99 | <|skeleton|>
class ArmMotors:
def __init__(self):
"""Call set_values to set angles ofs servos. Will need to callibrate for limits"""
<|body_0|>
def set_values(self, values):
"""Receives value as -135 to 135 so there is an offset put into place."""
<|body_1|>
def _set_angle... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArmMotors:
def __init__(self):
"""Call set_values to set angles ofs servos. Will need to callibrate for limits"""
Resource.__init__(self)
self.policy = Policy.UNIQUE
self.register_name('Arm')
self.i2c = busio.I2C(board.SCL, board.SDA)
self.servo = adafruit_pca96... | the_stack_v2_python_sparse | RaspiCode/resources/motors.py | ranul-pallemulle/Mars-Rover | train | 0 | |
e92b934674eb1f0a260a6c0a85bf0a6b8fea6ed2 | [
"res = [[0 for _ in range(max_weight + 1)] for _ in range(len(weight) + 1)]\nfor i in range(1, len(res)):\n cur_value = value[i - 1]\n cur_weight = weight[i - 1]\n for j in range(1, len(res[0])):\n if cur_weight <= j:\n res[i][j] = max(res[i - 1][j], cur_value + res[i - 1][j - cur_weight]... | <|body_start_0|>
res = [[0 for _ in range(max_weight + 1)] for _ in range(len(weight) + 1)]
for i in range(1, len(res)):
cur_value = value[i - 1]
cur_weight = weight[i - 1]
for j in range(1, len(res[0])):
if cur_weight <= j:
res[i][... | Bag01 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bag01:
def bag01(self, weight, value, max_weight):
""":param weight: 物品重量 :param value: 物品价值 :param max_weight: 背包最大重量 :return: 最大价值"""
<|body_0|>
def show(self, res, weight):
"""装入背包的物品索引(索引从0开始) :param res: :param weight: :return: 返回物品索引"""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus_train_067140 | 2,438 | no_license | [
{
"docstring": ":param weight: 物品重量 :param value: 物品价值 :param max_weight: 背包最大重量 :return: 最大价值",
"name": "bag01",
"signature": "def bag01(self, weight, value, max_weight)"
},
{
"docstring": "装入背包的物品索引(索引从0开始) :param res: :param weight: :return: 返回物品索引",
"name": "show",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_037793 | Implement the Python class `Bag01` described below.
Class description:
Implement the Bag01 class.
Method signatures and docstrings:
- def bag01(self, weight, value, max_weight): :param weight: 物品重量 :param value: 物品价值 :param max_weight: 背包最大重量 :return: 最大价值
- def show(self, res, weight): 装入背包的物品索引(索引从0开始) :param res: ... | Implement the Python class `Bag01` described below.
Class description:
Implement the Bag01 class.
Method signatures and docstrings:
- def bag01(self, weight, value, max_weight): :param weight: 物品重量 :param value: 物品价值 :param max_weight: 背包最大重量 :return: 最大价值
- def show(self, res, weight): 装入背包的物品索引(索引从0开始) :param res: ... | 3eddc77d2f3dafffd177f2a9ee28e9850da2f020 | <|skeleton|>
class Bag01:
def bag01(self, weight, value, max_weight):
""":param weight: 物品重量 :param value: 物品价值 :param max_weight: 背包最大重量 :return: 最大价值"""
<|body_0|>
def show(self, res, weight):
"""装入背包的物品索引(索引从0开始) :param res: :param weight: :return: 返回物品索引"""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bag01:
def bag01(self, weight, value, max_weight):
""":param weight: 物品重量 :param value: 物品价值 :param max_weight: 背包最大重量 :return: 最大价值"""
res = [[0 for _ in range(max_weight + 1)] for _ in range(len(weight) + 1)]
for i in range(1, len(res)):
cur_value = value[i - 1]
... | the_stack_v2_python_sparse | DP/0-1Bag.py | ii0/algorithms-6 | train | 0 | |
7bdcec777bcb6f1444a4bc6d7146dc5f5b91b9dd | [
"path = request.path.split('/')\nfunc = '_'.join([p for p in path if p])\nreturn getattr(self, func)()",
"if 'status' not in kwargs:\n kwargs.setdefault('status', 0)\nif 'message' not in kwargs:\n kwargs.setdefault('message', '')\nif 'data' not in kwargs:\n kwargs.setdefault('data', {})\nreturn jsonify(*... | <|body_start_0|>
path = request.path.split('/')
func = '_'.join([p for p in path if p])
return getattr(self, func)()
<|end_body_0|>
<|body_start_1|>
if 'status' not in kwargs:
kwargs.setdefault('status', 0)
if 'message' not in kwargs:
kwargs.setdefault('m... | # base view for clover. | CloverView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloverView:
"""# base view for clover."""
def dispatch_request(self):
"""# split url and use last word as method name, # use getattr call method and return result. :return:"""
<|body_0|>
def response(self, **kwargs):
""":param kwargs: :return:"""
<|body_1... | stack_v2_sparse_classes_75kplus_train_067141 | 948 | permissive | [
{
"docstring": "# split url and use last word as method name, # use getattr call method and return result. :return:",
"name": "dispatch_request",
"signature": "def dispatch_request(self)"
},
{
"docstring": ":param kwargs: :return:",
"name": "response",
"signature": "def response(self, **... | 2 | stack_v2_sparse_classes_30k_train_054636 | Implement the Python class `CloverView` described below.
Class description:
# base view for clover.
Method signatures and docstrings:
- def dispatch_request(self): # split url and use last word as method name, # use getattr call method and return result. :return:
- def response(self, **kwargs): :param kwargs: :return... | Implement the Python class `CloverView` described below.
Class description:
# base view for clover.
Method signatures and docstrings:
- def dispatch_request(self): # split url and use last word as method name, # use getattr call method and return result. :return:
- def response(self, **kwargs): :param kwargs: :return... | 54dc4000263ab9e8873f0d429a7fe48b11fb727a | <|skeleton|>
class CloverView:
"""# base view for clover."""
def dispatch_request(self):
"""# split url and use last word as method name, # use getattr call method and return result. :return:"""
<|body_0|>
def response(self, **kwargs):
""":param kwargs: :return:"""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CloverView:
"""# base view for clover."""
def dispatch_request(self):
"""# split url and use last word as method name, # use getattr call method and return result. :return:"""
path = request.path.split('/')
func = '_'.join([p for p in path if p])
return getattr(self, func)... | the_stack_v2_python_sparse | clover/views.py | taoyanli0808/clover | train | 18 |
f784e4744c05b9f94cc8f2e29442ffbc198dba39 | [
"users = User.objects.all()\nresponse = UserListSchema().dump({'users': users}).data\nself.write(response)",
"self.verify_user_global_permission(USER_CREATE)\nuser_data = UserCreateSchema().load(self.request_body).data\ncreate_user(**user_data)\nself.set_status(201)"
] | <|body_start_0|>
users = User.objects.all()
response = UserListSchema().dump({'users': users}).data
self.write(response)
<|end_body_0|>
<|body_start_1|>
self.verify_user_global_permission(USER_CREATE)
user_data = UserCreateSchema().load(self.request_body).data
create_use... | UserListAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserListAPI:
def get(self):
"""--- summary: Retrieve all Users responses: 200: description: All Users schema: $ref: '#/definitions/UserList' 50x: $ref: '#/definitions/50xError' tags: - Users"""
<|body_0|>
def post(self):
"""--- summary: Create a new User parameters: ... | stack_v2_sparse_classes_75kplus_train_067142 | 6,509 | permissive | [
{
"docstring": "--- summary: Retrieve all Users responses: 200: description: All Users schema: $ref: '#/definitions/UserList' 50x: $ref: '#/definitions/50xError' tags: - Users",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "--- summary: Create a new User parameters: - name: user... | 2 | stack_v2_sparse_classes_30k_val_000003 | Implement the Python class `UserListAPI` described below.
Class description:
Implement the UserListAPI class.
Method signatures and docstrings:
- def get(self): --- summary: Retrieve all Users responses: 200: description: All Users schema: $ref: '#/definitions/UserList' 50x: $ref: '#/definitions/50xError' tags: - Use... | Implement the Python class `UserListAPI` described below.
Class description:
Implement the UserListAPI class.
Method signatures and docstrings:
- def get(self): --- summary: Retrieve all Users responses: 200: description: All Users schema: $ref: '#/definitions/UserList' 50x: $ref: '#/definitions/50xError' tags: - Use... | a5fd2dcc2444409e243d3fdaa43d86695e5cb142 | <|skeleton|>
class UserListAPI:
def get(self):
"""--- summary: Retrieve all Users responses: 200: description: All Users schema: $ref: '#/definitions/UserList' 50x: $ref: '#/definitions/50xError' tags: - Users"""
<|body_0|>
def post(self):
"""--- summary: Create a new User parameters: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserListAPI:
def get(self):
"""--- summary: Retrieve all Users responses: 200: description: All Users schema: $ref: '#/definitions/UserList' 50x: $ref: '#/definitions/50xError' tags: - Users"""
users = User.objects.all()
response = UserListSchema().dump({'users': users}).data
s... | the_stack_v2_python_sparse | src/app/beer_garden/api/http/handlers/v1/user.py | beer-garden/beer-garden | train | 254 | |
49fb86bf29ebda6462a66605b031dca418cd173d | [
"if name == 'Tool':\n return super(cls, cls).__new__(cls, name, bases, properties)\n_subtools, _arguments = ([], [])\nfor key, value in properties.viewitems():\n if isinstance(value, (list, tuple)) and key is 'arguments':\n\n def _add_argument(_parser, _flag, _config):\n if isinstance(_flag,... | <|body_start_0|>
if name == 'Tool':
return super(cls, cls).__new__(cls, name, bases, properties)
_subtools, _arguments = ([], [])
for key, value in properties.viewitems():
if isinstance(value, (list, tuple)) and key is 'arguments':
def _add_argument(_pars... | Bound utility metaclass that re-writes embedded comand classes on-the-fly, into :py:mod:`argparse`-provided objects. | __metaclass__ | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class __metaclass__:
"""Bound utility metaclass that re-writes embedded comand classes on-the-fly, into :py:mod:`argparse`-provided objects."""
def __new__(cls, name, bases, properties):
"""Check to see if we're initializing a new subcommand class, and if we are, construct the appropriate ... | stack_v2_sparse_classes_75kplus_train_067143 | 7,474 | permissive | [
{
"docstring": "Check to see if we're initializing a new subcommand class, and if we are, construct the appropriate subparser. :param name: Target class name. :param bases: Target class bases. :param properties: Class dict properties. :raises RuntimeError: If invalid tool bindings are expressed in a meta-initia... | 2 | stack_v2_sparse_classes_30k_train_009154 | Implement the Python class `__metaclass__` described below.
Class description:
Bound utility metaclass that re-writes embedded comand classes on-the-fly, into :py:mod:`argparse`-provided objects.
Method signatures and docstrings:
- def __new__(cls, name, bases, properties): Check to see if we're initializing a new su... | Implement the Python class `__metaclass__` described below.
Class description:
Bound utility metaclass that re-writes embedded comand classes on-the-fly, into :py:mod:`argparse`-provided objects.
Method signatures and docstrings:
- def __new__(cls, name, bases, properties): Check to see if we're initializing a new su... | cfc4ef00ec67df97e08b57222ca16aa9f2659a3e | <|skeleton|>
class __metaclass__:
"""Bound utility metaclass that re-writes embedded comand classes on-the-fly, into :py:mod:`argparse`-provided objects."""
def __new__(cls, name, bases, properties):
"""Check to see if we're initializing a new subcommand class, and if we are, construct the appropriate ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class __metaclass__:
"""Bound utility metaclass that re-writes embedded comand classes on-the-fly, into :py:mod:`argparse`-provided objects."""
def __new__(cls, name, bases, properties):
"""Check to see if we're initializing a new subcommand class, and if we are, construct the appropriate subparser. :p... | the_stack_v2_python_sparse | canteen/util/cli.py | ianjw11/canteen | train | 0 |
e6587cd1d84b414915b93acc9e234932d4818750 | [
"self.owner_object = owner_object\nself.owner_restore_params = owner_restore_params\nself.perform_restore = perform_restore",
"if dictionary is None:\n return None\nowner_object = cohesity_management_sdk.models.restore_object.RestoreObject.from_dictionary(dictionary.get('ownerObject')) if dictionary.get('owner... | <|body_start_0|>
self.owner_object = owner_object
self.owner_restore_params = owner_restore_params
self.perform_restore = perform_restore
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
owner_object = cohesity_management_sdk.models.restore_object.R... | Implementation of the 'AppOwnerRestoreInfo' model. TODO: type description here. Attributes: owner_object (RestoreObject): In the SQL and Oracle applications, this also specifies the full/incremental snapshot to use for non-PIT restore operations, and optionally PIT restore operations as well. owner_restore_params (Rest... | AppOwnerRestoreInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppOwnerRestoreInfo:
"""Implementation of the 'AppOwnerRestoreInfo' model. TODO: type description here. Attributes: owner_object (RestoreObject): In the SQL and Oracle applications, this also specifies the full/incremental snapshot to use for non-PIT restore operations, and optionally PIT restore... | stack_v2_sparse_classes_75kplus_train_067144 | 2,816 | permissive | [
{
"docstring": "Constructor for the AppOwnerRestoreInfo class",
"name": "__init__",
"signature": "def __init__(self, owner_object=None, owner_restore_params=None, perform_restore=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictio... | 2 | stack_v2_sparse_classes_30k_train_012697 | Implement the Python class `AppOwnerRestoreInfo` described below.
Class description:
Implementation of the 'AppOwnerRestoreInfo' model. TODO: type description here. Attributes: owner_object (RestoreObject): In the SQL and Oracle applications, this also specifies the full/incremental snapshot to use for non-PIT restore... | Implement the Python class `AppOwnerRestoreInfo` described below.
Class description:
Implementation of the 'AppOwnerRestoreInfo' model. TODO: type description here. Attributes: owner_object (RestoreObject): In the SQL and Oracle applications, this also specifies the full/incremental snapshot to use for non-PIT restore... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AppOwnerRestoreInfo:
"""Implementation of the 'AppOwnerRestoreInfo' model. TODO: type description here. Attributes: owner_object (RestoreObject): In the SQL and Oracle applications, this also specifies the full/incremental snapshot to use for non-PIT restore operations, and optionally PIT restore... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AppOwnerRestoreInfo:
"""Implementation of the 'AppOwnerRestoreInfo' model. TODO: type description here. Attributes: owner_object (RestoreObject): In the SQL and Oracle applications, this also specifies the full/incremental snapshot to use for non-PIT restore operations, and optionally PIT restore operations a... | the_stack_v2_python_sparse | cohesity_management_sdk/models/app_owner_restore_info.py | cohesity/management-sdk-python | train | 24 |
d223d1b46c524734f9d1613f821b143e6909a891 | [
"if stdin is None:\n stdin = sys.stdin.fileno()\nelif hasattr(stdin, 'fileno'):\n stdin = stdin.fileno()\nif stdout is None:\n stdout = sys.stdout.fileno()\nelif hasattr(stdout, 'fileno'):\n stdout = stdout.fileno()\nwith self._client() as podman:\n attach = podman.GetAttachSockets(self._id)\nio_sock... | <|body_start_0|>
if stdin is None:
stdin = sys.stdin.fileno()
elif hasattr(stdin, 'fileno'):
stdin = stdin.fileno()
if stdout is None:
stdout = sys.stdout.fileno()
elif hasattr(stdout, 'fileno'):
stdout = stdout.fileno()
with self._... | Publish attach() for inclusion in Container class. | Mixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mixin:
"""Publish attach() for inclusion in Container class."""
def attach(self, eot=4, stdin=None, stdout=None):
"""Attach to container's PID1 stdin and stdout. stderr is ignored. PseudoTTY work is done in start()."""
<|body_0|>
def resize_handler(self):
"""Send... | stack_v2_sparse_classes_75kplus_train_067145 | 2,635 | permissive | [
{
"docstring": "Attach to container's PID1 stdin and stdout. stderr is ignored. PseudoTTY work is done in start().",
"name": "attach",
"signature": "def attach(self, eot=4, stdin=None, stdout=None)"
},
{
"docstring": "Send the new window size to conmon.",
"name": "resize_handler",
"signa... | 3 | stack_v2_sparse_classes_30k_train_000206 | Implement the Python class `Mixin` described below.
Class description:
Publish attach() for inclusion in Container class.
Method signatures and docstrings:
- def attach(self, eot=4, stdin=None, stdout=None): Attach to container's PID1 stdin and stdout. stderr is ignored. PseudoTTY work is done in start().
- def resiz... | Implement the Python class `Mixin` described below.
Class description:
Publish attach() for inclusion in Container class.
Method signatures and docstrings:
- def attach(self, eot=4, stdin=None, stdout=None): Attach to container's PID1 stdin and stdout. stderr is ignored. PseudoTTY work is done in start().
- def resiz... | ce2a8734f8b4203ec38078207297062263c49f6f | <|skeleton|>
class Mixin:
"""Publish attach() for inclusion in Container class."""
def attach(self, eot=4, stdin=None, stdout=None):
"""Attach to container's PID1 stdin and stdout. stderr is ignored. PseudoTTY work is done in start()."""
<|body_0|>
def resize_handler(self):
"""Send... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Mixin:
"""Publish attach() for inclusion in Container class."""
def attach(self, eot=4, stdin=None, stdout=None):
"""Attach to container's PID1 stdin and stdout. stderr is ignored. PseudoTTY work is done in start()."""
if stdin is None:
stdin = sys.stdin.fileno()
elif ... | the_stack_v2_python_sparse | tobiko/podman/_podman1/libs/_containers_attach.py | FedericoRessi/tobiko | train | 1 |
57c565b8016d446e7c477007a03cfd2e2e13dbb1 | [
"slug = self.kwargs['slug']\narticle = self.util.check_article(slug)\nparent = self.util.check_comment(id)\ncomment = request.data\ncomment.update({'article': article.id, 'parent': id})\nserializer = self.serializer_class(data=comment)\nserializer.is_valid(raise_exception=True)\nserializer.save(author=request.user)... | <|body_start_0|>
slug = self.kwargs['slug']
article = self.util.check_article(slug)
parent = self.util.check_comment(id)
comment = request.data
comment.update({'article': article.id, 'parent': id})
serializer = self.serializer_class(data=comment)
serializer.is_val... | CommentThreadApiView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentThreadApiView:
def post(self, request, id, *args, **kwargs):
"""This method comments on a comment creating a thread"""
<|body_0|>
def get(self, request, id, *args, **kwargs):
"""This method gets an entire thread of comments"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_067146 | 7,485 | permissive | [
{
"docstring": "This method comments on a comment creating a thread",
"name": "post",
"signature": "def post(self, request, id, *args, **kwargs)"
},
{
"docstring": "This method gets an entire thread of comments",
"name": "get",
"signature": "def get(self, request, id, *args, **kwargs)"
... | 2 | null | Implement the Python class `CommentThreadApiView` described below.
Class description:
Implement the CommentThreadApiView class.
Method signatures and docstrings:
- def post(self, request, id, *args, **kwargs): This method comments on a comment creating a thread
- def get(self, request, id, *args, **kwargs): This meth... | Implement the Python class `CommentThreadApiView` described below.
Class description:
Implement the CommentThreadApiView class.
Method signatures and docstrings:
- def post(self, request, id, *args, **kwargs): This method comments on a comment creating a thread
- def get(self, request, id, *args, **kwargs): This meth... | cc84c18f7c222bc69cf4a263a1c2296b6d335c8b | <|skeleton|>
class CommentThreadApiView:
def post(self, request, id, *args, **kwargs):
"""This method comments on a comment creating a thread"""
<|body_0|>
def get(self, request, id, *args, **kwargs):
"""This method gets an entire thread of comments"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentThreadApiView:
def post(self, request, id, *args, **kwargs):
"""This method comments on a comment creating a thread"""
slug = self.kwargs['slug']
article = self.util.check_article(slug)
parent = self.util.check_comment(id)
comment = request.data
comment.u... | the_stack_v2_python_sparse | authors/apps/comments/views.py | andela/Ah-backend-guardians | train | 0 | |
161f2a74ca7be6d3a43c2102b9499cdcc129fc8c | [
"super().__init__()\nself.num_atoms = num_atoms\ntau_min = 1 / (2 * self.num_atoms)\ntau_max = 1 - tau_min\nself.tau = torch.linspace(start=tau_min, end=tau_max, steps=self.num_atoms)\nself.criterion = HuberLossV0(clip_delta=clip_delta)",
"atoms_diff = targets[:, None, :] - outputs[:, :, None]\ndelta_atoms_diff =... | <|body_start_0|>
super().__init__()
self.num_atoms = num_atoms
tau_min = 1 / (2 * self.num_atoms)
tau_max = 1 - tau_min
self.tau = torch.linspace(start=tau_min, end=tau_max, steps=self.num_atoms)
self.criterion = HuberLossV0(clip_delta=clip_delta)
<|end_body_0|>
<|body_s... | QuantileRegressionLoss | QuantileRegressionLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuantileRegressionLoss:
"""QuantileRegressionLoss"""
def __init__(self, num_atoms: int=51, clip_delta: float=1.0):
"""Init."""
<|body_0|>
def forward(self, outputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
"""Compute the loss. Args: outputs (torch.Te... | stack_v2_sparse_classes_75kplus_train_067147 | 4,457 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, num_atoms: int=51, clip_delta: float=1.0)"
},
{
"docstring": "Compute the loss. Args: outputs (torch.Tensor): predicted atoms, shape: [bs; num_atoms] targets (torch.Tensor): target atoms, shape: [bs; num_atoms] Returns:... | 2 | stack_v2_sparse_classes_30k_train_022072 | Implement the Python class `QuantileRegressionLoss` described below.
Class description:
QuantileRegressionLoss
Method signatures and docstrings:
- def __init__(self, num_atoms: int=51, clip_delta: float=1.0): Init.
- def forward(self, outputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: Compute the loss. Ar... | Implement the Python class `QuantileRegressionLoss` described below.
Class description:
QuantileRegressionLoss
Method signatures and docstrings:
- def __init__(self, num_atoms: int=51, clip_delta: float=1.0): Init.
- def forward(self, outputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: Compute the loss. Ar... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class QuantileRegressionLoss:
"""QuantileRegressionLoss"""
def __init__(self, num_atoms: int=51, clip_delta: float=1.0):
"""Init."""
<|body_0|>
def forward(self, outputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
"""Compute the loss. Args: outputs (torch.Te... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuantileRegressionLoss:
"""QuantileRegressionLoss"""
def __init__(self, num_atoms: int=51, clip_delta: float=1.0):
"""Init."""
super().__init__()
self.num_atoms = num_atoms
tau_min = 1 / (2 * self.num_atoms)
tau_max = 1 - tau_min
self.tau = torch.linspace(s... | the_stack_v2_python_sparse | catalyst/contrib/losses/regression.py | catalyst-team/catalyst | train | 3,038 |
86f58c7871770dc391eef7b03ce6abe55f637f65 | [
"if isinstance(key, int):\n return RevocationStatusCode(key)\nif key not in RevocationStatusCode._member_map_:\n return extend_enum(RevocationStatusCode, key, default)\nreturn RevocationStatusCode[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (... | <|body_start_0|>
if isinstance(key, int):
return RevocationStatusCode(key)
if key not in RevocationStatusCode._member_map_:
return extend_enum(RevocationStatusCode, key, default)
return RevocationStatusCode[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(... | [RevocationStatusCode] Binding Revocation Acknowledgement Status Codes | RevocationStatusCode | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RevocationStatusCode:
"""[RevocationStatusCode] Binding Revocation Acknowledgement Status Codes"""
def get(key: 'int | str', default: 'int'=-1) -> 'RevocationStatusCode':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :me... | stack_v2_sparse_classes_75kplus_train_067148 | 2,773 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'RevocationStatusCode'"
},
{
"docstring": "Lookup function used when value is n... | 2 | stack_v2_sparse_classes_30k_train_000841 | Implement the Python class `RevocationStatusCode` described below.
Class description:
[RevocationStatusCode] Binding Revocation Acknowledgement Status Codes
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'RevocationStatusCode': Backport support for original codes. Args: key: Key t... | Implement the Python class `RevocationStatusCode` described below.
Class description:
[RevocationStatusCode] Binding Revocation Acknowledgement Status Codes
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'RevocationStatusCode': Backport support for original codes. Args: key: Key t... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class RevocationStatusCode:
"""[RevocationStatusCode] Binding Revocation Acknowledgement Status Codes"""
def get(key: 'int | str', default: 'int'=-1) -> 'RevocationStatusCode':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :me... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RevocationStatusCode:
"""[RevocationStatusCode] Binding Revocation Acknowledgement Status Codes"""
def get(key: 'int | str', default: 'int'=-1) -> 'RevocationStatusCode':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:""... | the_stack_v2_python_sparse | pcapkit/const/mh/revocation_status_code.py | JarryShaw/PyPCAPKit | train | 204 |
734dfb90aa36e313b993b584aa43139193fc8621 | [
"customer_data = self.parse_request()\ncustomer = Customer.objects.create(**customer_data)\nsession.auth.set_data(self.request, customer)\nreturn http.HttpResponse()",
"customer = session.auth.get_data(self.request)\nif customer is None:\n return http.HttpResponseForbidden()\npassword_old = kwargs.pop('passwor... | <|body_start_0|>
customer_data = self.parse_request()
customer = Customer.objects.create(**customer_data)
session.auth.set_data(self.request, customer)
return http.HttpResponse()
<|end_body_0|>
<|body_start_1|>
customer = session.auth.get_data(self.request)
if customer i... | CustomerView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerView:
def post(self, request, *args, **kwargs):
"""Create customer. Automatically logins."""
<|body_0|>
def put(self, request, *args, **kwargs):
"""Update customer fields. 404 if not logged in. If want to set password, old password has to be provided in 'pass... | stack_v2_sparse_classes_75kplus_train_067149 | 5,815 | no_license | [
{
"docstring": "Create customer. Automatically logins.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Update customer fields. 404 if not logged in. If want to set password, old password has to be provided in 'password_old' parameter.",
"name": "p... | 2 | stack_v2_sparse_classes_30k_train_040383 | Implement the Python class `CustomerView` described below.
Class description:
Implement the CustomerView class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Create customer. Automatically logins.
- def put(self, request, *args, **kwargs): Update customer fields. 404 if not logged in. ... | Implement the Python class `CustomerView` described below.
Class description:
Implement the CustomerView class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Create customer. Automatically logins.
- def put(self, request, *args, **kwargs): Update customer fields. 404 if not logged in. ... | 038834c0f544d6997613d61d593a7d5abf673c70 | <|skeleton|>
class CustomerView:
def post(self, request, *args, **kwargs):
"""Create customer. Automatically logins."""
<|body_0|>
def put(self, request, *args, **kwargs):
"""Update customer fields. 404 if not logged in. If want to set password, old password has to be provided in 'pass... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomerView:
def post(self, request, *args, **kwargs):
"""Create customer. Automatically logins."""
customer_data = self.parse_request()
customer = Customer.objects.create(**customer_data)
session.auth.set_data(self.request, customer)
return http.HttpResponse()
de... | the_stack_v2_python_sparse | sites/hermanmiller/shop/views.py | alexgula/django_sites | train | 0 | |
92cdcabd82b1879c52261ba887362c1c4e63a9d2 | [
"super(CustomBatchNormAutograd, self).__init__()\nself.n_neurons = n_neurons\nself.eps = eps\nself.gamma = nn.Parameter(torch.ones(n_neurons))\nself.beta = nn.Parameter(torch.zeros(n_neurons))",
"if not input.shape[1] == self.n_neurons:\n raise Exception('Input size is not correct. Input is {}, while it was in... | <|body_start_0|>
super(CustomBatchNormAutograd, self).__init__()
self.n_neurons = n_neurons
self.eps = eps
self.gamma = nn.Parameter(torch.ones(n_neurons))
self.beta = nn.Parameter(torch.zeros(n_neurons))
<|end_body_0|>
<|body_start_1|>
if not input.shape[1] == self.n_ne... | This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by the automatic differentiation provided by PyTorch. | CustomBatchNormAutograd | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomBatchNormAutograd:
"""This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by... | stack_v2_sparse_classes_75kplus_train_067150 | 11,418 | no_license | [
{
"docstring": "Initializes CustomBatchNormAutograd object. Args: n_neurons: int specifying the number of neurons eps: small float to be added to the variance for stability TODO: Save parameters for the number of neurons and eps. Initialize parameters gamma and beta via nn.Parameter",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_052162 | Implement the Python class `CustomBatchNormAutograd` described below.
Class description:
This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need... | Implement the Python class `CustomBatchNormAutograd` described below.
Class description:
This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need... | c50b7d208baa441e8ee9e12c83b018320213af67 | <|skeleton|>
class CustomBatchNormAutograd:
"""This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomBatchNormAutograd:
"""This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by the automati... | the_stack_v2_python_sparse | assignment_1/code/custom_batchnorm.py | YoniSchirris/dl | train | 1 |
ccc15f4945c845632b67bd54ce6f0ab43a3de15c | [
"seq = list(str(n))\nN = len(seq)\nif N < 2:\n return -1\ni = N - 2\nwhile seq[i] >= seq[i + 1]:\n i -= 1\n if i < 0:\n return -1\nj = N - 1\nwhile seq[i] >= seq[j]:\n j -= 1\nseq[i], seq[j] = (seq[j], seq[i])\nseq[i + 1:] = reversed(seq[i + 1:])\nret = int(''.join(seq))\nif ret <= 1 << 31 - 1:\n... | <|body_start_0|>
seq = list(str(n))
N = len(seq)
if N < 2:
return -1
i = N - 2
while seq[i] >= seq[i + 1]:
i -= 1
if i < 0:
return -1
j = N - 1
while seq[i] >= seq[j]:
j -= 1
seq[i], seq[j] = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreaterElement(self, n: int) -> int:
"""next permutation http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html why reverse? reverse the increasing from right to left to decreasing from right to left (i.e. sorted)"""
<|body_0|>
def nextGreater... | stack_v2_sparse_classes_75kplus_train_067151 | 2,158 | no_license | [
{
"docstring": "next permutation http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html why reverse? reverse the increasing from right to left to decreasing from right to left (i.e. sorted)",
"name": "nextGreaterElement",
"signature": "def nextGreaterElement(self, n: int) -> int"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_027462 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement(self, n: int) -> int: next permutation http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html why reverse? reverse the increasing from right ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement(self, n: int) -> int: next permutation http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html why reverse? reverse the increasing from right ... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def nextGreaterElement(self, n: int) -> int:
"""next permutation http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html why reverse? reverse the increasing from right to left to decreasing from right to left (i.e. sorted)"""
<|body_0|>
def nextGreater... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def nextGreaterElement(self, n: int) -> int:
"""next permutation http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html why reverse? reverse the increasing from right to left to decreasing from right to left (i.e. sorted)"""
seq = list(str(n))
N = len(seq)
... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/556 Next Greater Element III.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
40b37e7e96924811468d9e0e368beb798c02949a | [
"command = subparsers.add_parser('test', help=textwrap.fill('Test operational status.', width=width))\nself.subcommand = command.add_subparsers(dest='qualifier')\nfor name in dir(self):\n attribute = getattr(self, name)\n if ismethod(attribute):\n if name.startswith('_'):\n continue\n ... | <|body_start_0|>
command = subparsers.add_parser('test', help=textwrap.fill('Test operational status.', width=width))
self.subcommand = command.add_subparsers(dest='qualifier')
for name in dir(self):
attribute = getattr(self, name)
if ismethod(attribute):
... | Class handles CLI 'test' option. | _Test | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Test:
"""Class handles CLI 'test' option."""
def __init__(self, subparsers, width=80):
"""Function for intializing the class."""
<|body_0|>
def poller(self, width=80):
"""Process test poller CLI commands. Args: width: Width of the help text string to STDIO befor... | stack_v2_sparse_classes_75kplus_train_067152 | 14,010 | permissive | [
{
"docstring": "Function for intializing the class.",
"name": "__init__",
"signature": "def __init__(self, subparsers, width=80)"
},
{
"docstring": "Process test poller CLI commands. Args: width: Width of the help text string to STDIO before wrapping Returns: None",
"name": "poller",
"si... | 2 | stack_v2_sparse_classes_30k_train_035261 | Implement the Python class `_Test` described below.
Class description:
Class handles CLI 'test' option.
Method signatures and docstrings:
- def __init__(self, subparsers, width=80): Function for intializing the class.
- def poller(self, width=80): Process test poller CLI commands. Args: width: Width of the help text ... | Implement the Python class `_Test` described below.
Class description:
Class handles CLI 'test' option.
Method signatures and docstrings:
- def __init__(self, subparsers, width=80): Function for intializing the class.
- def poller(self, width=80): Process test poller CLI commands. Args: width: Width of the help text ... | ae82589fbbab77fef6d6be09c1fcca5846f595a8 | <|skeleton|>
class _Test:
"""Class handles CLI 'test' option."""
def __init__(self, subparsers, width=80):
"""Function for intializing the class."""
<|body_0|>
def poller(self, width=80):
"""Process test poller CLI commands. Args: width: Width of the help text string to STDIO befor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Test:
"""Class handles CLI 'test' option."""
def __init__(self, subparsers, width=80):
"""Function for intializing the class."""
command = subparsers.add_parser('test', help=textwrap.fill('Test operational status.', width=width))
self.subcommand = command.add_subparsers(dest='qua... | the_stack_v2_python_sparse | switchmap/cli/cli.py | PalisadoesFoundation/switchmap-ng | train | 8 |
c41af2e518ba860abbecb7e7d728a660271fd029 | [
"try:\n reg = RegManager.free_registers.pop()\n return reg\nexcept IndexError:\n raise Exception('There are no free registers!')",
"if reg in RegManager.free_registers:\n raise Exception('Trying to free not used register {}'.format(reg))\nelse:\n RegManager.free_registers += [reg]",
"try:\n re... | <|body_start_0|>
try:
reg = RegManager.free_registers.pop()
return reg
except IndexError:
raise Exception('There are no free registers!')
<|end_body_0|>
<|body_start_1|>
if reg in RegManager.free_registers:
raise Exception('Trying to free not used... | RegManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegManager:
def get_free_register():
"""Funkcja zwraca wolny rejest TODO: i przydziela obiekt do tego rejestru"""
<|body_0|>
def free_register(reg):
"""Funkcja zwalnia rejestr i dodaje do wolnych rejestrow"""
<|body_1|>
def get_reg_of(var):
"""Fu... | stack_v2_sparse_classes_75kplus_train_067153 | 1,220 | no_license | [
{
"docstring": "Funkcja zwraca wolny rejest TODO: i przydziela obiekt do tego rejestru",
"name": "get_free_register",
"signature": "def get_free_register()"
},
{
"docstring": "Funkcja zwalnia rejestr i dodaje do wolnych rejestrow",
"name": "free_register",
"signature": "def free_register... | 3 | null | Implement the Python class `RegManager` described below.
Class description:
Implement the RegManager class.
Method signatures and docstrings:
- def get_free_register(): Funkcja zwraca wolny rejest TODO: i przydziela obiekt do tego rejestru
- def free_register(reg): Funkcja zwalnia rejestr i dodaje do wolnych rejestro... | Implement the Python class `RegManager` described below.
Class description:
Implement the RegManager class.
Method signatures and docstrings:
- def get_free_register(): Funkcja zwraca wolny rejest TODO: i przydziela obiekt do tego rejestru
- def free_register(reg): Funkcja zwalnia rejestr i dodaje do wolnych rejestro... | 525364a03b2d3c7ae46a3b15145c2a055ef4bcfa | <|skeleton|>
class RegManager:
def get_free_register():
"""Funkcja zwraca wolny rejest TODO: i przydziela obiekt do tego rejestru"""
<|body_0|>
def free_register(reg):
"""Funkcja zwalnia rejestr i dodaje do wolnych rejestrow"""
<|body_1|>
def get_reg_of(var):
"""Fu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegManager:
def get_free_register():
"""Funkcja zwraca wolny rejest TODO: i przydziela obiekt do tego rejestru"""
try:
reg = RegManager.free_registers.pop()
return reg
except IndexError:
raise Exception('There are no free registers!')
def free_r... | the_stack_v2_python_sparse | compiler/reg_manager.py | Marcin-Szadkowski/JFTT-kompilator | train | 0 | |
0e640092ea7e07df479faf3941557ee6cd6c1fe7 | [
"try:\n self.rotHor = kws.pop('rotHor')\nexcept:\n self.rotHor = False\nRowlandCircle.__init__(self, *args, **kws)",
"if self.rotHor:\n return rotate(vect, np.array([1, 0, 0]), math.pi / 2.0 - self.rtheta0)\nelse:\n return vect",
"zDet = 4 * self.Rm * math.sin(self.rtheta0) * math.cos(self.rtheta0)\... | <|body_start_0|>
try:
self.rotHor = kws.pop('rotHor')
except:
self.rotHor = False
RowlandCircle.__init__(self, *args, **kws)
<|end_body_0|>
<|body_start_1|>
if self.rotHor:
return rotate(vect, np.array([1, 0, 0]), math.pi / 2.0 - self.rtheta0)
... | Rowland circle vertical frame: sample-detector on XZ plane along Z axis | RcVert | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RcVert:
"""Rowland circle vertical frame: sample-detector on XZ plane along Z axis"""
def __init__(self, *args, **kws):
"""RowlandCircle init Parameters ========== rotHor : boolean, rotate to horizontal [False]"""
<|body_0|>
def get_pos(self, vect):
"""utility me... | stack_v2_sparse_classes_75kplus_train_067154 | 31,784 | permissive | [
{
"docstring": "RowlandCircle init Parameters ========== rotHor : boolean, rotate to horizontal [False]",
"name": "__init__",
"signature": "def __init__(self, *args, **kws)"
},
{
"docstring": "utility method: return 'vect' or its rotated form if self.rotHor",
"name": "get_pos",
"signatur... | 5 | stack_v2_sparse_classes_30k_train_045140 | Implement the Python class `RcVert` described below.
Class description:
Rowland circle vertical frame: sample-detector on XZ plane along Z axis
Method signatures and docstrings:
- def __init__(self, *args, **kws): RowlandCircle init Parameters ========== rotHor : boolean, rotate to horizontal [False]
- def get_pos(se... | Implement the Python class `RcVert` described below.
Class description:
Rowland circle vertical frame: sample-detector on XZ plane along Z axis
Method signatures and docstrings:
- def __init__(self, *args, **kws): RowlandCircle init Parameters ========== rotHor : boolean, rotate to horizontal [False]
- def get_pos(se... | d0ff10530833fa8b0866f7303a6a8c99d5a9b208 | <|skeleton|>
class RcVert:
"""Rowland circle vertical frame: sample-detector on XZ plane along Z axis"""
def __init__(self, *args, **kws):
"""RowlandCircle init Parameters ========== rotHor : boolean, rotate to horizontal [False]"""
<|body_0|>
def get_pos(self, vect):
"""utility me... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RcVert:
"""Rowland circle vertical frame: sample-detector on XZ plane along Z axis"""
def __init__(self, *args, **kws):
"""RowlandCircle init Parameters ========== rotHor : boolean, rotate to horizontal [False]"""
try:
self.rotHor = kws.pop('rotHor')
except:
... | the_stack_v2_python_sparse | sloth/inst/rowland.py | maurov/xraysloth | train | 6 |
4a1210159cc9c9bb09317bb09a45d33b4db812f6 | [
"xy = np.vstack((x, y))\nra, dec = np.vsplit(self.getTransform().getMapping().applyForward(xy), 2)\nra %= 2.0 * np.pi\nif degrees:\n return (np.rad2deg(ra.ravel()), np.rad2deg(dec.ravel()))\nelse:\n return (ra.ravel(), dec.ravel())",
"radec = np.vstack((ra, dec))\nif degrees:\n radec = np.deg2rad(radec)\... | <|body_start_0|>
xy = np.vstack((x, y))
ra, dec = np.vsplit(self.getTransform().getMapping().applyForward(xy), 2)
ra %= 2.0 * np.pi
if degrees:
return (np.rad2deg(ra.ravel()), np.rad2deg(dec.ravel()))
else:
return (ra.ravel(), dec.ravel())
<|end_body_0|>
... | SkyWcs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkyWcs:
def pixelToSkyArray(self, x, y, degrees=False):
"""Convert numpy array pixels (x, y) to numpy array sky (ra, dec) positions. Parameters ---------- x : `np.ndarray` Array of x values. y : `np.ndarray` Array of y values. degrees : `bool`, optional Return ra, dec arrays in degrees i... | stack_v2_sparse_classes_75kplus_train_067155 | 2,937 | no_license | [
{
"docstring": "Convert numpy array pixels (x, y) to numpy array sky (ra, dec) positions. Parameters ---------- x : `np.ndarray` Array of x values. y : `np.ndarray` Array of y values. degrees : `bool`, optional Return ra, dec arrays in degrees if True. Returns ------- ra : `np.ndarray` Array of Right Ascension.... | 2 | null | Implement the Python class `SkyWcs` described below.
Class description:
Implement the SkyWcs class.
Method signatures and docstrings:
- def pixelToSkyArray(self, x, y, degrees=False): Convert numpy array pixels (x, y) to numpy array sky (ra, dec) positions. Parameters ---------- x : `np.ndarray` Array of x values. y ... | Implement the Python class `SkyWcs` described below.
Class description:
Implement the SkyWcs class.
Method signatures and docstrings:
- def pixelToSkyArray(self, x, y, degrees=False): Convert numpy array pixels (x, y) to numpy array sky (ra, dec) positions. Parameters ---------- x : `np.ndarray` Array of x values. y ... | 7bed000b91fe98b9ab0cf4b852630e2e7bd34b24 | <|skeleton|>
class SkyWcs:
def pixelToSkyArray(self, x, y, degrees=False):
"""Convert numpy array pixels (x, y) to numpy array sky (ra, dec) positions. Parameters ---------- x : `np.ndarray` Array of x values. y : `np.ndarray` Array of y values. degrees : `bool`, optional Return ra, dec arrays in degrees i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SkyWcs:
def pixelToSkyArray(self, x, y, degrees=False):
"""Convert numpy array pixels (x, y) to numpy array sky (ra, dec) positions. Parameters ---------- x : `np.ndarray` Array of x values. y : `np.ndarray` Array of y values. degrees : `bool`, optional Return ra, dec arrays in degrees if True. Return... | the_stack_v2_python_sparse | python/lsst/afw/geom/skyWcs/skyWcsContinued.py | gcmshadow/afw | train | 1 | |
78f0a240ab57c19985438e8df1f22100ef8c3e16 | [
"if not HAVE_PYMOAB:\n raise RuntimeError('PyMOAB is not available, unable to create Meshtal.')\nself.tally = {}\nwith open(filename, 'r') as fh:\n self._read_tallies(fh)",
"line = fh.readline()\nwhile line != '' and line[0] == '1':\n new_tally = UsrbinTally(fh)\n self.tally[new_tally.name] = new_tall... | <|body_start_0|>
if not HAVE_PYMOAB:
raise RuntimeError('PyMOAB is not available, unable to create Meshtal.')
self.tally = {}
with open(filename, 'r') as fh:
self._read_tallies(fh)
<|end_body_0|>
<|body_start_1|>
line = fh.readline()
while line != '' and ... | This class is the wrapper class for UsrbinTally. This class stores all information for a single file that contains one or more usrbin tallies. The "tally" attribute provides key/value access to individual UsrbinTally objects. Attributes ---------- filename : string Path to Fluka usrbin file tally : dict A dictionary wi... | Usrbin | [
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Usrbin:
"""This class is the wrapper class for UsrbinTally. This class stores all information for a single file that contains one or more usrbin tallies. The "tally" attribute provides key/value access to individual UsrbinTally objects. Attributes ---------- filename : string Path to Fluka usrbin... | stack_v2_sparse_classes_75kplus_train_067156 | 7,670 | permissive | [
{
"docstring": "Parameters ---------- filename : string FLUKA USRBIN file",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Read in all of the USRBIN tallies from the USRBIN file.",
"name": "_read_tallies",
"signature": "def _read_tallies(self, fh)"
}... | 2 | stack_v2_sparse_classes_30k_train_011648 | Implement the Python class `Usrbin` described below.
Class description:
This class is the wrapper class for UsrbinTally. This class stores all information for a single file that contains one or more usrbin tallies. The "tally" attribute provides key/value access to individual UsrbinTally objects. Attributes ----------... | Implement the Python class `Usrbin` described below.
Class description:
This class is the wrapper class for UsrbinTally. This class stores all information for a single file that contains one or more usrbin tallies. The "tally" attribute provides key/value access to individual UsrbinTally objects. Attributes ----------... | 8a9ef7291ca5a23ec4da8794cd19cbac93f849ef | <|skeleton|>
class Usrbin:
"""This class is the wrapper class for UsrbinTally. This class stores all information for a single file that contains one or more usrbin tallies. The "tally" attribute provides key/value access to individual UsrbinTally objects. Attributes ---------- filename : string Path to Fluka usrbin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Usrbin:
"""This class is the wrapper class for UsrbinTally. This class stores all information for a single file that contains one or more usrbin tallies. The "tally" attribute provides key/value access to individual UsrbinTally objects. Attributes ---------- filename : string Path to Fluka usrbin file tally :... | the_stack_v2_python_sparse | pyne/fluka.py | pyne/pyne | train | 218 |
3e9af28a4872dd2a0eb5fafb9a1795c385c75977 | [
"if not matrix:\n self.dp = None\n return\nm = len(matrix)\nn = len(matrix[0])\ndp = self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]\nfor x in range(1, m + 1):\n for y in range(1, n + 1):\n dp[x][y] = dp[x - 1][y] + dp[x][y - 1] - dp[x - 1][y - 1] + matrix[x - 1][y - 1]",
"if not self.... | <|body_start_0|>
if not matrix:
self.dp = None
return
m = len(matrix)
n = len(matrix[0])
dp = self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for x in range(1, m + 1):
for y in range(1, n + 1):
dp[x][y] = dp[x - 1][y... | 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_75kplus_train_067157 | 1,287 | 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 | stack_v2_sparse_classes_30k_train_053950 | 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)... | a041962eeab9192799ad7f74b4bbd3e4f74933d0 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
if not matrix:
self.dp = None
return
m = len(matrix)
n = len(matrix[0])
dp = self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1... | the_stack_v2_python_sparse | codes/304. Range Sum Query 2D - Immutable.py | zcgu/leetcode | train | 1 | |
f6385401d8c629160def6ec1c034d84bc1c2b776 | [
"n = len(matrix)\nidxs = [0 for i in range(0, n)]\ni = 1\nwhile i <= k:\n j = -1\n current = float('inf')\n for q, p in enumerate(idxs):\n if p < n and matrix[q][p] < current:\n current = matrix[q][p]\n j = q\n idxs[j] += 1\n i += 1\nreturn current",
"n = len(matrix)\nl... | <|body_start_0|>
n = len(matrix)
idxs = [0 for i in range(0, n)]
i = 1
while i <= k:
j = -1
current = float('inf')
for q, p in enumerate(idxs):
if p < n and matrix[q][p] < current:
current = matrix[q][p]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest1(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_0|>
def kthSmallest(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_067158 | 1,162 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type k: int :rtype: int",
"name": "kthSmallest1",
"signature": "def kthSmallest1(self, matrix, k)"
},
{
"docstring": ":type matrix: List[List[int]] :type k: int :rtype: int",
"name": "kthSmallest",
"signature": "def kthSmallest(self, matrix,... | 2 | stack_v2_sparse_classes_30k_train_040367 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest1(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: int
- def kthSmallest(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest1(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: int
- def kthSmallest(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: i... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def kthSmallest1(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_0|>
def kthSmallest(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def kthSmallest1(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
n = len(matrix)
idxs = [0 for i in range(0, n)]
i = 1
while i <= k:
j = -1
current = float('inf')
for q, p in enumerate(idxs):
... | the_stack_v2_python_sparse | py/leetcode/378.py | wfeng1991/learnpy | train | 0 | |
b28445bf260542d83963acdbb41e61482411c05f | [
"if not inspect.isclass(member):\n return False\nif not issubclass(member, BaseForm):\n return False\nreturn member.__module__.startswith(__name__)",
"Random.atfork()\nlocal_installed_apps = [app for app in settings.INSTALLED_APPS if app.startswith('%s.' % __name__)]\nfor app in local_installed_apps:\n t... | <|body_start_0|>
if not inspect.isclass(member):
return False
if not issubclass(member, BaseForm):
return False
return member.__module__.startswith(__name__)
<|end_body_0|>
<|body_start_1|>
Random.atfork()
local_installed_apps = [app for app in settings.I... | This is the custom app configuration for the lily app. Custom startup code is defined here. | LilyConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LilyConfig:
"""This is the custom app configuration for the lily app. Custom startup code is defined here."""
def is_form(member):
"""Allow only custom made classes which are a subclass from BaseForm to pass."""
<|body_0|>
def ready(self):
"""Code run on startup ... | stack_v2_sparse_classes_75kplus_train_067159 | 1,742 | no_license | [
{
"docstring": "Allow only custom made classes which are a subclass from BaseForm to pass.",
"name": "is_form",
"signature": "def is_form(member)"
},
{
"docstring": "Code run on startup of django.",
"name": "ready",
"signature": "def ready(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050172 | Implement the Python class `LilyConfig` described below.
Class description:
This is the custom app configuration for the lily app. Custom startup code is defined here.
Method signatures and docstrings:
- def is_form(member): Allow only custom made classes which are a subclass from BaseForm to pass.
- def ready(self):... | Implement the Python class `LilyConfig` described below.
Class description:
This is the custom app configuration for the lily app. Custom startup code is defined here.
Method signatures and docstrings:
- def is_form(member): Allow only custom made classes which are a subclass from BaseForm to pass.
- def ready(self):... | ddb25fa16280d1ca5fba32f71d65c90815648f0a | <|skeleton|>
class LilyConfig:
"""This is the custom app configuration for the lily app. Custom startup code is defined here."""
def is_form(member):
"""Allow only custom made classes which are a subclass from BaseForm to pass."""
<|body_0|>
def ready(self):
"""Code run on startup ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LilyConfig:
"""This is the custom app configuration for the lily app. Custom startup code is defined here."""
def is_form(member):
"""Allow only custom made classes which are a subclass from BaseForm to pass."""
if not inspect.isclass(member):
return False
if not issub... | the_stack_v2_python_sparse | lily/app.py | Vegulla/hellolily | train | 0 |
64408be96db06881e861843f259609107a189517 | [
"user = self.context.get('request').user\nif user.is_authenticated():\n try:\n user_follow_relation = user.following_relations.get(target=obj.user.pk)\n except UserFollowRelation.DoesNotExist:\n return None\n else:\n return user_follow_relation.pk\nelse:\n return None",
"instance.... | <|body_start_0|>
user = self.context.get('request').user
if user.is_authenticated():
try:
user_follow_relation = user.following_relations.get(target=obj.user.pk)
except UserFollowRelation.DoesNotExist:
return None
else:
... | 프로필 main-detail 가져오기/업데이트를 위한 Serializer update 시에는 일반 'image'를 업로드 retrieve 시에는 200*200 사이즈의 'thumbnail_image_200' 가져오기 | ProfileSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileSerializer:
"""프로필 main-detail 가져오기/업데이트를 위한 Serializer update 시에는 일반 'image'를 업로드 retrieve 시에는 200*200 사이즈의 'thumbnail_image_200' 가져오기"""
def get_follow_relation_pk(self, obj):
"""해당 유저의 프로필 보기를 "요청"한 유저와, 프로필의 유저의, 팔로우 관계를 나타내는 pk 해당 페이지에 있는 "유저 팔로우 버튼"이 어떻게 표시되는지를 결정한다"""
... | stack_v2_sparse_classes_75kplus_train_067160 | 6,491 | no_license | [
{
"docstring": "해당 유저의 프로필 보기를 \"요청\"한 유저와, 프로필의 유저의, 팔로우 관계를 나타내는 pk 해당 페이지에 있는 \"유저 팔로우 버튼\"이 어떻게 표시되는지를 결정한다",
"name": "get_follow_relation_pk",
"signature": "def get_follow_relation_pk(self, obj)"
},
{
"docstring": "프로필 업데이트 - name의 경우는 유저 모델에 속하므로 유저 모델에 name 값을 추가한 뒤 저장한다 :param Profile ob... | 2 | null | Implement the Python class `ProfileSerializer` described below.
Class description:
프로필 main-detail 가져오기/업데이트를 위한 Serializer update 시에는 일반 'image'를 업로드 retrieve 시에는 200*200 사이즈의 'thumbnail_image_200' 가져오기
Method signatures and docstrings:
- def get_follow_relation_pk(self, obj): 해당 유저의 프로필 보기를 "요청"한 유저와, 프로필의 유저의, 팔로우... | Implement the Python class `ProfileSerializer` described below.
Class description:
프로필 main-detail 가져오기/업데이트를 위한 Serializer update 시에는 일반 'image'를 업로드 retrieve 시에는 200*200 사이즈의 'thumbnail_image_200' 가져오기
Method signatures and docstrings:
- def get_follow_relation_pk(self, obj): 해당 유저의 프로필 보기를 "요청"한 유저와, 프로필의 유저의, 팔로우... | 399064b62a7c8049b37efd77a98f17a903754070 | <|skeleton|>
class ProfileSerializer:
"""프로필 main-detail 가져오기/업데이트를 위한 Serializer update 시에는 일반 'image'를 업로드 retrieve 시에는 200*200 사이즈의 'thumbnail_image_200' 가져오기"""
def get_follow_relation_pk(self, obj):
"""해당 유저의 프로필 보기를 "요청"한 유저와, 프로필의 유저의, 팔로우 관계를 나타내는 pk 해당 페이지에 있는 "유저 팔로우 버튼"이 어떻게 표시되는지를 결정한다"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfileSerializer:
"""프로필 main-detail 가져오기/업데이트를 위한 Serializer update 시에는 일반 'image'를 업로드 retrieve 시에는 200*200 사이즈의 'thumbnail_image_200' 가져오기"""
def get_follow_relation_pk(self, obj):
"""해당 유저의 프로필 보기를 "요청"한 유저와, 프로필의 유저의, 팔로우 관계를 나타내는 pk 해당 페이지에 있는 "유저 팔로우 버튼"이 어떻게 표시되는지를 결정한다"""
user =... | the_stack_v2_python_sparse | nanum/users/serializers/profile.py | markui/nanum-project | train | 1 |
f28daa8e8d56ff63e92da13ef0ca64f11f60a493 | [
"super().__init__()\nself.name = 'VoxelMeanVFE'\nnum_output_filters = [num_input_features + 6] + list(num_filters)\nvfe_layers = []\nfor i in range(len(num_output_filters) - 1):\n in_filters = num_output_filters[i]\n out_filters = num_output_filters[i + 1]\n if i < len(num_output_filters) - 2:\n las... | <|body_start_0|>
super().__init__()
self.name = 'VoxelMeanVFE'
num_output_filters = [num_input_features + 6] + list(num_filters)
vfe_layers = []
for i in range(len(num_output_filters) - 1):
in_filters = num_output_filters[i]
out_filters = num_output_filter... | VoxelMeanVFE | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VoxelMeanVFE:
def __init__(self, num_input_features=4, num_filters=(64,), voxel_size=[0.2, 0.2, 4], pc_range=[0.0, -40.0, -3.0, 70.4, 40.0, 1.0]):
"""Voxel Feature Net. The network prepares the voxel features and performs forward pass through VFELayers. :param num_input_features: <int>. ... | stack_v2_sparse_classes_75kplus_train_067161 | 8,913 | permissive | [
{
"docstring": "Voxel Feature Net. The network prepares the voxel features and performs forward pass through VFELayers. :param num_input_features: <int>. Number of input features, either x, y, z or x, y, z, r. :param num_filters: (<int>: N). Number of features in each of the N PFNLayers.",
"name": "__init__... | 3 | stack_v2_sparse_classes_30k_train_039612 | Implement the Python class `VoxelMeanVFE` described below.
Class description:
Implement the VoxelMeanVFE class.
Method signatures and docstrings:
- def __init__(self, num_input_features=4, num_filters=(64,), voxel_size=[0.2, 0.2, 4], pc_range=[0.0, -40.0, -3.0, 70.4, 40.0, 1.0]): Voxel Feature Net. The network prepar... | Implement the Python class `VoxelMeanVFE` described below.
Class description:
Implement the VoxelMeanVFE class.
Method signatures and docstrings:
- def __init__(self, num_input_features=4, num_filters=(64,), voxel_size=[0.2, 0.2, 4], pc_range=[0.0, -40.0, -3.0, 70.4, 40.0, 1.0]): Voxel Feature Net. The network prepar... | 7f2bd81c41bcd41af34f6953101038201a4f7d37 | <|skeleton|>
class VoxelMeanVFE:
def __init__(self, num_input_features=4, num_filters=(64,), voxel_size=[0.2, 0.2, 4], pc_range=[0.0, -40.0, -3.0, 70.4, 40.0, 1.0]):
"""Voxel Feature Net. The network prepares the voxel features and performs forward pass through VFELayers. :param num_input_features: <int>. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VoxelMeanVFE:
def __init__(self, num_input_features=4, num_filters=(64,), voxel_size=[0.2, 0.2, 4], pc_range=[0.0, -40.0, -3.0, 70.4, 40.0, 1.0]):
"""Voxel Feature Net. The network prepares the voxel features and performs forward pass through VFELayers. :param num_input_features: <int>. Number of inpu... | the_stack_v2_python_sparse | mvt/blocks/backbones/voxel_vfe.py | visriv/multi-visual-tasks | train | 1 | |
3297759d1589d178b8e093cda55dfb05b68b0d0a | [
"if categoria_id:\n categoria = Categoria.objects.get(pk=categoria_id)\n form = FormCategoria(instance=categoria)\nelse:\n form = FormCategoria()\nreturn render(request, self.template, {'form': form})",
"if categoria_id:\n categoria = Categoria.objects.get(pk=categoria_id)\n form = FormCategoria(in... | <|body_start_0|>
if categoria_id:
categoria = Categoria.objects.get(pk=categoria_id)
form = FormCategoria(instance=categoria)
else:
form = FormCategoria()
return render(request, self.template, {'form': form})
<|end_body_0|>
<|body_start_1|>
if categor... | Cadastra as categorias | CadastroCategoriaView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CadastroCategoriaView:
"""Cadastra as categorias"""
def get(self, request, categoria_id=None):
"""Pega o formulário para cadastrar e atualizar uma categoria"""
<|body_0|>
def post(self, request, categoria_id=None):
"""Envia para o servidor a nova categoria cadast... | stack_v2_sparse_classes_75kplus_train_067162 | 4,955 | no_license | [
{
"docstring": "Pega o formulário para cadastrar e atualizar uma categoria",
"name": "get",
"signature": "def get(self, request, categoria_id=None)"
},
{
"docstring": "Envia para o servidor a nova categoria cadastrada ou atualizada",
"name": "post",
"signature": "def post(self, request, ... | 2 | stack_v2_sparse_classes_30k_train_033144 | Implement the Python class `CadastroCategoriaView` described below.
Class description:
Cadastra as categorias
Method signatures and docstrings:
- def get(self, request, categoria_id=None): Pega o formulário para cadastrar e atualizar uma categoria
- def post(self, request, categoria_id=None): Envia para o servidor a ... | Implement the Python class `CadastroCategoriaView` described below.
Class description:
Cadastra as categorias
Method signatures and docstrings:
- def get(self, request, categoria_id=None): Pega o formulário para cadastrar e atualizar uma categoria
- def post(self, request, categoria_id=None): Envia para o servidor a ... | 7b799a71380aca342e879c5556cc24fcebdac1ca | <|skeleton|>
class CadastroCategoriaView:
"""Cadastra as categorias"""
def get(self, request, categoria_id=None):
"""Pega o formulário para cadastrar e atualizar uma categoria"""
<|body_0|>
def post(self, request, categoria_id=None):
"""Envia para o servidor a nova categoria cadast... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CadastroCategoriaView:
"""Cadastra as categorias"""
def get(self, request, categoria_id=None):
"""Pega o formulário para cadastrar e atualizar uma categoria"""
if categoria_id:
categoria = Categoria.objects.get(pk=categoria_id)
form = FormCategoria(instance=categor... | the_stack_v2_python_sparse | detransapp/views/categoria.py | brunowber/transnote2 | train | 0 |
a5aca745624ef6c32074c18a62eb7edfdf2169fa | [
"self.val_to_indices = defaultdict(list)\nfor i, val in enumerate(arr):\n self.val_to_indices[val].append(i)\nself.vals = sorted(self.val_to_indices.keys(), key=lambda x: len(self.val_to_indices[x]), reverse=True)",
"for val in self.vals:\n if len(self.val_to_indices[val]) < threshold:\n break\n l... | <|body_start_0|>
self.val_to_indices = defaultdict(list)
for i, val in enumerate(arr):
self.val_to_indices[val].append(i)
self.vals = sorted(self.val_to_indices.keys(), key=lambda x: len(self.val_to_indices[x]), reverse=True)
<|end_body_0|>
<|body_start_1|>
for val in self.v... | MajorityChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
<|body_0|>
def query(self, left, right, threshold):
""":type left: int :type right: int :type threshold: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.val_to... | stack_v2_sparse_classes_75kplus_train_067163 | 2,056 | no_license | [
{
"docstring": ":type arr: List[int]",
"name": "__init__",
"signature": "def __init__(self, arr)"
},
{
"docstring": ":type left: int :type right: int :type threshold: int :rtype: int",
"name": "query",
"signature": "def query(self, left, right, threshold)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001186 | Implement the Python class `MajorityChecker` described below.
Class description:
Implement the MajorityChecker class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int]
- def query(self, left, right, threshold): :type left: int :type right: int :type threshold: int :rtype: int | Implement the Python class `MajorityChecker` described below.
Class description:
Implement the MajorityChecker class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int]
- def query(self, left, right, threshold): :type left: int :type right: int :type threshold: int :rtype: int
<|skelet... | 05e0beff0047f0ad399d0b46d625bb8d3459814e | <|skeleton|>
class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
<|body_0|>
def query(self, left, right, threshold):
""":type left: int :type right: int :type threshold: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
self.val_to_indices = defaultdict(list)
for i, val in enumerate(arr):
self.val_to_indices[val].append(i)
self.vals = sorted(self.val_to_indices.keys(), key=lambda x: len(self.val_to_indices[x]), re... | the_stack_v2_python_sparse | python_1001_to_2000/1157_Online_Majority_Element_In_Subarray.py | jakehoare/leetcode | train | 58 | |
13d66e87f939505f7226a8fdeedeaf4eb0c3ade8 | [
"game_name = self.request.GET.get('term', '')\nsearched_games = Game.objects.search_by_term(game_name, annotated=False)\nreturn searched_games",
"context = super(GameSearch, self).get_context_data()\ncontext['games_list'] = self.object_list\ncontext['title'] = 'Search Results'\ncontext['searching'] = True\ncontex... | <|body_start_0|>
game_name = self.request.GET.get('term', '')
searched_games = Game.objects.search_by_term(game_name, annotated=False)
return searched_games
<|end_body_0|>
<|body_start_1|>
context = super(GameSearch, self).get_context_data()
context['games_list'] = self.object_l... | Handle searching of games. | GameSearch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameSearch:
"""Handle searching of games."""
def get_queryset(self):
"""Search for games based on a provided term."""
<|body_0|>
def get_context_data(self):
"""Set the list and the page title."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
game... | stack_v2_sparse_classes_75kplus_train_067164 | 9,267 | permissive | [
{
"docstring": "Search for games based on a provided term.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Set the list and the page title.",
"name": "get_context_data",
"signature": "def get_context_data(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021734 | Implement the Python class `GameSearch` described below.
Class description:
Handle searching of games.
Method signatures and docstrings:
- def get_queryset(self): Search for games based on a provided term.
- def get_context_data(self): Set the list and the page title. | Implement the Python class `GameSearch` described below.
Class description:
Handle searching of games.
Method signatures and docstrings:
- def get_queryset(self): Search for games based on a provided term.
- def get_context_data(self): Set the list and the page title.
<|skeleton|>
class GameSearch:
"""Handle sea... | 1d9edd1959a7d401a76ced29ffbc430017d3dd8b | <|skeleton|>
class GameSearch:
"""Handle searching of games."""
def get_queryset(self):
"""Search for games based on a provided term."""
<|body_0|>
def get_context_data(self):
"""Set the list and the page title."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GameSearch:
"""Handle searching of games."""
def get_queryset(self):
"""Search for games based on a provided term."""
game_name = self.request.GET.get('term', '')
searched_games = Game.objects.search_by_term(game_name, annotated=False)
return searched_games
def get_co... | the_stack_v2_python_sparse | core/views/games.py | joshsamara/game-website | train | 3 |
3ea614c150c99296cac7392f5825d260e1d2273a | [
"self.__include_deps_supply = include_deps_supply\nif closure:\n self.__transform_pre = GraphAlgorithms.transitive_closure\nelse:\n self.__transform_pre = lambda x: x\nif sort:\n self.__transform_post = sorted\nelse:\n self.__transform_post = lambda x: x",
"args_set = set(args)\nedge_list = self.__tra... | <|body_start_0|>
self.__include_deps_supply = include_deps_supply
if closure:
self.__transform_pre = GraphAlgorithms.transitive_closure
else:
self.__transform_pre = lambda x: x
if sort:
self.__transform_post = sorted
else:
self.__tr... | FileIncludeDepsListerFacade | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileIncludeDepsListerFacade:
def __init__(self, include_deps_supply, closure, sort):
"""@param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param closure: if True, consider transitive closure of dependencies, otherwise only direct dependencies @type closure: Boo... | stack_v2_sparse_classes_75kplus_train_067165 | 2,930 | permissive | [
{
"docstring": "@param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param closure: if True, consider transitive closure of dependencies, otherwise only direct dependencies @type closure: Boolean @param sort: if True, return output sorted by filenames @type sort: Boolean",
"name": "... | 2 | stack_v2_sparse_classes_30k_val_000672 | Implement the Python class `FileIncludeDepsListerFacade` described below.
Class description:
Implement the FileIncludeDepsListerFacade class.
Method signatures and docstrings:
- def __init__(self, include_deps_supply, closure, sort): @param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param ... | Implement the Python class `FileIncludeDepsListerFacade` described below.
Class description:
Implement the FileIncludeDepsListerFacade class.
Method signatures and docstrings:
- def __init__(self, include_deps_supply, closure, sort): @param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param ... | d58680ef7d6bdc8ef518860d5d13a5acc0d01758 | <|skeleton|>
class FileIncludeDepsListerFacade:
def __init__(self, include_deps_supply, closure, sort):
"""@param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param closure: if True, consider transitive closure of dependencies, otherwise only direct dependencies @type closure: Boo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileIncludeDepsListerFacade:
def __init__(self, include_deps_supply, closure, sort):
"""@param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param closure: if True, consider transitive closure of dependencies, otherwise only direct dependencies @type closure: Boolean @param so... | the_stack_v2_python_sparse | cpp/incl_deps/include_deps_util.py | btc-ag/revengtools | train | 2 | |
ae650e6ef8dcb1c0941cfb86e935f8c71f157c8a | [
"from icu import Locale, BreakIterator\nif locale in {'en', 'de', 'es', 'it', 'pt'}:\n locale += '@ss=standard'\nself.locale = Locale(locale)\nself.breaker = BreakIterator.createSentenceInstance(self.locale)",
"text = ''.join((c if c <= '\\uffff' else ' ' for c in text))\nself.breaker.setText(text)\nstart_idx ... | <|body_start_0|>
from icu import Locale, BreakIterator
if locale in {'en', 'de', 'es', 'it', 'pt'}:
locale += '@ss=standard'
self.locale = Locale(locale)
self.breaker = BreakIterator.createSentenceInstance(self.locale)
<|end_body_0|>
<|body_start_1|>
text = ''.join((... | Segment text to sentences. | ICUSentenceTokenizer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ICUSentenceTokenizer:
"""Segment text to sentences."""
def __init__(self, locale='en'):
"""init fun"""
<|body_0|>
def span_tokenize(self, text: str):
"""ICU's BreakIterator gives boundary indices by counting *codeunits*, not *codepoints*. (https://stackoverflow.c... | stack_v2_sparse_classes_75kplus_train_067166 | 4,704 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, locale='en')"
},
{
"docstring": "ICU's BreakIterator gives boundary indices by counting *codeunits*, not *codepoints*. (https://stackoverflow.com/questions/30775689/python-length-of-unicode-string-confusion) As a res... | 2 | stack_v2_sparse_classes_30k_train_024749 | Implement the Python class `ICUSentenceTokenizer` described below.
Class description:
Segment text to sentences.
Method signatures and docstrings:
- def __init__(self, locale='en'): init fun
- def span_tokenize(self, text: str): ICU's BreakIterator gives boundary indices by counting *codeunits*, not *codepoints*. (ht... | Implement the Python class `ICUSentenceTokenizer` described below.
Class description:
Segment text to sentences.
Method signatures and docstrings:
- def __init__(self, locale='en'): init fun
- def span_tokenize(self, text: str): ICU's BreakIterator gives boundary indices by counting *codeunits*, not *codepoints*. (ht... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class ICUSentenceTokenizer:
"""Segment text to sentences."""
def __init__(self, locale='en'):
"""init fun"""
<|body_0|>
def span_tokenize(self, text: str):
"""ICU's BreakIterator gives boundary indices by counting *codeunits*, not *codepoints*. (https://stackoverflow.c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ICUSentenceTokenizer:
"""Segment text to sentences."""
def __init__(self, locale='en'):
"""init fun"""
from icu import Locale, BreakIterator
if locale in {'en', 'de', 'es', 'it', 'pt'}:
locale += '@ss=standard'
self.locale = Locale(locale)
self.breaker ... | the_stack_v2_python_sparse | research/nlp/luke/src/utils/sentence_tokenizer.py | mindspore-ai/models | train | 301 |
bf154569623460e58a97283d85354d415244bc27 | [
"_LOGGER.debug('%s [%s]: BLE connection limits: used=%s free=%s limit=%s', self.name, self.mac_address, limit - free, free, limit)\nself.ble_connections_free = free\nself.ble_connections_limit = limit\nif not free:\n return\nfor fut in self._ble_connection_free_futures:\n if not fut.done():\n fut.set_r... | <|body_start_0|>
_LOGGER.debug('%s [%s]: BLE connection limits: used=%s free=%s limit=%s', self.name, self.mac_address, limit - free, free, limit)
self.ble_connections_free = free
self.ble_connections_limit = limit
if not free:
return
for fut in self._ble_connection_f... | Bluetooth data for a specific ESPHome device. | ESPHomeBluetoothDevice | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESPHomeBluetoothDevice:
"""Bluetooth data for a specific ESPHome device."""
def async_update_ble_connection_limits(self, free: int, limit: int) -> None:
"""Update the BLE connection limits."""
<|body_0|>
async def wait_for_ble_connections_free(self) -> int:
"""Wa... | stack_v2_sparse_classes_75kplus_train_067167 | 1,729 | permissive | [
{
"docstring": "Update the BLE connection limits.",
"name": "async_update_ble_connection_limits",
"signature": "def async_update_ble_connection_limits(self, free: int, limit: int) -> None"
},
{
"docstring": "Wait until there are free BLE connections.",
"name": "wait_for_ble_connections_free"... | 2 | stack_v2_sparse_classes_30k_train_010531 | Implement the Python class `ESPHomeBluetoothDevice` described below.
Class description:
Bluetooth data for a specific ESPHome device.
Method signatures and docstrings:
- def async_update_ble_connection_limits(self, free: int, limit: int) -> None: Update the BLE connection limits.
- async def wait_for_ble_connections_... | Implement the Python class `ESPHomeBluetoothDevice` described below.
Class description:
Bluetooth data for a specific ESPHome device.
Method signatures and docstrings:
- def async_update_ble_connection_limits(self, free: int, limit: int) -> None: Update the BLE connection limits.
- async def wait_for_ble_connections_... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ESPHomeBluetoothDevice:
"""Bluetooth data for a specific ESPHome device."""
def async_update_ble_connection_limits(self, free: int, limit: int) -> None:
"""Update the BLE connection limits."""
<|body_0|>
async def wait_for_ble_connections_free(self) -> int:
"""Wa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ESPHomeBluetoothDevice:
"""Bluetooth data for a specific ESPHome device."""
def async_update_ble_connection_limits(self, free: int, limit: int) -> None:
"""Update the BLE connection limits."""
_LOGGER.debug('%s [%s]: BLE connection limits: used=%s free=%s limit=%s', self.name, self.mac_ad... | the_stack_v2_python_sparse | homeassistant/components/esphome/bluetooth/device.py | home-assistant/core | train | 35,501 |
298ca184f3e67ac7cfdd44e60f88ee1ca299386f | [
"wx.Panel.__init__(self, parent)\nself.SetBackgroundColour('3399FF')\nself.father = manipulador\nself.lbldesc = wx.StaticText(self, label='Descripcion Tipo de Examen :', pos=(100, 35))\nself.editdesc = wx.TextCtrl(self, value='', pos=(0, 35), size=(140, -1))\nself.button = wx.Button(self, wx.ID_OK, label='Siguiente... | <|body_start_0|>
wx.Panel.__init__(self, parent)
self.SetBackgroundColour('3399FF')
self.father = manipulador
self.lbldesc = wx.StaticText(self, label='Descripcion Tipo de Examen :', pos=(100, 35))
self.editdesc = wx.TextCtrl(self, value='', pos=(0, 35), size=(140, -1))
s... | Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen podra ingresar datos como el nombre del examen, la fecha del examen, el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que este tendra. | paneltipoexamen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class paneltipoexamen:
"""Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen podra ingresar datos como el nombre del examen, la fecha del examen, el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que este tendra."""
def __init__(self, par... | stack_v2_sparse_classes_75kplus_train_067168 | 10,739 | no_license | [
{
"docstring": "contructor requiere de parent como interfaz contenedor y manipulador como clase que accedera a la informacion",
"name": "__init__",
"signature": "def __init__(self, parent, manipulador, accion)"
},
{
"docstring": "metodo que atendera el boton siguiente y registrara la informacion... | 2 | stack_v2_sparse_classes_30k_train_052122 | Implement the Python class `paneltipoexamen` described below.
Class description:
Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen podra ingresar datos como el nombre del examen, la fecha del examen, el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que este... | Implement the Python class `paneltipoexamen` described below.
Class description:
Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen podra ingresar datos como el nombre del examen, la fecha del examen, el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que este... | b7fa1939056baa01b48d310d981a5fb1493d6698 | <|skeleton|>
class paneltipoexamen:
"""Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen podra ingresar datos como el nombre del examen, la fecha del examen, el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que este tendra."""
def __init__(self, par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class paneltipoexamen:
"""Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen podra ingresar datos como el nombre del examen, la fecha del examen, el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que este tendra."""
def __init__(self, parent, manipula... | the_stack_v2_python_sparse | NewPythonProject/src/administrador Interfaz/admparametros.py | wahello/gesdatos | train | 0 |
3b6145ab6f3e46d85d39739b07b32f30d4baef7a | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the Recommendation service. Service to manage recommendations. | RecommendationServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecommendationServiceServicer:
"""Proto file describing the Recommendation service. Service to manage recommendations."""
def GetRecommendation(self, request, context):
"""Returns the requested recommendation in full detail."""
<|body_0|>
def ApplyRecommendation(self, re... | stack_v2_sparse_classes_75kplus_train_067169 | 4,622 | permissive | [
{
"docstring": "Returns the requested recommendation in full detail.",
"name": "GetRecommendation",
"signature": "def GetRecommendation(self, request, context)"
},
{
"docstring": "Applies given recommendations with corresponding apply parameters.",
"name": "ApplyRecommendation",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_050377 | Implement the Python class `RecommendationServiceServicer` described below.
Class description:
Proto file describing the Recommendation service. Service to manage recommendations.
Method signatures and docstrings:
- def GetRecommendation(self, request, context): Returns the requested recommendation in full detail.
- ... | Implement the Python class `RecommendationServiceServicer` described below.
Class description:
Proto file describing the Recommendation service. Service to manage recommendations.
Method signatures and docstrings:
- def GetRecommendation(self, request, context): Returns the requested recommendation in full detail.
- ... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class RecommendationServiceServicer:
"""Proto file describing the Recommendation service. Service to manage recommendations."""
def GetRecommendation(self, request, context):
"""Returns the requested recommendation in full detail."""
<|body_0|>
def ApplyRecommendation(self, re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecommendationServiceServicer:
"""Proto file describing the Recommendation service. Service to manage recommendations."""
def GetRecommendation(self, request, context):
"""Returns the requested recommendation in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
conte... | the_stack_v2_python_sparse | google/ads/google_ads/v1/proto/services/recommendation_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
2d2c89df27b33d9d85291737d6a232609f4cda4b | [
"if type(arg_index) is int:\n return {cls.CATEGORY: category, cls.ARG_INDEX: [arg_index]}\nif type(arg_index) is list and all((isinstance(i, int) for i in arg_index)):\n return {cls.CATEGORY: category, cls.ARG_INDEX: arg_index}\nreturn {cls.CATEGORY: category}",
"self.name = propertiesDict.pop('name', None)... | <|body_start_0|>
if type(arg_index) is int:
return {cls.CATEGORY: category, cls.ARG_INDEX: [arg_index]}
if type(arg_index) is list and all((isinstance(i, int) for i in arg_index)):
return {cls.CATEGORY: category, cls.ARG_INDEX: arg_index}
return {cls.CATEGORY: category}
<... | Base class for formatting log messages. This implementation delegates everything to logging.Formatter using the messagefmt and datefmt properties. Subclasses may be implemented to provide required customizations, and can be registered by specifying classname in the formatter node of the project configuration file. | BaseLogFormatter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseLogFormatter:
"""Base class for formatting log messages. This implementation delegates everything to logging.Formatter using the messagefmt and datefmt properties. Subclasses may be implemented to provide required customizations, and can be registered by specifying classname in the formatter ... | stack_v2_sparse_classes_75kplus_train_067170 | 8,804 | no_license | [
{
"docstring": "Return dictionary to tag a string to format with color encodings. @param category: The category, as defined in L{ColorLogFormatter.COLOR_CATEGORIES} @param arg_index: The index of argument in the string expansion to color. This can be either a single integer value representing the index, or a li... | 2 | stack_v2_sparse_classes_30k_train_012098 | Implement the Python class `BaseLogFormatter` described below.
Class description:
Base class for formatting log messages. This implementation delegates everything to logging.Formatter using the messagefmt and datefmt properties. Subclasses may be implemented to provide required customizations, and can be registered by... | Implement the Python class `BaseLogFormatter` described below.
Class description:
Base class for formatting log messages. This implementation delegates everything to logging.Formatter using the messagefmt and datefmt properties. Subclasses may be implemented to provide required customizations, and can be registered by... | 3f93cbedbb806b6c53de89358025f93c740ebdc3 | <|skeleton|>
class BaseLogFormatter:
"""Base class for formatting log messages. This implementation delegates everything to logging.Formatter using the messagefmt and datefmt properties. Subclasses may be implemented to provide required customizations, and can be registered by specifying classname in the formatter ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseLogFormatter:
"""Base class for formatting log messages. This implementation delegates everything to logging.Formatter using the messagefmt and datefmt properties. Subclasses may be implemented to provide required customizations, and can be registered by specifying classname in the formatter node of the p... | the_stack_v2_python_sparse | pysys/utils/logutils.py | moraygrieve/pysys | train | 0 |
3987e18cf43ade73fa4a89b1f14494b3f24b9300 | [
"if msg == None:\n print('不保存数据')\n return\nwith open(SaveData._path, 'a+') as fn:\n fn.write(msg + '\\n')",
"with open(SaveData._path, 'r') as fn:\n txt = fn.readlines()\nwith open(SaveData._path, 'w') as fn:\n fn.write('')\ntxt2 = []\nfor line in txt:\n key = line.split(':')[0]\n value = li... | <|body_start_0|>
if msg == None:
print('不保存数据')
return
with open(SaveData._path, 'a+') as fn:
fn.write(msg + '\n')
<|end_body_0|>
<|body_start_1|>
with open(SaveData._path, 'r') as fn:
txt = fn.readlines()
with open(SaveData._path, 'w') as... | SaveData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaveData:
def save(self, msg=None):
"""写入的数据格式与 runTest的格式一致(中文名)"""
<|body_0|>
def get_value(self):
"""主要不错数据格式:中文名(case固定):时延"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if msg == None:
print('不保存数据')
return
wit... | stack_v2_sparse_classes_75kplus_train_067171 | 974 | no_license | [
{
"docstring": "写入的数据格式与 runTest的格式一致(中文名)",
"name": "save",
"signature": "def save(self, msg=None)"
},
{
"docstring": "主要不错数据格式:中文名(case固定):时延",
"name": "get_value",
"signature": "def get_value(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015300 | Implement the Python class `SaveData` described below.
Class description:
Implement the SaveData class.
Method signatures and docstrings:
- def save(self, msg=None): 写入的数据格式与 runTest的格式一致(中文名)
- def get_value(self): 主要不错数据格式:中文名(case固定):时延 | Implement the Python class `SaveData` described below.
Class description:
Implement the SaveData class.
Method signatures and docstrings:
- def save(self, msg=None): 写入的数据格式与 runTest的格式一致(中文名)
- def get_value(self): 主要不错数据格式:中文名(case固定):时延
<|skeleton|>
class SaveData:
def save(self, msg=None):
"""写入的数据格... | 287e14dc458c4128b1327010a139e927470397cf | <|skeleton|>
class SaveData:
def save(self, msg=None):
"""写入的数据格式与 runTest的格式一致(中文名)"""
<|body_0|>
def get_value(self):
"""主要不错数据格式:中文名(case固定):时延"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SaveData:
def save(self, msg=None):
"""写入的数据格式与 runTest的格式一致(中文名)"""
if msg == None:
print('不保存数据')
return
with open(SaveData._path, 'a+') as fn:
fn.write(msg + '\n')
def get_value(self):
"""主要不错数据格式:中文名(case固定):时延"""
with open(S... | the_stack_v2_python_sparse | src/readwriteconf/saveData.py | hi-cbh/IOStest | train | 0 | |
0b3ae5a005c107545d62417ede276973f73da32d | [
"data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.add_dataStage01RNASequencingAnalysis(data.data)\ndata.clear_data()",
"data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.update_dataStage01RNASequencingAnalysis(data.data)\ndata.clear_data()"
] | <|body_start_0|>
data = base_importData()
data.read_csv(filename)
data.format_data()
self.add_dataStage01RNASequencingAnalysis(data.data)
data.clear_data()
<|end_body_0|>
<|body_start_1|>
data = base_importData()
data.read_csv(filename)
data.format_data()... | stage01_rnasequencing_analysis_io | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stage01_rnasequencing_analysis_io:
def import_dataStage01RNASequencingAnalysis_add(self, filename):
"""table adds"""
<|body_0|>
def import_dataStage01RNASequencingAnalysis_update(self, filename):
"""table adds"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_067172 | 961 | permissive | [
{
"docstring": "table adds",
"name": "import_dataStage01RNASequencingAnalysis_add",
"signature": "def import_dataStage01RNASequencingAnalysis_add(self, filename)"
},
{
"docstring": "table adds",
"name": "import_dataStage01RNASequencingAnalysis_update",
"signature": "def import_dataStage0... | 2 | null | Implement the Python class `stage01_rnasequencing_analysis_io` described below.
Class description:
Implement the stage01_rnasequencing_analysis_io class.
Method signatures and docstrings:
- def import_dataStage01RNASequencingAnalysis_add(self, filename): table adds
- def import_dataStage01RNASequencingAnalysis_update... | Implement the Python class `stage01_rnasequencing_analysis_io` described below.
Class description:
Implement the stage01_rnasequencing_analysis_io class.
Method signatures and docstrings:
- def import_dataStage01RNASequencingAnalysis_add(self, filename): table adds
- def import_dataStage01RNASequencingAnalysis_update... | 521ad0b671b0bca02e9cebfc1b372f2265955418 | <|skeleton|>
class stage01_rnasequencing_analysis_io:
def import_dataStage01RNASequencingAnalysis_add(self, filename):
"""table adds"""
<|body_0|>
def import_dataStage01RNASequencingAnalysis_update(self, filename):
"""table adds"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class stage01_rnasequencing_analysis_io:
def import_dataStage01RNASequencingAnalysis_add(self, filename):
"""table adds"""
data = base_importData()
data.read_csv(filename)
data.format_data()
self.add_dataStage01RNASequencingAnalysis(data.data)
data.clear_data()
d... | the_stack_v2_python_sparse | SBaaS_rnasequencing/stage01_rnasequencing_analysis_io.py | dmccloskey/SBaaS_rnasequencing | train | 0 | |
b9cd4e1ab9cb30bf63b8487027b548f0388e16b0 | [
"super().__init__()\nself.out_channels = query_dim\nself.num_heads = num_heads\nproj_dim = head_dim * num_heads\nif cross_attention_dim is None:\n cross_attention_dim = query_dim\nself.to_q = nn.Linear(query_dim, proj_dim, bias=bias)\nself.to_k = nn.Linear(cross_attention_dim, proj_dim, bias=bias)\nself.to_v = n... | <|body_start_0|>
super().__init__()
self.out_channels = query_dim
self.num_heads = num_heads
proj_dim = head_dim * num_heads
if cross_attention_dim is None:
cross_attention_dim = query_dim
self.to_q = nn.Linear(query_dim, proj_dim, bias=bias)
self.to_k... | SelfAttention | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
def __init__(self, query_dim: int, name: str='exact', how: str='basic', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: bool=False, slice_size: int=4, **kwargs) -> None:
"""Compute self-attention. Includes all the data wrangling... | stack_v2_sparse_classes_75kplus_train_067173 | 10,093 | permissive | [
{
"docstring": "Compute self-attention. Includes all the data wrangling on the input before attention computation. Input Shape: (B, H'*W', query_dim). Output Shape: (B, H'*W', query_dim). Parameters ---------- query_dim : int The number of channels in the query. Typically: num_heads*head_dim name : str Name of ... | 5 | stack_v2_sparse_classes_30k_train_021158 | Implement the Python class `SelfAttention` described below.
Class description:
Implement the SelfAttention class.
Method signatures and docstrings:
- def __init__(self, query_dim: int, name: str='exact', how: str='basic', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: boo... | Implement the Python class `SelfAttention` described below.
Class description:
Implement the SelfAttention class.
Method signatures and docstrings:
- def __init__(self, query_dim: int, name: str='exact', how: str='basic', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: boo... | 7f79405012eb934b419bbdba8de23f35e840ca85 | <|skeleton|>
class SelfAttention:
def __init__(self, query_dim: int, name: str='exact', how: str='basic', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: bool=False, slice_size: int=4, **kwargs) -> None:
"""Compute self-attention. Includes all the data wrangling... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelfAttention:
def __init__(self, query_dim: int, name: str='exact', how: str='basic', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: bool=False, slice_size: int=4, **kwargs) -> None:
"""Compute self-attention. Includes all the data wrangling on the input ... | the_stack_v2_python_sparse | cellseg_models_pytorch/modules/self_attention_modules.py | okunator/cellseg_models.pytorch | train | 43 | |
6e704f65fcb9c9cc3e1a188e613c2ba7fa0d64fb | [
"if x < 0:\n out = int(''.join(reversed(str(x * -1))))\n return 0 if (out > 2 ** 31 - 1) | (out < -2 ** 31) else -1 * out\nelse:\n out = int(''.join(reversed(str(x))))\n return 0 if (out > 2 ** 31 - 1) | (out < -2 ** 31) else out",
"if x == 0:\n return 0\nelif (x > 2 ** 31 - 1) | (x < -2 ** 31):\n ... | <|body_start_0|>
if x < 0:
out = int(''.join(reversed(str(x * -1))))
return 0 if (out > 2 ** 31 - 1) | (out < -2 ** 31) else -1 * out
else:
out = int(''.join(reversed(str(x))))
return 0 if (out > 2 ** 31 - 1) | (out < -2 ** 31) else out
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse_myfirst(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x < 0:
out = int(''.join(reversed(str(x * -1))))
... | stack_v2_sparse_classes_75kplus_train_067174 | 1,126 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse_myfirst",
"signature": "def reverse_myfirst(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032429 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse_myfirst(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse_myfirst(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def reverse(self, x):
""":type ... | f0d9070fa292ca36971a465a805faddb12025482 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse_myfirst(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
if x < 0:
out = int(''.join(reversed(str(x * -1))))
return 0 if (out > 2 ** 31 - 1) | (out < -2 ** 31) else -1 * out
else:
out = int(''.join(reversed(str(x))))
return 0 if (ou... | the_stack_v2_python_sparse | 7.ReverseInteger.py | JerryRoc/leetcode | train | 0 | |
ceee5d9bf3c6dea30409573a72723f3f4df753f7 | [
"auth = client.get_authorization_token()['authorizationData'][0]\nauth_token = base64.b64decode(auth['authorizationToken']).decode()\n_, password = auth_token.split(':')\nreturn password",
"query, args = cls.parse(value)\nsession = context.get_session(region=args.get('region'))\nclient = session.client('ecr')\nif... | <|body_start_0|>
auth = client.get_authorization_token()['authorizationData'][0]
auth_token = base64.b64decode(auth['authorizationToken']).decode()
_, password = auth_token.split(':')
return password
<|end_body_0|>
<|body_start_1|>
query, args = cls.parse(value)
session ... | ECR Lookup. | EcrLookup | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EcrLookup:
"""ECR Lookup."""
def get_login_password(client):
"""Get a password to login to ECR registry."""
<|body_0|>
def handle(cls, value, context, **_):
"""Retrieve a value from AWS Elastic Container Registry (ECR). Args: value: The value passed to the Lookup... | stack_v2_sparse_classes_75kplus_train_067175 | 2,978 | permissive | [
{
"docstring": "Get a password to login to ECR registry.",
"name": "get_login_password",
"signature": "def get_login_password(client)"
},
{
"docstring": "Retrieve a value from AWS Elastic Container Registry (ECR). Args: value: The value passed to the Lookup. context: The current context object."... | 2 | null | Implement the Python class `EcrLookup` described below.
Class description:
ECR Lookup.
Method signatures and docstrings:
- def get_login_password(client): Get a password to login to ECR registry.
- def handle(cls, value, context, **_): Retrieve a value from AWS Elastic Container Registry (ECR). Args: value: The value... | Implement the Python class `EcrLookup` described below.
Class description:
ECR Lookup.
Method signatures and docstrings:
- def get_login_password(client): Get a password to login to ECR registry.
- def handle(cls, value, context, **_): Retrieve a value from AWS Elastic Container Registry (ECR). Args: value: The value... | 4fd299961a4b73df39e14f4f19a7236f7be17dd8 | <|skeleton|>
class EcrLookup:
"""ECR Lookup."""
def get_login_password(client):
"""Get a password to login to ECR registry."""
<|body_0|>
def handle(cls, value, context, **_):
"""Retrieve a value from AWS Elastic Container Registry (ECR). Args: value: The value passed to the Lookup... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EcrLookup:
"""ECR Lookup."""
def get_login_password(client):
"""Get a password to login to ECR registry."""
auth = client.get_authorization_token()['authorizationData'][0]
auth_token = base64.b64decode(auth['authorizationToken']).decode()
_, password = auth_token.split(':'... | the_stack_v2_python_sparse | runway/lookups/handlers/ecr.py | troyready/runway | train | 0 |
dbb03e317204bceffa8a455524e54557644695e4 | [
"super(CurrentResourceValue, self).__init__()\nself.device_id = device_id\nself.resource_path = resource_path\nself.async_id = utils.new_async_id()\nLOG.debug('new async id: %s', self.async_id)\nself._route_keys = expand_dict_as_keys(dict(id=self.async_id, channel=ChannelIdentifiers.async_responses))\nself._optiona... | <|body_start_0|>
super(CurrentResourceValue, self).__init__()
self.device_id = device_id
self.resource_path = resource_path
self.async_id = utils.new_async_id()
LOG.debug('new async id: %s', self.async_id)
self._route_keys = expand_dict_as_keys(dict(id=self.async_id, chan... | Triggers on response to a request for a current resource value | CurrentResourceValue | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurrentResourceValue:
"""Triggers on response to a request for a current resource value"""
def __init__(self, device_id, resource_path, **extra_filters):
"""Triggers on response to a request for a current resource value .. warning:: This functionality is considered experimental; the ... | stack_v2_sparse_classes_75kplus_train_067176 | 3,067 | permissive | [
{
"docstring": "Triggers on response to a request for a current resource value .. warning:: This functionality is considered experimental; the interface may change in future releases :param device_id: a device identifier :param resource_path: a resource path :param extra_filters:",
"name": "__init__",
"... | 3 | stack_v2_sparse_classes_30k_train_019315 | Implement the Python class `CurrentResourceValue` described below.
Class description:
Triggers on response to a request for a current resource value
Method signatures and docstrings:
- def __init__(self, device_id, resource_path, **extra_filters): Triggers on response to a request for a current resource value .. warn... | Implement the Python class `CurrentResourceValue` described below.
Class description:
Triggers on response to a request for a current resource value
Method signatures and docstrings:
- def __init__(self, device_id, resource_path, **extra_filters): Triggers on response to a request for a current resource value .. warn... | 76ef009903415f37f69dcc5778be8f5fb14c08fe | <|skeleton|>
class CurrentResourceValue:
"""Triggers on response to a request for a current resource value"""
def __init__(self, device_id, resource_path, **extra_filters):
"""Triggers on response to a request for a current resource value .. warning:: This functionality is considered experimental; the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CurrentResourceValue:
"""Triggers on response to a request for a current resource value"""
def __init__(self, device_id, resource_path, **extra_filters):
"""Triggers on response to a request for a current resource value .. warning:: This functionality is considered experimental; the interface may... | the_stack_v2_python_sparse | src/mbed_cloud/subscribe/channels/current_resource_value.py | GQMai/mbed-cloud-sdk-python | train | 0 |
582a483d5267069a52fb11eb078e0a5ff18cddaa | [
"index = 0\napi_url = 'http://proxy.httpdaili.com/apinew.asp?sl=10&noinfo=true&ddbh=302094241791519942'\nprint('获取本次的 http 代理IP')\nwhile True:\n now = Date.now().format()\n print('第: {} 次更新代理, time: {}'.format(index, now))\n try:\n loop = asyncio.get_event_loop()\n ips = requests.get(api_url,... | <|body_start_0|>
index = 0
api_url = 'http://proxy.httpdaili.com/apinew.asp?sl=10&noinfo=true&ddbh=302094241791519942'
print('获取本次的 http 代理IP')
while True:
now = Date.now().format()
print('第: {} 次更新代理, time: {}'.format(index, now))
try:
... | Cron | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cron:
def update_proxy_ip(self):
"""更新代理 :return:"""
<|body_0|>
def check_all_ip(self):
"""轮询检查所有的代理IP,剔除失效的IP :return:"""
<|body_1|>
async def _get_ip_result(self, proxy_ip):
"""异步测试IP是否可用 :param proxy_ip: :return:"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_067177 | 3,268 | permissive | [
{
"docstring": "更新代理 :return:",
"name": "update_proxy_ip",
"signature": "def update_proxy_ip(self)"
},
{
"docstring": "轮询检查所有的代理IP,剔除失效的IP :return:",
"name": "check_all_ip",
"signature": "def check_all_ip(self)"
},
{
"docstring": "异步测试IP是否可用 :param proxy_ip: :return:",
"name"... | 3 | stack_v2_sparse_classes_30k_test_001893 | Implement the Python class `Cron` described below.
Class description:
Implement the Cron class.
Method signatures and docstrings:
- def update_proxy_ip(self): 更新代理 :return:
- def check_all_ip(self): 轮询检查所有的代理IP,剔除失效的IP :return:
- async def _get_ip_result(self, proxy_ip): 异步测试IP是否可用 :param proxy_ip: :return: | Implement the Python class `Cron` described below.
Class description:
Implement the Cron class.
Method signatures and docstrings:
- def update_proxy_ip(self): 更新代理 :return:
- def check_all_ip(self): 轮询检查所有的代理IP,剔除失效的IP :return:
- async def _get_ip_result(self, proxy_ip): 异步测试IP是否可用 :param proxy_ip: :return:
<|skelet... | 29ba13905c73081097df9ef646a5c8194eb024be | <|skeleton|>
class Cron:
def update_proxy_ip(self):
"""更新代理 :return:"""
<|body_0|>
def check_all_ip(self):
"""轮询检查所有的代理IP,剔除失效的IP :return:"""
<|body_1|>
async def _get_ip_result(self, proxy_ip):
"""异步测试IP是否可用 :param proxy_ip: :return:"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cron:
def update_proxy_ip(self):
"""更新代理 :return:"""
index = 0
api_url = 'http://proxy.httpdaili.com/apinew.asp?sl=10&noinfo=true&ddbh=302094241791519942'
print('获取本次的 http 代理IP')
while True:
now = Date.now().format()
print('第: {} 次更新代理, time: {}... | the_stack_v2_python_sparse | projects/ip_proxy/cron.py | UoToGK/crawler-pyspider | train | 0 | |
b7965422ed2e90ebb81b5d5af35798dac106e409 | [
"import collections\ndicts_row = collections.defaultdict(set)\nfor point in points:\n dicts_row[point[0]].add(point[1])\nl = len(points)\nmin_val = float('inf')\nfor i in range(l - 1):\n for j in range(i + 1, l):\n if points[i][0] != points[j][0] and points[i][1] != points[j][1]:\n if points... | <|body_start_0|>
import collections
dicts_row = collections.defaultdict(set)
for point in points:
dicts_row[point[0]].add(point[1])
l = len(points)
min_val = float('inf')
for i in range(l - 1):
for j in range(i + 1, l):
if points[i]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minAreaRect(self, points):
""":type points: List[List[int]] :rtype: int 2028 ms"""
<|body_0|>
def minAreaRect_1(self, points):
"""112ms :param points: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import collections
... | stack_v2_sparse_classes_75kplus_train_067178 | 2,528 | no_license | [
{
"docstring": ":type points: List[List[int]] :rtype: int 2028 ms",
"name": "minAreaRect",
"signature": "def minAreaRect(self, points)"
},
{
"docstring": "112ms :param points: :return:",
"name": "minAreaRect_1",
"signature": "def minAreaRect_1(self, points)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034253 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minAreaRect(self, points): :type points: List[List[int]] :rtype: int 2028 ms
- def minAreaRect_1(self, points): 112ms :param points: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minAreaRect(self, points): :type points: List[List[int]] :rtype: int 2028 ms
- def minAreaRect_1(self, points): 112ms :param points: :return:
<|skeleton|>
class Solution:
... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def minAreaRect(self, points):
""":type points: List[List[int]] :rtype: int 2028 ms"""
<|body_0|>
def minAreaRect_1(self, points):
"""112ms :param points: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minAreaRect(self, points):
""":type points: List[List[int]] :rtype: int 2028 ms"""
import collections
dicts_row = collections.defaultdict(set)
for point in points:
dicts_row[point[0]].add(point[1])
l = len(points)
min_val = float('inf')... | the_stack_v2_python_sparse | MinimumAreaRectangle_MID_939.py | 953250587/leetcode-python | train | 2 | |
239f3dd4cded374620e23801d32532ace7dca3f5 | [
"super(EncoderBlock, self).__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(... | <|body_start_0|>
super(EncoderBlock, self).__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)
... | Class EncoderBlock | EncoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderBlock:
"""Class EncoderBlock"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Class constructor"""
<|body_0|>
def call(self, x, training, mask=None):
"""Public instance method that returns a tersor of shape (batch, input_seq_len, dm) containing the ... | stack_v2_sparse_classes_75kplus_train_067179 | 1,500 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "Public instance method that returns a tersor of shape (batch, input_seq_len, dm) containing the block’s output",
"name": "call",
"signature": "def ca... | 2 | stack_v2_sparse_classes_30k_train_019383 | Implement the Python class `EncoderBlock` described below.
Class description:
Class EncoderBlock
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): Class constructor
- def call(self, x, training, mask=None): Public instance method that returns a tersor of shape (batch, input_seq_len... | Implement the Python class `EncoderBlock` described below.
Class description:
Class EncoderBlock
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): Class constructor
- def call(self, x, training, mask=None): Public instance method that returns a tersor of shape (batch, input_seq_len... | b1d0995023630f2a2b7ed953983c405077c0d5a8 | <|skeleton|>
class EncoderBlock:
"""Class EncoderBlock"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Class constructor"""
<|body_0|>
def call(self, x, training, mask=None):
"""Public instance method that returns a tersor of shape (batch, input_seq_len, dm) containing the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EncoderBlock:
"""Class EncoderBlock"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Class constructor"""
super(EncoderBlock, self).__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dens... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/7-transformer_encoder_block.py | oscarmrt/holbertonschool-machine_learning | train | 1 |
a897d5354267cb455dd977be1e47b66840b34685 | [
"def flatten_helper(node: TreeNode) -> None:\n left = node.left\n right = node.right\n if left:\n flatten_helper(left)\n node.left = None\n node.right = left\n if right:\n flatten_helper(right)\n if left:\n n = node.right\n while n:\n ... | <|body_start_0|>
def flatten_helper(node: TreeNode) -> None:
left = node.left
right = node.right
if left:
flatten_helper(left)
node.left = None
node.right = left
if right:
flatten_helper(right)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten_v1(self, root: TreeNode) -> None:
"""An in-order approach."""
<|body_0|>
def flatten_v2(self, root: TreeNode) -> None:
"""Use a stack to change the priority of the links."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def flat... | stack_v2_sparse_classes_75kplus_train_067180 | 2,701 | no_license | [
{
"docstring": "An in-order approach.",
"name": "flatten_v1",
"signature": "def flatten_v1(self, root: TreeNode) -> None"
},
{
"docstring": "Use a stack to change the priority of the links.",
"name": "flatten_v2",
"signature": "def flatten_v2(self, root: TreeNode) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_003703 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten_v1(self, root: TreeNode) -> None: An in-order approach.
- def flatten_v2(self, root: TreeNode) -> None: Use a stack to change the priority of the links. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten_v1(self, root: TreeNode) -> None: An in-order approach.
- def flatten_v2(self, root: TreeNode) -> None: Use a stack to change the priority of the links.
<|skeleton|>... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def flatten_v1(self, root: TreeNode) -> None:
"""An in-order approach."""
<|body_0|>
def flatten_v2(self, root: TreeNode) -> None:
"""Use a stack to change the priority of the links."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def flatten_v1(self, root: TreeNode) -> None:
"""An in-order approach."""
def flatten_helper(node: TreeNode) -> None:
left = node.left
right = node.right
if left:
flatten_helper(left)
node.left = None
... | the_stack_v2_python_sparse | python3/trees_and_graphs/flatten_binary_tree_to_linked_list.py | victorchu/algorithms | train | 0 | |
47345ea6f6e3c1be7961462dbf704fcec0504e9e | [
"res = {}\nfor line in self.browse(cr, uid, ids):\n res[line.id] = line.price_unit * line.product_qty\nreturn res",
"res = {}\nif price or qty:\n res = {'value': {'price_subtotal': price * qty}}\nreturn res"
] | <|body_start_0|>
res = {}
for line in self.browse(cr, uid, ids):
res[line.id] = line.price_unit * line.product_qty
return res
<|end_body_0|>
<|body_start_1|>
res = {}
if price or qty:
res = {'value': {'price_subtotal': price * qty}}
return res
<|e... | Manage the products of purchase inintail quotaion | pq_products | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pq_products:
"""Manage the products of purchase inintail quotaion"""
def _amount_line(self, cr, uid, ids, fields, arg, context):
"""Compute the price amount of each quotaion line. @return: dictionary of lines subtotal"""
<|body_0|>
def subtotal(self, cr, uid, ids, price,... | stack_v2_sparse_classes_75kplus_train_067181 | 20,327 | no_license | [
{
"docstring": "Compute the price amount of each quotaion line. @return: dictionary of lines subtotal",
"name": "_amount_line",
"signature": "def _amount_line(self, cr, uid, ids, fields, arg, context)"
},
{
"docstring": "On change function to recompute the total price after changing product qty ... | 2 | stack_v2_sparse_classes_30k_train_047371 | Implement the Python class `pq_products` described below.
Class description:
Manage the products of purchase inintail quotaion
Method signatures and docstrings:
- def _amount_line(self, cr, uid, ids, fields, arg, context): Compute the price amount of each quotaion line. @return: dictionary of lines subtotal
- def sub... | Implement the Python class `pq_products` described below.
Class description:
Manage the products of purchase inintail quotaion
Method signatures and docstrings:
- def _amount_line(self, cr, uid, ids, fields, arg, context): Compute the price amount of each quotaion line. @return: dictionary of lines subtotal
- def sub... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class pq_products:
"""Manage the products of purchase inintail quotaion"""
def _amount_line(self, cr, uid, ids, fields, arg, context):
"""Compute the price amount of each quotaion line. @return: dictionary of lines subtotal"""
<|body_0|>
def subtotal(self, cr, uid, ids, price,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class pq_products:
"""Manage the products of purchase inintail quotaion"""
def _amount_line(self, cr, uid, ids, fields, arg, context):
"""Compute the price amount of each quotaion line. @return: dictionary of lines subtotal"""
res = {}
for line in self.browse(cr, uid, ids):
... | the_stack_v2_python_sparse | v_7/GDS/shamil_v3/purchase_custom/quote.py | musabahmed/baba | train | 0 |
72a8522fc69be77f904596b91ccea40132540c59 | [
"super(boris_2nd_order, self).__init__(params)\n[self.S, self.ST, self.SQ, self.Sx, self.QQ] = self.__get_Qd()\nself.qQ = np.dot(self.coll.weights, self.coll.Qmat[1:, 1:])",
"QI = self.get_Qdelta_implicit(self.coll, 'IE')\nQE = self.get_Qdelta_explicit(self.coll, 'EE')\nQT = 1 / 2 * (QI + QE)\nQx = np.dot(QE, QT)... | <|body_start_0|>
super(boris_2nd_order, self).__init__(params)
[self.S, self.ST, self.SQ, self.Sx, self.QQ] = self.__get_Qd()
self.qQ = np.dot(self.coll.weights, self.coll.Qmat[1:, 1:])
<|end_body_0|>
<|body_start_1|>
QI = self.get_Qdelta_implicit(self.coll, 'IE')
QE = self.get_... | Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet with Boris scheme as base integrator Attributes: S: node-to-node collocation matrix (first order) SQ: node-to-node collocation matrix (second order) ST: node-to-node trapezoidal matrix Sx: node-to-node Euler half-step for position up... | boris_2nd_order | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class boris_2nd_order:
"""Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet with Boris scheme as base integrator Attributes: S: node-to-node collocation matrix (first order) SQ: node-to-node collocation matrix (second order) ST: node-to-node trapezoidal matrix Sx: n... | stack_v2_sparse_classes_75kplus_train_067182 | 6,829 | permissive | [
{
"docstring": "Initialization routine for the custom sweeper Args: params: parameters for the sweeper",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Get integration matrices for 2nd-order SDC Returns: S: node-to-node collocation matrix (first order) SQ: node-... | 5 | stack_v2_sparse_classes_30k_train_004522 | Implement the Python class `boris_2nd_order` described below.
Class description:
Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet with Boris scheme as base integrator Attributes: S: node-to-node collocation matrix (first order) SQ: node-to-node collocation matrix (second order) ST... | Implement the Python class `boris_2nd_order` described below.
Class description:
Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet with Boris scheme as base integrator Attributes: S: node-to-node collocation matrix (first order) SQ: node-to-node collocation matrix (second order) ST... | de2cd523411276083355389d7e7993106cedf93d | <|skeleton|>
class boris_2nd_order:
"""Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet with Boris scheme as base integrator Attributes: S: node-to-node collocation matrix (first order) SQ: node-to-node collocation matrix (second order) ST: node-to-node trapezoidal matrix Sx: n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class boris_2nd_order:
"""Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet with Boris scheme as base integrator Attributes: S: node-to-node collocation matrix (first order) SQ: node-to-node collocation matrix (second order) ST: node-to-node trapezoidal matrix Sx: node-to-node E... | the_stack_v2_python_sparse | pySDC/implementations/sweeper_classes/boris_2nd_order.py | ruthschoebel/pySDC | train | 0 |
fc5964a2ebb934f9e9084b0fee571d2e5a9bfe86 | [
"super(TDecoder, self).__init__()\nself.model_type = 'transformer'\nself.hidden_size = hidden_size\nself.output_size = output_size\nself.num_layers = num_layers\nself.dropout = dropout\nself.num_attention_heads = num_attention_heads\nself.embedding = torch.nn.Embedding(output_size, hidden_size)\ndecoder_layers = to... | <|body_start_0|>
super(TDecoder, self).__init__()
self.model_type = 'transformer'
self.hidden_size = hidden_size
self.output_size = output_size
self.num_layers = num_layers
self.dropout = dropout
self.num_attention_heads = num_attention_heads
self.embeddin... | Transformer Decoder class. | TDecoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TDecoder:
"""Transformer Decoder class."""
def __init__(self, hidden_size, output_size, num_layers, dropout, num_attention_heads):
"""Initialize decoder model."""
<|body_0|>
def forward(self, input_tensor, memory_tensor):
"""Apply forward computation."""
... | stack_v2_sparse_classes_75kplus_train_067183 | 3,941 | permissive | [
{
"docstring": "Initialize decoder model.",
"name": "__init__",
"signature": "def __init__(self, hidden_size, output_size, num_layers, dropout, num_attention_heads)"
},
{
"docstring": "Apply forward computation.",
"name": "forward",
"signature": "def forward(self, input_tensor, memory_te... | 2 | null | Implement the Python class `TDecoder` described below.
Class description:
Transformer Decoder class.
Method signatures and docstrings:
- def __init__(self, hidden_size, output_size, num_layers, dropout, num_attention_heads): Initialize decoder model.
- def forward(self, input_tensor, memory_tensor): Apply forward com... | Implement the Python class `TDecoder` described below.
Class description:
Transformer Decoder class.
Method signatures and docstrings:
- def __init__(self, hidden_size, output_size, num_layers, dropout, num_attention_heads): Initialize decoder model.
- def forward(self, input_tensor, memory_tensor): Apply forward com... | 85c5cc91cedff092d29d4c98983d8c0ba4497be1 | <|skeleton|>
class TDecoder:
"""Transformer Decoder class."""
def __init__(self, hidden_size, output_size, num_layers, dropout, num_attention_heads):
"""Initialize decoder model."""
<|body_0|>
def forward(self, input_tensor, memory_tensor):
"""Apply forward computation."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TDecoder:
"""Transformer Decoder class."""
def __init__(self, hidden_size, output_size, num_layers, dropout, num_attention_heads):
"""Initialize decoder model."""
super(TDecoder, self).__init__()
self.model_type = 'transformer'
self.hidden_size = hidden_size
self.o... | the_stack_v2_python_sparse | ortografix/model/transformer.py | akb89/ortografix | train | 0 |
8433aeb800774dae1fac95bc41fb395145acfabb | [
"@lru_cache(None)\ndef _rec(target):\n if target <= 0:\n return 1 if target == 0 else 0\n return sum((_rec(target - n) for n in nums))\nreturn _rec(target)",
"@lru_cache(None)\ndef dfs(t):\n if t == 0:\n return 1\n return sum((dfs(t - n) for n in nums if n <= t))\nreturn dfs(target)"
] | <|body_start_0|>
@lru_cache(None)
def _rec(target):
if target <= 0:
return 1 if target == 0 else 0
return sum((_rec(target - n) for n in nums))
return _rec(target)
<|end_body_0|>
<|body_start_1|>
@lru_cache(None)
def dfs(t):
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
"""04/12/2020 22:17"""
<|body_0|>
def combinationSum4(self, nums: List[int], target: int) -> int:
"""08/15/2022 10:05"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
@lru_cach... | stack_v2_sparse_classes_75kplus_train_067184 | 2,343 | no_license | [
{
"docstring": "04/12/2020 22:17",
"name": "combinationSum4",
"signature": "def combinationSum4(self, nums: List[int], target: int) -> int"
},
{
"docstring": "08/15/2022 10:05",
"name": "combinationSum4",
"signature": "def combinationSum4(self, nums: List[int], target: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_031765 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum4(self, nums: List[int], target: int) -> int: 04/12/2020 22:17
- def combinationSum4(self, nums: List[int], target: int) -> int: 08/15/2022 10:05 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum4(self, nums: List[int], target: int) -> int: 04/12/2020 22:17
- def combinationSum4(self, nums: List[int], target: int) -> int: 08/15/2022 10:05
<|skeleton|>
... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
"""04/12/2020 22:17"""
<|body_0|>
def combinationSum4(self, nums: List[int], target: int) -> int:
"""08/15/2022 10:05"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
"""04/12/2020 22:17"""
@lru_cache(None)
def _rec(target):
if target <= 0:
return 1 if target == 0 else 0
return sum((_rec(target - n) for n in nums))
return _rec(ta... | the_stack_v2_python_sparse | leetcode/solved/377_Combination_Sum_IV/solution.py | sungminoh/algorithms | train | 0 | |
65773b1cf093ca44b66838dcb9b6238dbd005466 | [
"if site is None:\n site = Site.objects.get_current()\nreturn self.filter(content_type=ContentType.objects.get_for_model(obj), object_pk=obj.pk, site=site).count()",
"if site is None:\n site = Site.objects.get_current()\nqueryset = self.filter(content_type=ContentType.objects.get_for_model(obj), object_pk=o... | <|body_start_0|>
if site is None:
site = Site.objects.get_current()
return self.filter(content_type=ContentType.objects.get_for_model(obj), object_pk=obj.pk, site=site).count()
<|end_body_0|>
<|body_start_1|>
if site is None:
site = Site.objects.get_current()
que... | Manage how users are able to interact with the Like mechanism. | LikeManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LikeManager:
"""Manage how users are able to interact with the Like mechanism."""
def get_num_likes_for_object(self, obj, site=None):
"""Retrieve the number of likes an object has received."""
<|body_0|>
def get_already_liked(self, user, obj, site=None):
"""Retur... | stack_v2_sparse_classes_75kplus_train_067185 | 1,264 | no_license | [
{
"docstring": "Retrieve the number of likes an object has received.",
"name": "get_num_likes_for_object",
"signature": "def get_num_likes_for_object(self, obj, site=None)"
},
{
"docstring": "Return a flag stating whether an object has already been liked.",
"name": "get_already_liked",
"... | 2 | stack_v2_sparse_classes_30k_train_032347 | Implement the Python class `LikeManager` described below.
Class description:
Manage how users are able to interact with the Like mechanism.
Method signatures and docstrings:
- def get_num_likes_for_object(self, obj, site=None): Retrieve the number of likes an object has received.
- def get_already_liked(self, user, o... | Implement the Python class `LikeManager` described below.
Class description:
Manage how users are able to interact with the Like mechanism.
Method signatures and docstrings:
- def get_num_likes_for_object(self, obj, site=None): Retrieve the number of likes an object has received.
- def get_already_liked(self, user, o... | 9219e6c5a49eecd1c66dd1b518640c5d678acab6 | <|skeleton|>
class LikeManager:
"""Manage how users are able to interact with the Like mechanism."""
def get_num_likes_for_object(self, obj, site=None):
"""Retrieve the number of likes an object has received."""
<|body_0|>
def get_already_liked(self, user, obj, site=None):
"""Retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LikeManager:
"""Manage how users are able to interact with the Like mechanism."""
def get_num_likes_for_object(self, obj, site=None):
"""Retrieve the number of likes an object has received."""
if site is None:
site = Site.objects.get_current()
return self.filter(conten... | the_stack_v2_python_sparse | tunobase/social_media/tunosocial/managers.py | unomena/tunobase | train | 0 |
a6ca4fae47d954ed846d3246afef26febbf8fe90 | [
"H = self.units\nassert isinstance(input_shape, list)\nnb_inputs = len(input_shape)\nassert nb_inputs >= 2\nassert len(input_shape[0]) == 3\nB, P, H_ = input_shape[0]\nassert H_ == 2 * H\nassert len(input_shape[1]) == 3\nB, Q, H_ = input_shape[1]\nassert H_ == 2 * H\nself.input_spec = [None]\nsuper(QuestionAttnGRU,... | <|body_start_0|>
H = self.units
assert isinstance(input_shape, list)
nb_inputs = len(input_shape)
assert nb_inputs >= 2
assert len(input_shape[0]) == 3
B, P, H_ = input_shape[0]
assert H_ == 2 * H
assert len(input_shape[1]) == 3
B, Q, H_ = input_sh... | Class implementing attention mechanism, to get the relevance/importance of one tensor on other. Used to obtain question-aware representation of the passage, i.e. importance of each word in the question w.r.t passage. | QuestionAttnGRU | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionAttnGRU:
"""Class implementing attention mechanism, to get the relevance/importance of one tensor on other. Used to obtain question-aware representation of the passage, i.e. importance of each word in the question w.r.t passage."""
def build(self, input_shape):
"""Creates the... | stack_v2_sparse_classes_75kplus_train_067186 | 2,239 | permissive | [
{
"docstring": "Creates the layer weights. Must be implemented on all layers that have weights. # Arguments input_shape: Keras tensor (future input to layer) or list/tuple of Keras tensors to reference for weight shape computations",
"name": "build",
"signature": "def build(self, input_shape)"
},
{
... | 2 | stack_v2_sparse_classes_30k_val_000815 | Implement the Python class `QuestionAttnGRU` described below.
Class description:
Class implementing attention mechanism, to get the relevance/importance of one tensor on other. Used to obtain question-aware representation of the passage, i.e. importance of each word in the question w.r.t passage.
Method signatures an... | Implement the Python class `QuestionAttnGRU` described below.
Class description:
Class implementing attention mechanism, to get the relevance/importance of one tensor on other. Used to obtain question-aware representation of the passage, i.e. importance of each word in the question w.r.t passage.
Method signatures an... | 34dca815e9f4b7a9def0d4d9292f7a409515cac9 | <|skeleton|>
class QuestionAttnGRU:
"""Class implementing attention mechanism, to get the relevance/importance of one tensor on other. Used to obtain question-aware representation of the passage, i.e. importance of each word in the question w.r.t passage."""
def build(self, input_shape):
"""Creates the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestionAttnGRU:
"""Class implementing attention mechanism, to get the relevance/importance of one tensor on other. Used to obtain question-aware representation of the passage, i.e. importance of each word in the question w.r.t passage."""
def build(self, input_shape):
"""Creates the layer weight... | the_stack_v2_python_sparse | layers/QuestionAttnGRU.py | halloTheCoder/RNet-Keras | train | 2 |
0d0ab41b4dc36448f0f5b8b28aa72add18b9ee9d | [
"id_proyecto = UrlParser.parse_id(request.url, 'proyectos')\nclase = 'actions'\nvalue = '<div>'\nurl_cont = '/proyectos/%d/' % id_proyecto\nid = str(obj.id_usuario)\nvalue += '<div>' + '<a href=\"' + url_cont + 'nomiembros/' + id + '\" ' + 'class=\"' + clase + '\">Ver</a>' + '</div><br />'\nif PoseePermiso('asignar... | <|body_start_0|>
id_proyecto = UrlParser.parse_id(request.url, 'proyectos')
clase = 'actions'
value = '<div>'
url_cont = '/proyectos/%d/' % id_proyecto
id = str(obj.id_usuario)
value += '<div>' + '<a href="' + url_cont + 'nomiembros/' + id + '" ' + 'class="' + clase + '">... | NoMiembrosProyectoTableFiller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoMiembrosProyectoTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, id_proyecto=None, **kw):
"""Se muestra la lista de usuarios que no tienen algun rol de proyecto para el proye... | stack_v2_sparse_classes_75kplus_train_067187 | 14,195 | no_license | [
{
"docstring": "Links de acciones para un registro dado",
"name": "__actions__",
"signature": "def __actions__(self, obj)"
},
{
"docstring": "Se muestra la lista de usuarios que no tienen algun rol de proyecto para el proyecto en cuestion.",
"name": "_do_get_provider_count_and_objs",
"si... | 2 | null | Implement the Python class `NoMiembrosProyectoTableFiller` described below.
Class description:
Implement the NoMiembrosProyectoTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, id_proyecto=None, **kw):... | Implement the Python class `NoMiembrosProyectoTableFiller` described below.
Class description:
Implement the NoMiembrosProyectoTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, id_proyecto=None, **kw):... | 997531e130d1951b483f4a6a67f2df7467cd9fd1 | <|skeleton|>
class NoMiembrosProyectoTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, id_proyecto=None, **kw):
"""Se muestra la lista de usuarios que no tienen algun rol de proyecto para el proye... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NoMiembrosProyectoTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
id_proyecto = UrlParser.parse_id(request.url, 'proyectos')
clase = 'actions'
value = '<div>'
url_cont = '/proyectos/%d/' % id_proyecto
id = str(obj.id_usuari... | the_stack_v2_python_sparse | lpm/controllers/no_miembros_proyecto.py | jorgeramirez/LPM | train | 1 | |
348afe50ba07b9f802e44f46d330c6f51a4e6e62 | [
"stas = STAs(nids=nids, experiment=self, trange=trange, nt=nt)\nstas.calc()\nreturn stas",
"stcs = STCs(nids=nids, experiment=self, trange=trange, nt=nt)\nstcs.calc()\nreturn stcso"
] | <|body_start_0|>
stas = STAs(nids=nids, experiment=self, trange=trange, nt=nt)
stas.calc()
return stas
<|end_body_0|>
<|body_start_1|>
stcs = STCs(nids=nids, experiment=self, trange=trange, nt=nt)
stcs.calc()
return stcso
<|end_body_1|>
| Mix-in class that defines the reverse correlation related experiment methods | ExperimentRevCorr | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExperimentRevCorr:
"""Mix-in class that defines the reverse correlation related experiment methods"""
def sta(self, nids=None, trange=None, nt=10):
"""Return an STAs RevCorrs object"""
<|body_0|>
def stc(self, nids=None, trange=None, nt=10):
"""Returns an STCs Re... | stack_v2_sparse_classes_75kplus_train_067188 | 45,008 | permissive | [
{
"docstring": "Return an STAs RevCorrs object",
"name": "sta",
"signature": "def sta(self, nids=None, trange=None, nt=10)"
},
{
"docstring": "Returns an STCs RevCorrs object",
"name": "stc",
"signature": "def stc(self, nids=None, trange=None, nt=10)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007563 | Implement the Python class `ExperimentRevCorr` described below.
Class description:
Mix-in class that defines the reverse correlation related experiment methods
Method signatures and docstrings:
- def sta(self, nids=None, trange=None, nt=10): Return an STAs RevCorrs object
- def stc(self, nids=None, trange=None, nt=10... | Implement the Python class `ExperimentRevCorr` described below.
Class description:
Mix-in class that defines the reverse correlation related experiment methods
Method signatures and docstrings:
- def sta(self, nids=None, trange=None, nt=10): Return an STAs RevCorrs object
- def stc(self, nids=None, trange=None, nt=10... | ab576a41ec00e3c126bca45c2504dd61bd1cda56 | <|skeleton|>
class ExperimentRevCorr:
"""Mix-in class that defines the reverse correlation related experiment methods"""
def sta(self, nids=None, trange=None, nt=10):
"""Return an STAs RevCorrs object"""
<|body_0|>
def stc(self, nids=None, trange=None, nt=10):
"""Returns an STCs Re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExperimentRevCorr:
"""Mix-in class that defines the reverse correlation related experiment methods"""
def sta(self, nids=None, trange=None, nt=10):
"""Return an STAs RevCorrs object"""
stas = STAs(nids=nids, experiment=self, trange=trange, nt=nt)
stas.calc()
return stas
... | the_stack_v2_python_sparse | neuropy/experiment.py | node2319/neuropy-1 | train | 0 |
6d695534710d9c62902c0649bbedc02a386225d8 | [
"from __builtin__ import xrange\nresult = []\n\ndef dfs(previous_total, previous_value, pop, low_index, previous_str):\n \"\"\"\n :param int previous_total: previous total, shoud not be modified.\n :param int previous_value: previous single value.\n :param str pop: previous op.\n... | <|body_start_0|>
from __builtin__ import xrange
result = []
def dfs(previous_total, previous_value, pop, low_index, previous_str):
"""
:param int previous_total: previous total, shoud not be modified.
:param int previous_value: previous single... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addOperators(self, num, target):
""":type num: str :type target: int :rtype: List[str] 1 23 12 3 123 -- 1 23 1 2 3 1 23 -- 12 3 12 3 -- 123 123 beware of "001" convert to int is '1' '00' -> '0' '01' -> '1' moving index"""
<|body_0|>
def rewrite(self, num, targe... | stack_v2_sparse_classes_75kplus_train_067189 | 5,951 | no_license | [
{
"docstring": ":type num: str :type target: int :rtype: List[str] 1 23 12 3 123 -- 1 23 1 2 3 1 23 -- 12 3 12 3 -- 123 123 beware of \"001\" convert to int is '1' '00' -> '0' '01' -> '1' moving index",
"name": "addOperators",
"signature": "def addOperators(self, num, target)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_048258 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addOperators(self, num, target): :type num: str :type target: int :rtype: List[str] 1 23 12 3 123 -- 1 23 1 2 3 1 23 -- 12 3 12 3 -- 123 123 beware of "001" convert to int is... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addOperators(self, num, target): :type num: str :type target: int :rtype: List[str] 1 23 12 3 123 -- 1 23 1 2 3 1 23 -- 12 3 12 3 -- 123 123 beware of "001" convert to int is... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def addOperators(self, num, target):
""":type num: str :type target: int :rtype: List[str] 1 23 12 3 123 -- 1 23 1 2 3 1 23 -- 12 3 12 3 -- 123 123 beware of "001" convert to int is '1' '00' -> '0' '01' -> '1' moving index"""
<|body_0|>
def rewrite(self, num, targe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def addOperators(self, num, target):
""":type num: str :type target: int :rtype: List[str] 1 23 12 3 123 -- 1 23 1 2 3 1 23 -- 12 3 12 3 -- 123 123 beware of "001" convert to int is '1' '00' -> '0' '01' -> '1' moving index"""
from __builtin__ import xrange
result = []
... | the_stack_v2_python_sparse | depth-first-search/282_Expression_Add_Operators_hard.py | vsdrun/lc_public | train | 6 | |
d1245383e7aa7822e65793c7f0579eca24e7d9a3 | [
"files = os.path.join(os.path.expanduser(FLAGS.dataset_dir), '%s@%i')\nfilenames = {'train': generate_sharded_filenames(files % ('train', 1024))[:-40], 'val': generate_sharded_filenames(files % ('train', 1024))[-40:], 'trainval': generate_sharded_filenames(files % ('train', 1024)), 'test': generate_sharded_filename... | <|body_start_0|>
files = os.path.join(os.path.expanduser(FLAGS.dataset_dir), '%s@%i')
filenames = {'train': generate_sharded_filenames(files % ('train', 1024))[:-40], 'val': generate_sharded_filenames(files % ('train', 1024))[-40:], 'trainval': generate_sharded_filenames(files % ('train', 1024)), 'test'... | Provides train/val/trainval/test splits for Imagenet data. -> trainval split represents official Imagenet train split. -> train split is derived by taking the first 984 of 1024 shards of the offcial training data. -> val split is derived by taking the last 40 shard of the official training data. -> test split represent... | DatasetImagenet | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetImagenet:
"""Provides train/val/trainval/test splits for Imagenet data. -> trainval split represents official Imagenet train split. -> train split is derived by taking the first 984 of 1024 shards of the offcial training data. -> val split is derived by taking the last 40 shard of the offi... | stack_v2_sparse_classes_75kplus_train_067190 | 10,159 | permissive | [
{
"docstring": "Initialize the dataset object. Args: split_name: A string split name, to load from the dataset. preprocess_fn: Preprocess a single example. The example is already parsed into a dictionary. num_epochs: An int, defaults to `None`. Number of epochs to cycle through the dataset before stopping. If s... | 2 | null | Implement the Python class `DatasetImagenet` described below.
Class description:
Provides train/val/trainval/test splits for Imagenet data. -> trainval split represents official Imagenet train split. -> train split is derived by taking the first 984 of 1024 shards of the offcial training data. -> val split is derived ... | Implement the Python class `DatasetImagenet` described below.
Class description:
Provides train/val/trainval/test splits for Imagenet data. -> trainval split represents official Imagenet train split. -> train split is derived by taking the first 984 of 1024 shards of the offcial training data. -> val split is derived ... | 18b4e83ab1e3064e5528c6a8f17fd763d99224bc | <|skeleton|>
class DatasetImagenet:
"""Provides train/val/trainval/test splits for Imagenet data. -> trainval split represents official Imagenet train split. -> train split is derived by taking the first 984 of 1024 shards of the offcial training data. -> val split is derived by taking the last 40 shard of the offi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatasetImagenet:
"""Provides train/val/trainval/test splits for Imagenet data. -> trainval split represents official Imagenet train split. -> train split is derived by taking the first 984 of 1024 shards of the offcial training data. -> val split is derived by taking the last 40 shard of the official training... | the_stack_v2_python_sparse | datasets.py | hgasoft/revisiting-self-supervised | train | 0 |
650f7159c5b610bbbb2c8d9731334738c96e9088 | [
"super(SimulatedFileReader, self).__init__(queue, f, *args, **kwargs)\n'\\n Validate the inputs.\\n '\nif speed <= 0:\n raise ValueError(f'The speed must be positive; received {speed}')\nself.speed = speed",
"file = self.file\n'\\n Extract the timestamp from the first tweet, then reset the... | <|body_start_0|>
super(SimulatedFileReader, self).__init__(queue, f, *args, **kwargs)
'\n Validate the inputs.\n '
if speed <= 0:
raise ValueError(f'The speed must be positive; received {speed}')
self.speed = speed
<|end_body_0|>
<|body_start_1|>
file =... | The :class:`~twitter.file.simulated_reader.SimulatedFileReader` is based on the :class:`~twitter.file.FileReader`, so it reads tweets from a file and adds it to a queue. This works like a simulation, as if the event was happening at the same time. In addition to the parameters accepted by the :class:`~twitter.file.File... | SimulatedFileReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulatedFileReader:
"""The :class:`~twitter.file.simulated_reader.SimulatedFileReader` is based on the :class:`~twitter.file.FileReader`, so it reads tweets from a file and adds it to a queue. This works like a simulation, as if the event was happening at the same time. In addition to the parame... | stack_v2_sparse_classes_75kplus_train_067191 | 4,718 | no_license | [
{
"docstring": "Create the :class:`~twitter.file.simulated_reader.SimulatedFileReader` with the file from where to read tweets and the :class:`~queues.Queue` where to store them. The ``speed`` is an extra parameter in addition to the :class:`~twitter.file.FileReader`'s parameters. :param queue: The queue to whi... | 2 | null | Implement the Python class `SimulatedFileReader` described below.
Class description:
The :class:`~twitter.file.simulated_reader.SimulatedFileReader` is based on the :class:`~twitter.file.FileReader`, so it reads tweets from a file and adds it to a queue. This works like a simulation, as if the event was happening at t... | Implement the Python class `SimulatedFileReader` described below.
Class description:
The :class:`~twitter.file.simulated_reader.SimulatedFileReader` is based on the :class:`~twitter.file.FileReader`, so it reads tweets from a file and adds it to a queue. This works like a simulation, as if the event was happening at t... | 6320913c6adf31347d4b1f8d398bd65b61428cfb | <|skeleton|>
class SimulatedFileReader:
"""The :class:`~twitter.file.simulated_reader.SimulatedFileReader` is based on the :class:`~twitter.file.FileReader`, so it reads tweets from a file and adds it to a queue. This works like a simulation, as if the event was happening at the same time. In addition to the parame... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimulatedFileReader:
"""The :class:`~twitter.file.simulated_reader.SimulatedFileReader` is based on the :class:`~twitter.file.FileReader`, so it reads tweets from a file and adds it to a queue. This works like a simulation, as if the event was happening at the same time. In addition to the parameters accepted... | the_stack_v2_python_sparse | lib/twitter/file/simulated_reader.py | TianhaoFu/eld-data | train | 0 |
194d21990cbf7c490d4ba2d82c7ed628a05408c0 | [
"self.head = None\nself._counter = 0\nif isinstance(iterable, (str, tuple, list)):\n for item in iterable:\n self.push(item)",
"new_head = Node(val, self.head)\nself.head = new_head\nself._counter += 1",
"node = self.head\nvalue = 0\nwhile node and value >= 0:\n if node.data == '(':\n value ... | <|body_start_0|>
self.head = None
self._counter = 0
if isinstance(iterable, (str, tuple, list)):
for item in iterable:
self.push(item)
<|end_body_0|>
<|body_start_1|>
new_head = Node(val, self.head)
self.head = new_head
self._counter += 1
<|en... | Build linked list. | LinkedList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkedList:
"""Build linked list."""
def __init__(self, iterable=()):
"""Constructor for the Linked List object."""
<|body_0|>
def push(self, val):
"""Add a new value to the head of the Linked List."""
<|body_1|>
def value(self):
"""Get the v... | stack_v2_sparse_classes_75kplus_train_067192 | 1,433 | permissive | [
{
"docstring": "Constructor for the Linked List object.",
"name": "__init__",
"signature": "def __init__(self, iterable=())"
},
{
"docstring": "Add a new value to the head of the Linked List.",
"name": "push",
"signature": "def push(self, val)"
},
{
"docstring": "Get the value of... | 3 | null | Implement the Python class `LinkedList` described below.
Class description:
Build linked list.
Method signatures and docstrings:
- def __init__(self, iterable=()): Constructor for the Linked List object.
- def push(self, val): Add a new value to the head of the Linked List.
- def value(self): Get the value of the str... | Implement the Python class `LinkedList` described below.
Class description:
Build linked list.
Method signatures and docstrings:
- def __init__(self, iterable=()): Constructor for the Linked List object.
- def push(self, val): Add a new value to the head of the Linked List.
- def value(self): Get the value of the str... | c90c51780174110d6292b57248b77723db6ad6ac | <|skeleton|>
class LinkedList:
"""Build linked list."""
def __init__(self, iterable=()):
"""Constructor for the Linked List object."""
<|body_0|>
def push(self, val):
"""Add a new value to the head of the Linked List."""
<|body_1|>
def value(self):
"""Get the v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinkedList:
"""Build linked list."""
def __init__(self, iterable=()):
"""Constructor for the Linked List object."""
self.head = None
self._counter = 0
if isinstance(iterable, (str, tuple, list)):
for item in iterable:
self.push(item)
def pu... | the_stack_v2_python_sparse | proper_parenthetics.py | akarnoski/code-katas | train | 0 |
d1294c190f8e519585c7e11b0097b879b3eb4c8c | [
"res = None\nqueue = collections.deque()\nqueue.append(root)\nwhile queue:\n root = queue.popleft()\n res = root.val\n if root.right:\n queue.append(root.right)\n if root.left:\n queue.append(root.left)\nreturn res",
"res = None\nmaxDepth = -1\n\ndef dfs(root, i):\n if not root:\n ... | <|body_start_0|>
res = None
queue = collections.deque()
queue.append(root)
while queue:
root = queue.popleft()
res = root.val
if root.right:
queue.append(root.right)
if root.left:
queue.append(root.left)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findBottomLeftValue1(self, root: TreeNode) -> int:
"""思路:层次遍历 1. 求最后一层最左边的点,可以通过层次遍历 @param root: @return:"""
<|body_0|>
def findBottomLeftValue2(self, root: TreeNode) -> int:
"""思路:DFS 1. 每次进到下一层的肯定是最左边的点,如果是同一层的就不会比较,比最大层还深,就重新记录 @param root: @return:... | stack_v2_sparse_classes_75kplus_train_067193 | 1,880 | no_license | [
{
"docstring": "思路:层次遍历 1. 求最后一层最左边的点,可以通过层次遍历 @param root: @return:",
"name": "findBottomLeftValue1",
"signature": "def findBottomLeftValue1(self, root: TreeNode) -> int"
},
{
"docstring": "思路:DFS 1. 每次进到下一层的肯定是最左边的点,如果是同一层的就不会比较,比最大层还深,就重新记录 @param root: @return:",
"name": "findBottomLeftV... | 2 | stack_v2_sparse_classes_30k_train_033457 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findBottomLeftValue1(self, root: TreeNode) -> int: 思路:层次遍历 1. 求最后一层最左边的点,可以通过层次遍历 @param root: @return:
- def findBottomLeftValue2(self, root: TreeNode) -> int: 思路:DFS 1. 每次进... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findBottomLeftValue1(self, root: TreeNode) -> int: 思路:层次遍历 1. 求最后一层最左边的点,可以通过层次遍历 @param root: @return:
- def findBottomLeftValue2(self, root: TreeNode) -> int: 思路:DFS 1. 每次进... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def findBottomLeftValue1(self, root: TreeNode) -> int:
"""思路:层次遍历 1. 求最后一层最左边的点,可以通过层次遍历 @param root: @return:"""
<|body_0|>
def findBottomLeftValue2(self, root: TreeNode) -> int:
"""思路:DFS 1. 每次进到下一层的肯定是最左边的点,如果是同一层的就不会比较,比最大层还深,就重新记录 @param root: @return:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findBottomLeftValue1(self, root: TreeNode) -> int:
"""思路:层次遍历 1. 求最后一层最左边的点,可以通过层次遍历 @param root: @return:"""
res = None
queue = collections.deque()
queue.append(root)
while queue:
root = queue.popleft()
res = root.val
i... | the_stack_v2_python_sparse | LeetCode/树(Binary Tree)/513. 找树左下角的值.py | yiming1012/MyLeetCode | train | 2 | |
ada60b98e0477bc8ef082f0deec0d2d0ee02f451 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BroadcastMeetingSettings()",
"from .broadcast_meeting_audience import BroadcastMeetingAudience\nfrom .broadcast_meeting_caption_settings import BroadcastMeetingCaptionSettings\nfrom .broadcast_meeting_audience import BroadcastMeetingAu... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return BroadcastMeetingSettings()
<|end_body_0|>
<|body_start_1|>
from .broadcast_meeting_audience import BroadcastMeetingAudience
from .broadcast_meeting_caption_settings import BroadcastMeeti... | BroadcastMeetingSettings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BroadcastMeetingSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BroadcastMeetingSettings:
"""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 cre... | stack_v2_sparse_classes_75kplus_train_067194 | 4,835 | 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: BroadcastMeetingSettings",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimi... | 3 | stack_v2_sparse_classes_30k_val_002422 | Implement the Python class `BroadcastMeetingSettings` described below.
Class description:
Implement the BroadcastMeetingSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BroadcastMeetingSettings: Creates a new instance of the appropriate c... | Implement the Python class `BroadcastMeetingSettings` described below.
Class description:
Implement the BroadcastMeetingSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BroadcastMeetingSettings: Creates a new instance of the appropriate c... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BroadcastMeetingSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BroadcastMeetingSettings:
"""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 cre... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BroadcastMeetingSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BroadcastMeetingSettings:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/broadcast_meeting_settings.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
9cc842e99936e8d32ce34fd31564a42dd4dee5ec | [
"self.worktree = worktree\nself.mpml = mpml_path\nself.pml_paths = list()\nself.name = None\nself.version = None\nself.load()",
"tree = qisys.qixml.read(self.mpml)\nroot = tree.getroot()\nif root.tag != 'metapackage':\n raise Exception('\\nInvalid mpml %s\\nRoot element must be <metapackage>\\n' % self.mpml)\n... | <|body_start_0|>
self.worktree = worktree
self.mpml = mpml_path
self.pml_paths = list()
self.name = None
self.version = None
self.load()
<|end_body_0|>
<|body_start_1|>
tree = qisys.qixml.read(self.mpml)
root = tree.getroot()
if root.tag != 'metap... | Built with a mpml path. Contains a list of pml paths | MetaPackage | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetaPackage:
"""Built with a mpml path. Contains a list of pml paths"""
def __init__(self, worktree, mpml_path):
"""MetaPackage Init"""
<|body_0|>
def load(self):
"""Load"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.worktree = worktree
... | stack_v2_sparse_classes_75kplus_train_067195 | 1,560 | permissive | [
{
"docstring": "MetaPackage Init",
"name": "__init__",
"signature": "def __init__(self, worktree, mpml_path)"
},
{
"docstring": "Load",
"name": "load",
"signature": "def load(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025457 | Implement the Python class `MetaPackage` described below.
Class description:
Built with a mpml path. Contains a list of pml paths
Method signatures and docstrings:
- def __init__(self, worktree, mpml_path): MetaPackage Init
- def load(self): Load | Implement the Python class `MetaPackage` described below.
Class description:
Built with a mpml path. Contains a list of pml paths
Method signatures and docstrings:
- def __init__(self, worktree, mpml_path): MetaPackage Init
- def load(self): Load
<|skeleton|>
class MetaPackage:
"""Built with a mpml path. Contain... | efea6fa3744664348717fe5e8df708a3cf392072 | <|skeleton|>
class MetaPackage:
"""Built with a mpml path. Contains a list of pml paths"""
def __init__(self, worktree, mpml_path):
"""MetaPackage Init"""
<|body_0|>
def load(self):
"""Load"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetaPackage:
"""Built with a mpml path. Contains a list of pml paths"""
def __init__(self, worktree, mpml_path):
"""MetaPackage Init"""
self.worktree = worktree
self.mpml = mpml_path
self.pml_paths = list()
self.name = None
self.version = None
self.... | the_stack_v2_python_sparse | python/qipkg/metapackage.py | aldebaran/qibuild | train | 60 |
90eed52965b93f79e6f03ac37e49c796c666b539 | [
"self.path = path\nwith open(self.path, 'w') as file:\n file.write('Logger initiated: {} \\n \\n'.format(date.today()))",
"with open(self.path, 'a+') as file:\n file.write(text + '\\n')\nprint(text)",
"text = ''\nfor key, value in dict.items():\n text = text + '{}: {} \\n'.format(key, value)\nwith open... | <|body_start_0|>
self.path = path
with open(self.path, 'w') as file:
file.write('Logger initiated: {} \n \n'.format(date.today()))
<|end_body_0|>
<|body_start_1|>
with open(self.path, 'a+') as file:
file.write(text + '\n')
print(text)
<|end_body_1|>
<|body_start... | Logger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logger:
def __init__(self, path):
"""Instantiates the logger as a .txt file at the specified path :param path: (str) path to model outputs"""
<|body_0|>
def write(self, text):
"""Writes text to logger and prints text. :param text: (str) :return: void"""
<|bod... | stack_v2_sparse_classes_75kplus_train_067196 | 3,982 | permissive | [
{
"docstring": "Instantiates the logger as a .txt file at the specified path :param path: (str) path to model outputs",
"name": "__init__",
"signature": "def __init__(self, path)"
},
{
"docstring": "Writes text to logger and prints text. :param text: (str) :return: void",
"name": "write",
... | 3 | stack_v2_sparse_classes_30k_train_021281 | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self, path): Instantiates the logger as a .txt file at the specified path :param path: (str) path to model outputs
- def write(self, text): Writes text to logger and pri... | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self, path): Instantiates the logger as a .txt file at the specified path :param path: (str) path to model outputs
- def write(self, text): Writes text to logger and pri... | 94c0c01e01a9d221f2611b1f5c585434f3b0cb22 | <|skeleton|>
class Logger:
def __init__(self, path):
"""Instantiates the logger as a .txt file at the specified path :param path: (str) path to model outputs"""
<|body_0|>
def write(self, text):
"""Writes text to logger and prints text. :param text: (str) :return: void"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Logger:
def __init__(self, path):
"""Instantiates the logger as a .txt file at the specified path :param path: (str) path to model outputs"""
self.path = path
with open(self.path, 'w') as file:
file.write('Logger initiated: {} \n \n'.format(date.today()))
def write(sel... | the_stack_v2_python_sparse | utils.py | avaimar/urban_emissions | train | 1 | |
800a992b573e5f34cd554a5201ea2a3af15634db | [
"self.__capacity = capacity\nself.__q = []\nself.__dic = {}",
"if key not in self.__dic:\n return -1\nself.__q.remove(key)\nself.__q.insert(0, key)\nreturn self.__dic[key]",
"if key in self.__dic:\n self.__q.remove(key)\nif len(self.__q) == self.__capacity:\n k = self.__q.pop()\n del self.__dic[k]\n... | <|body_start_0|>
self.__capacity = capacity
self.__q = []
self.__dic = {}
<|end_body_0|>
<|body_start_1|>
if key not in self.__dic:
return -1
self.__q.remove(key)
self.__q.insert(0, key)
return self.__dic[key]
<|end_body_1|>
<|body_start_2|>
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_067197 | 790 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_050439 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.__capacity = capacity
self.__q = []
self.__dic = {}
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.__dic:
return -1
self.__q.remove(key)
... | the_stack_v2_python_sparse | lru-cache/solution.py | uxlsl/leetcode_practice | train | 0 | |
ba656317c2d47dbb9d57ae667e8fa60782bd8a6e | [
"super().__init__()\nself.upsample = upsample\nself.denselayers = nn.ModuleList([DenseLayer(in_channels=in_channels + i * growth_rate, out_channels=growth_rate) for i in range(n_layers)])",
"if self.upsample:\n new_feature_maps = []\n for l in self.denselayers:\n out = l(x)\n x = torch.cat(ten... | <|body_start_0|>
super().__init__()
self.upsample = upsample
self.denselayers = nn.ModuleList([DenseLayer(in_channels=in_channels + i * growth_rate, out_channels=growth_rate) for i in range(n_layers)])
<|end_body_0|>
<|body_start_1|>
if self.upsample:
new_feature_maps = []
... | Implements the DenseBlock containing several denselayers | DenseBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DenseBlock:
"""Implements the DenseBlock containing several denselayers"""
def __init__(self, in_channels, growth_rate=12, n_layers=5, upsample=False):
"""Initializes a DenseBlock. :param in_channels: Dimension of input featuremap :param growth_rate: Dimension of outout featuremap fo... | stack_v2_sparse_classes_75kplus_train_067198 | 6,099 | permissive | [
{
"docstring": "Initializes a DenseBlock. :param in_channels: Dimension of input featuremap :param growth_rate: Dimension of outout featuremap for each denselayer. Defaults to 12 :param n_layers: Number of denselayers in each denseblock. Defaults to 5 :param upsample: Boolean whether to store the results from t... | 2 | null | Implement the Python class `DenseBlock` described below.
Class description:
Implements the DenseBlock containing several denselayers
Method signatures and docstrings:
- def __init__(self, in_channels, growth_rate=12, n_layers=5, upsample=False): Initializes a DenseBlock. :param in_channels: Dimension of input feature... | Implement the Python class `DenseBlock` described below.
Class description:
Implements the DenseBlock containing several denselayers
Method signatures and docstrings:
- def __init__(self, in_channels, growth_rate=12, n_layers=5, upsample=False): Initializes a DenseBlock. :param in_channels: Dimension of input feature... | d1c14516b41da4d4128d7ae758a386a95baab72d | <|skeleton|>
class DenseBlock:
"""Implements the DenseBlock containing several denselayers"""
def __init__(self, in_channels, growth_rate=12, n_layers=5, upsample=False):
"""Initializes a DenseBlock. :param in_channels: Dimension of input featuremap :param growth_rate: Dimension of outout featuremap fo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DenseBlock:
"""Implements the DenseBlock containing several denselayers"""
def __init__(self, in_channels, growth_rate=12, n_layers=5, upsample=False):
"""Initializes a DenseBlock. :param in_channels: Dimension of input featuremap :param growth_rate: Dimension of outout featuremap for each densel... | the_stack_v2_python_sparse | tiramisu/layers.py | tuanle618/image-segmentation | train | 0 |
9c62560105cc0cce95532315a357d22d164ece7d | [
"queryset = UserCategory.objects.filter(parent=None)\nserializer = UserCategoryChildrenSerializer(queryset, many=True, context={'request': request})\nreturn Response(serializer.data)",
"queryset = UserCategory.objects.all()\ncategory = get_object_or_404(queryset, pk=pk)\nserializer = UserCategoryChildrenSerialize... | <|body_start_0|>
queryset = UserCategory.objects.filter(parent=None)
serializer = UserCategoryChildrenSerializer(queryset, many=True, context={'request': request})
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
queryset = UserCategory.objects.all()
category = g... | UserCategoryViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCategoryViewSet:
def list(self, request):
"""Returns the tree of all user categories via GET. Allows any."""
<|body_0|>
def retrieve(self, request, pk):
"""Returns a particular branch of user categories via GET. Allows any."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_75kplus_train_067199 | 9,571 | no_license | [
{
"docstring": "Returns the tree of all user categories via GET. Allows any.",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Returns a particular branch of user categories via GET. Allows any.",
"name": "retrieve",
"signature": "def retrieve(self, request, pk)... | 2 | stack_v2_sparse_classes_30k_train_005089 | Implement the Python class `UserCategoryViewSet` described below.
Class description:
Implement the UserCategoryViewSet class.
Method signatures and docstrings:
- def list(self, request): Returns the tree of all user categories via GET. Allows any.
- def retrieve(self, request, pk): Returns a particular branch of user... | Implement the Python class `UserCategoryViewSet` described below.
Class description:
Implement the UserCategoryViewSet class.
Method signatures and docstrings:
- def list(self, request): Returns the tree of all user categories via GET. Allows any.
- def retrieve(self, request, pk): Returns a particular branch of user... | 78ef668111d7552c98795c8aa07698b642cf09a5 | <|skeleton|>
class UserCategoryViewSet:
def list(self, request):
"""Returns the tree of all user categories via GET. Allows any."""
<|body_0|>
def retrieve(self, request, pk):
"""Returns a particular branch of user categories via GET. Allows any."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserCategoryViewSet:
def list(self, request):
"""Returns the tree of all user categories via GET. Allows any."""
queryset = UserCategory.objects.filter(parent=None)
serializer = UserCategoryChildrenSerializer(queryset, many=True, context={'request': request})
return Response(se... | the_stack_v2_python_sparse | backend/core/views.py | lawrencejberry/bridge | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.