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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
79fe33879daaf7191e44567c3d43c9c598e32f2b | [
"children = []\nfor path in paths:\n path = Path(path)\n if path.suffix.lower() in ('.jpg', '.jpeg'):\n upload_id, width, height = self.photo_rupload(path, to_album=True)\n children.append({'upload_id': upload_id, 'edits': dumps({'crop_original_size': [width, height], 'crop_center': [0.0, -0.0],... | <|body_start_0|>
children = []
for path in paths:
path = Path(path)
if path.suffix.lower() in ('.jpg', '.jpeg'):
upload_id, width, height = self.photo_rupload(path, to_album=True)
children.append({'upload_id': upload_id, 'edits': dumps({'crop_origi... | UploadAlbumMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadAlbumMixin:
def album_upload(self, paths: List[Path], caption: str, usertags: List[Usertag]=[], location: Location=None, configure_timeout: int=3, configure_handler=None, configure_exception=None, to_story=False) -> Media:
"""Upload album to feed Parameters ---------- paths: List[P... | stack_v2_sparse_classes_75kplus_train_004500 | 8,777 | permissive | [
{
"docstring": "Upload album to feed Parameters ---------- paths: List[Path] List of paths for media to upload caption: str Media caption usertags: List[Usertag], optional List of users to be tagged on this upload, default is empty list. location: Location, optional Location tag for this upload, default is none... | 2 | stack_v2_sparse_classes_30k_val_002688 | Implement the Python class `UploadAlbumMixin` described below.
Class description:
Implement the UploadAlbumMixin class.
Method signatures and docstrings:
- def album_upload(self, paths: List[Path], caption: str, usertags: List[Usertag]=[], location: Location=None, configure_timeout: int=3, configure_handler=None, con... | Implement the Python class `UploadAlbumMixin` described below.
Class description:
Implement the UploadAlbumMixin class.
Method signatures and docstrings:
- def album_upload(self, paths: List[Path], caption: str, usertags: List[Usertag]=[], location: Location=None, configure_timeout: int=3, configure_handler=None, con... | 14922b4038de0b693c6dd396c7ee0b57e626f32e | <|skeleton|>
class UploadAlbumMixin:
def album_upload(self, paths: List[Path], caption: str, usertags: List[Usertag]=[], location: Location=None, configure_timeout: int=3, configure_handler=None, configure_exception=None, to_story=False) -> Media:
"""Upload album to feed Parameters ---------- paths: List[P... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UploadAlbumMixin:
def album_upload(self, paths: List[Path], caption: str, usertags: List[Usertag]=[], location: Location=None, configure_timeout: int=3, configure_handler=None, configure_exception=None, to_story=False) -> Media:
"""Upload album to feed Parameters ---------- paths: List[Path] List of p... | the_stack_v2_python_sparse | instagrapi/mixins/album.py | bedefaced/instagrapi | train | 1 | |
8bb89a28ea428f14bcc43f61511bd8830b712f77 | [
"countries_filename = 'wrong_countries_file.csv'\nincome_filename = ['wrong_income_file.csv', 'Data']\nwith self.assertRaises(IOError):\n load_dataframes(countries_filename, income_filename)",
"countries_filename = 'countries.csv'\nincome_filename = ['indicator gapminder gdp_per_capita_ppp.xlsx']\nwith self.as... | <|body_start_0|>
countries_filename = 'wrong_countries_file.csv'
income_filename = ['wrong_income_file.csv', 'Data']
with self.assertRaises(IOError):
load_dataframes(countries_filename, income_filename)
<|end_body_0|>
<|body_start_1|>
countries_filename = 'countries.csv'
... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def test_open_files(self):
"""Passing wrong filenames to load_dataframes function Result: It should raise IO exception"""
<|body_0|>
def test_wrong_format_incomefile(self):
"""Passing a wrong income file format (It should include a filename and the name of the ... | stack_v2_sparse_classes_75kplus_train_004501 | 3,587 | no_license | [
{
"docstring": "Passing wrong filenames to load_dataframes function Result: It should raise IO exception",
"name": "test_open_files",
"signature": "def test_open_files(self)"
},
{
"docstring": "Passing a wrong income file format (It should include a filename and the name of the Sheet Result: It ... | 5 | null | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_open_files(self): Passing wrong filenames to load_dataframes function Result: It should raise IO exception
- def test_wrong_format_incomefile(self): Passing a wrong income file ... | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_open_files(self): Passing wrong filenames to load_dataframes function Result: It should raise IO exception
- def test_wrong_format_incomefile(self): Passing a wrong income file ... | b493aea42bf5421e1c0bbc4514e8f6b691ad2200 | <|skeleton|>
class Test:
def test_open_files(self):
"""Passing wrong filenames to load_dataframes function Result: It should raise IO exception"""
<|body_0|>
def test_wrong_format_incomefile(self):
"""Passing a wrong income file format (It should include a filename and the name of the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test:
def test_open_files(self):
"""Passing wrong filenames to load_dataframes function Result: It should raise IO exception"""
countries_filename = 'wrong_countries_file.csv'
income_filename = ['wrong_income_file.csv', 'Data']
with self.assertRaises(IOError):
load_... | the_stack_v2_python_sparse | obr214/test.py | SeanRosario/assignment9 | train | 0 | |
05ffbeee2eb933b53053c2f2a11218a3725a61d4 | [
"original_mesh_shape = (10, 11)\nif columns < 1 or columns > original_mesh_shape[0]:\n columns = original_mesh_shape[0]\nfinals = {(0, 1): 5, (1, 2): 80, (2, 3): 120, (3, 4): 140, (4, 4): 145, (5, 4): 150, (6, 7): 163, (7, 7): 166, (8, 9): 173, (9, 10): 175}\nfinals = dict(filter(lambda x: x[0][0] < columns, fin... | <|body_start_0|>
original_mesh_shape = (10, 11)
if columns < 1 or columns > original_mesh_shape[0]:
columns = original_mesh_shape[0]
finals = {(0, 1): 5, (1, 2): 80, (2, 3): 120, (3, 4): 140, (4, 4): 145, (5, 4): 150, (6, 7): 163, (7, 7): 166, (8, 9): 173, (9, 10): 175}
final... | PressurizedBountifulSeaTreasure | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PressurizedBountifulSeaTreasure:
def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=0, action_space: gym.spaces=None):
""":param initial_state: Initial state where start the agent. :param default_reward: (treasure_value, ) :param seed: S... | stack_v2_sparse_classes_75kplus_train_004502 | 4,453 | no_license | [
{
"docstring": ":param initial_state: Initial state where start the agent. :param default_reward: (treasure_value, ) :param seed: Seed used for np.random.RandomState method.",
"name": "__init__",
"signature": "def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, colum... | 3 | stack_v2_sparse_classes_30k_train_035863 | Implement the Python class `PressurizedBountifulSeaTreasure` described below.
Class description:
Implement the PressurizedBountifulSeaTreasure class.
Method signatures and docstrings:
- def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=0, action_space: gym.spaces=No... | Implement the Python class `PressurizedBountifulSeaTreasure` described below.
Class description:
Implement the PressurizedBountifulSeaTreasure class.
Method signatures and docstrings:
- def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=0, action_space: gym.spaces=No... | b51c64c867e15356c9f978839fd0040182324edd | <|skeleton|>
class PressurizedBountifulSeaTreasure:
def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=0, action_space: gym.spaces=None):
""":param initial_state: Initial state where start the agent. :param default_reward: (treasure_value, ) :param seed: S... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PressurizedBountifulSeaTreasure:
def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=0, action_space: gym.spaces=None):
""":param initial_state: Initial state where start the agent. :param default_reward: (treasure_value, ) :param seed: Seed used for n... | the_stack_v2_python_sparse | environments/pressurized_bountiful_sea_treasure.py | Pozas91/tiadas | train | 1 | |
cf95c7490d9d6a868c9c1e5340d304329e08258c | [
"request.auth = copy.deepcopy(options.identity.auth)\nrequest.cookies = copy.deepcopy(options.identity.cookies)\nrequest.headers = copy.deepcopy(options.identity.headers)\nrequest.proxies = copy.deepcopy(options.identity.proxies)\nrequest.timeout = copy.copy(options.performance.request_timeout)\nif parent_queue_ite... | <|body_start_0|>
request.auth = copy.deepcopy(options.identity.auth)
request.cookies = copy.deepcopy(options.identity.cookies)
request.headers = copy.deepcopy(options.identity.headers)
request.proxies = copy.deepcopy(options.identity.proxies)
request.timeout = copy.copy(options.p... | A helper for the src.http.Request module. | HTTPRequestHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTTPRequestHelper:
"""A helper for the src.http.Request module."""
def patch_with_options(request, options, parent_queue_item=None):
"""Patch the given request with the given options (e.g. user agent). Args: request (:class:`nyawc.http.Request`): The request to patch. options (:class... | stack_v2_sparse_classes_75kplus_train_004503 | 5,219 | permissive | [
{
"docstring": "Patch the given request with the given options (e.g. user agent). Args: request (:class:`nyawc.http.Request`): The request to patch. options (:class:`nyawc.Options`): The options to patch the request with. parent_queue_item (:class:`nyawc.QueueItem`): The parent queue item object (request/respon... | 3 | null | Implement the Python class `HTTPRequestHelper` described below.
Class description:
A helper for the src.http.Request module.
Method signatures and docstrings:
- def patch_with_options(request, options, parent_queue_item=None): Patch the given request with the given options (e.g. user agent). Args: request (:class:`ny... | Implement the Python class `HTTPRequestHelper` described below.
Class description:
A helper for the src.http.Request module.
Method signatures and docstrings:
- def patch_with_options(request, options, parent_queue_item=None): Patch the given request with the given options (e.g. user agent). Args: request (:class:`ny... | ef14f94c2d9e6c5acdc4e8f5ee7044278c4af9ef | <|skeleton|>
class HTTPRequestHelper:
"""A helper for the src.http.Request module."""
def patch_with_options(request, options, parent_queue_item=None):
"""Patch the given request with the given options (e.g. user agent). Args: request (:class:`nyawc.http.Request`): The request to patch. options (:class... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HTTPRequestHelper:
"""A helper for the src.http.Request module."""
def patch_with_options(request, options, parent_queue_item=None):
"""Patch the given request with the given options (e.g. user agent). Args: request (:class:`nyawc.http.Request`): The request to patch. options (:class:`nyawc.Optio... | the_stack_v2_python_sparse | lib/third/nyawc/helpers/HTTPRequestHelper.py | xz-zone/WSPIH | train | 3 |
83fc4dc72e565efb45938c0a2f461139a6553f99 | [
"self.current_run_setting = self.default_run_setting.update(run_setting=run_setting)\nfor step in self.module.id_to_step.values():\n step.set_run_setting(run_setting)\nself.module.current_run_setting = self.current_run_setting",
"super().reset(keep_buffer=keep_buffer)\nfor step in self.module.id_to_step.values... | <|body_start_0|>
self.current_run_setting = self.default_run_setting.update(run_setting=run_setting)
for step in self.module.id_to_step.values():
step.set_run_setting(run_setting)
self.module.current_run_setting = self.current_run_setting
<|end_body_0|>
<|body_start_1|>
supe... | This step is necessary for subpipelining. Since it contains functionality for adding a pipeline as a subpipeline to a other pipeline. :param module: The module which is wrapped by the step- :type module: Pipeline :param input_step: The input_step of the module. :type input_step: Step :param file_manager: The file_manag... | PipelineStep | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelineStep:
"""This step is necessary for subpipelining. Since it contains functionality for adding a pipeline as a subpipeline to a other pipeline. :param module: The module which is wrapped by the step- :type module: Pipeline :param input_step: The input_step of the module. :type input_step: ... | stack_v2_sparse_classes_75kplus_train_004504 | 2,480 | permissive | [
{
"docstring": "Sets the run settings of the step for the current run. Note that after reset old setting is restored. Moreover, setting the computation_mode is only possible if the computation_mode is not set explicitly while adding the corresponding module to the pipeline. Moreover, it sets also the computatio... | 2 | stack_v2_sparse_classes_30k_train_050066 | Implement the Python class `PipelineStep` described below.
Class description:
This step is necessary for subpipelining. Since it contains functionality for adding a pipeline as a subpipeline to a other pipeline. :param module: The module which is wrapped by the step- :type module: Pipeline :param input_step: The input... | Implement the Python class `PipelineStep` described below.
Class description:
This step is necessary for subpipelining. Since it contains functionality for adding a pipeline as a subpipeline to a other pipeline. :param module: The module which is wrapped by the step- :type module: Pipeline :param input_step: The input... | a71f50838ade1fc93840acc017826c5058c42717 | <|skeleton|>
class PipelineStep:
"""This step is necessary for subpipelining. Since it contains functionality for adding a pipeline as a subpipeline to a other pipeline. :param module: The module which is wrapped by the step- :type module: Pipeline :param input_step: The input_step of the module. :type input_step: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PipelineStep:
"""This step is necessary for subpipelining. Since it contains functionality for adding a pipeline as a subpipeline to a other pipeline. :param module: The module which is wrapped by the step- :type module: Pipeline :param input_step: The input_step of the module. :type input_step: Step :param f... | the_stack_v2_python_sparse | pywatts/core/pipeline_step.py | SMEISEN/pyWATTS | train | 0 |
38a04c78becd2b7623a30a4732a893fdec34cd1d | [
"super(Collector, self).__init__()\nself.store = Store()\nself.queue = Queue()",
"while True:\n data = self.queue.get()\n if data is None:\n Logger.get_logger(__name__).info('Stopping collector process ...')\n break\n self.store.update(data)\n generate(self.store, 'html', os.getcwd())"
] | <|body_start_0|>
super(Collector, self).__init__()
self.store = Store()
self.queue = Queue()
<|end_body_0|>
<|body_start_1|>
while True:
data = self.queue.get()
if data is None:
Logger.get_logger(__name__).info('Stopping collector process ...')
... | Process that does collect updates updating the report data. | Collector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collector:
"""Process that does collect updates updating the report data."""
def __init__(self):
"""Initialize collector with the store and a queue."""
<|body_0|>
def run(self):
"""Collector main loop."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_004505 | 10,388 | permissive | [
{
"docstring": "Initialize collector with the store and a queue.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Collector main loop.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `Collector` described below.
Class description:
Process that does collect updates updating the report data.
Method signatures and docstrings:
- def __init__(self): Initialize collector with the store and a queue.
- def run(self): Collector main loop. | Implement the Python class `Collector` described below.
Class description:
Process that does collect updates updating the report data.
Method signatures and docstrings:
- def __init__(self): Initialize collector with the store and a queue.
- def run(self): Collector main loop.
<|skeleton|>
class Collector:
"""Pr... | ee15d98f4d8f343d57dd5b84339ea41b4e2dc673 | <|skeleton|>
class Collector:
"""Process that does collect updates updating the report data."""
def __init__(self):
"""Initialize collector with the store and a queue."""
<|body_0|>
def run(self):
"""Collector main loop."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Collector:
"""Process that does collect updates updating the report data."""
def __init__(self):
"""Initialize collector with the store and a queue."""
super(Collector, self).__init__()
self.store = Store()
self.queue = Queue()
def run(self):
"""Collector main... | the_stack_v2_python_sparse | spline/tools/report/collector.py | Nachtfeuer/pipeline | train | 30 |
0b9cfc599125e9662e9e12ff66692e92cd9cd486 | [
"split_sentences = [sentence.split() for sentence in text]\ntokenizedText = [[word.strip().lower() for word in temp_list if len(word.strip()) > 0 and (not word in string.punctuation)] for temp_list in split_sentences]\nreturn tokenizedText",
"tokenizedText = [TreebankWordTokenizer().tokenize(sentence) for sentenc... | <|body_start_0|>
split_sentences = [sentence.split() for sentence in text]
tokenizedText = [[word.strip().lower() for word in temp_list if len(word.strip()) > 0 and (not word in string.punctuation)] for temp_list in split_sentences]
return tokenizedText
<|end_body_0|>
<|body_start_1|>
t... | Tokenization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tokenization:
def naive(self, text):
"""Tokenization using a Naive Approach Parameters ---------- arg1 : list A list of strings where each string is a single sentence Returns ------- list A list of lists where each sub-list is a sequence of tokens"""
<|body_0|>
def pennTreeB... | stack_v2_sparse_classes_75kplus_train_004506 | 1,479 | no_license | [
{
"docstring": "Tokenization using a Naive Approach Parameters ---------- arg1 : list A list of strings where each string is a single sentence Returns ------- list A list of lists where each sub-list is a sequence of tokens",
"name": "naive",
"signature": "def naive(self, text)"
},
{
"docstring"... | 2 | null | Implement the Python class `Tokenization` described below.
Class description:
Implement the Tokenization class.
Method signatures and docstrings:
- def naive(self, text): Tokenization using a Naive Approach Parameters ---------- arg1 : list A list of strings where each string is a single sentence Returns ------- list... | Implement the Python class `Tokenization` described below.
Class description:
Implement the Tokenization class.
Method signatures and docstrings:
- def naive(self, text): Tokenization using a Naive Approach Parameters ---------- arg1 : list A list of strings where each string is a single sentence Returns ------- list... | 4695cc2a1af9ac5d1a6fa12e4c81c5f4a3924f76 | <|skeleton|>
class Tokenization:
def naive(self, text):
"""Tokenization using a Naive Approach Parameters ---------- arg1 : list A list of strings where each string is a single sentence Returns ------- list A list of lists where each sub-list is a sequence of tokens"""
<|body_0|>
def pennTreeB... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tokenization:
def naive(self, text):
"""Tokenization using a Naive Approach Parameters ---------- arg1 : list A list of strings where each string is a single sentence Returns ------- list A list of lists where each sub-list is a sequence of tokens"""
split_sentences = [sentence.split() for sen... | the_stack_v2_python_sparse | Code/tokenization.py | emilbiju/CranfieldInformationRetrieval | train | 0 | |
ecfbb7619ad69652fba8c29608cadcb7db8389c8 | [
"super().__init__()\nself.resize_input = resize_input\nself.normalize_input = normalize_input\ninception = fid_inception_v3()\nself.features = nn.Sequential(inception.Conv2d_1a_3x3, inception.Conv2d_2a_3x3, inception.Conv2d_2b_3x3, nn.MaxPool2d(kernel_size=3, stride=2), inception.Conv2d_3b_1x1, inception.Conv2d_4a_... | <|body_start_0|>
super().__init__()
self.resize_input = resize_input
self.normalize_input = normalize_input
inception = fid_inception_v3()
self.features = nn.Sequential(inception.Conv2d_1a_3x3, inception.Conv2d_2a_3x3, inception.Conv2d_2b_3x3, nn.MaxPool2d(kernel_size=3, stride=2... | Pretrained InceptionV3 network returning feature maps | FIDInceptionV3 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FIDInceptionV3:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, resize_input=True, normalize_input=True, requires_grad=False):
"""Build pretrained InceptionV3 Parameters ---------- resize_input : bool If true, bilinearly resizes input to width and heigh... | stack_v2_sparse_classes_75kplus_train_004507 | 10,118 | permissive | [
{
"docstring": "Build pretrained InceptionV3 Parameters ---------- resize_input : bool If true, bilinearly resizes input to width and height 299 before feeding input to model. As the network without fully connected layers is fully convolutional, it should be able to handle inputs of arbitrary size, so resizing ... | 2 | stack_v2_sparse_classes_30k_train_011674 | Implement the Python class `FIDInceptionV3` described below.
Class description:
Pretrained InceptionV3 network returning feature maps
Method signatures and docstrings:
- def __init__(self, resize_input=True, normalize_input=True, requires_grad=False): Build pretrained InceptionV3 Parameters ---------- resize_input : ... | Implement the Python class `FIDInceptionV3` described below.
Class description:
Pretrained InceptionV3 network returning feature maps
Method signatures and docstrings:
- def __init__(self, resize_input=True, normalize_input=True, requires_grad=False): Build pretrained InceptionV3 Parameters ---------- resize_input : ... | f19abcbedd844a700b2e2596dd817ea80cbb6287 | <|skeleton|>
class FIDInceptionV3:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, resize_input=True, normalize_input=True, requires_grad=False):
"""Build pretrained InceptionV3 Parameters ---------- resize_input : bool If true, bilinearly resizes input to width and heigh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FIDInceptionV3:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, resize_input=True, normalize_input=True, requires_grad=False):
"""Build pretrained InceptionV3 Parameters ---------- resize_input : bool If true, bilinearly resizes input to width and height 299 before ... | the_stack_v2_python_sparse | horch/legacy/gan/inception.py | sbl1996/pytorch-hrvvi-ext | train | 18 |
2bbc284d144b39f340609372533f389e36457043 | [
"high = highscore.Highscore('file_test.txt')\nhigh.log_score(12, 1)\nres = high.get_scores()\nexp = ['12:1']\nself.assertEqual(res, exp)\nos.remove('file_test.txt')",
"high = highscore.Highscore('file_test.txt')\ntest_list = ['12:1', '1:2']\nres = high.sort_scores(test_list)\nexp = ['1:2', '12:1']\nself.assertEqu... | <|body_start_0|>
high = highscore.Highscore('file_test.txt')
high.log_score(12, 1)
res = high.get_scores()
exp = ['12:1']
self.assertEqual(res, exp)
os.remove('file_test.txt')
<|end_body_0|>
<|body_start_1|>
high = highscore.Highscore('file_test.txt')
tes... | Unittesting the highscore class. | TestHighScoreClass | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHighScoreClass:
"""Unittesting the highscore class."""
def test_get_scores(self):
"""Test get the highscores."""
<|body_0|>
def test_sort_scores(self):
"""Test sorting the scores."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
high = highsc... | stack_v2_sparse_classes_75kplus_train_004508 | 780 | permissive | [
{
"docstring": "Test get the highscores.",
"name": "test_get_scores",
"signature": "def test_get_scores(self)"
},
{
"docstring": "Test sorting the scores.",
"name": "test_sort_scores",
"signature": "def test_sort_scores(self)"
}
] | 2 | null | Implement the Python class `TestHighScoreClass` described below.
Class description:
Unittesting the highscore class.
Method signatures and docstrings:
- def test_get_scores(self): Test get the highscores.
- def test_sort_scores(self): Test sorting the scores. | Implement the Python class `TestHighScoreClass` described below.
Class description:
Unittesting the highscore class.
Method signatures and docstrings:
- def test_get_scores(self): Test get the highscores.
- def test_sort_scores(self): Test sorting the scores.
<|skeleton|>
class TestHighScoreClass:
"""Unittesting... | 6e4793e568c9e7e4eacfd9c0e94169cdafd07c2d | <|skeleton|>
class TestHighScoreClass:
"""Unittesting the highscore class."""
def test_get_scores(self):
"""Test get the highscores."""
<|body_0|>
def test_sort_scores(self):
"""Test sorting the scores."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestHighScoreClass:
"""Unittesting the highscore class."""
def test_get_scores(self):
"""Test get the highscores."""
high = highscore.Highscore('file_test.txt')
high.log_score(12, 1)
res = high.get_scores()
exp = ['12:1']
self.assertEqual(res, exp)
... | the_stack_v2_python_sparse | highscore_test.py | Tjejer/game | train | 0 |
af9816297dd3a3ca58c1e068123a39d3cc83fda7 | [
"self.turns = turns\nself.length = length\nself.radius = diameter / 2.0\nself.current = current\nself.use_biot_savart = use_biot_savart",
"phi = np.linspace(0, 2 * np.pi * self.turns, 10000)\nsPhi = np.sin(phi)\ncPhi = np.cos(phi)\nlx = self.radius * sPhi\nly = self.radius * cPhi\nlz = self.length / 2 * (phi / (n... | <|body_start_0|>
self.turns = turns
self.length = length
self.radius = diameter / 2.0
self.current = current
self.use_biot_savart = use_biot_savart
<|end_body_0|>
<|body_start_1|>
phi = np.linspace(0, 2 * np.pi * self.turns, 10000)
sPhi = np.sin(phi)
cPhi... | A coil parametrized by number of turns, length, diameter and current. You can calculate the magnetic field cause by the coil at any point in space. | Coil | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Coil:
"""A coil parametrized by number of turns, length, diameter and current. You can calculate the magnetic field cause by the coil at any point in space."""
def __init__(self, turns, length, diameter, current, use_biot_savart=False):
"""Generates a coil objsect. Parameters: * turn... | stack_v2_sparse_classes_75kplus_train_004509 | 2,858 | permissive | [
{
"docstring": "Generates a coil objsect. Parameters: * turns: int * length: float * diameter: float * current: float",
"name": "__init__",
"signature": "def __init__(self, turns, length, diameter, current, use_biot_savart=False)"
},
{
"docstring": "The magnetic field of the coil Assume Biot-Sav... | 3 | stack_v2_sparse_classes_30k_test_001690 | Implement the Python class `Coil` described below.
Class description:
A coil parametrized by number of turns, length, diameter and current. You can calculate the magnetic field cause by the coil at any point in space.
Method signatures and docstrings:
- def __init__(self, turns, length, diameter, current, use_biot_sa... | Implement the Python class `Coil` described below.
Class description:
A coil parametrized by number of turns, length, diameter and current. You can calculate the magnetic field cause by the coil at any point in space.
Method signatures and docstrings:
- def __init__(self, turns, length, diameter, current, use_biot_sa... | 40fe7f0892a5f4600d863658f748906bff050b67 | <|skeleton|>
class Coil:
"""A coil parametrized by number of turns, length, diameter and current. You can calculate the magnetic field cause by the coil at any point in space."""
def __init__(self, turns, length, diameter, current, use_biot_savart=False):
"""Generates a coil objsect. Parameters: * turn... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Coil:
"""A coil parametrized by number of turns, length, diameter and current. You can calculate the magnetic field cause by the coil at any point in space."""
def __init__(self, turns, length, diameter, current, use_biot_savart=False):
"""Generates a coil objsect. Parameters: * turns: int * leng... | the_stack_v2_python_sparse | FreeInductionDecay/simulation/coil.py | renereimann/FID_Simulation | train | 0 |
e7605ad4441c94d78fd87f89f21df78acc8efadc | [
"if n == 0 or n == 1:\n return n\nelif n < 0:\n raise ValueError('No sequence can be created starting from {}'.format(n))\nreturn self.recursive(n - 1) + self.recursive(n - 2)",
"cache = {}\n\ndef recurse(n):\n \"\"\"Helper function. Populate cache with fibonacci numbers\"\"\"\n if n == 0 or n == 1:\n... | <|body_start_0|>
if n == 0 or n == 1:
return n
elif n < 0:
raise ValueError('No sequence can be created starting from {}'.format(n))
return self.recursive(n - 1) + self.recursive(n - 2)
<|end_body_0|>
<|body_start_1|>
cache = {}
def recurse(n):
... | a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers | FibonacciSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FibonacciSolution:
"""a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers"""
def recursive(self, n):
"""recursively create fibonacci square. Runs in O(2^n) time where is the number of recursive calls. This is due to the naive recursio... | stack_v2_sparse_classes_75kplus_train_004510 | 2,021 | no_license | [
{
"docstring": "recursively create fibonacci square. Runs in O(2^n) time where is the number of recursive calls. This is due to the naive recursion process having to re-calculate each fibonacci seqeuences for each number",
"name": "recursive",
"signature": "def recursive(self, n)"
},
{
"docstrin... | 3 | null | Implement the Python class `FibonacciSolution` described below.
Class description:
a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers
Method signatures and docstrings:
- def recursive(self, n): recursively create fibonacci square. Runs in O(2^n) time where is the num... | Implement the Python class `FibonacciSolution` described below.
Class description:
a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers
Method signatures and docstrings:
- def recursive(self, n): recursively create fibonacci square. Runs in O(2^n) time where is the num... | 5347a98a61efbfef75e3e27ac564c423c4ec25bb | <|skeleton|>
class FibonacciSolution:
"""a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers"""
def recursive(self, n):
"""recursively create fibonacci square. Runs in O(2^n) time where is the number of recursive calls. This is due to the naive recursio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FibonacciSolution:
"""a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers"""
def recursive(self, n):
"""recursively create fibonacci square. Runs in O(2^n) time where is the number of recursive calls. This is due to the naive recursion process hav... | the_stack_v2_python_sparse | dynamic_programming/fibonacci.py | gtang31/algorithms | train | 0 |
095be8e95ef0c7d2a6a00e792fceb8794da8b0f0 | [
"k %= len(nums)\nself.reverse(nums, 0, len(nums) - 1)\nself.reverse(nums, 0, k - 1)\nself.reverse(nums, k, len(nums) - 1)",
"while start < end:\n temp = nums[start]\n nums[start] = nums[end]\n nums[end] = temp\n start += 1\n end -= 1"
] | <|body_start_0|>
k %= len(nums)
self.reverse(nums, 0, len(nums) - 1)
self.reverse(nums, 0, k - 1)
self.reverse(nums, k, len(nums) - 1)
<|end_body_0|>
<|body_start_1|>
while start < end:
temp = nums[start]
nums[start] = nums[end]
nums[end] = te... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k) -> None:
""":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. First reverse all, then reverse first k, then reverse others O(n) time O(1) space"""
<|body_0|>
def reverse(self, nums, start... | stack_v2_sparse_classes_75kplus_train_004511 | 2,000 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. First reverse all, then reverse first k, then reverse others O(n) time O(1) space",
"name": "rotate",
"signature": "def rotate(self, nums, k) -> None"
},
{
"docstring": ":type nu... | 2 | stack_v2_sparse_classes_30k_train_014685 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k) -> None: :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. First reverse all, then reverse first k, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k) -> None: :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. First reverse all, then reverse first k, ... | 237985eea9853a658f811355e8c75d6b141e40b2 | <|skeleton|>
class Solution:
def rotate(self, nums, k) -> None:
""":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. First reverse all, then reverse first k, then reverse others O(n) time O(1) space"""
<|body_0|>
def reverse(self, nums, start... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotate(self, nums, k) -> None:
""":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. First reverse all, then reverse first k, then reverse others O(n) time O(1) space"""
k %= len(nums)
self.reverse(nums, 0, len(nums) - 1)... | the_stack_v2_python_sparse | 189. Rotate Array.py | Eustaceyi/Leetcode | train | 0 | |
5234a2e733c2b76f6f965f4182d2c06044eb665e | [
"super(InvertedResidualSE, self).__init__()\nself.identity = stride == 1 and inp == oup\nself.ir_block = Sequential(ops.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False), ops.BatchNorm2d(hidden_dim, momentum=momentum), ops.Hswish() if use_hs else ops.Relu(inplace=True), ops.Conv2d(hidden_dim, hidden_dim, kernel_size, st... | <|body_start_0|>
super(InvertedResidualSE, self).__init__()
self.identity = stride == 1 and inp == oup
self.ir_block = Sequential(ops.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False), ops.BatchNorm2d(hidden_dim, momentum=momentum), ops.Hswish() if use_hs else ops.Relu(inplace=True), ops.Conv2d(hidde... | This is the class of InvertedResidual with SELayer for MobileNetV3. | InvertedResidualSE | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvertedResidualSE:
"""This is the class of InvertedResidual with SELayer for MobileNetV3."""
def __init__(self, inp, hidden_dim, oup, kernel_size, stride, use_se=False, use_hs=False, momentum=0.1):
"""Init InvertedResidualSE."""
<|body_0|>
def __call__(self, x):
... | stack_v2_sparse_classes_75kplus_train_004512 | 9,288 | permissive | [
{
"docstring": "Init InvertedResidualSE.",
"name": "__init__",
"signature": "def __init__(self, inp, hidden_dim, oup, kernel_size, stride, use_se=False, use_hs=False, momentum=0.1)"
},
{
"docstring": "Forward compute of InvertedResidualSE.",
"name": "__call__",
"signature": "def __call__... | 2 | stack_v2_sparse_classes_30k_train_021376 | Implement the Python class `InvertedResidualSE` described below.
Class description:
This is the class of InvertedResidual with SELayer for MobileNetV3.
Method signatures and docstrings:
- def __init__(self, inp, hidden_dim, oup, kernel_size, stride, use_se=False, use_hs=False, momentum=0.1): Init InvertedResidualSE.
... | Implement the Python class `InvertedResidualSE` described below.
Class description:
This is the class of InvertedResidual with SELayer for MobileNetV3.
Method signatures and docstrings:
- def __init__(self, inp, hidden_dim, oup, kernel_size, stride, use_se=False, use_hs=False, momentum=0.1): Init InvertedResidualSE.
... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class InvertedResidualSE:
"""This is the class of InvertedResidual with SELayer for MobileNetV3."""
def __init__(self, inp, hidden_dim, oup, kernel_size, stride, use_se=False, use_hs=False, momentum=0.1):
"""Init InvertedResidualSE."""
<|body_0|>
def __call__(self, x):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InvertedResidualSE:
"""This is the class of InvertedResidual with SELayer for MobileNetV3."""
def __init__(self, inp, hidden_dim, oup, kernel_size, stride, use_se=False, use_hs=False, momentum=0.1):
"""Init InvertedResidualSE."""
super(InvertedResidualSE, self).__init__()
self.ide... | the_stack_v2_python_sparse | zeus/networks/mobilenetv3.py | huawei-noah/xingtian | train | 308 |
d4017458ff2330ae832679fd0779d14daecf3bb1 | [
"if data is not None:\n if type(data) != list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple values')\n mean = 0.0\n count = 0\n for element in data:\n if type(element) not in {int, float}:\n raise TypeError... | <|body_start_0|>
if data is not None:
if type(data) != list:
raise TypeError('data must be a list')
if len(data) < 2:
raise ValueError('data must contain multiple values')
mean = 0.0
count = 0
for element in data:
... | Class that represents a poisson distribution. | Poisson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poisson:
"""Class that represents a poisson distribution."""
def __init__(self, data=None, lambtha=1.0):
"""Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used to estimate the distribution. lambtha is the expected number of oc... | stack_v2_sparse_classes_75kplus_train_004513 | 2,052 | no_license | [
{
"docstring": "Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used to estimate the distribution. lambtha is the expected number of occurences in a given time frame.",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
... | 4 | stack_v2_sparse_classes_30k_train_046869 | Implement the Python class `Poisson` described below.
Class description:
Class that represents a poisson distribution.
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used to estima... | Implement the Python class `Poisson` described below.
Class description:
Class that represents a poisson distribution.
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used to estima... | 1e7cd1589e6e4896ee48a24b9ca85595e16e929d | <|skeleton|>
class Poisson:
"""Class that represents a poisson distribution."""
def __init__(self, data=None, lambtha=1.0):
"""Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used to estimate the distribution. lambtha is the expected number of oc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Poisson:
"""Class that represents a poisson distribution."""
def __init__(self, data=None, lambtha=1.0):
"""Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used to estimate the distribution. lambtha is the expected number of occurences in a... | the_stack_v2_python_sparse | math/0x03-probability/poisson.py | Daransoto/holbertonschool-machine_learning | train | 0 |
f165afefdae14002164488adf9913d0e0f2d9a27 | [
"def pre_order_serialize(node):\n if node is None:\n return '#!'\n string = str(node.val) + '!'\n string += pre_order_serialize(node.left)\n string += pre_order_serialize(node.right)\n return string\nreturn pre_order_serialize(root)",
"def pre_order_deserialize(que):\n if que:\n va... | <|body_start_0|>
def pre_order_serialize(node):
if node is None:
return '#!'
string = str(node.val) + '!'
string += pre_order_serialize(node.left)
string += pre_order_serialize(node.right)
return string
return pre_order_serializ... | 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_004514 | 1,518 | 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_005877 | 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:... | 2828811ae2f905865b4f391672693375c124c185 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def pre_order_serialize(node):
if node is None:
return '#!'
string = str(node.val) + '!'
string += pre_order_serialize(node.left)
... | the_stack_v2_python_sparse | LeetCode/剑指 Offer/37. 序列化二叉树/solve.py | koking0/Algorithm | train | 35 | |
7ea8e7aca8d438a9e4fce24dece2d81e64fd27ba | [
"self.tr_losses = []\nself.val_losses = []\nself.tr_accs = []\nself.val_accs = []",
"logs = logs or {}\nself.tr_losses.append(logs.get('loss'))\nself.val_losses.append(logs.get('val_loss'))\nself.tr_accs.append(logs.get('acc'))\nself.val_accs.append(logs.get('val_acc'))"
] | <|body_start_0|>
self.tr_losses = []
self.val_losses = []
self.tr_accs = []
self.val_accs = []
<|end_body_0|>
<|body_start_1|>
logs = logs or {}
self.tr_losses.append(logs.get('loss'))
self.val_losses.append(logs.get('val_loss'))
self.tr_accs.append(logs.... | Class for training history | History | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class History:
"""Class for training history"""
def on_train_begin(self, logs=None):
"""Initialization"""
<|body_0|>
def on_epoch_end(self, epoch, logs=None):
"""Log training information"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.tr_losses =... | stack_v2_sparse_classes_75kplus_train_004515 | 5,899 | no_license | [
{
"docstring": "Initialization",
"name": "on_train_begin",
"signature": "def on_train_begin(self, logs=None)"
},
{
"docstring": "Log training information",
"name": "on_epoch_end",
"signature": "def on_epoch_end(self, epoch, logs=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051077 | Implement the Python class `History` described below.
Class description:
Class for training history
Method signatures and docstrings:
- def on_train_begin(self, logs=None): Initialization
- def on_epoch_end(self, epoch, logs=None): Log training information | Implement the Python class `History` described below.
Class description:
Class for training history
Method signatures and docstrings:
- def on_train_begin(self, logs=None): Initialization
- def on_epoch_end(self, epoch, logs=None): Log training information
<|skeleton|>
class History:
"""Class for training histor... | 234c2972f57a73ec81382f449dfa9df9f75c3c5e | <|skeleton|>
class History:
"""Class for training history"""
def on_train_begin(self, logs=None):
"""Initialization"""
<|body_0|>
def on_epoch_end(self, epoch, logs=None):
"""Log training information"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class History:
"""Class for training history"""
def on_train_begin(self, logs=None):
"""Initialization"""
self.tr_losses = []
self.val_losses = []
self.tr_accs = []
self.val_accs = []
def on_epoch_end(self, epoch, logs=None):
"""Log training information"""
... | the_stack_v2_python_sparse | hw3/model.py | dinotuku/ML2017 | train | 1 |
0327d3ea29a6a44d1e3872f78d14ddacff4db860 | [
"try:\n serializer = ReportFilesSerializers(ReportFiles.objects.all(), many=True)\n return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)\nexcept Exception as e:\n info_message = 'Internal Server Error'\n logger.error(info_message, e)\n return JsonResponse({'error': str(... | <|body_start_0|>
try:
serializer = ReportFilesSerializers(ReportFiles.objects.all(), many=True)
return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)
except Exception as e:
info_message = 'Internal Server Error'
logger.error(i... | ReportFilesView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportFilesView:
def get(self, request):
"""Get all reports_file"""
<|body_0|>
def post(self, request):
"""Save reports_file data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
serializer = ReportFilesSerializers(ReportFiles.object... | stack_v2_sparse_classes_75kplus_train_004516 | 30,353 | no_license | [
{
"docstring": "Get all reports_file",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Save reports_file data",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013478 | Implement the Python class `ReportFilesView` described below.
Class description:
Implement the ReportFilesView class.
Method signatures and docstrings:
- def get(self, request): Get all reports_file
- def post(self, request): Save reports_file data | Implement the Python class `ReportFilesView` described below.
Class description:
Implement the ReportFilesView class.
Method signatures and docstrings:
- def get(self, request): Get all reports_file
- def post(self, request): Save reports_file data
<|skeleton|>
class ReportFilesView:
def get(self, request):
... | b63849983a592fd6a1f654191020fd86aa0787ae | <|skeleton|>
class ReportFilesView:
def get(self, request):
"""Get all reports_file"""
<|body_0|>
def post(self, request):
"""Save reports_file data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReportFilesView:
def get(self, request):
"""Get all reports_file"""
try:
serializer = ReportFilesSerializers(ReportFiles.objects.all(), many=True)
return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)
except Exception as e:
... | the_stack_v2_python_sparse | reports/views.py | RupeshKurlekar/biocare | train | 1 | |
890759477b96b9012964e6246ae10b4a65957586 | [
"super(LabelSmoothingLoss, self).__init__()\nself.criterion = criterion\nself.padding_idx = padding_idx\nself.confidence = 1.0 - smoothing\nself.smoothing = smoothing\nself.size = size\nself.true_dist = None\nself.normalize_length = normalize_length",
"assert x.size(2) == self.size\nbatch_size = x.size(0)\nx = x.... | <|body_start_0|>
super(LabelSmoothingLoss, self).__init__()
self.criterion = criterion
self.padding_idx = padding_idx
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
self.size = size
self.true_dist = None
self.normalize_length = normalize_leng... | Label-smoothing loss. :param int size: the number of class :param int padding_idx: ignored class id :param float smoothing: smoothing rate (0.0 means the conventional CE) :param bool normalize_length: normalize loss by sequence length if True :param torch.nn.Module criterion: loss function to be smoothed | LabelSmoothingLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelSmoothingLoss:
"""Label-smoothing loss. :param int size: the number of class :param int padding_idx: ignored class id :param float smoothing: smoothing rate (0.0 means the conventional CE) :param bool normalize_length: normalize loss by sequence length if True :param torch.nn.Module criterio... | stack_v2_sparse_classes_75kplus_train_004517 | 2,164 | permissive | [
{
"docstring": "Construct an LabelSmoothingLoss object.",
"name": "__init__",
"signature": "def __init__(self, size, padding_idx, smoothing, normalize_length=False, criterion=nn.KLDivLoss(reduction='none'))"
},
{
"docstring": "Compute loss between x and target. :param torch.Tensor x: prediction ... | 2 | stack_v2_sparse_classes_30k_train_052713 | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Label-smoothing loss. :param int size: the number of class :param int padding_idx: ignored class id :param float smoothing: smoothing rate (0.0 means the conventional CE) :param bool normalize_length: normalize loss by sequence length ... | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Label-smoothing loss. :param int size: the number of class :param int padding_idx: ignored class id :param float smoothing: smoothing rate (0.0 means the conventional CE) :param bool normalize_length: normalize loss by sequence length ... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class LabelSmoothingLoss:
"""Label-smoothing loss. :param int size: the number of class :param int padding_idx: ignored class id :param float smoothing: smoothing rate (0.0 means the conventional CE) :param bool normalize_length: normalize loss by sequence length if True :param torch.nn.Module criterio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LabelSmoothingLoss:
"""Label-smoothing loss. :param int size: the number of class :param int padding_idx: ignored class id :param float smoothing: smoothing rate (0.0 means the conventional CE) :param bool normalize_length: normalize loss by sequence length if True :param torch.nn.Module criterion: loss funct... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transformer/label_smoothing_loss.py | espnet/espnet | train | 7,242 |
6388bb454685d44a9614dbe4e441fbc8a99b0d62 | [
"if num_rows == 1:\n return s\nres = []\ncycle = 2 * num_rows - 2\nfor row in range(num_rows):\n for idx in range(row, len(s), cycle):\n res.append(s[idx])\n in_row_idx = idx + cycle - 2 * row\n if row != 0 and row != num_rows - 1 and (in_row_idx < len(s)):\n res.append(s[in_ro... | <|body_start_0|>
if num_rows == 1:
return s
res = []
cycle = 2 * num_rows - 2
for row in range(num_rows):
for idx in range(row, len(s), cycle):
res.append(s[idx])
in_row_idx = idx + cycle - 2 * row
if row != 0 and ro... | ZigZag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigZag:
def convert(self, s: str, num_rows: int) -> str:
"""Approach: Visit By Row Time Complexity: O(N) Space Complexity: O(N) :param s: :param num_rows: :return:"""
<|body_0|>
def convert_(self, s: str, num_rows: int) -> str:
"""Approach: Sort By Row Time Complexit... | stack_v2_sparse_classes_75kplus_train_004518 | 1,792 | no_license | [
{
"docstring": "Approach: Visit By Row Time Complexity: O(N) Space Complexity: O(N) :param s: :param num_rows: :return:",
"name": "convert",
"signature": "def convert(self, s: str, num_rows: int) -> str"
},
{
"docstring": "Approach: Sort By Row Time Complexity: O(N) Space Complexity: O(N) :param... | 2 | null | Implement the Python class `ZigZag` described below.
Class description:
Implement the ZigZag class.
Method signatures and docstrings:
- def convert(self, s: str, num_rows: int) -> str: Approach: Visit By Row Time Complexity: O(N) Space Complexity: O(N) :param s: :param num_rows: :return:
- def convert_(self, s: str, ... | Implement the Python class `ZigZag` described below.
Class description:
Implement the ZigZag class.
Method signatures and docstrings:
- def convert(self, s: str, num_rows: int) -> str: Approach: Visit By Row Time Complexity: O(N) Space Complexity: O(N) :param s: :param num_rows: :return:
- def convert_(self, s: str, ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class ZigZag:
def convert(self, s: str, num_rows: int) -> str:
"""Approach: Visit By Row Time Complexity: O(N) Space Complexity: O(N) :param s: :param num_rows: :return:"""
<|body_0|>
def convert_(self, s: str, num_rows: int) -> str:
"""Approach: Sort By Row Time Complexit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZigZag:
def convert(self, s: str, num_rows: int) -> str:
"""Approach: Visit By Row Time Complexity: O(N) Space Complexity: O(N) :param s: :param num_rows: :return:"""
if num_rows == 1:
return s
res = []
cycle = 2 * num_rows - 2
for row in range(num_rows):
... | the_stack_v2_python_sparse | revisited/math_and_strings/strings/zig_zag_conversion.py | Shiv2157k/leet_code | train | 1 | |
1331d7cf6343ec52e245f29563001289094723b2 | [
"self.qvalues = qvalues\nself.states = list(self.qvalues.keys())\nself.actions = list(map(lambda a: a[0], self.qvalues[self.states[0]]))\nself.totPlays = dict(map(lambda s: (s, 0), self.states))\nself.actPlays = dict()\nfor s in self.states:\n self.actPlays[s] = dict(map(lambda a: (a, 0), self.actions))",
"sac... | <|body_start_0|>
self.qvalues = qvalues
self.states = list(self.qvalues.keys())
self.actions = list(map(lambda a: a[0], self.qvalues[self.states[0]]))
self.totPlays = dict(map(lambda s: (s, 0), self.states))
self.actPlays = dict()
for s in self.states:
self.ac... | upper confidence bound multi arm bandit policy (ucb) | UpperConfBoundPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpperConfBoundPolicy:
"""upper confidence bound multi arm bandit policy (ucb)"""
def __init__(self, qvalues):
"""initializer Parameters qvalues : q values"""
<|body_0|>
def getAction(self, state):
"""next play return selected action Parameters state : state"""
... | stack_v2_sparse_classes_75kplus_train_004519 | 11,723 | permissive | [
{
"docstring": "initializer Parameters qvalues : q values",
"name": "__init__",
"signature": "def __init__(self, qvalues)"
},
{
"docstring": "next play return selected action Parameters state : state",
"name": "getAction",
"signature": "def getAction(self, state)"
}
] | 2 | null | Implement the Python class `UpperConfBoundPolicy` described below.
Class description:
upper confidence bound multi arm bandit policy (ucb)
Method signatures and docstrings:
- def __init__(self, qvalues): initializer Parameters qvalues : q values
- def getAction(self, state): next play return selected action Parameter... | Implement the Python class `UpperConfBoundPolicy` described below.
Class description:
upper confidence bound multi arm bandit policy (ucb)
Method signatures and docstrings:
- def __init__(self, qvalues): initializer Parameters qvalues : q values
- def getAction(self, state): next play return selected action Parameter... | 861fd06b6b7abaffe5e8ca795136ab0fbb2234b5 | <|skeleton|>
class UpperConfBoundPolicy:
"""upper confidence bound multi arm bandit policy (ucb)"""
def __init__(self, qvalues):
"""initializer Parameters qvalues : q values"""
<|body_0|>
def getAction(self, state):
"""next play return selected action Parameters state : state"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpperConfBoundPolicy:
"""upper confidence bound multi arm bandit policy (ucb)"""
def __init__(self, qvalues):
"""initializer Parameters qvalues : q values"""
self.qvalues = qvalues
self.states = list(self.qvalues.keys())
self.actions = list(map(lambda a: a[0], self.qvalues... | the_stack_v2_python_sparse | qinisa/qinisa/mab.py | pranab/whakapai | train | 18 |
c07c23407693db449e7186799dac2856b8274cae | [
"backend = self.create_backend()\ncontact = self.create_contact({'primary_backend': backend})\nconnection = contact.get_primary_connection()\nself.assertEqual(connection.backend_id, backend.pk)\nself.assertEqual(connection.contact_id, contact.pk)",
"backend = self.create_backend()\ncontact = self.create_contact()... | <|body_start_0|>
backend = self.create_backend()
contact = self.create_contact({'primary_backend': backend})
connection = contact.get_primary_connection()
self.assertEqual(connection.backend_id, backend.pk)
self.assertEqual(connection.contact_id, contact.pk)
<|end_body_0|>
<|bod... | DefaultConnectionTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultConnectionTest:
def test_defined_primary_backend(self):
"""Random backend is chosen if contact's default is not set"""
<|body_0|>
def test_random_primary_backend(self):
"""Random backend is fallback"""
<|body_1|>
def test_backend_setting(self):
... | stack_v2_sparse_classes_75kplus_train_004520 | 1,385 | no_license | [
{
"docstring": "Random backend is chosen if contact's default is not set",
"name": "test_defined_primary_backend",
"signature": "def test_defined_primary_backend(self)"
},
{
"docstring": "Random backend is fallback",
"name": "test_random_primary_backend",
"signature": "def test_random_pr... | 3 | null | Implement the Python class `DefaultConnectionTest` described below.
Class description:
Implement the DefaultConnectionTest class.
Method signatures and docstrings:
- def test_defined_primary_backend(self): Random backend is chosen if contact's default is not set
- def test_random_primary_backend(self): Random backend... | Implement the Python class `DefaultConnectionTest` described below.
Class description:
Implement the DefaultConnectionTest class.
Method signatures and docstrings:
- def test_defined_primary_backend(self): Random backend is chosen if contact's default is not set
- def test_random_primary_backend(self): Random backend... | c0a8de3c3cc17880f62b1d3b4c3eaa43c986e8b0 | <|skeleton|>
class DefaultConnectionTest:
def test_defined_primary_backend(self):
"""Random backend is chosen if contact's default is not set"""
<|body_0|>
def test_random_primary_backend(self):
"""Random backend is fallback"""
<|body_1|>
def test_backend_setting(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DefaultConnectionTest:
def test_defined_primary_backend(self):
"""Random backend is chosen if contact's default is not set"""
backend = self.create_backend()
contact = self.create_contact({'primary_backend': backend})
connection = contact.get_primary_connection()
self.a... | the_stack_v2_python_sparse | afrims/apps/default_connection/tests.py | afrims/afrims | train | 5 | |
f6c61c25f3ec4f454aca2419073cca7b423cc080 | [
"super(Decoder2, self).__init__()\nself.embedding1 = tf.keras.layers.Embedding(vocab_size, embedding_dim)\nself.gru1 = tf.keras.layers.GRU(units, return_sequences=True, return_state=True, recurrent_initializer=tf.keras.initializers.GlorotUniform(), name='feature_gru1')\nself.dense1 = tf.keras.layers.Dense(vocab_siz... | <|body_start_0|>
super(Decoder2, self).__init__()
self.embedding1 = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.gru1 = tf.keras.layers.GRU(units, return_sequences=True, return_state=True, recurrent_initializer=tf.keras.initializers.GlorotUniform(), name='feature_gru1')
self... | 解码器 | Decoder2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder2:
"""解码器"""
def __init__(self, vocab_size, embedding_dim, units):
"""vocab_size:字符数 embedding_dim:字符编码特征数 units:隐藏层神经元数量"""
<|body_0|>
def call(self, input_data, gru_state1=None, gru_state2=None):
"""input_data:单步预测数据(None,1) gru_state1:上一步的状态(None,units)... | stack_v2_sparse_classes_75kplus_train_004521 | 26,365 | no_license | [
{
"docstring": "vocab_size:字符数 embedding_dim:字符编码特征数 units:隐藏层神经元数量",
"name": "__init__",
"signature": "def __init__(self, vocab_size, embedding_dim, units)"
},
{
"docstring": "input_data:单步预测数据(None,1) gru_state1:上一步的状态(None,units) gru_state2:上一步的状态(None,units)",
"name": "call",
"signat... | 2 | stack_v2_sparse_classes_30k_train_008692 | Implement the Python class `Decoder2` described below.
Class description:
解码器
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, units): vocab_size:字符数 embedding_dim:字符编码特征数 units:隐藏层神经元数量
- def call(self, input_data, gru_state1=None, gru_state2=None): input_data:单步预测数据(None,1) gru_stat... | Implement the Python class `Decoder2` described below.
Class description:
解码器
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, units): vocab_size:字符数 embedding_dim:字符编码特征数 units:隐藏层神经元数量
- def call(self, input_data, gru_state1=None, gru_state2=None): input_data:单步预测数据(None,1) gru_stat... | c74c69556c1898d711f86422d469afe38829ebba | <|skeleton|>
class Decoder2:
"""解码器"""
def __init__(self, vocab_size, embedding_dim, units):
"""vocab_size:字符数 embedding_dim:字符编码特征数 units:隐藏层神经元数量"""
<|body_0|>
def call(self, input_data, gru_state1=None, gru_state2=None):
"""input_data:单步预测数据(None,1) gru_state1:上一步的状态(None,units)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decoder2:
"""解码器"""
def __init__(self, vocab_size, embedding_dim, units):
"""vocab_size:字符数 embedding_dim:字符编码特征数 units:隐藏层神经元数量"""
super(Decoder2, self).__init__()
self.embedding1 = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.gru1 = tf.keras.layers.GRU(units... | the_stack_v2_python_sparse | RNN/robot.py | zhangliangjing/AI | train | 0 |
ee7ee13f61bd7165a3a505c7cb1e908af70fa190 | [
"self.degree = degree\nself.cross = cross\nself.previous_statistics = previous_statistics\nself.InformativeIndices = InformativeIndices",
"if self.previous_statistics is not None:\n data = self.previous_statistics.statistics(data)\nelse:\n data = self._check_and_transform_input(data)\ndata = data[:, self.In... | <|body_start_0|>
self.degree = degree
self.cross = cross
self.previous_statistics = previous_statistics
self.InformativeIndices = InformativeIndices
<|end_body_0|>
<|body_start_1|>
if self.previous_statistics is not None:
data = self.previous_statistics.statistics(da... | This class implements identity statistics not applying any transformation to the data, before the optional polynomial expansion step. If the data set contains n numpy.ndarray of length p, it returns therefore an nx(p+degree*p+cross*nchoosek(p,2)) matrix, where for each of the n points with p statistics, degree*p polyno... | IdentityChosen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityChosen:
"""This class implements identity statistics not applying any transformation to the data, before the optional polynomial expansion step. If the data set contains n numpy.ndarray of length p, it returns therefore an nx(p+degree*p+cross*nchoosek(p,2)) matrix, where for each of the n... | stack_v2_sparse_classes_75kplus_train_004522 | 5,600 | no_license | [
{
"docstring": "Parameters ---------- degree : integer, optional Of polynomial expansion. The default value is 2 meaning second order polynomial expansion. cross : boolean, optional Defines whether to include the cross-product terms. The default value is True, meaning the cross product term is included. previou... | 2 | stack_v2_sparse_classes_30k_train_019102 | Implement the Python class `IdentityChosen` described below.
Class description:
This class implements identity statistics not applying any transformation to the data, before the optional polynomial expansion step. If the data set contains n numpy.ndarray of length p, it returns therefore an nx(p+degree*p+cross*nchoose... | Implement the Python class `IdentityChosen` described below.
Class description:
This class implements identity statistics not applying any transformation to the data, before the optional polynomial expansion step. If the data set contains n numpy.ndarray of length p, it returns therefore an nx(p+degree*p+cross*nchoose... | be3c648b19ddf5770482216a9381db5bbcdb3d24 | <|skeleton|>
class IdentityChosen:
"""This class implements identity statistics not applying any transformation to the data, before the optional polynomial expansion step. If the data set contains n numpy.ndarray of length p, it returns therefore an nx(p+degree*p+cross*nchoosek(p,2)) matrix, where for each of the n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IdentityChosen:
"""This class implements identity statistics not applying any transformation to the data, before the optional polynomial expansion step. If the data set contains n numpy.ndarray of length p, it returns therefore an nx(p+degree*p+cross*nchoosek(p,2)) matrix, where for each of the n points with ... | the_stack_v2_python_sparse | BiologicalScience/StochasticPlateletsDeposition/statistic.py | eth-cscs/abcpy-models | train | 11 |
fd67f2f14325c6d373d841f3e9913ff8b166a5d1 | [
"FeaturewiseDatasetMeasure.__init__(self, **kwargs)\nself.__pvalue = int(pvalue)\nself.__attr = attr",
"attrdata = eval('dataset.' + self.__attr)\nsamples = dataset.samples\npvalue_index = self.__pvalue\nresult = N.empty((dataset.nfeatures,), dtype=float)\nfor ifeature in xrange(dataset.nfeatures):\n samples_ ... | <|body_start_0|>
FeaturewiseDatasetMeasure.__init__(self, **kwargs)
self.__pvalue = int(pvalue)
self.__attr = attr
<|end_body_0|>
<|body_start_1|>
attrdata = eval('dataset.' + self.__attr)
samples = dataset.samples
pvalue_index = self.__pvalue
result = N.empty((d... | `FeaturewiseDatasetMeasure` that performs correlation with labels XXX: Explain me! | CorrCoef | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CorrCoef:
"""`FeaturewiseDatasetMeasure` that performs correlation with labels XXX: Explain me!"""
def __init__(self, pvalue=False, attr='labels', **kwargs):
"""Initialize :Parameters: pvalue : bool Either to report p-value of pearsons correlation coefficient instead of pure correlat... | stack_v2_sparse_classes_75kplus_train_004523 | 2,394 | permissive | [
{
"docstring": "Initialize :Parameters: pvalue : bool Either to report p-value of pearsons correlation coefficient instead of pure correlation coefficient attr : basestring What attribut to correlate with",
"name": "__init__",
"signature": "def __init__(self, pvalue=False, attr='labels', **kwargs)"
},... | 2 | stack_v2_sparse_classes_30k_train_036786 | Implement the Python class `CorrCoef` described below.
Class description:
`FeaturewiseDatasetMeasure` that performs correlation with labels XXX: Explain me!
Method signatures and docstrings:
- def __init__(self, pvalue=False, attr='labels', **kwargs): Initialize :Parameters: pvalue : bool Either to report p-value of ... | Implement the Python class `CorrCoef` described below.
Class description:
`FeaturewiseDatasetMeasure` that performs correlation with labels XXX: Explain me!
Method signatures and docstrings:
- def __init__(self, pvalue=False, attr='labels', **kwargs): Initialize :Parameters: pvalue : bool Either to report p-value of ... | 2a8fcaa57457c8994455144e9e69494d167204c4 | <|skeleton|>
class CorrCoef:
"""`FeaturewiseDatasetMeasure` that performs correlation with labels XXX: Explain me!"""
def __init__(self, pvalue=False, attr='labels', **kwargs):
"""Initialize :Parameters: pvalue : bool Either to report p-value of pearsons correlation coefficient instead of pure correlat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CorrCoef:
"""`FeaturewiseDatasetMeasure` that performs correlation with labels XXX: Explain me!"""
def __init__(self, pvalue=False, attr='labels', **kwargs):
"""Initialize :Parameters: pvalue : bool Either to report p-value of pearsons correlation coefficient instead of pure correlation coefficie... | the_stack_v2_python_sparse | mvpa/measures/corrcoef.py | gorlins/PyMVPA | train | 0 |
4395971b7d74e4ae6a4349881674b8f84da8c061 | [
"if seed is not None:\n np.random.seed(seed)\nif images.shape[0] != labels.shape[0]:\n raise ValueError('Image and labels should have the same size')\nif batch_size > images.shape[0]:\n raise ValueError('Batch size should not exceed image number')\nself._len = images.shape[0]\nself._images = images\nself._... | <|body_start_0|>
if seed is not None:
np.random.seed(seed)
if images.shape[0] != labels.shape[0]:
raise ValueError('Image and labels should have the same size')
if batch_size > images.shape[0]:
raise ValueError('Batch size should not exceed image number')
... | Container class for a dataset. | Dataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""Container class for a dataset."""
def __init__(self, images, labels, batch_size, shuffle=True, seed=None):
"""Construct a Dataset. Args: images: Image data. labels: Label data. batch_size: Batch size. shuffle: Whether to shuffle data or not. seed: Random seed. Raises: Val... | stack_v2_sparse_classes_75kplus_train_004524 | 4,320 | permissive | [
{
"docstring": "Construct a Dataset. Args: images: Image data. labels: Label data. batch_size: Batch size. shuffle: Whether to shuffle data or not. seed: Random seed. Raises: ValueError: Wrong input arguments.",
"name": "__init__",
"signature": "def __init__(self, images, labels, batch_size, shuffle=Tru... | 3 | stack_v2_sparse_classes_30k_train_045388 | Implement the Python class `Dataset` described below.
Class description:
Container class for a dataset.
Method signatures and docstrings:
- def __init__(self, images, labels, batch_size, shuffle=True, seed=None): Construct a Dataset. Args: images: Image data. labels: Label data. batch_size: Batch size. shuffle: Wheth... | Implement the Python class `Dataset` described below.
Class description:
Container class for a dataset.
Method signatures and docstrings:
- def __init__(self, images, labels, batch_size, shuffle=True, seed=None): Construct a Dataset. Args: images: Image data. labels: Label data. batch_size: Batch size. shuffle: Wheth... | 757aac75a0f3921c6d1b4d98599bd7d4ffda936b | <|skeleton|>
class Dataset:
"""Container class for a dataset."""
def __init__(self, images, labels, batch_size, shuffle=True, seed=None):
"""Construct a Dataset. Args: images: Image data. labels: Label data. batch_size: Batch size. shuffle: Whether to shuffle data or not. seed: Random seed. Raises: Val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dataset:
"""Container class for a dataset."""
def __init__(self, images, labels, batch_size, shuffle=True, seed=None):
"""Construct a Dataset. Args: images: Image data. labels: Label data. batch_size: Batch size. shuffle: Whether to shuffle data or not. seed: Random seed. Raises: ValueError: Wron... | the_stack_v2_python_sparse | python/level1_single_api/9_amct/amct_tensorflow/tensor_decompose/src/common/dataset.py | RomanGaraev/samples | train | 0 |
ff5ee6997b097f1367bcbd9434ff708ceca8c1da | [
"if not root:\n return '{}'\nresult = {}\ndq = deque([(0, root)])\nwhile dq:\n i, node = dq.popleft()\n if node.left:\n dq.append([2 * i + 1, node.left])\n if node.right:\n dq.append([2 * i + 2, node.right])\n result[i] = node.val\nreturn str(result)",
"nodes = {i: TreeNode(val) for i... | <|body_start_0|>
if not root:
return '{}'
result = {}
dq = deque([(0, root)])
while dq:
i, node = dq.popleft()
if node.left:
dq.append([2 * i + 1, node.left])
if node.right:
dq.append([2 * i + 2, node.right])... | 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_004525 | 942 | 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_val_001203 | 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:... | f4cd43f082b58d4410008af49325770bc84d3aba | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '{}'
result = {}
dq = deque([(0, root)])
while dq:
i, node = dq.popleft()
if node.left:
dq... | the_stack_v2_python_sparse | 297.Serialize_and_Deserialize_Binary_Tree.py | welsny/solutions | train | 1 | |
48bfe869ff09ca5080793c5c582296002c99feb6 | [
"num = '0'\nstack = [[num, '']]\nfor x in s:\n if x.isdigit():\n num += x\n elif x.isalpha():\n stack[-1][1] += x\n elif x == '[':\n stack.append([num, ''])\n num = '0'\n elif x == ']':\n count, cur = stack.pop()\n count = 1 if not int(count) else int(count)\n ... | <|body_start_0|>
num = '0'
stack = [[num, '']]
for x in s:
if x.isdigit():
num += x
elif x.isalpha():
stack[-1][1] += x
elif x == '[':
stack.append([num, ''])
num = '0'
elif x == ']':
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def decodeString1(self, s: str) -> str:
"""辅助栈:当前次数和当前字符串以数组形式入栈,遇到特定字符时出栈计算"""
<|body_0|>
def decodeString2(self, s: str) -> str:
"""递归"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
num = '0'
stack = [[num, '']]
for x in... | stack_v2_sparse_classes_75kplus_train_004526 | 1,892 | no_license | [
{
"docstring": "辅助栈:当前次数和当前字符串以数组形式入栈,遇到特定字符时出栈计算",
"name": "decodeString1",
"signature": "def decodeString1(self, s: str) -> str"
},
{
"docstring": "递归",
"name": "decodeString2",
"signature": "def decodeString2(self, s: str) -> str"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeString1(self, s: str) -> str: 辅助栈:当前次数和当前字符串以数组形式入栈,遇到特定字符时出栈计算
- def decodeString2(self, s: str) -> str: 递归 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeString1(self, s: str) -> str: 辅助栈:当前次数和当前字符串以数组形式入栈,遇到特定字符时出栈计算
- def decodeString2(self, s: str) -> str: 递归
<|skeleton|>
class Solution:
def decodeString1(self, ... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def decodeString1(self, s: str) -> str:
"""辅助栈:当前次数和当前字符串以数组形式入栈,遇到特定字符时出栈计算"""
<|body_0|>
def decodeString2(self, s: str) -> str:
"""递归"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def decodeString1(self, s: str) -> str:
"""辅助栈:当前次数和当前字符串以数组形式入栈,遇到特定字符时出栈计算"""
num = '0'
stack = [[num, '']]
for x in s:
if x.isdigit():
num += x
elif x.isalpha():
stack[-1][1] += x
elif x == '[':
... | the_stack_v2_python_sparse | 394_decode-string.py | helloocc/algorithm | train | 1 | |
ec94f4206d0aeedb2d20b006b7da61b93c75041c | [
"self.number_of_workers = number_of_workers\nself.max_requests = maximum_requests_per_thread\nself.max_age = maximum_age\nself.task_handler = task_handler\nself.handler_args = handler_args or ()\nself.handler_kwargs = handler_kwargs or {}\nself.workers = []",
"worker_dict = {}\nw = Worker(self.task_handler, self.... | <|body_start_0|>
self.number_of_workers = number_of_workers
self.max_requests = maximum_requests_per_thread
self.max_age = maximum_age
self.task_handler = task_handler
self.handler_args = handler_args or ()
self.handler_kwargs = handler_kwargs or {}
self.workers =... | Class managing workers | Manager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Manager:
"""Class managing workers"""
def __init__(self, task_handler, number_of_workers=10, maximum_requests_per_thread=5000, maximum_age=3600, handler_args=None, handler_kwargs=None):
"""Create a new Manager. :param task_handler: The Task object that will execute tasks. :param numb... | stack_v2_sparse_classes_75kplus_train_004527 | 2,977 | permissive | [
{
"docstring": "Create a new Manager. :param task_handler: The Task object that will execute tasks. :param number_of_workers: Maximum number of workers for this manager. :param maximum_requests_per_thread: Maximum number of tasks per worker. :param maximum_age: Maximum age of workers.",
"name": "__init__",
... | 6 | stack_v2_sparse_classes_30k_train_028336 | Implement the Python class `Manager` described below.
Class description:
Class managing workers
Method signatures and docstrings:
- def __init__(self, task_handler, number_of_workers=10, maximum_requests_per_thread=5000, maximum_age=3600, handler_args=None, handler_kwargs=None): Create a new Manager. :param task_hand... | Implement the Python class `Manager` described below.
Class description:
Class managing workers
Method signatures and docstrings:
- def __init__(self, task_handler, number_of_workers=10, maximum_requests_per_thread=5000, maximum_age=3600, handler_args=None, handler_kwargs=None): Create a new Manager. :param task_hand... | d8d3c9a86ab3235d4e36583fcee6f656e5209b7e | <|skeleton|>
class Manager:
"""Class managing workers"""
def __init__(self, task_handler, number_of_workers=10, maximum_requests_per_thread=5000, maximum_age=3600, handler_args=None, handler_kwargs=None):
"""Create a new Manager. :param task_handler: The Task object that will execute tasks. :param numb... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Manager:
"""Class managing workers"""
def __init__(self, task_handler, number_of_workers=10, maximum_requests_per_thread=5000, maximum_age=3600, handler_args=None, handler_kwargs=None):
"""Create a new Manager. :param task_handler: The Task object that will execute tasks. :param number_of_workers... | the_stack_v2_python_sparse | src/mercury/common/task_managers/base/manager.py | jr0d/mercury | train | 4 |
b6d751bee3e871bce59453d32b8c4bb19b1aa645 | [
"self.parser = reqparse.RequestParser()\nself.parser.add_argument('name')\nself.parser.add_argument('token')\nsuper(CtaStrategyParam, self).__init__()",
"args = self.parser.parse_args()\nname = 'strategyHedge_syt'\nengine = me.getApp('CtaStrategy')\nl = engine.getStrategyParam(name)\nfrom collections import Order... | <|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_argument('token')
super(CtaStrategyParam, self).__init__()
<|end_body_0|>
<|body_start_1|>
args = self.parser.parse_args()
name = 'strategyHedge_syt'
engine =... | 查询策略参数 | CtaStrategyParam | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CtaStrategyParam:
"""查询策略参数"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""订阅"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_... | stack_v2_sparse_classes_75kplus_train_004528 | 24,002 | permissive | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "订阅",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041040 | Implement the Python class `CtaStrategyParam` described below.
Class description:
查询策略参数
Method signatures and docstrings:
- def __init__(self): 初始化
- def get(self): 订阅 | Implement the Python class `CtaStrategyParam` described below.
Class description:
查询策略参数
Method signatures and docstrings:
- def __init__(self): 初始化
- def get(self): 订阅
<|skeleton|>
class CtaStrategyParam:
"""查询策略参数"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""订... | c316649161086da2543d39bf0455d0f793cdd08f | <|skeleton|>
class CtaStrategyParam:
"""查询策略参数"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""订阅"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CtaStrategyParam:
"""查询策略参数"""
def __init__(self):
"""初始化"""
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_argument('token')
super(CtaStrategyParam, self).__init__()
def get(self):
"""订阅"""
args = self.... | the_stack_v2_python_sparse | WebTrader/webServer.py | webclinic017/riskBacktestingPlatform | train | 0 |
ec82a496e70c97466b75f32b6f4a9fc23b104023 | [
"self.maxCSpaceJump = maxCSpaceJump\nself.timeout = timeout\nself.trajectoryPub = rospy.Publisher('/trajectory', Marker, queue_size=1)\nself.samplesPub = rospy.Publisher('/planning_samples', Marker, queue_size=1)",
"pts = []\nfor q in traj:\n pts.append(env.CalcFk(q)[0:4, 3])\nmarker = plot_rviz.CreateMarker('... | <|body_start_0|>
self.maxCSpaceJump = maxCSpaceJump
self.timeout = timeout
self.trajectoryPub = rospy.Publisher('/trajectory', Marker, queue_size=1)
self.samplesPub = rospy.Publisher('/planning_samples', Marker, queue_size=1)
<|end_body_0|>
<|body_start_1|>
pts = []
for ... | View planner base class. | MotionPlanner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MotionPlanner:
"""View planner base class."""
def __init__(self, maxCSpaceJump, timeout):
"""Constructor for view planner."""
<|body_0|>
def DrawTrajectory(self, traj, env, rgb, indices=[-1, -1]):
"""Draw a given trajectory in rviz."""
<|body_1|>
def... | stack_v2_sparse_classes_75kplus_train_004529 | 14,509 | permissive | [
{
"docstring": "Constructor for view planner.",
"name": "__init__",
"signature": "def __init__(self, maxCSpaceJump, timeout)"
},
{
"docstring": "Draw a given trajectory in rviz.",
"name": "DrawTrajectory",
"signature": "def DrawTrajectory(self, traj, env, rgb, indices=[-1, -1])"
},
{... | 5 | null | Implement the Python class `MotionPlanner` described below.
Class description:
View planner base class.
Method signatures and docstrings:
- def __init__(self, maxCSpaceJump, timeout): Constructor for view planner.
- def DrawTrajectory(self, traj, env, rgb, indices=[-1, -1]): Draw a given trajectory in rviz.
- def Hie... | Implement the Python class `MotionPlanner` described below.
Class description:
View planner base class.
Method signatures and docstrings:
- def __init__(self, maxCSpaceJump, timeout): Constructor for view planner.
- def DrawTrajectory(self, traj, env, rgb, indices=[-1, -1]): Draw a given trajectory in rviz.
- def Hie... | 563cde0618349f0ef5c59a104fb1936bad46f845 | <|skeleton|>
class MotionPlanner:
"""View planner base class."""
def __init__(self, maxCSpaceJump, timeout):
"""Constructor for view planner."""
<|body_0|>
def DrawTrajectory(self, traj, env, rgb, indices=[-1, -1]):
"""Draw a given trajectory in rviz."""
<|body_1|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MotionPlanner:
"""View planner base class."""
def __init__(self, maxCSpaceJump, timeout):
"""Constructor for view planner."""
self.maxCSpaceJump = maxCSpaceJump
self.timeout = timeout
self.trajectoryPub = rospy.Publisher('/trajectory', Marker, queue_size=1)
self.sa... | the_stack_v2_python_sparse | Robot/scripts/robot/motion_planner.py | elegantprogrammer/GeomPickPlace | train | 0 |
94cc6d2adfd1186347360a5dfe4e44be6ea3b3df | [
"bl = 1125 * np.log(1 + fl * fs / 700)\nbh = 1125 * np.log(1 + fh * fs / 700)\nB = bh - bl\ny = np.linspace(0, B, p + 2)\nFb = 700 * (np.exp(y / 1125) - 1)\nW = int(n / 2 + 1)\ndf = fs / n\nbank = np.zeros((p, W))\nfor m in range(1, p + 1):\n f0, f1, f2 = (Fb[m], Fb[m - 1], Fb[m + 1])\n n0 = f0 / df\n n1 =... | <|body_start_0|>
bl = 1125 * np.log(1 + fl * fs / 700)
bh = 1125 * np.log(1 + fh * fs / 700)
B = bh - bl
y = np.linspace(0, B, p + 2)
Fb = 700 * (np.exp(y / 1125) - 1)
W = int(n / 2 + 1)
df = fs / n
bank = np.zeros((p, W))
for m in range(1, p + 1):... | MFCC | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MFCC:
def melbankm(self, p, n, fs, fl=0, fh=0.5, w='t'):
"""再Mel频率上设计平均分布的滤波器 :param p: fl和fh之间设计的Mel滤波器的个数 :param n: FFT长度 :param fs: 采样频率 :param fl: 设计滤波器的最低频率(用fs归一化,一般取0) :param fh: 设计滤波器的最高频率(用fs归一化,一般取0.5) :param w: 窗函数,'t'=triangle,'n'=hanning, 'm'=hanmming :return bank: 滤波器频率响应,s... | stack_v2_sparse_classes_75kplus_train_004530 | 3,700 | permissive | [
{
"docstring": "再Mel频率上设计平均分布的滤波器 :param p: fl和fh之间设计的Mel滤波器的个数 :param n: FFT长度 :param fs: 采样频率 :param fl: 设计滤波器的最低频率(用fs归一化,一般取0) :param fh: 设计滤波器的最高频率(用fs归一化,一般取0.5) :param w: 窗函数,'t'=triangle,'n'=hanning, 'm'=hanmming :return bank: 滤波器频率响应,size = p x (n/2 + 1), 只取正频率部分",
"name": "melbankm",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_047443 | Implement the Python class `MFCC` described below.
Class description:
Implement the MFCC class.
Method signatures and docstrings:
- def melbankm(self, p, n, fs, fl=0, fh=0.5, w='t'): 再Mel频率上设计平均分布的滤波器 :param p: fl和fh之间设计的Mel滤波器的个数 :param n: FFT长度 :param fs: 采样频率 :param fl: 设计滤波器的最低频率(用fs归一化,一般取0) :param fh: 设计滤波器的最高频... | Implement the Python class `MFCC` described below.
Class description:
Implement the MFCC class.
Method signatures and docstrings:
- def melbankm(self, p, n, fs, fl=0, fh=0.5, w='t'): 再Mel频率上设计平均分布的滤波器 :param p: fl和fh之间设计的Mel滤波器的个数 :param n: FFT长度 :param fs: 采样频率 :param fl: 设计滤波器的最低频率(用fs归一化,一般取0) :param fh: 设计滤波器的最高频... | 0074ad1d519387a75d5eca42c77f4d6966eb0a0e | <|skeleton|>
class MFCC:
def melbankm(self, p, n, fs, fl=0, fh=0.5, w='t'):
"""再Mel频率上设计平均分布的滤波器 :param p: fl和fh之间设计的Mel滤波器的个数 :param n: FFT长度 :param fs: 采样频率 :param fl: 设计滤波器的最低频率(用fs归一化,一般取0) :param fh: 设计滤波器的最高频率(用fs归一化,一般取0.5) :param w: 窗函数,'t'=triangle,'n'=hanning, 'm'=hanmming :return bank: 滤波器频率响应,s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MFCC:
def melbankm(self, p, n, fs, fl=0, fh=0.5, w='t'):
"""再Mel频率上设计平均分布的滤波器 :param p: fl和fh之间设计的Mel滤波器的个数 :param n: FFT长度 :param fs: 采样频率 :param fl: 设计滤波器的最低频率(用fs归一化,一般取0) :param fh: 设计滤波器的最高频率(用fs归一化,一般取0.5) :param w: 窗函数,'t'=triangle,'n'=hanning, 'm'=hanmming :return bank: 滤波器频率响应,size = p x (n/2... | the_stack_v2_python_sparse | Chapter6_VoiceActivityDetection/MFCC.py | BarryZM/Python_Speech_SZY | train | 0 | |
70df75befe5a6fe23884255e8034bbd6765cc6af | [
"Parametre.__init__(self, 'créer', 'create')\nself.schema = '<modele_navire>'\nself.aide_courte = 'crée un navire sur un modèle'\nself.aide_longue = \"Crée un navire sur un modèle existant. Cette commande crée un navire mais ne le place dans aucune étendue d'eau.\"",
"modele = dic_masques['modele_navire'].modele\... | <|body_start_0|>
Parametre.__init__(self, 'créer', 'create')
self.schema = '<modele_navire>'
self.aide_courte = 'crée un navire sur un modèle'
self.aide_longue = "Crée un navire sur un modèle existant. Cette commande crée un navire mais ne le place dans aucune étendue d'eau."
<|end_body_... | Commande 'navire créer'. | PrmCreer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmCreer:
"""Commande 'navire créer'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre.__in... | stack_v2_sparse_classes_75kplus_train_004531 | 3,038 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000042 | Implement the Python class `PrmCreer` described below.
Class description:
Commande 'navire créer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmCreer` described below.
Class description:
Commande 'navire créer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmCreer:
"""Commande 'navire créer... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmCreer:
"""Commande 'navire créer'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrmCreer:
"""Commande 'navire créer'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'créer', 'create')
self.schema = '<modele_navire>'
self.aide_courte = 'crée un navire sur un modèle'
self.aide_longue = "Crée un navire sur un modè... | the_stack_v2_python_sparse | src/secondaires/navigation/commandes/navire/creer.py | vincent-lg/tsunami | train | 5 |
d785846b51eed4711716ba7ba821ba1315e4b85a | [
"entropy = frac * self.entropy / self.num_modules\nnew_sample_args = SampleArgs(num_modules=self.num_modules, entropy=self.entropy - entropy)\nreturn (entropy, new_sample_args)",
"num_child_modules = self.num_modules - 1\nmodule_counts = combinatorics.uniform_non_negative_integers_with_sum(count, num_child_module... | <|body_start_0|>
entropy = frac * self.entropy / self.num_modules
new_sample_args = SampleArgs(num_modules=self.num_modules, entropy=self.entropy - entropy)
return (entropy, new_sample_args)
<|end_body_0|>
<|body_start_1|>
num_child_modules = self.num_modules - 1
module_counts =... | For sampling mathematical entities / questions. | SampleArgs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleArgs:
"""For sampling mathematical entities / questions."""
def peel(self, frac=1):
"""Peels one (or `frac`) of a module's entropy. In addition to a portion of the entropy, this returns a new `SampleArgs` (since this object is immutable), which you should use when creating chil... | stack_v2_sparse_classes_75kplus_train_004532 | 19,332 | permissive | [
{
"docstring": "Peels one (or `frac`) of a module's entropy. In addition to a portion of the entropy, this returns a new `SampleArgs` (since this object is immutable), which you should use when creating child modules. Args: frac: Float; proportion of module's entropy to take. Returns: Triple `(entropy, new_samp... | 2 | stack_v2_sparse_classes_30k_train_043468 | Implement the Python class `SampleArgs` described below.
Class description:
For sampling mathematical entities / questions.
Method signatures and docstrings:
- def peel(self, frac=1): Peels one (or `frac`) of a module's entropy. In addition to a portion of the entropy, this returns a new `SampleArgs` (since this obje... | Implement the Python class `SampleArgs` described below.
Class description:
For sampling mathematical entities / questions.
Method signatures and docstrings:
- def peel(self, frac=1): Peels one (or `frac`) of a module's entropy. In addition to a portion of the entropy, this returns a new `SampleArgs` (since this obje... | 4fd371919d57258dcdedaa21b111fa61ee0a771f | <|skeleton|>
class SampleArgs:
"""For sampling mathematical entities / questions."""
def peel(self, frac=1):
"""Peels one (or `frac`) of a module's entropy. In addition to a portion of the entropy, this returns a new `SampleArgs` (since this object is immutable), which you should use when creating chil... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SampleArgs:
"""For sampling mathematical entities / questions."""
def peel(self, frac=1):
"""Peels one (or `frac`) of a module's entropy. In addition to a portion of the entropy, this returns a new `SampleArgs` (since this object is immutable), which you should use when creating child modules. Ar... | the_stack_v2_python_sparse | mathematics_dataset/util/composition.py | AhmedHathout/mathematics_dataset | train | 0 |
d75c2855b6003912eacd5eca248cbd259b338fa1 | [
"with open(path, mode='r') as file:\n data = file.read()\n blocks = data.split('--')[1:]\n word_definitions = [list(filter(None, block.split('\\n'))) for block in blocks]\n return {item[0]: item[1:] for item in word_definitions}",
"with open(path, mode='w') as file:\n for word in words:\n fi... | <|body_start_0|>
with open(path, mode='r') as file:
data = file.read()
blocks = data.split('--')[1:]
word_definitions = [list(filter(None, block.split('\n'))) for block in blocks]
return {item[0]: item[1:] for item in word_definitions}
<|end_body_0|>
<|body_start... | This class is responsible for reading and writing to dictionary text files. | DictionaryFileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DictionaryFileManager:
"""This class is responsible for reading and writing to dictionary text files."""
def load_dictionary(self, path: str) -> dict:
"""Loads dictionary from a file path, constructs and returns a dict object with key is the word and value is a list of definitions it... | stack_v2_sparse_classes_75kplus_train_004533 | 4,251 | no_license | [
{
"docstring": "Loads dictionary from a file path, constructs and returns a dict object with key is the word and value is a list of definitions it has. :param path: a str, the path to the dictionary data file :return: a dict, key is the word and value is a list of definitions it has",
"name": "load_dictiona... | 2 | stack_v2_sparse_classes_30k_train_052169 | Implement the Python class `DictionaryFileManager` described below.
Class description:
This class is responsible for reading and writing to dictionary text files.
Method signatures and docstrings:
- def load_dictionary(self, path: str) -> dict: Loads dictionary from a file path, constructs and returns a dict object w... | Implement the Python class `DictionaryFileManager` described below.
Class description:
This class is responsible for reading and writing to dictionary text files.
Method signatures and docstrings:
- def load_dictionary(self, path: str) -> dict: Loads dictionary from a file path, constructs and returns a dict object w... | e86956c69006f96221349fe9bd4925ad2255601e | <|skeleton|>
class DictionaryFileManager:
"""This class is responsible for reading and writing to dictionary text files."""
def load_dictionary(self, path: str) -> dict:
"""Loads dictionary from a file path, constructs and returns a dict object with key is the word and value is a list of definitions it... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DictionaryFileManager:
"""This class is responsible for reading and writing to dictionary text files."""
def load_dictionary(self, path: str) -> dict:
"""Loads dictionary from a file path, constructs and returns a dict object with key is the word and value is a list of definitions it has. :param ... | the_stack_v2_python_sparse | lab-6-linguistic-error-handling-lizhiquan/custom_dictionary.py | lizhiquan/learning-python | train | 0 |
d813a4f9013c9770cf1b0828877f4ed64c0c29e9 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SimulationAutomationRun()",
"from .entity import Entity\nfrom .simulation_automation_run_status import SimulationAutomationRunStatus\nfrom .entity import Entity\nfrom .simulation_automation_run_status import SimulationAutomationRunStat... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SimulationAutomationRun()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .simulation_automation_run_status import SimulationAutomationRunStatus
from .entity impo... | SimulationAutomationRun | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulationAutomationRun:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomationRun:
"""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 creat... | stack_v2_sparse_classes_75kplus_train_004534 | 3,312 | 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: SimulationAutomationRun",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimin... | 3 | stack_v2_sparse_classes_30k_train_040680 | Implement the Python class `SimulationAutomationRun` described below.
Class description:
Implement the SimulationAutomationRun class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomationRun: Creates a new instance of the appropriate clas... | Implement the Python class `SimulationAutomationRun` described below.
Class description:
Implement the SimulationAutomationRun class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomationRun: Creates a new instance of the appropriate clas... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SimulationAutomationRun:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomationRun:
"""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 creat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimulationAutomationRun:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomationRun:
"""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 R... | the_stack_v2_python_sparse | msgraph/generated/models/simulation_automation_run.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
9ad5d56a2414c2fd9cf81e60bf8ed5a2b460f87a | [
"self.class_ = 'd-block flex-wrap'\nsuper().__init__(**kwargs)\nself.planet_model = planet_model if planet_model else PlanetModel()\nself.btn = btn if btn else sw.Btn('Validate', small=True, class_='mr-1')\nself.alert = alert if alert else sw.Alert()\nself.w_username = sw.TextField(label=ms.planet.widget.username, ... | <|body_start_0|>
self.class_ = 'd-block flex-wrap'
super().__init__(**kwargs)
self.planet_model = planet_model if planet_model else PlanetModel()
self.btn = btn if btn else sw.Btn('Validate', small=True, class_='mr-1')
self.alert = alert if alert else sw.Alert()
self.w_us... | PlanetView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlanetView:
def __init__(self, btn: Optional[sw.Btn]=None, alert: Optional[sw.Alert]=None, planet_model: Optional[PlanetModel]=None, info: bool=False, **kwargs):
"""Stand-alone interface to capture planet lab credentials. It also validate its subscription and connect to the client stored... | stack_v2_sparse_classes_75kplus_train_004535 | 4,677 | permissive | [
{
"docstring": "Stand-alone interface to capture planet lab credentials. It also validate its subscription and connect to the client stored in the model. Args: btn (sw.Btn, optional): Button to trigger the validation process in the associated model. alert (sw.Alert, v.Alert, optional): Alert component to displa... | 4 | stack_v2_sparse_classes_30k_train_036132 | Implement the Python class `PlanetView` described below.
Class description:
Implement the PlanetView class.
Method signatures and docstrings:
- def __init__(self, btn: Optional[sw.Btn]=None, alert: Optional[sw.Alert]=None, planet_model: Optional[PlanetModel]=None, info: bool=False, **kwargs): Stand-alone interface to... | Implement the Python class `PlanetView` described below.
Class description:
Implement the PlanetView class.
Method signatures and docstrings:
- def __init__(self, btn: Optional[sw.Btn]=None, alert: Optional[sw.Alert]=None, planet_model: Optional[PlanetModel]=None, info: bool=False, **kwargs): Stand-alone interface to... | b26c7d698659d5c5a2029d02fc94dcd9daf0df98 | <|skeleton|>
class PlanetView:
def __init__(self, btn: Optional[sw.Btn]=None, alert: Optional[sw.Alert]=None, planet_model: Optional[PlanetModel]=None, info: bool=False, **kwargs):
"""Stand-alone interface to capture planet lab credentials. It also validate its subscription and connect to the client stored... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlanetView:
def __init__(self, btn: Optional[sw.Btn]=None, alert: Optional[sw.Alert]=None, planet_model: Optional[PlanetModel]=None, info: bool=False, **kwargs):
"""Stand-alone interface to capture planet lab credentials. It also validate its subscription and connect to the client stored in the model.... | the_stack_v2_python_sparse | sepal_ui/planetapi/planet_view.py | 12rambau/sepal_ui | train | 17 | |
79b5d3b7c3c78b84b2f5a224d186146150820a9d | [
"super().__init__()\nself.every_n_steps = every_n_steps\nself.nrow = nrow\nself.padding = padding\nself.normalize = normalize\nself.norm_range = norm_range\nself.scale_each = scale_each\nself.pad_value = pad_value\nself.multi_optim = multi_optim\nself.use_wandb = use_wandb",
"if batch_idx % self.every_n_steps == ... | <|body_start_0|>
super().__init__()
self.every_n_steps = every_n_steps
self.nrow = nrow
self.padding = padding
self.normalize = normalize
self.norm_range = norm_range
self.scale_each = scale_each
self.pad_value = pad_value
self.multi_optim = multi_... | ReconstructedImageLogger | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReconstructedImageLogger:
def __init__(self, every_n_steps: int=1000, nrow: int=8, padding: int=2, normalize: bool=True, norm_range: Optional[Tuple[int, int]]=None, scale_each: bool=False, pad_value: int=0, use_wandb: bool=False, multi_optim=False) -> None:
"""Args: num_samples: Number o... | stack_v2_sparse_classes_75kplus_train_004536 | 6,454 | permissive | [
{
"docstring": "Args: num_samples: Number of images displayed in the grid. Default: ``3``. nrow: Number of images displayed in each row of the grid. The final grid size is ``(B / nrow, nrow)``. Default: ``8``. padding: Amount of padding. Default: ``2``. normalize: If ``True``, shift the image to the range (0, 1... | 4 | stack_v2_sparse_classes_30k_train_054506 | Implement the Python class `ReconstructedImageLogger` described below.
Class description:
Implement the ReconstructedImageLogger class.
Method signatures and docstrings:
- def __init__(self, every_n_steps: int=1000, nrow: int=8, padding: int=2, normalize: bool=True, norm_range: Optional[Tuple[int, int]]=None, scale_e... | Implement the Python class `ReconstructedImageLogger` described below.
Class description:
Implement the ReconstructedImageLogger class.
Method signatures and docstrings:
- def __init__(self, every_n_steps: int=1000, nrow: int=8, padding: int=2, normalize: bool=True, norm_range: Optional[Tuple[int, int]]=None, scale_e... | 9d643e88946fc4a24f2d4d073c08b05ea693f4c5 | <|skeleton|>
class ReconstructedImageLogger:
def __init__(self, every_n_steps: int=1000, nrow: int=8, padding: int=2, normalize: bool=True, norm_range: Optional[Tuple[int, int]]=None, scale_each: bool=False, pad_value: int=0, use_wandb: bool=False, multi_optim=False) -> None:
"""Args: num_samples: Number o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReconstructedImageLogger:
def __init__(self, every_n_steps: int=1000, nrow: int=8, padding: int=2, normalize: bool=True, norm_range: Optional[Tuple[int, int]]=None, scale_each: bool=False, pad_value: int=0, use_wandb: bool=False, multi_optim=False) -> None:
"""Args: num_samples: Number of images displ... | the_stack_v2_python_sparse | multimodal/Language-Image_Pre-Training/L-Verse/pytorch/latent_verse/callbacks.py | Deep-Spark/DeepSparkHub | train | 7 | |
25ea46673f5cd6641610961618d119b9f708fb5a | [
"test_address = LabAddress(type='Primary', address=Address.objects.get(pk=1))\ntest_address.save()\nself.assertEqual(test_address.pk, 1)",
"test_address = LabAddress(type='Primary', address=Address.objects.get(pk=1))\ntest_address.save()\nself.assertEqual(test_address.pk, 1)\nself.assertEqual(test_address.__unico... | <|body_start_0|>
test_address = LabAddress(type='Primary', address=Address.objects.get(pk=1))
test_address.save()
self.assertEqual(test_address.pk, 1)
<|end_body_0|>
<|body_start_1|>
test_address = LabAddress(type='Primary', address=Address.objects.get(pk=1))
test_address.save()... | This class tests the views associated with models in the :mod:`communication` app. | CommunicationModelTests | [
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommunicationModelTests:
"""This class tests the views associated with models in the :mod:`communication` app."""
def test_create_new_lab_address(self):
"""This test creates a :class:`~communication.models.LabAddress` with the required information."""
<|body_0|>
def test... | stack_v2_sparse_classes_75kplus_train_004537 | 14,526 | permissive | [
{
"docstring": "This test creates a :class:`~communication.models.LabAddress` with the required information.",
"name": "test_create_new_lab_address",
"signature": "def test_create_new_lab_address(self)"
},
{
"docstring": "This tests the unicode representation of a :class:`~communication.models.L... | 5 | stack_v2_sparse_classes_30k_train_004927 | Implement the Python class `CommunicationModelTests` described below.
Class description:
This class tests the views associated with models in the :mod:`communication` app.
Method signatures and docstrings:
- def test_create_new_lab_address(self): This test creates a :class:`~communication.models.LabAddress` with the ... | Implement the Python class `CommunicationModelTests` described below.
Class description:
This class tests the views associated with models in the :mod:`communication` app.
Method signatures and docstrings:
- def test_create_new_lab_address(self): This test creates a :class:`~communication.models.LabAddress` with the ... | d6f6c9c068bbf668c253e5943d9514947023e66d | <|skeleton|>
class CommunicationModelTests:
"""This class tests the views associated with models in the :mod:`communication` app."""
def test_create_new_lab_address(self):
"""This test creates a :class:`~communication.models.LabAddress` with the required information."""
<|body_0|>
def test... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommunicationModelTests:
"""This class tests the views associated with models in the :mod:`communication` app."""
def test_create_new_lab_address(self):
"""This test creates a :class:`~communication.models.LabAddress` with the required information."""
test_address = LabAddress(type='Prima... | the_stack_v2_python_sparse | communication/tests.py | BridgesLab/Lab-Website | train | 0 |
6d98b11147c322146ad510c2ec9b5039d6970f6c | [
"image_bytes = decoded_tensors[self._image_field_key]\nif self._decode_jpeg_only:\n image_shape = tf.image.extract_jpeg_shape(image_bytes)\n cropped_image = random_crop_image_v2(image_bytes, image_shape)\n image = tf.cond(tf.reduce_all(tf.equal(tf.shape(cropped_image), image_shape)), lambda: preprocess_ops... | <|body_start_0|>
image_bytes = decoded_tensors[self._image_field_key]
if self._decode_jpeg_only:
image_shape = tf.image.extract_jpeg_shape(image_bytes)
cropped_image = random_crop_image_v2(image_bytes, image_shape)
image = tf.cond(tf.reduce_all(tf.equal(tf.shape(cropp... | Parser to parse an image and its annotations into a dictionary of tensors. | Parser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parser:
"""Parser to parse an image and its annotations into a dictionary of tensors."""
def _parse_train_image(self, decoded_tensors):
"""Parses image data for training."""
<|body_0|>
def _parse_eval_image(self, decoded_tensors):
"""Parses image data for evaluat... | stack_v2_sparse_classes_75kplus_train_004538 | 7,102 | permissive | [
{
"docstring": "Parses image data for training.",
"name": "_parse_train_image",
"signature": "def _parse_train_image(self, decoded_tensors)"
},
{
"docstring": "Parses image data for evaluation.",
"name": "_parse_eval_image",
"signature": "def _parse_eval_image(self, decoded_tensors)"
}... | 2 | stack_v2_sparse_classes_30k_train_052512 | Implement the Python class `Parser` described below.
Class description:
Parser to parse an image and its annotations into a dictionary of tensors.
Method signatures and docstrings:
- def _parse_train_image(self, decoded_tensors): Parses image data for training.
- def _parse_eval_image(self, decoded_tensors): Parses i... | Implement the Python class `Parser` described below.
Class description:
Parser to parse an image and its annotations into a dictionary of tensors.
Method signatures and docstrings:
- def _parse_train_image(self, decoded_tensors): Parses image data for training.
- def _parse_eval_image(self, decoded_tensors): Parses i... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class Parser:
"""Parser to parse an image and its annotations into a dictionary of tensors."""
def _parse_train_image(self, decoded_tensors):
"""Parses image data for training."""
<|body_0|>
def _parse_eval_image(self, decoded_tensors):
"""Parses image data for evaluat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Parser:
"""Parser to parse an image and its annotations into a dictionary of tensors."""
def _parse_train_image(self, decoded_tensors):
"""Parses image data for training."""
image_bytes = decoded_tensors[self._image_field_key]
if self._decode_jpeg_only:
image_shape = t... | the_stack_v2_python_sparse | official/projects/edgetpu/vision/dataloaders/classification_input.py | jianzhnie/models | train | 2 |
67c9292d3cb767571920b27bcc1d9700f377706b | [
"try:\n release = Release.objects.get(organization_id=organization.id, version=version)\nexcept Release.DoesNotExist:\n raise ResourceDoesNotExist\nif not self.has_release_permission(request, organization, release):\n raise ResourceDoesNotExist\nreturn self.get_releasefile(request, release, file_id, check_... | <|body_start_0|>
try:
release = Release.objects.get(organization_id=organization.id, version=version)
except Release.DoesNotExist:
raise ResourceDoesNotExist
if not self.has_release_permission(request, organization, release):
raise ResourceDoesNotExist
... | OrganizationReleaseFileDetailsEndpoint | [
"Apache-2.0",
"BUSL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationReleaseFileDetailsEndpoint:
def get(self, request: Request, organization, version, file_id) -> Response:
"""Retrieve an Organization Release's File ``````````````````````````````````````` Return details on an individual file within a release. This does not actually return the... | stack_v2_sparse_classes_75kplus_train_004539 | 3,870 | permissive | [
{
"docstring": "Retrieve an Organization Release's File ``````````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of the file, just the associated metadata. :pparam string organization_slug: the slug of the organization the release ... | 3 | stack_v2_sparse_classes_30k_test_001163 | Implement the Python class `OrganizationReleaseFileDetailsEndpoint` described below.
Class description:
Implement the OrganizationReleaseFileDetailsEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, organization, version, file_id) -> Response: Retrieve an Organization Release's File `... | Implement the Python class `OrganizationReleaseFileDetailsEndpoint` described below.
Class description:
Implement the OrganizationReleaseFileDetailsEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, organization, version, file_id) -> Response: Retrieve an Organization Release's File `... | d9dd4f382f96b5c4576b64cbf015db651556c18b | <|skeleton|>
class OrganizationReleaseFileDetailsEndpoint:
def get(self, request: Request, organization, version, file_id) -> Response:
"""Retrieve an Organization Release's File ``````````````````````````````````````` Return details on an individual file within a release. This does not actually return the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrganizationReleaseFileDetailsEndpoint:
def get(self, request: Request, organization, version, file_id) -> Response:
"""Retrieve an Organization Release's File ``````````````````````````````````````` Return details on an individual file within a release. This does not actually return the contents of t... | the_stack_v2_python_sparse | src/sentry/api/endpoints/organization_release_file_details.py | nagyist/sentry | train | 0 | |
b12f50a63657bb28db93a7f86ac75242eaa17641 | [
"res = []\n\ndef addTolist(node, dep):\n if not node:\n return\n if dep >= len(res):\n res.append([])\n res[dep].append(node.val)\n if node.left:\n addTolist(node.left, dep + 1)\n if node.right:\n addTolist(node.right, dep + 1)\naddTolist(root, 0)\nres.reverse()\nreturn re... | <|body_start_0|>
res = []
def addTolist(node, dep):
if not node:
return
if dep >= len(res):
res.append([])
res[dep].append(node.val)
if node.left:
addTolist(node.left, dep + 1)
if node.right:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrderBottom(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrderBottom2(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
... | stack_v2_sparse_classes_75kplus_train_004540 | 1,682 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrderBottom",
"signature": "def levelOrderBottom(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrderBottom2",
"signature": "def levelOrderBottom2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020005 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrderBottom2(self, root): :type root: TreeNode :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrderBottom2(self, root): :type root: TreeNode :rtype: List[List[int]]
<|skeleton|>
cla... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def levelOrderBottom(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrderBottom2(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def levelOrderBottom(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
res = []
def addTolist(node, dep):
if not node:
return
if dep >= len(res):
res.append([])
res[dep].append(node.val)
... | the_stack_v2_python_sparse | 107. Binary Tree Level Order Traversal II/level_order.py | Macielyoung/LeetCode | train | 1 | |
b1b7cb6f73bcd92a9a8f4aeddf7cbdf159d42b76 | [
"if not auth.is_admin():\n raise endpoints.NotFoundException()\nif Tree.get_by_id(request.name):\n raise endpoints.ForbiddenException(\"Duplicate tree with name '%s' found.\" % request.name)\ntree = Tree(id=request.name, display_name=request.display_name, bug_labels=request.bug_labels, group=request.group)\nt... | <|body_start_0|>
if not auth.is_admin():
raise endpoints.NotFoundException()
if Tree.get_by_id(request.name):
raise endpoints.ForbiddenException("Duplicate tree with name '%s' found." % request.name)
tree = Tree(id=request.name, display_name=request.display_name, bug_labe... | API for editing the tree list. | TreeEndpointsApi | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeEndpointsApi:
"""API for editing the tree list."""
def new(self, request):
"""Add a new tree."""
<|body_0|>
def add_bug_label(self, request):
"""Add a new bug label to a tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not auth.is_ad... | stack_v2_sparse_classes_75kplus_train_004541 | 4,197 | permissive | [
{
"docstring": "Add a new tree.",
"name": "new",
"signature": "def new(self, request)"
},
{
"docstring": "Add a new bug label to a tree.",
"name": "add_bug_label",
"signature": "def add_bug_label(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_029866 | Implement the Python class `TreeEndpointsApi` described below.
Class description:
API for editing the tree list.
Method signatures and docstrings:
- def new(self, request): Add a new tree.
- def add_bug_label(self, request): Add a new bug label to a tree. | Implement the Python class `TreeEndpointsApi` described below.
Class description:
API for editing the tree list.
Method signatures and docstrings:
- def new(self, request): Add a new tree.
- def add_bug_label(self, request): Add a new bug label to a tree.
<|skeleton|>
class TreeEndpointsApi:
"""API for editing t... | ce3728559112bfb3e8b32137eada517aec6d22f9 | <|skeleton|>
class TreeEndpointsApi:
"""API for editing the tree list."""
def new(self, request):
"""Add a new tree."""
<|body_0|>
def add_bug_label(self, request):
"""Add a new bug label to a tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TreeEndpointsApi:
"""API for editing the tree list."""
def new(self, request):
"""Add a new tree."""
if not auth.is_admin():
raise endpoints.NotFoundException()
if Tree.get_by_id(request.name):
raise endpoints.ForbiddenException("Duplicate tree with name '%... | the_stack_v2_python_sparse | appengine/sheriff_o_matic/tree.py | eunchong/infra | train | 0 |
fadae926f5acf42a8be8287d3cf746374602b35f | [
"self._values = []\nif 'Values' in decision_variables:\n self._values = decision_variables['Values']\nself._weights = []\nif 'Weights' in decision_variables:\n self._weights = decision_variables['Weights']\nself._capacity = 0\nif 'Max-Weight' in constraints:\n self._capacity = constraints['Max-Weight']\nen... | <|body_start_0|>
self._values = []
if 'Values' in decision_variables:
self._values = decision_variables['Values']
self._weights = []
if 'Weights' in decision_variables:
self._weights = decision_variables['Weights']
self._capacity = 0
if 'Max-Weight... | The goal of the knapsack problem is to pack a set of items, with given weights and values, into a "knapsack" with a maximum capacity. The objective is to maximize the total value of the packed items. | KnapsackProblem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnapsackProblem:
"""The goal of the knapsack problem is to pack a set of items, with given weights and values, into a "knapsack" with a maximum capacity. The objective is to maximize the total value of the packed items."""
def __init__(self, decision_variables, constraints, encoding_rule=kna... | stack_v2_sparse_classes_75kplus_train_004542 | 8,294 | permissive | [
{
"docstring": "Knapsack Problem Template CONSTRUCTOR Parameters: @decision_variables Expected Decision Variables, so the dictionary must have the following keys and values of them must be lists: e.g: decision_variables_example = { \"Values\" : [10,11,13,9,13,18,12,21,12,25], #<< Number, Mandatory \"Weights\" :... | 4 | null | Implement the Python class `KnapsackProblem` described below.
Class description:
The goal of the knapsack problem is to pack a set of items, with given weights and values, into a "knapsack" with a maximum capacity. The objective is to maximize the total value of the packed items.
Method signatures and docstrings:
- d... | Implement the Python class `KnapsackProblem` described below.
Class description:
The goal of the knapsack problem is to pack a set of items, with given weights and values, into a "knapsack" with a maximum capacity. The objective is to maximize the total value of the packed items.
Method signatures and docstrings:
- d... | 04dd7896fd0df4349291ad4d4919bbe7cff9f830 | <|skeleton|>
class KnapsackProblem:
"""The goal of the knapsack problem is to pack a set of items, with given weights and values, into a "knapsack" with a maximum capacity. The objective is to maximize the total value of the packed items."""
def __init__(self, decision_variables, constraints, encoding_rule=kna... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KnapsackProblem:
"""The goal of the knapsack problem is to pack a set of items, with given weights and values, into a "knapsack" with a maximum capacity. The objective is to maximize the total value of the packed items."""
def __init__(self, decision_variables, constraints, encoding_rule=knapsack_encodin... | the_stack_v2_python_sparse | dssg_challenge/ga/custom_problem/knapsack_problem.py | joaopfonseca/dssgsummit2020-challenge | train | 0 |
3be32a078629544eb473ce51e66c5afc84139bbe | [
"if angle_choices is None:\n self.angle_choices = [0, 90, 180, 270]\nelse:\n self.angle_choices = angle_choices\nif rotator_kwargs is None:\n self.rotator_kwargs = {'preserve_range': True}\nelse:\n self.rotator_kwargs = rotator_kwargs\nself.angle_sampler_prob = angle_sampler_prob",
"rotation_angle = r... | <|body_start_0|>
if angle_choices is None:
self.angle_choices = [0, 90, 180, 270]
else:
self.angle_choices = angle_choices
if rotator_kwargs is None:
self.rotator_kwargs = {'preserve_range': True}
else:
self.rotator_kwargs = rotator_kwargs
... | Implements a rotation of a random amount of degrees. | RandomRotateXForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomRotateXForm:
"""Implements a rotation of a random amount of degrees."""
def __init__(self, angle_choices: Sequence[float]=None, angle_sampler_prob: Sequence[float]=None, rotator_kwargs: Dict=None) -> None:
"""Creates a random rotator Transform object :param angle_choices: An Se... | stack_v2_sparse_classes_75kplus_train_004543 | 4,028 | permissive | [
{
"docstring": "Creates a random rotator Transform object :param angle_choices: An Sequence object of floats which represent the possible angles from which the sampler can choose from :param angle_sampler_kwargs: any keyword arguments to pass to the sampler",
"name": "__init__",
"signature": "def __init... | 2 | stack_v2_sparse_classes_30k_val_002703 | Implement the Python class `RandomRotateXForm` described below.
Class description:
Implements a rotation of a random amount of degrees.
Method signatures and docstrings:
- def __init__(self, angle_choices: Sequence[float]=None, angle_sampler_prob: Sequence[float]=None, rotator_kwargs: Dict=None) -> None: Creates a ra... | Implement the Python class `RandomRotateXForm` described below.
Class description:
Implements a rotation of a random amount of degrees.
Method signatures and docstrings:
- def __init__(self, angle_choices: Sequence[float]=None, angle_sampler_prob: Sequence[float]=None, rotator_kwargs: Dict=None) -> None: Creates a ra... | 6ee5912f1fa57f49a4dd4feeeaf7862153bb6a9f | <|skeleton|>
class RandomRotateXForm:
"""Implements a rotation of a random amount of degrees."""
def __init__(self, angle_choices: Sequence[float]=None, angle_sampler_prob: Sequence[float]=None, rotator_kwargs: Dict=None) -> None:
"""Creates a random rotator Transform object :param angle_choices: An Se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomRotateXForm:
"""Implements a rotation of a random amount of degrees."""
def __init__(self, angle_choices: Sequence[float]=None, angle_sampler_prob: Sequence[float]=None, rotator_kwargs: Dict=None) -> None:
"""Creates a random rotator Transform object :param angle_choices: An Sequence object... | the_stack_v2_python_sparse | trojai/trojai/datagen/image_affine_xforms.py | ionutmodo/TrojAI-UMD | train | 1 |
98c401d52db430c169cb8443bae59b0afb50a6c4 | [
"len_nums = len(nums)\nif not (0 <= start < len_nums and 0 <= end < len_nums):\n return\nwhile start < end:\n nums[start], nums[end] = (nums[end], nums[start])\n start += 1\n end -= 1",
"if not nums:\n return\nfor i in range(len(nums) - 2, -2, -1):\n if i >= 0 and nums[i] < nums[i + 1]:\n ... | <|body_start_0|>
len_nums = len(nums)
if not (0 <= start < len_nums and 0 <= end < len_nums):
return
while start < end:
nums[start], nums[end] = (nums[end], nums[start])
start += 1
end -= 1
<|end_body_0|>
<|body_start_1|>
if not nums:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, nums, start, end):
""":param nums: list [int] :param start: int :param end: int :return: None"""
<|body_0|>
def nextPermutation(self, nums):
""":type nums: list [int] :rtype: void Do not return anything, modify nums in-place instead."""
... | stack_v2_sparse_classes_75kplus_train_004544 | 1,956 | no_license | [
{
"docstring": ":param nums: list [int] :param start: int :param end: int :return: None",
"name": "reverse",
"signature": "def reverse(self, nums, start, end)"
},
{
"docstring": ":type nums: list [int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "nextPermutat... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, nums, start, end): :param nums: list [int] :param start: int :param end: int :return: None
- def nextPermutation(self, nums): :type nums: list [int] :rtype: voi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, nums, start, end): :param nums: list [int] :param start: int :param end: int :return: None
- def nextPermutation(self, nums): :type nums: list [int] :rtype: voi... | f8f3b0cdb47ee6bb4bf9bdc7c2a983f4a882d9dd | <|skeleton|>
class Solution:
def reverse(self, nums, start, end):
""":param nums: list [int] :param start: int :param end: int :return: None"""
<|body_0|>
def nextPermutation(self, nums):
""":type nums: list [int] :rtype: void Do not return anything, modify nums in-place instead."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverse(self, nums, start, end):
""":param nums: list [int] :param start: int :param end: int :return: None"""
len_nums = len(nums)
if not (0 <= start < len_nums and 0 <= end < len_nums):
return
while start < end:
nums[start], nums[end] = (... | the_stack_v2_python_sparse | solutions/031-next-permutation/main.py | CallMeNP/leetcode | train | 0 | |
f86afad4b5d34211e634268527d1b9030f17525f | [
"\"\"\"\n torch.Size([3, 500, 500]) torch.Size([4])\n \"\"\"\nimage = Image(t[0].float().clamp(min=0, max=1))\nbboxes = rois2bboxes(t[1].view(-1, 4).tolist())\nif len(bboxes) <= len(self.classes):\n labels = list(range(len(bboxes)))\nelse:\n labels = [1] * len(bboxes)\nimageBBox = ImageBBox.crea... | <|body_start_0|>
"""
torch.Size([3, 500, 500]) torch.Size([4])
"""
image = Image(t[0].float().clamp(min=0, max=1))
bboxes = rois2bboxes(t[1].view(-1, 4).tolist())
if len(bboxes) <= len(self.classes):
labels = list(range(len(bboxes)))
el... | ImageRoisList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageRoisList:
def reconstruct(self, t: Tensor):
"""Reconstruct one of the underlying item for its data `t`."""
<|body_0|>
def show_xys(self, xs, ys, imgsize: int=4, figsize: Optional[Tuple[int, int]]=None, **kwargs):
"""Show the `xs` and `ys` on a figure of `figsize... | stack_v2_sparse_classes_75kplus_train_004545 | 4,547 | permissive | [
{
"docstring": "Reconstruct one of the underlying item for its data `t`.",
"name": "reconstruct",
"signature": "def reconstruct(self, t: Tensor)"
},
{
"docstring": "Show the `xs` and `ys` on a figure of `figsize`. `kwargs` are passed to the show method.",
"name": "show_xys",
"signature":... | 2 | null | Implement the Python class `ImageRoisList` described below.
Class description:
Implement the ImageRoisList class.
Method signatures and docstrings:
- def reconstruct(self, t: Tensor): Reconstruct one of the underlying item for its data `t`.
- def show_xys(self, xs, ys, imgsize: int=4, figsize: Optional[Tuple[int, int... | Implement the Python class `ImageRoisList` described below.
Class description:
Implement the ImageRoisList class.
Method signatures and docstrings:
- def reconstruct(self, t: Tensor): Reconstruct one of the underlying item for its data `t`.
- def show_xys(self, xs, ys, imgsize: int=4, figsize: Optional[Tuple[int, int... | 8ce4fb86d17fdda4d692ac692c70ba449b1c7d42 | <|skeleton|>
class ImageRoisList:
def reconstruct(self, t: Tensor):
"""Reconstruct one of the underlying item for its data `t`."""
<|body_0|>
def show_xys(self, xs, ys, imgsize: int=4, figsize: Optional[Tuple[int, int]]=None, **kwargs):
"""Show the `xs` and `ys` on a figure of `figsize... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageRoisList:
def reconstruct(self, t: Tensor):
"""Reconstruct one of the underlying item for its data `t`."""
"""
torch.Size([3, 500, 500]) torch.Size([4])
"""
image = Image(t[0].float().clamp(min=0, max=1))
bboxes = rois2bboxes(t[1].view(-1, 4... | the_stack_v2_python_sparse | app/fastiqa/models/bunches/_rois.py | baidut/google-app-engine | train | 0 | |
a2e1ee8b35aaffa56758f3e39e10f81d8660b4bd | [
"self.SetStartDate(2013, 10, 7)\nself.SetEndDate(2013, 10, 8)\nself.AddEquity('SPY', Resolution.Minute)",
"try:\n self.MarketOrder('PEPE', 1)\nexcept Exception as exception:\n if 'This asset symbol (PEPE 0) was not found in your security list' in str(exception) and (not self.Portfolio.Invested):\n se... | <|body_start_0|>
self.SetStartDate(2013, 10, 7)
self.SetEndDate(2013, 10, 8)
self.AddEquity('SPY', Resolution.Minute)
<|end_body_0|>
<|body_start_1|>
try:
self.MarketOrder('PEPE', 1)
except Exception as exception:
if 'This asset symbol (PEPE 0) was not fo... | StringToSymbolImplicitConversionRegressionAlgorithm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringToSymbolImplicitConversionRegressionAlgorithm:
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
<|body_0|>
def OnData(self, data):
"""OnData eve... | stack_v2_sparse_classes_75kplus_train_004546 | 1,785 | permissive | [
{
"docstring": "Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.",
"name": "Initialize",
"signature": "def Initialize(self)"
},
{
"docstring": "OnData event is the primary entry point for your algorithm. Eac... | 2 | stack_v2_sparse_classes_30k_train_046793 | Implement the Python class `StringToSymbolImplicitConversionRegressionAlgorithm` described below.
Class description:
Implement the StringToSymbolImplicitConversionRegressionAlgorithm class.
Method signatures and docstrings:
- def Initialize(self): Initialise the data and resolution required, as well as the cash and s... | Implement the Python class `StringToSymbolImplicitConversionRegressionAlgorithm` described below.
Class description:
Implement the StringToSymbolImplicitConversionRegressionAlgorithm class.
Method signatures and docstrings:
- def Initialize(self): Initialise the data and resolution required, as well as the cash and s... | b33dd3bc140e14b883f39ecf848a793cf7292277 | <|skeleton|>
class StringToSymbolImplicitConversionRegressionAlgorithm:
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
<|body_0|>
def OnData(self, data):
"""OnData eve... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StringToSymbolImplicitConversionRegressionAlgorithm:
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
self.SetStartDate(2013, 10, 7)
self.SetEndDate(2013, 10, 8)
... | the_stack_v2_python_sparse | Algorithm.Python/StringToSymbolImplicitConversionRegressionAlgorithm.py | Capnode/Algoloop | train | 87 | |
4936a2bca30e380eac8ee5bc04d8dff16e5bae85 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn PstnCallLogRow()",
"from .pstn_call_duration_source import PstnCallDurationSource\nfrom .pstn_call_duration_source import PstnCallDurationSource\nfields: Dict[str, Callable[[Any], None]] = {'callDurationSource': lambda n: setattr(self,... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return PstnCallLogRow()
<|end_body_0|>
<|body_start_1|>
from .pstn_call_duration_source import PstnCallDurationSource
from .pstn_call_duration_source import PstnCallDurationSource
field... | PstnCallLogRow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PstnCallLogRow:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PstnCallLogRow:
"""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 Retur... | stack_v2_sparse_classes_75kplus_train_004547 | 8,993 | 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: PstnCallLogRow",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | stack_v2_sparse_classes_30k_train_025212 | Implement the Python class `PstnCallLogRow` described below.
Class description:
Implement the PstnCallLogRow class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PstnCallLogRow: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `PstnCallLogRow` described below.
Class description:
Implement the PstnCallLogRow class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PstnCallLogRow: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class PstnCallLogRow:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PstnCallLogRow:
"""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 Retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PstnCallLogRow:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PstnCallLogRow:
"""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: PstnCallLo... | the_stack_v2_python_sparse | msgraph/generated/models/call_records/pstn_call_log_row.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
04cd1062501b8e58434ec630024d07f1899addaf | [
"projects = proj_dao.ProjectDao(self.global_configs).get_projects(self.cycle_timestamp)\nke_services = {}\nfor project in projects:\n clusters = self.safe_api_call('get_clusters', project.id)\n if clusters:\n for cluster in clusters:\n self_link_parts = cluster.get('selfLink').split('/')\n ... | <|body_start_0|>
projects = proj_dao.ProjectDao(self.global_configs).get_projects(self.cycle_timestamp)
ke_services = {}
for project in projects:
clusters = self.safe_api_call('get_clusters', project.id)
if clusters:
for cluster in clusters:
... | Load all KE services for all projects. | LoadKePipeline | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadKePipeline:
"""Load all KE services for all projects."""
def _retrieve(self):
"""Retrieve KE data from GCP. Get all the projects in the current snapshot and retrieve the the clusters for each project. For each distinct zone in cluster, get the server config. server_config data wi... | stack_v2_sparse_classes_75kplus_train_004548 | 5,909 | permissive | [
{
"docstring": "Retrieve KE data from GCP. Get all the projects in the current snapshot and retrieve the the clusters for each project. For each distinct zone in cluster, get the server config. server_config data will be incorporated into the cluster data as there is a 1:1 relationship, which saves adding anoth... | 3 | null | Implement the Python class `LoadKePipeline` described below.
Class description:
Load all KE services for all projects.
Method signatures and docstrings:
- def _retrieve(self): Retrieve KE data from GCP. Get all the projects in the current snapshot and retrieve the the clusters for each project. For each distinct zone... | Implement the Python class `LoadKePipeline` described below.
Class description:
Load all KE services for all projects.
Method signatures and docstrings:
- def _retrieve(self): Retrieve KE data from GCP. Get all the projects in the current snapshot and retrieve the the clusters for each project. For each distinct zone... | a6a1aa7464cda2ad5948e3e8876eb8dded5e2514 | <|skeleton|>
class LoadKePipeline:
"""Load all KE services for all projects."""
def _retrieve(self):
"""Retrieve KE data from GCP. Get all the projects in the current snapshot and retrieve the the clusters for each project. For each distinct zone in cluster, get the server config. server_config data wi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoadKePipeline:
"""Load all KE services for all projects."""
def _retrieve(self):
"""Retrieve KE data from GCP. Get all the projects in the current snapshot and retrieve the the clusters for each project. For each distinct zone in cluster, get the server config. server_config data will be incorpo... | the_stack_v2_python_sparse | google/cloud/security/inventory/pipelines/load_ke_pipeline.py | shimizu19691210/forseti-security | train | 1 |
9fbc04645e7c1da04d6d95cdf3bbd7a4f983a8c9 | [
"A = strs\nm, n = (len(A), len(A[0]))\nres, k = (n - 1, 0)\ndp = [1] * n\nfor i in range(1, n):\n for j in range(i):\n for k in range(m):\n if A[k][j] > A[k][i]:\n break\n else:\n if dp[j] + 1 > dp[i]:\n dp[i] = dp[j] + 1\nreturn n - max(dp)",
"... | <|body_start_0|>
A = strs
m, n = (len(A), len(A[0]))
res, k = (n - 1, 0)
dp = [1] * n
for i in range(1, n):
for j in range(i):
for k in range(m):
if A[k][j] > A[k][i]:
break
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDeletionSizeAC(self, strs):
""":type strs: List[str] :rtype: int"""
<|body_0|>
def minDeletionSize(self, strs):
""":type strs: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
A = strs
m, n = (len(A), le... | stack_v2_sparse_classes_75kplus_train_004549 | 2,477 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: int",
"name": "minDeletionSizeAC",
"signature": "def minDeletionSizeAC(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: int",
"name": "minDeletionSize",
"signature": "def minDeletionSize(self, strs)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDeletionSizeAC(self, strs): :type strs: List[str] :rtype: int
- def minDeletionSize(self, strs): :type strs: List[str] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDeletionSizeAC(self, strs): :type strs: List[str] :rtype: int
- def minDeletionSize(self, strs): :type strs: List[str] :rtype: int
<|skeleton|>
class Solution:
def m... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def minDeletionSizeAC(self, strs):
""":type strs: List[str] :rtype: int"""
<|body_0|>
def minDeletionSize(self, strs):
""":type strs: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minDeletionSizeAC(self, strs):
""":type strs: List[str] :rtype: int"""
A = strs
m, n = (len(A), len(A[0]))
res, k = (n - 1, 0)
dp = [1] * n
for i in range(1, n):
for j in range(i):
for k in range(m):
... | the_stack_v2_python_sparse | D/DeleteColumnstoMakeSortedIII.py | bssrdf/pyleet | train | 2 | |
9add2994c216d3991e2479738ae86904b12ef61c | [
"ref_match = [s for s in re.findall(regexp, '\\n'.join(ref_out)) if s != '']\nstu_match = [s for s in re.findall(regexp, '\\n'.join(stu_out)) if s != '']\nref_tree = self.toTree(ref_match)\nstu_tree = self.toTree(stu_match)\nassert ref_tree is not None, 'Parse ref tree error'\nif stu_tree is not None and self.toStr... | <|body_start_0|>
ref_match = [s for s in re.findall(regexp, '\n'.join(ref_out)) if s != '']
stu_match = [s for s in re.findall(regexp, '\n'.join(stu_out)) if s != '']
ref_tree = self.toTree(ref_match)
stu_tree = self.toTree(stu_match)
assert ref_tree is not None, 'Parse ref tree ... | TreeStructCmp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeStructCmp:
def cmpCmd(self, ref_out, stu_out, regexp='.*'):
"""Compare ref output and student output. Args: ref_out: Ref output in list of strings. stu_out: Student output in list of strings. regexp: Regular expression for filtering. Returns: Tuple (1, 0, stat.STAT_OK) if the filtere... | stack_v2_sparse_classes_75kplus_train_004550 | 2,468 | no_license | [
{
"docstring": "Compare ref output and student output. Args: ref_out: Ref output in list of strings. stu_out: Student output in list of strings. regexp: Regular expression for filtering. Returns: Tuple (1, 0, stat.STAT_OK) if the filtered ref_out and stu_out has the same tree structure, otherwise return (0, 0, ... | 5 | stack_v2_sparse_classes_30k_test_001221 | Implement the Python class `TreeStructCmp` described below.
Class description:
Implement the TreeStructCmp class.
Method signatures and docstrings:
- def cmpCmd(self, ref_out, stu_out, regexp='.*'): Compare ref output and student output. Args: ref_out: Ref output in list of strings. stu_out: Student output in list of... | Implement the Python class `TreeStructCmp` described below.
Class description:
Implement the TreeStructCmp class.
Method signatures and docstrings:
- def cmpCmd(self, ref_out, stu_out, regexp='.*'): Compare ref output and student output. Args: ref_out: Ref output in list of strings. stu_out: Student output in list of... | c0a8bd1244a3bff5b7152f660f4c77c937c514d8 | <|skeleton|>
class TreeStructCmp:
def cmpCmd(self, ref_out, stu_out, regexp='.*'):
"""Compare ref output and student output. Args: ref_out: Ref output in list of strings. stu_out: Student output in list of strings. regexp: Regular expression for filtering. Returns: Tuple (1, 0, stat.STAT_OK) if the filtere... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TreeStructCmp:
def cmpCmd(self, ref_out, stu_out, regexp='.*'):
"""Compare ref output and student output. Args: ref_out: Ref output in list of strings. stu_out: Student output in list of strings. regexp: Regular expression for filtering. Returns: Tuple (1, 0, stat.STAT_OK) if the filtered ref_out and ... | the_stack_v2_python_sparse | py/compare/functions/treestruct.py | music960633/DSnP_grading | train | 8 | |
3c86df6f985efacce7b89b8d0d6690c892f8b459 | [
"animals = ['cat', 'dog', 'cog dat', 'moose']\ncorrect_solution = [('cat', 'dog', 'cog dat')]\ns = SpooningAnimalsSolver('Simple Test', verbose=False)\nself.assertEqual(correct_solution, s.solve(animals=animals))",
"animals = ['phoenix', 'squirrel', 'phuirrel sqoenix', 'horse']\ncorrect_solution = [('phoenix', 's... | <|body_start_0|>
animals = ['cat', 'dog', 'cog dat', 'moose']
correct_solution = [('cat', 'dog', 'cog dat')]
s = SpooningAnimalsSolver('Simple Test', verbose=False)
self.assertEqual(correct_solution, s.solve(animals=animals))
<|end_body_0|>
<|body_start_1|>
animals = ['phoenix',... | TestAnimals | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnimals:
def test_simple(self):
"""Test to switch first consonant letters"""
<|body_0|>
def test_hard(self):
"""Test to switch first sounds"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
animals = ['cat', 'dog', 'cog dat', 'moose']
corr... | stack_v2_sparse_classes_75kplus_train_004551 | 872 | permissive | [
{
"docstring": "Test to switch first consonant letters",
"name": "test_simple",
"signature": "def test_simple(self)"
},
{
"docstring": "Test to switch first sounds",
"name": "test_hard",
"signature": "def test_hard(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041147 | Implement the Python class `TestAnimals` described below.
Class description:
Implement the TestAnimals class.
Method signatures and docstrings:
- def test_simple(self): Test to switch first consonant letters
- def test_hard(self): Test to switch first sounds | Implement the Python class `TestAnimals` described below.
Class description:
Implement the TestAnimals class.
Method signatures and docstrings:
- def test_simple(self): Test to switch first consonant letters
- def test_hard(self): Test to switch first sounds
<|skeleton|>
class TestAnimals:
def test_simple(self)... | c84c1b51d83c7e780430175e41588632441aa180 | <|skeleton|>
class TestAnimals:
def test_simple(self):
"""Test to switch first consonant letters"""
<|body_0|>
def test_hard(self):
"""Test to switch first sounds"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAnimals:
def test_simple(self):
"""Test to switch first consonant letters"""
animals = ['cat', 'dog', 'cog dat', 'moose']
correct_solution = [('cat', 'dog', 'cog dat')]
s = SpooningAnimalsSolver('Simple Test', verbose=False)
self.assertEqual(correct_solution, s.solv... | the_stack_v2_python_sparse | solutions/20150802/test_spooning_animals.py | johnobrien/pyshortz | train | 0 | |
78e5409add72f1ae97417a4b3d4b401c9ddd9989 | [
"Frame.__init__(self, master)\nself.master.rowconfigure(0, weight=1)\nself.master.columnconfigure(0, weight=1)\nself.grid(sticky=N + S + E + W)\nl0 = Label(self, text='Email Database Search', font=('Helvetica', 16))\nl0.grid(row=0, column=1, columnspan=2)\nl1 = Label(self, text='Not Before (yyy-mm-dd):')\nl1.grid(r... | <|body_start_0|>
Frame.__init__(self, master)
self.master.rowconfigure(0, weight=1)
self.master.columnconfigure(0, weight=1)
self.grid(sticky=N + S + E + W)
l0 = Label(self, text='Email Database Search', font=('Helvetica', 16))
l0.grid(row=0, column=1, columnspan=2)
... | Create window app signature | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Create window app signature"""
def __init__(self, master=None):
"""Establish the window structure, leaving some widgets accessible as app instance variables. Connect button clicks to search_mail method and subject double-clicks to display_mail method."""
<|bod... | stack_v2_sparse_classes_75kplus_train_004552 | 5,775 | no_license | [
{
"docstring": "Establish the window structure, leaving some widgets accessible as app instance variables. Connect button clicks to search_mail method and subject double-clicks to display_mail method.",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Take th... | 3 | stack_v2_sparse_classes_30k_train_003295 | Implement the Python class `Application` described below.
Class description:
Create window app signature
Method signatures and docstrings:
- def __init__(self, master=None): Establish the window structure, leaving some widgets accessible as app instance variables. Connect button clicks to search_mail method and subje... | Implement the Python class `Application` described below.
Class description:
Create window app signature
Method signatures and docstrings:
- def __init__(self, master=None): Establish the window structure, leaving some widgets accessible as app instance variables. Connect button clicks to search_mail method and subje... | 06c45545ed064d0e9c4fd15cc81cf454cb079c9d | <|skeleton|>
class Application:
"""Create window app signature"""
def __init__(self, master=None):
"""Establish the window structure, leaving some widgets accessible as app instance variables. Connect button clicks to search_mail method and subject double-clicks to display_mail method."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""Create window app signature"""
def __init__(self, master=None):
"""Establish the window structure, leaving some widgets accessible as app instance variables. Connect button clicks to search_mail method and subject double-clicks to display_mail method."""
Frame.__init__(sel... | the_stack_v2_python_sparse | Lesson 13 - Email Search and Display/mailgui.py | jmwoloso/Python_2 | train | 0 |
d49c8f41c53fdaaab953182b00271307ac4a2fd3 | [
"DriftTEAPOT.__init__(self, name)\nself.kicker = XKicker(bunch, kx, waveform)\nself.setType('XKicker')\nself.setLength(0.0)",
"length = self.getLength(self.getActivePartIndex())\nbunch = paramsDict['bunch']\nself.kicker.kick()"
] | <|body_start_0|>
DriftTEAPOT.__init__(self, name)
self.kicker = XKicker(bunch, kx, waveform)
self.setType('XKicker')
self.setLength(0.0)
<|end_body_0|>
<|body_start_1|>
length = self.getLength(self.getActivePartIndex())
bunch = paramsDict['bunch']
self.kicker.kic... | The kicker node class for TEAPOT lattice | TeapotXKickerNode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeapotXKickerNode:
"""The kicker node class for TEAPOT lattice"""
def __init__(self, bunch, kx, waveform, name='kicker'):
"""Constructor. Creates the Kicker TEAPOT element."""
<|body_0|>
def track(self, paramsDict):
"""The kicker-teapot class implementation of th... | stack_v2_sparse_classes_75kplus_train_004553 | 1,695 | permissive | [
{
"docstring": "Constructor. Creates the Kicker TEAPOT element.",
"name": "__init__",
"signature": "def __init__(self, bunch, kx, waveform, name='kicker')"
},
{
"docstring": "The kicker-teapot class implementation of the AccNodeBunchTracker class track(probe) method.",
"name": "track",
"... | 2 | stack_v2_sparse_classes_30k_train_025240 | Implement the Python class `TeapotXKickerNode` described below.
Class description:
The kicker node class for TEAPOT lattice
Method signatures and docstrings:
- def __init__(self, bunch, kx, waveform, name='kicker'): Constructor. Creates the Kicker TEAPOT element.
- def track(self, paramsDict): The kicker-teapot class... | Implement the Python class `TeapotXKickerNode` described below.
Class description:
The kicker node class for TEAPOT lattice
Method signatures and docstrings:
- def __init__(self, bunch, kx, waveform, name='kicker'): Constructor. Creates the Kicker TEAPOT element.
- def track(self, paramsDict): The kicker-teapot class... | 3c193f6dd3f8a9d6a35db67b055f1bb3c0788360 | <|skeleton|>
class TeapotXKickerNode:
"""The kicker node class for TEAPOT lattice"""
def __init__(self, bunch, kx, waveform, name='kicker'):
"""Constructor. Creates the Kicker TEAPOT element."""
<|body_0|>
def track(self, paramsDict):
"""The kicker-teapot class implementation of th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeapotXKickerNode:
"""The kicker node class for TEAPOT lattice"""
def __init__(self, bunch, kx, waveform, name='kicker'):
"""Constructor. Creates the Kicker TEAPOT element."""
DriftTEAPOT.__init__(self, name)
self.kicker = XKicker(bunch, kx, waveform)
self.setType('XKicker... | the_stack_v2_python_sparse | py/orbit/kickernodes/TeapotKickerNode.py | shishlo/py-orbit | train | 0 |
0baed6a93a2775d3ff999f532afd4ac9be0bc929 | [
"reply = await message.get_reply_message()\nif not reply or not reply.message:\n await message.edit('<b>Reply to text!</b>')\n return\ntext = bytes(reply.raw_text, 'utf8')\nfname = utils.get_args_raw(message) or str(message.id + reply.id) + '.txt'\nfile = io.BytesIO(text)\nfile.name = fname\nfile.seek(0)\nawa... | <|body_start_0|>
reply = await message.get_reply_message()
if not reply or not reply.message:
await message.edit('<b>Reply to text!</b>')
return
text = bytes(reply.raw_text, 'utf8')
fname = utils.get_args_raw(message) or str(message.id + reply.id) + '.txt'
... | send Message file | MessageFMod | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageFMod:
"""send Message file"""
async def filecmd(self, message):
""".file <reply to text>"""
<|body_0|>
async def kodcmd(self, message):
""".kod <reply to file>"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
reply = await message.get_repl... | stack_v2_sparse_classes_75kplus_train_004554 | 1,014 | no_license | [
{
"docstring": ".file <reply to text>",
"name": "filecmd",
"signature": "async def filecmd(self, message)"
},
{
"docstring": ".kod <reply to file>",
"name": "kodcmd",
"signature": "async def kodcmd(self, message)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044081 | Implement the Python class `MessageFMod` described below.
Class description:
send Message file
Method signatures and docstrings:
- async def filecmd(self, message): .file <reply to text>
- async def kodcmd(self, message): .kod <reply to file> | Implement the Python class `MessageFMod` described below.
Class description:
send Message file
Method signatures and docstrings:
- async def filecmd(self, message): .file <reply to text>
- async def kodcmd(self, message): .kod <reply to file>
<|skeleton|>
class MessageFMod:
"""send Message file"""
async def... | 8f5c8d7e1f9a03789342580353c536cc50ee6d16 | <|skeleton|>
class MessageFMod:
"""send Message file"""
async def filecmd(self, message):
""".file <reply to text>"""
<|body_0|>
async def kodcmd(self, message):
""".kod <reply to file>"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MessageFMod:
"""send Message file"""
async def filecmd(self, message):
""".file <reply to text>"""
reply = await message.get_reply_message()
if not reply or not reply.message:
await message.edit('<b>Reply to text!</b>')
return
text = bytes(reply.raw... | the_stack_v2_python_sparse | MessageFMod.py | Stanislav2908/ftg-modules | train | 2 |
89f6cd86b76cf6046fe2e7d27a678da1b771d5f9 | [
"rarity_icon = ''\nif rarity == 0:\n rarity_icon = game_icon['n']\n return rarity_icon\nif rarity == 1:\n rarity_icon = game_icon['r']\n return rarity_icon\nif rarity == 2:\n rarity_icon = game_icon['sr']\n return rarity_icon\nif rarity == 3:\n rarity_icon = game_icon['ssr']\n return rarity_... | <|body_start_0|>
rarity_icon = ''
if rarity == 0:
rarity_icon = game_icon['n']
return rarity_icon
if rarity == 1:
rarity_icon = game_icon['r']
return rarity_icon
if rarity == 2:
rarity_icon = game_icon['sr']
return r... | Manages the displaying of most of the game icons. - Parameter : - Attribute : - Method : :coro:`get_rarity_icon(rarity : int)` : Convert the rarity into the discord.Emoji icon :coro:`get_type_icon(type : int)` : Convert the type icon the discord.Emoji icon | Icon_displayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Icon_displayer:
"""Manages the displaying of most of the game icons. - Parameter : - Attribute : - Method : :coro:`get_rarity_icon(rarity : int)` : Convert the rarity into the discord.Emoji icon :coro:`get_type_icon(type : int)` : Convert the type icon the discord.Emoji icon"""
async def get... | stack_v2_sparse_classes_75kplus_train_004555 | 2,522 | permissive | [
{
"docstring": "`couroutine` Convert the icon id into the discord.Emoji -- Return : discord.Emoji",
"name": "get_rarity_icon",
"signature": "async def get_rarity_icon(self, rarity: int)"
},
{
"docstring": "`coroutine` Convert the type into the discord.Emoji icon -- Return : discord.Emoji",
"... | 2 | stack_v2_sparse_classes_30k_test_000325 | Implement the Python class `Icon_displayer` described below.
Class description:
Manages the displaying of most of the game icons. - Parameter : - Attribute : - Method : :coro:`get_rarity_icon(rarity : int)` : Convert the rarity into the discord.Emoji icon :coro:`get_type_icon(type : int)` : Convert the type icon the d... | Implement the Python class `Icon_displayer` described below.
Class description:
Manages the displaying of most of the game icons. - Parameter : - Attribute : - Method : :coro:`get_rarity_icon(rarity : int)` : Convert the rarity into the discord.Emoji icon :coro:`get_type_icon(type : int)` : Convert the type icon the d... | ada6456f434df19c74a30ec8ae5b7de248d8f79c | <|skeleton|>
class Icon_displayer:
"""Manages the displaying of most of the game icons. - Parameter : - Attribute : - Method : :coro:`get_rarity_icon(rarity : int)` : Convert the rarity into the discord.Emoji icon :coro:`get_type_icon(type : int)` : Convert the type icon the discord.Emoji icon"""
async def get... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Icon_displayer:
"""Manages the displaying of most of the game icons. - Parameter : - Attribute : - Method : :coro:`get_rarity_icon(rarity : int)` : Convert the rarity into the discord.Emoji icon :coro:`get_type_icon(type : int)` : Convert the type icon the discord.Emoji icon"""
async def get_rarity_icon(... | the_stack_v2_python_sparse | utility/cog/displayer/icon.py | RvstFyth/discordballz | train | 0 |
29c1ba95c190ecd19993a4e2eb4a14cbdd3a08ea | [
"requesting_user = self.context['requesting_user']\nrequested_user = self.context['requested_user']\nif requesting_user == requested_user:\n raise serializers.ValidationError(\"You can't send friend request to yourself.\")\nif requesting_user.profile in requested_user.friends.all():\n raise serializers.Valida... | <|body_start_0|>
requesting_user = self.context['requesting_user']
requested_user = self.context['requested_user']
if requesting_user == requested_user:
raise serializers.ValidationError("You can't send friend request to yourself.")
if requesting_user.profile in requested_use... | Friend request model serializer. | FriendRequestModelSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FriendRequestModelSerializer:
"""Friend request model serializer."""
def validate(self, data):
"""Verify friend request"""
<|body_0|>
def create(self, data):
"""Create a friend's request."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
requestin... | stack_v2_sparse_classes_75kplus_train_004556 | 3,697 | no_license | [
{
"docstring": "Verify friend request",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Create a friend's request.",
"name": "create",
"signature": "def create(self, data)"
}
] | 2 | null | Implement the Python class `FriendRequestModelSerializer` described below.
Class description:
Friend request model serializer.
Method signatures and docstrings:
- def validate(self, data): Verify friend request
- def create(self, data): Create a friend's request. | Implement the Python class `FriendRequestModelSerializer` described below.
Class description:
Friend request model serializer.
Method signatures and docstrings:
- def validate(self, data): Verify friend request
- def create(self, data): Create a friend's request.
<|skeleton|>
class FriendRequestModelSerializer:
... | fae5c0b2e388239e2e32a3fbf52aa7cfd48a7cbb | <|skeleton|>
class FriendRequestModelSerializer:
"""Friend request model serializer."""
def validate(self, data):
"""Verify friend request"""
<|body_0|>
def create(self, data):
"""Create a friend's request."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FriendRequestModelSerializer:
"""Friend request model serializer."""
def validate(self, data):
"""Verify friend request"""
requesting_user = self.context['requesting_user']
requested_user = self.context['requested_user']
if requesting_user == requested_user:
ra... | the_stack_v2_python_sparse | facebook/app/users/serializers/friend_requests.py | ricagome/Api-Facebook-Clone | train | 0 |
600020798a8c754992643c362a952a21f48902b1 | [
"if node is None:\n return\nnode.parent = parent\nself._dfs(node.left, node)\nself._dfs(node.right, node)",
"if node is None:\n return []\nif K == 0:\n return [node.val]\nres = []\nnode_list = [node.left, node.right, node.parent]\nfor i_node in node_list:\n if i_node != from_node:\n res += self... | <|body_start_0|>
if node is None:
return
node.parent = parent
self._dfs(node.left, node)
self._dfs(node.right, node)
<|end_body_0|>
<|body_start_1|>
if node is None:
return []
if K == 0:
return [node.val]
res = []
node_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _dfs(self, node, parent):
""":param node: TreeNode :param parent: TreeNode :return: void"""
<|body_0|>
def _bfs(self, node, from_node, K):
""":param node: :param from_node: :param K: :return:"""
<|body_1|>
def distanceK(self, root, target, ... | stack_v2_sparse_classes_75kplus_train_004557 | 4,964 | no_license | [
{
"docstring": ":param node: TreeNode :param parent: TreeNode :return: void",
"name": "_dfs",
"signature": "def _dfs(self, node, parent)"
},
{
"docstring": ":param node: :param from_node: :param K: :return:",
"name": "_bfs",
"signature": "def _bfs(self, node, from_node, K)"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _dfs(self, node, parent): :param node: TreeNode :param parent: TreeNode :return: void
- def _bfs(self, node, from_node, K): :param node: :param from_node: :param K: :return:
... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _dfs(self, node, parent): :param node: TreeNode :param parent: TreeNode :return: void
- def _bfs(self, node, from_node, K): :param node: :param from_node: :param K: :return:
... | 3b11b7cef3a9f6a97cd63b5f019d0a391e54aea6 | <|skeleton|>
class Solution:
def _dfs(self, node, parent):
""":param node: TreeNode :param parent: TreeNode :return: void"""
<|body_0|>
def _bfs(self, node, from_node, K):
""":param node: :param from_node: :param K: :return:"""
<|body_1|>
def distanceK(self, root, target, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _dfs(self, node, parent):
""":param node: TreeNode :param parent: TreeNode :return: void"""
if node is None:
return
node.parent = parent
self._dfs(node.left, node)
self._dfs(node.right, node)
def _bfs(self, node, from_node, K):
"""... | the_stack_v2_python_sparse | leetcode/src/p863AllNodesDistanceKinBinaryTree/solution.py | yunfanLu/LeetCode | train | 1 | |
a6c1d14811b6753f1cfe0be226e1d62c1cb6b47f | [
"res = []\nif not intervals or len(intervals) == 0:\n return res\nintervals.sort(key=lambda x: x.start)\nlow, hi = (intervals[0].start, intervals[0].end)\nfor interval in intervals[1:]:\n if interval.start <= hi:\n if hi <= interval.end:\n hi = interval.end\n else:\n res.append(Int... | <|body_start_0|>
res = []
if not intervals or len(intervals) == 0:
return res
intervals.sort(key=lambda x: x.start)
low, hi = (intervals[0].start, intervals[0].end)
for interval in intervals[1:]:
if interval.start <= hi:
if hi <= interval.e... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge1(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_0|>
def merge(self, intervals):
"""Using last interval comparison method. :param intervals: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_004558 | 1,593 | no_license | [
{
"docstring": ":type intervals: List[Interval] :rtype: List[Interval]",
"name": "merge1",
"signature": "def merge1(self, intervals)"
},
{
"docstring": "Using last interval comparison method. :param intervals: :return:",
"name": "merge",
"signature": "def merge(self, intervals)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031288 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge1(self, intervals): :type intervals: List[Interval] :rtype: List[Interval]
- def merge(self, intervals): Using last interval comparison method. :param intervals: :return... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge1(self, intervals): :type intervals: List[Interval] :rtype: List[Interval]
- def merge(self, intervals): Using last interval comparison method. :param intervals: :return... | 11d6bf2ba7b50c07e048df37c4e05c8f46b92241 | <|skeleton|>
class Solution:
def merge1(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_0|>
def merge(self, intervals):
"""Using last interval comparison method. :param intervals: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def merge1(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
res = []
if not intervals or len(intervals) == 0:
return res
intervals.sort(key=lambda x: x.start)
low, hi = (intervals[0].start, intervals[0].end)
fo... | the_stack_v2_python_sparse | LeetCodes/facebook/MergeIntervals.py | chutianwen/LeetCodes | train | 0 | |
f82e9296841f43adeadcc36a1c3e3c04cc910179 | [
"with tempfile.NamedTemporaryFile(suffix='.ipynb') as tmp_notebook:\n args = ['jupyter', 'nbconvert', '--to', 'notebook', '--execute', '--ExecutePreprocessor.timeout=3600', '--output', tmp_notebook.name, path]\n subprocess.check_call(args)\n tmp_notebook.seek(0)\n return nbformat.read(tmp_notebook, nbfo... | <|body_start_0|>
with tempfile.NamedTemporaryFile(suffix='.ipynb') as tmp_notebook:
args = ['jupyter', 'nbconvert', '--to', 'notebook', '--execute', '--ExecutePreprocessor.timeout=3600', '--output', tmp_notebook.name, path]
subprocess.check_call(args)
tmp_notebook.seek(0)
... | TestNotebookConsistency | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNotebookConsistency:
def _execute_notebook(path):
"""Execute a Jupyter Notebook from scratch and convert it into another Jupyter Notebook. :returns a converted Jupyter Notebook"""
<|body_0|>
def _analise_notebook(notebook):
"""Analise notebook cell outputs. The f... | stack_v2_sparse_classes_75kplus_train_004559 | 3,437 | permissive | [
{
"docstring": "Execute a Jupyter Notebook from scratch and convert it into another Jupyter Notebook. :returns a converted Jupyter Notebook",
"name": "_execute_notebook",
"signature": "def _execute_notebook(path)"
},
{
"docstring": "Analise notebook cell outputs. The function goes through all ce... | 3 | stack_v2_sparse_classes_30k_train_004519 | Implement the Python class `TestNotebookConsistency` described below.
Class description:
Implement the TestNotebookConsistency class.
Method signatures and docstrings:
- def _execute_notebook(path): Execute a Jupyter Notebook from scratch and convert it into another Jupyter Notebook. :returns a converted Jupyter Note... | Implement the Python class `TestNotebookConsistency` described below.
Class description:
Implement the TestNotebookConsistency class.
Method signatures and docstrings:
- def _execute_notebook(path): Execute a Jupyter Notebook from scratch and convert it into another Jupyter Notebook. :returns a converted Jupyter Note... | fc5ac51d5c4c7c313861b9f83a86239335b21ddc | <|skeleton|>
class TestNotebookConsistency:
def _execute_notebook(path):
"""Execute a Jupyter Notebook from scratch and convert it into another Jupyter Notebook. :returns a converted Jupyter Notebook"""
<|body_0|>
def _analise_notebook(notebook):
"""Analise notebook cell outputs. The f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestNotebookConsistency:
def _execute_notebook(path):
"""Execute a Jupyter Notebook from scratch and convert it into another Jupyter Notebook. :returns a converted Jupyter Notebook"""
with tempfile.NamedTemporaryFile(suffix='.ipynb') as tmp_notebook:
args = ['jupyter', 'nbconvert',... | the_stack_v2_python_sparse | quality_test.py | GuillaumeDufau/reco-gym | train | 0 | |
8202b65efd2e9414410d73fc04decc39c5fd5749 | [
"if not graph.is_directed():\n raise ValueError('the graph is not directed')\nself.graph = graph\nself.distance = dict()\nfor source in self.graph.iternodes():\n self.distance[source] = dict()\n for target in self.graph.iternodes():\n self.distance[source][target] = float('inf')\n self.distance[s... | <|body_start_0|>
if not graph.is_directed():
raise ValueError('the graph is not directed')
self.graph = graph
self.distance = dict()
for source in self.graph.iternodes():
self.distance[source] = dict()
for target in self.graph.iternodes():
... | The Floyd-Warshall algorithm (all-pairs shortest paths). Negative cycles are forbidden. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph >>> from graphtheory.shortes... | FloydWarshall | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloydWarshall:
"""The Floyd-Warshall algorithm (all-pairs shortest paths). Negative cycles are forbidden. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs ... | stack_v2_sparse_classes_75kplus_train_004560 | 7,754 | permissive | [
{
"docstring": "The algorithm initialization. Parameters ---------- graph : directed weighted graph",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Finding all shortest paths.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002016 | Implement the Python class `FloydWarshall` described below.
Class description:
The Floyd-Warshall algorithm (all-pairs shortest paths). Negative cycles are forbidden. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge ... | Implement the Python class `FloydWarshall` described below.
Class description:
The Floyd-Warshall algorithm (all-pairs shortest paths). Negative cycles are forbidden. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge ... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class FloydWarshall:
"""The Floyd-Warshall algorithm (all-pairs shortest paths). Negative cycles are forbidden. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FloydWarshall:
"""The Floyd-Warshall algorithm (all-pairs shortest paths). Negative cycles are forbidden. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph ... | the_stack_v2_python_sparse | graphtheory/shortestpaths/floydwarshall.py | kgashok/graphs-dict | train | 0 |
427ea2fdf3aa35130db89821d50825302754d896 | [
"res = []\n\ndef dfs(root):\n if not root:\n res.append('N')\n else:\n res.append(str(root.val))\n dfs(root.left)\n dfs(root.right)\ndfs(root)\nreturn ','.join(res)",
"res = deque(data.split(','))\n\ndef dfs(res):\n if res[0] == 'N':\n res.popleft()\n return None... | <|body_start_0|>
res = []
def dfs(root):
if not root:
res.append('N')
else:
res.append(str(root.val))
dfs(root.left)
dfs(root.right)
dfs(root)
return ','.join(res)
<|end_body_0|>
<|body_start_1|>
... | 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_004561 | 4,525 | 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_038472 | 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:... | 060e809175cff96e91c694b93417c0c1d21719f0 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = []
def dfs(root):
if not root:
res.append('N')
else:
res.append(str(root.val))
dfs(root.left)
... | the_stack_v2_python_sparse | ProgrammingOJ/LeetCode_python/297_二叉树的序列化与反序列化.py | PandoraLS/CodingInterview | train | 2 | |
5b200bed84a3c38dbb7e90eeb52bb2e1ad1a36b7 | [
"if not s:\n return 0\ndp = [0] * (len(s) + 1)\ndp[0] = 1\nfor i in range(1, len(s) + 1):\n if s[i - 1] != '0':\n dp[i] += dp[i - 1]\n if i != 1 and s[i - 2:i] > '09' and (s[i - 2:i] < '27'):\n dp[i] += dp[i - 2]\nreturn dp[len(s)]",
"if s.startswith('0'):\n return 0\nn = len(s)\ndp = [1... | <|body_start_0|>
if not s:
return 0
dp = [0] * (len(s) + 1)
dp[0] = 1
for i in range(1, len(s) + 1):
if s[i - 1] != '0':
dp[i] += dp[i - 1]
if i != 1 and s[i - 2:i] > '09' and (s[i - 2:i] < '27'):
dp[i] += dp[i - 2]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numDecodings_20211226(self, s: str) -> int:
"""状态表示: - 集合: 所有前 i 个数字解码得到的字符串 - 属性: 数量 状态计算: - 最后一个字母是一位数 f[i-1] - 最后一个字母是两位数 f[i-2]"""
<|body_0|>
def numDecodings(self, s: str) -> int:
"""状态: dp[i]: 若前 i 个字符可以解码, 表示前 i 个字符可以解码的方法数 若前 i 个字符不能解码,那整个字符串肯定不... | stack_v2_sparse_classes_75kplus_train_004562 | 1,633 | no_license | [
{
"docstring": "状态表示: - 集合: 所有前 i 个数字解码得到的字符串 - 属性: 数量 状态计算: - 最后一个字母是一位数 f[i-1] - 最后一个字母是两位数 f[i-2]",
"name": "numDecodings_20211226",
"signature": "def numDecodings_20211226(self, s: str) -> int"
},
{
"docstring": "状态: dp[i]: 若前 i 个字符可以解码, 表示前 i 个字符可以解码的方法数 若前 i 个字符不能解码,那整个字符串肯定不能解码,我们无需再进行下去了... | 2 | stack_v2_sparse_classes_30k_train_011737 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDecodings_20211226(self, s: str) -> int: 状态表示: - 集合: 所有前 i 个数字解码得到的字符串 - 属性: 数量 状态计算: - 最后一个字母是一位数 f[i-1] - 最后一个字母是两位数 f[i-2]
- def numDecodings(self, s: str) -> int: 状态: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDecodings_20211226(self, s: str) -> int: 状态表示: - 集合: 所有前 i 个数字解码得到的字符串 - 属性: 数量 状态计算: - 最后一个字母是一位数 f[i-1] - 最后一个字母是两位数 f[i-2]
- def numDecodings(self, s: str) -> int: 状态: ... | f350b3d6e59fd5771e11ec0b466f9ba5eeb8e927 | <|skeleton|>
class Solution:
def numDecodings_20211226(self, s: str) -> int:
"""状态表示: - 集合: 所有前 i 个数字解码得到的字符串 - 属性: 数量 状态计算: - 最后一个字母是一位数 f[i-1] - 最后一个字母是两位数 f[i-2]"""
<|body_0|>
def numDecodings(self, s: str) -> int:
"""状态: dp[i]: 若前 i 个字符可以解码, 表示前 i 个字符可以解码的方法数 若前 i 个字符不能解码,那整个字符串肯定不... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numDecodings_20211226(self, s: str) -> int:
"""状态表示: - 集合: 所有前 i 个数字解码得到的字符串 - 属性: 数量 状态计算: - 最后一个字母是一位数 f[i-1] - 最后一个字母是两位数 f[i-2]"""
if not s:
return 0
dp = [0] * (len(s) + 1)
dp[0] = 1
for i in range(1, len(s) + 1):
if s[i - 1] !... | the_stack_v2_python_sparse | leetcode/python/91.py | ShawnDong98/Algorithm-Book | train | 0 | |
a1ca5f8716235199e061723eec0a3985736a94b8 | [
"dataset_dict = {'name': name, 'type': data_type, 'num_classes': num_classes, 'dim_data': dim_data}\nif data_type not in ('image', 'numeric'):\n raise ValueError('Unkown data type.')\nsuper(CustomDataContainer, self).__init__(dataset_dict)\nself._x_train_np = data_train\nself._y_train_np = label_train\nself._x_t... | <|body_start_0|>
dataset_dict = {'name': name, 'type': data_type, 'num_classes': num_classes, 'dim_data': dim_data}
if data_type not in ('image', 'numeric'):
raise ValueError('Unkown data type.')
super(CustomDataContainer, self).__init__(dataset_dict)
self._x_train_np = data_... | CustomDataContainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomDataContainer:
def __init__(self, data_train, label_train, data_test, label_test, name, data_type, num_classes, dim_data):
"""Create a CustomDataContainer instance Parameters ---------- data_train : numpy.ndarray Input data for training. label_train : numpy.ndarray The labels of tr... | stack_v2_sparse_classes_75kplus_train_004563 | 2,395 | no_license | [
{
"docstring": "Create a CustomDataContainer instance Parameters ---------- data_train : numpy.ndarray Input data for training. label_train : numpy.ndarray The labels of train data. data_test : numpy.ndarray Input data for evaluation. label_test : numpy.ndarray name : numpy.ndarray The labels of test data. data... | 2 | null | Implement the Python class `CustomDataContainer` described below.
Class description:
Implement the CustomDataContainer class.
Method signatures and docstrings:
- def __init__(self, data_train, label_train, data_test, label_test, name, data_type, num_classes, dim_data): Create a CustomDataContainer instance Parameters... | Implement the Python class `CustomDataContainer` described below.
Class description:
Implement the CustomDataContainer class.
Method signatures and docstrings:
- def __init__(self, data_train, label_train, data_test, label_test, name, data_type, num_classes, dim_data): Create a CustomDataContainer instance Parameters... | dbbf0ac585b1bfef5a8e8795c62e2ccbf3e8b066 | <|skeleton|>
class CustomDataContainer:
def __init__(self, data_train, label_train, data_test, label_test, name, data_type, num_classes, dim_data):
"""Create a CustomDataContainer instance Parameters ---------- data_train : numpy.ndarray Input data for training. label_train : numpy.ndarray The labels of tr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomDataContainer:
def __init__(self, data_train, label_train, data_test, label_test, name, data_type, num_classes, dim_data):
"""Create a CustomDataContainer instance Parameters ---------- data_train : numpy.ndarray Input data for training. label_train : numpy.ndarray The labels of train data. data... | the_stack_v2_python_sparse | aad/datasets/custom_data_container.py | changx03/adversarial_attack_defence | train | 4 | |
d918b3dc511871e512902d94b636886ae78fb537 | [
"self.input_size: int = input_size\nself.bias = bias\nself.delay: int = delay\nself.scale = scale\nself.hx: np.ndarray = None",
"if self.hx is None:\n self.hx = np.zeros((x.shape[0], 1), dtype=np.float64)\nself.hx = np.concatenate((self.hx, x), axis=1)\nif self.hx.shape[1] <= self.delay + 1:\n return self.h... | <|body_start_0|>
self.input_size: int = input_size
self.bias = bias
self.delay: int = delay
self.scale = scale
self.hx: np.ndarray = None
<|end_body_0|>
<|body_start_1|>
if self.hx is None:
self.hx = np.zeros((x.shape[0], 1), dtype=np.float64)
self.hx... | Small variation of the PyTorch implementation of the simple RNN-cell. | FixedCell | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixedCell:
"""Small variation of the PyTorch implementation of the simple RNN-cell."""
def __init__(self, input_size: int, bias, delay: int, scale):
"""Create the RNN-cell with the provided parameters. :param input_size: Number of inputs going into the cell :param delay: Bias for the... | stack_v2_sparse_classes_75kplus_train_004564 | 3,618 | permissive | [
{
"docstring": "Create the RNN-cell with the provided parameters. :param input_size: Number of inputs going into the cell :param delay: Bias for the internal node",
"name": "__init__",
"signature": "def __init__(self, input_size: int, bias, delay: int, scale)"
},
{
"docstring": "Forward the netw... | 2 | null | Implement the Python class `FixedCell` described below.
Class description:
Small variation of the PyTorch implementation of the simple RNN-cell.
Method signatures and docstrings:
- def __init__(self, input_size: int, bias, delay: int, scale): Create the RNN-cell with the provided parameters. :param input_size: Number... | Implement the Python class `FixedCell` described below.
Class description:
Small variation of the PyTorch implementation of the simple RNN-cell.
Method signatures and docstrings:
- def __init__(self, input_size: int, bias, delay: int, scale): Create the RNN-cell with the provided parameters. :param input_size: Number... | 818a4ce941536611c0f1780f7c4a6238f0e1884e | <|skeleton|>
class FixedCell:
"""Small variation of the PyTorch implementation of the simple RNN-cell."""
def __init__(self, input_size: int, bias, delay: int, scale):
"""Create the RNN-cell with the provided parameters. :param input_size: Number of inputs going into the cell :param delay: Bias for the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FixedCell:
"""Small variation of the PyTorch implementation of the simple RNN-cell."""
def __init__(self, input_size: int, bias, delay: int, scale):
"""Create the RNN-cell with the provided parameters. :param input_size: Number of inputs going into the cell :param delay: Bias for the internal nod... | the_stack_v2_python_sparse | population/utils/gene_util/fixed_rnn.py | RubenPants/EvolvableRNN | train | 1 |
03d8043ed370835402f59a31a7374e81677625fc | [
"table = read_csv(dimmfile, delim_whitespace=True, names=['year', 'month', 'day', 'hour', 'minute', 'second', 'seeing'])\nself.year = np.array(table['year'])\nself.month = np.array(table['month'])\nself.day = np.array(table['day'])\nself.hour = np.array(table['hour'])\nself.minute = np.array(table['minute'])\nself.... | <|body_start_0|>
table = read_csv(dimmfile, delim_whitespace=True, names=['year', 'month', 'day', 'hour', 'minute', 'second', 'seeing'])
self.year = np.array(table['year'])
self.month = np.array(table['month'])
self.day = np.array(table['day'])
self.hour = np.array(table['hour'])... | An object that can load a DIMM fil and find the nearest DIMM date given any time. | DIMM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DIMM:
"""An object that can load a DIMM fil and find the nearest DIMM date given any time."""
def __init__(self, dimmfile):
"""Load up a DIMM file into this object. You can then access the following object variables that contain numpy arrays: year month day hour -- UT, 24 hour based ... | stack_v2_sparse_classes_75kplus_train_004565 | 14,789 | no_license | [
{
"docstring": "Load up a DIMM file into this object. You can then access the following object variables that contain numpy arrays: year month day hour -- UT, 24 hour based (int) minute second timeInHours -- UT, 24 hour based, float r0",
"name": "__init__",
"signature": "def __init__(self, dimmfile)"
... | 2 | stack_v2_sparse_classes_30k_val_001037 | Implement the Python class `DIMM` described below.
Class description:
An object that can load a DIMM fil and find the nearest DIMM date given any time.
Method signatures and docstrings:
- def __init__(self, dimmfile): Load up a DIMM file into this object. You can then access the following object variables that contai... | Implement the Python class `DIMM` described below.
Class description:
An object that can load a DIMM fil and find the nearest DIMM date given any time.
Method signatures and docstrings:
- def __init__(self, dimmfile): Load up a DIMM file into this object. You can then access the following object variables that contai... | 27e43dc5f7fa1e4b496ddde6cee52198a4ab97a2 | <|skeleton|>
class DIMM:
"""An object that can load a DIMM fil and find the nearest DIMM date given any time."""
def __init__(self, dimmfile):
"""Load up a DIMM file into this object. You can then access the following object variables that contain numpy arrays: year month day hour -- UT, 24 hour based ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DIMM:
"""An object that can load a DIMM fil and find the nearest DIMM date given any time."""
def __init__(self, dimmfile):
"""Load up a DIMM file into this object. You can then access the following object variables that contain numpy arrays: year month day hour -- UT, 24 hour based (int) minute ... | the_stack_v2_python_sparse | imaka/reduce/massdimm.py | jluastro/imaka | train | 1 |
e5d1fbd725e3dcfa1fa4c667e06a871641547634 | [
"data = {'username': 'some_username', 'email': 'some_email@gmail.com', 'password': 'some_password'}\nresponse = self.client.post(self.url, data)\nself.assertEqual(response.status_code, status.HTTP_201_CREATED)\nself.assertEqual(Profile.objects.count(), 1)\nself.assertEqual(Profile.objects.get().user.username, 'some... | <|body_start_0|>
data = {'username': 'some_username', 'email': 'some_email@gmail.com', 'password': 'some_password'}
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Profile.objects.count(), 1)
self.assert... | UserRegistrationTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRegistrationTests:
def test_register_user(self):
"""Ensure we can register a new user profile"""
<|body_0|>
def test_email_required(self):
"""Ensure that email field is required and cannot be submitted blank"""
<|body_1|>
def test_unique_email(self):... | stack_v2_sparse_classes_75kplus_train_004566 | 13,549 | permissive | [
{
"docstring": "Ensure we can register a new user profile",
"name": "test_register_user",
"signature": "def test_register_user(self)"
},
{
"docstring": "Ensure that email field is required and cannot be submitted blank",
"name": "test_email_required",
"signature": "def test_email_require... | 3 | stack_v2_sparse_classes_30k_train_041424 | Implement the Python class `UserRegistrationTests` described below.
Class description:
Implement the UserRegistrationTests class.
Method signatures and docstrings:
- def test_register_user(self): Ensure we can register a new user profile
- def test_email_required(self): Ensure that email field is required and cannot ... | Implement the Python class `UserRegistrationTests` described below.
Class description:
Implement the UserRegistrationTests class.
Method signatures and docstrings:
- def test_register_user(self): Ensure we can register a new user profile
- def test_email_required(self): Ensure that email field is required and cannot ... | 9fa31e01c8fc3496f92540081a8c078474d59c0f | <|skeleton|>
class UserRegistrationTests:
def test_register_user(self):
"""Ensure we can register a new user profile"""
<|body_0|>
def test_email_required(self):
"""Ensure that email field is required and cannot be submitted blank"""
<|body_1|>
def test_unique_email(self):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserRegistrationTests:
def test_register_user(self):
"""Ensure we can register a new user profile"""
data = {'username': 'some_username', 'email': 'some_email@gmail.com', 'password': 'some_password'}
response = self.client.post(self.url, data)
self.assertEqual(response.status_c... | the_stack_v2_python_sparse | player/tests.py | apoorvaeternity/DirectMe | train | 1 | |
3e8fb70b7a6c4529f2d3c538743ce730daf37971 | [
"try:\n user = JourneyUser.objects.get(pk=pk)\n serializer = JourneyUserSerializer(user, context={'request': request})\n return Response(serializer.data)\nexcept Exception as ex:\n return HttpResponseServerError(ex)",
"users = JourneyUser.objects.all()\nserializer = JourneyUserListSerializer(users, ma... | <|body_start_0|>
try:
user = JourneyUser.objects.get(pk=pk)
serializer = JourneyUserSerializer(user, context={'request': request})
return Response(serializer.data)
except Exception as ex:
return HttpResponseServerError(ex)
<|end_body_0|>
<|body_start_1|>
... | JourneyUserViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JourneyUserViewSet:
def retrieve(self, request, pk=None):
"""Handle GET requests for single user returns: Response -- JSON serialized user"""
<|body_0|>
def list(self, request):
"""Handle GET requests to get all users Returns: Response -- JSON serialized list of user... | stack_v2_sparse_classes_75kplus_train_004567 | 2,180 | no_license | [
{
"docstring": "Handle GET requests for single user returns: Response -- JSON serialized user",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
},
{
"docstring": "Handle GET requests to get all users Returns: Response -- JSON serialized list of users",
"name": "list",... | 3 | stack_v2_sparse_classes_30k_train_015011 | Implement the Python class `JourneyUserViewSet` described below.
Class description:
Implement the JourneyUserViewSet class.
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for single user returns: Response -- JSON serialized user
- def list(self, request): Handle GET requ... | Implement the Python class `JourneyUserViewSet` described below.
Class description:
Implement the JourneyUserViewSet class.
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for single user returns: Response -- JSON serialized user
- def list(self, request): Handle GET requ... | bd996853f6bd9a95d15115248300e6d801c0dc47 | <|skeleton|>
class JourneyUserViewSet:
def retrieve(self, request, pk=None):
"""Handle GET requests for single user returns: Response -- JSON serialized user"""
<|body_0|>
def list(self, request):
"""Handle GET requests to get all users Returns: Response -- JSON serialized list of user... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JourneyUserViewSet:
def retrieve(self, request, pk=None):
"""Handle GET requests for single user returns: Response -- JSON serialized user"""
try:
user = JourneyUser.objects.get(pk=pk)
serializer = JourneyUserSerializer(user, context={'request': request})
re... | the_stack_v2_python_sparse | capstoneapi/views/journeyuser.py | jeaninebeckle/backend-capstone-api | train | 0 | |
26336f3849b304189664fdb30c9847cfc3e895ef | [
"is_empty = lambda l: l is None or l == EMPTY_ENTITY\nlocation = None\nlevels = ['region', 'cercle', 'commune', 'village']\nwhile len(levels) and is_empty(location):\n location = self.cleaned_data.get(levels.pop()) or None\nif is_empty(location):\n return None\ntry:\n return Entity.objects.get(slug=locatio... | <|body_start_0|>
is_empty = lambda l: l is None or l == EMPTY_ENTITY
location = None
levels = ['region', 'cercle', 'commune', 'village']
while len(levels) and is_empty(location):
location = self.cleaned_data.get(levels.pop()) or None
if is_empty(location):
... | Used to easily enter data for calls made by volunteers. | HotlineResponseForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HotlineResponseForm:
"""Used to easily enter data for calls made by volunteers."""
def clean_village(self):
"""Returns a Village Entity from the multiple selects"""
<|body_0|>
def clean_request_id(self):
"""Return a HotlineEvent from the id"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_004568 | 18,848 | no_license | [
{
"docstring": "Returns a Village Entity from the multiple selects",
"name": "clean_village",
"signature": "def clean_village(self)"
},
{
"docstring": "Return a HotlineEvent from the id",
"name": "clean_request_id",
"signature": "def clean_request_id(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001020 | Implement the Python class `HotlineResponseForm` described below.
Class description:
Used to easily enter data for calls made by volunteers.
Method signatures and docstrings:
- def clean_village(self): Returns a Village Entity from the multiple selects
- def clean_request_id(self): Return a HotlineEvent from the id | Implement the Python class `HotlineResponseForm` described below.
Class description:
Used to easily enter data for calls made by volunteers.
Method signatures and docstrings:
- def clean_village(self): Returns a Village Entity from the multiple selects
- def clean_request_id(self): Return a HotlineEvent from the id
... | e04eb7deb0a66574b30e6f7c5bad72c99cbbf274 | <|skeleton|>
class HotlineResponseForm:
"""Used to easily enter data for calls made by volunteers."""
def clean_village(self):
"""Returns a Village Entity from the multiple selects"""
<|body_0|>
def clean_request_id(self):
"""Return a HotlineEvent from the id"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HotlineResponseForm:
"""Used to easily enter data for calls made by volunteers."""
def clean_village(self):
"""Returns a Village Entity from the multiple selects"""
is_empty = lambda l: l is None or l == EMPTY_ENTITY
location = None
levels = ['region', 'cercle', 'commune',... | the_stack_v2_python_sparse | dispatcher/views.py | jokkolabs/hotline_dispatch | train | 0 |
1c7cba4b22ea00eddb9d2fdf84a85e2117aaebe0 | [
"while end > begin:\n if string[begin] != string[end]:\n return False\n begin += 1\n end -= 1\nreturn True",
"size = len(string)\nfor length in range(size, 1, -1):\n for offset in range(size - length + 1):\n if self._isPalindrome(string, offset, offset + length - 1):\n return ... | <|body_start_0|>
while end > begin:
if string[begin] != string[end]:
return False
begin += 1
end -= 1
return True
<|end_body_0|>
<|body_start_1|>
size = len(string)
for length in range(size, 1, -1):
for offset in range(size... | Naive | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Naive:
def _isPalindrome(self, string, begin, end):
"""Verify if substring is a palindrome."""
<|body_0|>
def longestPalindrome(self, string):
"""Solve the problem."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while end > begin:
if st... | stack_v2_sparse_classes_75kplus_train_004569 | 3,988 | no_license | [
{
"docstring": "Verify if substring is a palindrome.",
"name": "_isPalindrome",
"signature": "def _isPalindrome(self, string, begin, end)"
},
{
"docstring": "Solve the problem.",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, string)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033781 | Implement the Python class `Naive` described below.
Class description:
Implement the Naive class.
Method signatures and docstrings:
- def _isPalindrome(self, string, begin, end): Verify if substring is a palindrome.
- def longestPalindrome(self, string): Solve the problem. | Implement the Python class `Naive` described below.
Class description:
Implement the Naive class.
Method signatures and docstrings:
- def _isPalindrome(self, string, begin, end): Verify if substring is a palindrome.
- def longestPalindrome(self, string): Solve the problem.
<|skeleton|>
class Naive:
def _isPalin... | 97246c26483637b95198ed2ef76e234d3c0194dc | <|skeleton|>
class Naive:
def _isPalindrome(self, string, begin, end):
"""Verify if substring is a palindrome."""
<|body_0|>
def longestPalindrome(self, string):
"""Solve the problem."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Naive:
def _isPalindrome(self, string, begin, end):
"""Verify if substring is a palindrome."""
while end > begin:
if string[begin] != string[end]:
return False
begin += 1
end -= 1
return True
def longestPalindrome(self, string):
... | the_stack_v2_python_sparse | coding/leetcode/problems/longest_palindromic_substring_hashing_v3_stress.py | baites/examples | train | 4 | |
74429aaaf134e635efb53a3924168c6fa0e6dbba | [
"if not a or not a[0]:\n return False\nn = len(a)\nb = [a[r][0] for r in range(n)]\nif x < b[0]:\n return False\nelse:\n i = self.find_row_index(b, x)\nif x > a[i][-1]:\n return False\nelse:\n return self.is_target_present(a[i], x)",
"if not b:\n return False\nl = 0\nr = len(b) - 1\nwhile l < r:... | <|body_start_0|>
if not a or not a[0]:
return False
n = len(a)
b = [a[r][0] for r in range(n)]
if x < b[0]:
return False
else:
i = self.find_row_index(b, x)
if x > a[i][-1]:
return False
else:
return self... | Successive binary search of 2 1D arrays. Time complexity: O(n) - Create index array, then binary search on two arrays Space complexity: O(1) - Update constant pointers | Solution2 | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution2:
"""Successive binary search of 2 1D arrays. Time complexity: O(n) - Create index array, then binary search on two arrays Space complexity: O(1) - Update constant pointers"""
def search_matrix(self, a, x):
"""Determines whether target element exists in 2D array. :param list... | stack_v2_sparse_classes_75kplus_train_004570 | 5,845 | permissive | [
{
"docstring": "Determines whether target element exists in 2D array. :param list[list[int]] a: input 2D array of sorted integers :param int x: target integer to find in array :return: True if target element found in array :rtype: bool",
"name": "search_matrix",
"signature": "def search_matrix(self, a, ... | 3 | stack_v2_sparse_classes_30k_train_046838 | Implement the Python class `Solution2` described below.
Class description:
Successive binary search of 2 1D arrays. Time complexity: O(n) - Create index array, then binary search on two arrays Space complexity: O(1) - Update constant pointers
Method signatures and docstrings:
- def search_matrix(self, a, x): Determin... | Implement the Python class `Solution2` described below.
Class description:
Successive binary search of 2 1D arrays. Time complexity: O(n) - Create index array, then binary search on two arrays Space complexity: O(1) - Update constant pointers
Method signatures and docstrings:
- def search_matrix(self, a, x): Determin... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution2:
"""Successive binary search of 2 1D arrays. Time complexity: O(n) - Create index array, then binary search on two arrays Space complexity: O(1) - Update constant pointers"""
def search_matrix(self, a, x):
"""Determines whether target element exists in 2D array. :param list... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution2:
"""Successive binary search of 2 1D arrays. Time complexity: O(n) - Create index array, then binary search on two arrays Space complexity: O(1) - Update constant pointers"""
def search_matrix(self, a, x):
"""Determines whether target element exists in 2D array. :param list[list[int]] a... | the_stack_v2_python_sparse | 0074_search_2d_matrix/python_source.py | arthurdysart/LeetCode | train | 0 |
70ff702a6c0d7164c49ff4deff2e6722f477ebf2 | [
"loss_input = self._user_power_curve_input()\nif not loss_input:\n return\nwind_resource, weights = self.wind_resource_from_input()\npower_curve = self.input_power_curve\nif (wind_resource <= power_curve.cutin_wind_speed).all():\n msg = 'All wind speeds for site {} are below the wind speed cutin ({} m/s). No ... | <|body_start_0|>
loss_input = self._user_power_curve_input()
if not loss_input:
return
wind_resource, weights = self.wind_resource_from_input()
power_curve = self.input_power_curve
if (wind_resource <= power_curve.cutin_wind_speed).all():
msg = 'All wind s... | Mixin class for :class:`reV.SAM.generation.AbstractSamWind`. Warnings -------- Using this class for anything except as a mixin for :class:`~reV.SAM.generation.AbstractSamWind` may result in unexpected results and/or errors. | PowerCurveLossesMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PowerCurveLossesMixin:
"""Mixin class for :class:`reV.SAM.generation.AbstractSamWind`. Warnings -------- Using this class for anything except as a mixin for :class:`~reV.SAM.generation.AbstractSamWind` may result in unexpected results and/or errors."""
def add_power_curve_losses(self):
... | stack_v2_sparse_classes_75kplus_train_004571 | 40,707 | permissive | [
{
"docstring": "Adjust power curve in SAM config file to account for losses. This function reads the information in the ``reV_power_curve_losses`` key of the ``sam_sys_inputs`` dictionary and computes a new power curve that accounts for the loss percentage specified from that input. If no power curve loss info ... | 6 | stack_v2_sparse_classes_30k_train_052695 | Implement the Python class `PowerCurveLossesMixin` described below.
Class description:
Mixin class for :class:`reV.SAM.generation.AbstractSamWind`. Warnings -------- Using this class for anything except as a mixin for :class:`~reV.SAM.generation.AbstractSamWind` may result in unexpected results and/or errors.
Method ... | Implement the Python class `PowerCurveLossesMixin` described below.
Class description:
Mixin class for :class:`reV.SAM.generation.AbstractSamWind`. Warnings -------- Using this class for anything except as a mixin for :class:`~reV.SAM.generation.AbstractSamWind` may result in unexpected results and/or errors.
Method ... | 497bb7d172197e09a9e14b1b1ca891b8c828b80a | <|skeleton|>
class PowerCurveLossesMixin:
"""Mixin class for :class:`reV.SAM.generation.AbstractSamWind`. Warnings -------- Using this class for anything except as a mixin for :class:`~reV.SAM.generation.AbstractSamWind` may result in unexpected results and/or errors."""
def add_power_curve_losses(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PowerCurveLossesMixin:
"""Mixin class for :class:`reV.SAM.generation.AbstractSamWind`. Warnings -------- Using this class for anything except as a mixin for :class:`~reV.SAM.generation.AbstractSamWind` may result in unexpected results and/or errors."""
def add_power_curve_losses(self):
"""Adjust ... | the_stack_v2_python_sparse | reV/losses/power_curve.py | NREL/reV | train | 53 |
66220afbd85f15cc45dd5b94b64fabe3e5787643 | [
"pfx = self.getPrefixName()\nif pfx:\n pfx = '%s: ' % pfx\nmnem = self.mnem\nif self.prefixes & PREFIX_VEX:\n mnem = 'v' + mnem\nreturn pfx + mnem + ' ' + ','.join([o.repr(self) for o in self.opers])",
"if self.prefixes:\n pfx = self.getPrefixName()\n if pfx:\n mcanv.addNameText('%s: ' % pfx, p... | <|body_start_0|>
pfx = self.getPrefixName()
if pfx:
pfx = '%s: ' % pfx
mnem = self.mnem
if self.prefixes & PREFIX_VEX:
mnem = 'v' + mnem
return pfx + mnem + ' ' + ','.join([o.repr(self) for o in self.opers])
<|end_body_0|>
<|body_start_1|>
if self... | Amd64Opcode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Amd64Opcode:
def __repr__(self):
"""Over-ride this if you want to make arch specific repr."""
<|body_0|>
def render(self, mcanv):
"""Render this opcode to the specified memory canvas"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pfx = self.getPref... | stack_v2_sparse_classes_75kplus_train_004572 | 1,738 | permissive | [
{
"docstring": "Over-ride this if you want to make arch specific repr.",
"name": "__repr__",
"signature": "def __repr__(self)"
},
{
"docstring": "Render this opcode to the specified memory canvas",
"name": "render",
"signature": "def render(self, mcanv)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051871 | Implement the Python class `Amd64Opcode` described below.
Class description:
Implement the Amd64Opcode class.
Method signatures and docstrings:
- def __repr__(self): Over-ride this if you want to make arch specific repr.
- def render(self, mcanv): Render this opcode to the specified memory canvas | Implement the Python class `Amd64Opcode` described below.
Class description:
Implement the Amd64Opcode class.
Method signatures and docstrings:
- def __repr__(self): Over-ride this if you want to make arch specific repr.
- def render(self, mcanv): Render this opcode to the specified memory canvas
<|skeleton|>
class ... | 1938c92d7ff740e43d989d8868e3ac1c547752a4 | <|skeleton|>
class Amd64Opcode:
def __repr__(self):
"""Over-ride this if you want to make arch specific repr."""
<|body_0|>
def render(self, mcanv):
"""Render this opcode to the specified memory canvas"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Amd64Opcode:
def __repr__(self):
"""Over-ride this if you want to make arch specific repr."""
pfx = self.getPrefixName()
if pfx:
pfx = '%s: ' % pfx
mnem = self.mnem
if self.prefixes & PREFIX_VEX:
mnem = 'v' + mnem
return pfx + mnem + ' ' ... | the_stack_v2_python_sparse | envi/archs/amd64/disasm.py | bernhl/vivisect-py3 | train | 1 | |
d69baf0d22806ab3c48a4974095f51d7c249e278 | [
"self.secretWord = word\nself.randomword = [x for x in word]\nself.currentStatus = '_ ' * len(word)\nself.guessedChars = []\nself.numTries = 0",
"print('단어 완성 상태 : ', self.currentStatus)\nprint('사용한 알파벳 : ', self.guessedChars)\nprint('실패한 횟수 : ', self.numTries)\npass",
"self.guessedChars.append(character)\nwhil... | <|body_start_0|>
self.secretWord = word
self.randomword = [x for x in word]
self.currentStatus = '_ ' * len(word)
self.guessedChars = []
self.numTries = 0
<|end_body_0|>
<|body_start_1|>
print('단어 완성 상태 : ', self.currentStatus)
print('사용한 알파벳 : ', self.guessedCha... | Guess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Guess:
def __init__(self, word):
"""선택된 단어 선택한것 파라미터로 받음 1. 단어의 길이에 알맞게 빈 '_' 만들기 2. 입력한 알파벳 적어 넣을 리스트 초기화 3. 실패한 기회 변수 선언"""
<|body_0|>
def display(self):
"""알아낸 글자들과 그 위치를 가리키는 데이터 화면에 출력 + 실패한 횟수와 행맨 상태도 화면에 출력"""
<|body_1|>
def guess(self, character)... | stack_v2_sparse_classes_75kplus_train_004573 | 1,914 | no_license | [
{
"docstring": "선택된 단어 선택한것 파라미터로 받음 1. 단어의 길이에 알맞게 빈 '_' 만들기 2. 입력한 알파벳 적어 넣을 리스트 초기화 3. 실패한 기회 변수 선언",
"name": "__init__",
"signature": "def __init__(self, word)"
},
{
"docstring": "알아낸 글자들과 그 위치를 가리키는 데이터 화면에 출력 + 실패한 횟수와 행맨 상태도 화면에 출력",
"name": "display",
"signature": "def display(se... | 3 | stack_v2_sparse_classes_30k_train_010176 | Implement the Python class `Guess` described below.
Class description:
Implement the Guess class.
Method signatures and docstrings:
- def __init__(self, word): 선택된 단어 선택한것 파라미터로 받음 1. 단어의 길이에 알맞게 빈 '_' 만들기 2. 입력한 알파벳 적어 넣을 리스트 초기화 3. 실패한 기회 변수 선언
- def display(self): 알아낸 글자들과 그 위치를 가리키는 데이터 화면에 출력 + 실패한 횟수와 행맨 상태도 화면... | Implement the Python class `Guess` described below.
Class description:
Implement the Guess class.
Method signatures and docstrings:
- def __init__(self, word): 선택된 단어 선택한것 파라미터로 받음 1. 단어의 길이에 알맞게 빈 '_' 만들기 2. 입력한 알파벳 적어 넣을 리스트 초기화 3. 실패한 기회 변수 선언
- def display(self): 알아낸 글자들과 그 위치를 가리키는 데이터 화면에 출력 + 실패한 횟수와 행맨 상태도 화면... | bd60fbf3a4d1fb05fef8a40bb8edbe097a9fc324 | <|skeleton|>
class Guess:
def __init__(self, word):
"""선택된 단어 선택한것 파라미터로 받음 1. 단어의 길이에 알맞게 빈 '_' 만들기 2. 입력한 알파벳 적어 넣을 리스트 초기화 3. 실패한 기회 변수 선언"""
<|body_0|>
def display(self):
"""알아낸 글자들과 그 위치를 가리키는 데이터 화면에 출력 + 실패한 횟수와 행맨 상태도 화면에 출력"""
<|body_1|>
def guess(self, character)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Guess:
def __init__(self, word):
"""선택된 단어 선택한것 파라미터로 받음 1. 단어의 길이에 알맞게 빈 '_' 만들기 2. 입력한 알파벳 적어 넣을 리스트 초기화 3. 실패한 기회 변수 선언"""
self.secretWord = word
self.randomword = [x for x in word]
self.currentStatus = '_ ' * len(word)
self.guessedChars = []
self.numTries = ... | the_stack_v2_python_sparse | hangmancod/동설아_guess.py | hj9097/4jo | train | 0 | |
22bebda96d1e9f13f29b160954692e61e8739e44 | [
"if not root or (root.left == None and root.right == None):\n if not root:\n pass\n else:\n pass\n return root\nleft = self.flatten(root.left)\nright = self.flatten(root.right)\nroot.left = None\nif left:\n root.right = left\n while left.right:\n left = left.right\n left.right... | <|body_start_0|>
if not root or (root.left == None and root.right == None):
if not root:
pass
else:
pass
return root
left = self.flatten(root.left)
right = self.flatten(root.right)
root.left = None
if left:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten_fail(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten_myself(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.... | stack_v2_sparse_classes_75kplus_train_004574 | 3,580 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "flatten_fail",
"signature": "def flatten_fail(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_036104 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten_fail(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def flatten_myself(self, root): :type root: TreeNode :rtyp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten_fail(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def flatten_myself(self, root): :type root: TreeNode :rtyp... | 93266095329e2e8e949a72371b88b07382a60e0d | <|skeleton|>
class Solution:
def flatten_fail(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten_myself(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def flatten_fail(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
if not root or (root.left == None and root.right == None):
if not root:
pass
else:
pass
retu... | the_stack_v2_python_sparse | flatten_114.py | shivangi-prog/leetcode | train | 0 | |
827cd099c8f5140244a89fb7d64e6fab41ed1134 | [
"data = {}\nfor n in nums:\n data[n] = 1\nfor key in data:\n self.forward(data, key)\nif not data:\n return 0\nelse:\n return max(data.values())",
"if n not in data:\n return 0\ncnt = data[n]\nif cnt > 1:\n return cnt\nelse:\n if n + 1 in data:\n cnt = self.forward(data, n + 1) + 1\n ... | <|body_start_0|>
data = {}
for n in nums:
data[n] = 1
for key in data:
self.forward(data, key)
if not data:
return 0
else:
return max(data.values())
<|end_body_0|>
<|body_start_1|>
if n not in data:
return 0
... | hash, and recursion to build the path | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""hash, and recursion to build the path"""
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def forward(self, data, n):
"""length of the consecutive sequence starting from n"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_004575 | 1,871 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutive",
"signature": "def longestConsecutive(self, nums)"
},
{
"docstring": "length of the consecutive sequence starting from n",
"name": "forward",
"signature": "def forward(self, data, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021497 | Implement the Python class `Solution` described below.
Class description:
hash, and recursion to build the path
Method signatures and docstrings:
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int
- def forward(self, data, n): length of the consecutive sequence starting from n | Implement the Python class `Solution` described below.
Class description:
hash, and recursion to build the path
Method signatures and docstrings:
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int
- def forward(self, data, n): length of the consecutive sequence starting from n
<|skeleton|>
class... | e00cf94c5b86c8cca27e3bee69ad21e727b7679b | <|skeleton|>
class Solution:
"""hash, and recursion to build the path"""
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def forward(self, data, n):
"""length of the consecutive sequence starting from n"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""hash, and recursion to build the path"""
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
data = {}
for n in nums:
data[n] = 1
for key in data:
self.forward(data, key)
if not data:
return 0... | the_stack_v2_python_sparse | hashtable/prob128.py | binchen15/leet-python | train | 1 |
f8c0799c5f0103e065b108b545a5e9e0e43afcd9 | [
"stations = []\ndata = requests.get('http://tunein.com/search/?query={0!s}'.format(quote(query)), headers=self.headers)\nsoup = BeautifulSoup(''.join(data.text), 'html.parser')\nfor element in soup.find_all(lambda tag: tag.name == 'a' and 'profile-link' in tag.get('class', []) and ('/radio/' in tag.get('href', ''))... | <|body_start_0|>
stations = []
data = requests.get('http://tunein.com/search/?query={0!s}'.format(quote(query)), headers=self.headers)
soup = BeautifulSoup(''.join(data.text), 'html.parser')
for element in soup.find_all(lambda tag: tag.name == 'a' and 'profile-link' in tag.get('class', [... | TuneIn client TODO: Move out requestor to voiceplay.utils | TuneInClient | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TuneInClient:
"""TuneIn client TODO: Move out requestor to voiceplay.utils"""
def search(self, query):
"""Run TuneIn search"""
<|body_0|>
def get_station_info(self, station_url):
"""Get station info (i.e. extract JS from HTML)"""
<|body_1|>
def extra... | stack_v2_sparse_classes_75kplus_train_004576 | 5,725 | permissive | [
{
"docstring": "Run TuneIn search",
"name": "search",
"signature": "def search(self, query)"
},
{
"docstring": "Get station info (i.e. extract JS from HTML)",
"name": "get_station_info",
"signature": "def get_station_info(self, station_url)"
},
{
"docstring": "Extract stream url ... | 5 | stack_v2_sparse_classes_30k_train_016836 | Implement the Python class `TuneInClient` described below.
Class description:
TuneIn client TODO: Move out requestor to voiceplay.utils
Method signatures and docstrings:
- def search(self, query): Run TuneIn search
- def get_station_info(self, station_url): Get station info (i.e. extract JS from HTML)
- def extract_s... | Implement the Python class `TuneInClient` described below.
Class description:
TuneIn client TODO: Move out requestor to voiceplay.utils
Method signatures and docstrings:
- def search(self, query): Run TuneIn search
- def get_station_info(self, station_url): Get station info (i.e. extract JS from HTML)
- def extract_s... | 3e35a25cfcf982a3871cf0d819bae4374ee31ecf | <|skeleton|>
class TuneInClient:
"""TuneIn client TODO: Move out requestor to voiceplay.utils"""
def search(self, query):
"""Run TuneIn search"""
<|body_0|>
def get_station_info(self, station_url):
"""Get station info (i.e. extract JS from HTML)"""
<|body_1|>
def extra... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TuneInClient:
"""TuneIn client TODO: Move out requestor to voiceplay.utils"""
def search(self, query):
"""Run TuneIn search"""
stations = []
data = requests.get('http://tunein.com/search/?query={0!s}'.format(quote(query)), headers=self.headers)
soup = BeautifulSoup(''.join... | the_stack_v2_python_sparse | voiceplay/player/tasks/tunein.py | tb0hdan/voiceplay | train | 4 |
719b2648bc2848890cf516de7983b163c2847829 | [
"count = 0\naccumu = 0\nfor i in range(len(nums)):\n accumu += nums[i]\n if accumu > max_sum:\n count += 1\n if count >= m:\n return False\n accumu = nums[i]\nreturn True",
"result_max, result_min = (sum(nums), max(nums))\nleft, right = (result_min, result_max)\nwhile left < ... | <|body_start_0|>
count = 0
accumu = 0
for i in range(len(nums)):
accumu += nums[i]
if accumu > max_sum:
count += 1
if count >= m:
return False
accumu = nums[i]
return True
<|end_body_0|>
<|body_s... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def isValid(self, nums, m, max_sum):
""":rtype: bool"""
<|body_0|>
def splitArray(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = 0
accumu = 0
for i... | stack_v2_sparse_classes_75kplus_train_004577 | 915 | no_license | [
{
"docstring": ":rtype: bool",
"name": "isValid",
"signature": "def isValid(self, nums, m, max_sum)"
},
{
"docstring": ":type nums: List[int] :type m: int :rtype: int",
"name": "splitArray",
"signature": "def splitArray(self, nums, m)"
}
] | 2 | null | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def isValid(self, nums, m, max_sum): :rtype: bool
- def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtype: int | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def isValid(self, nums, m, max_sum): :rtype: bool
- def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtype: int
<|skeleton|>
class Solution1:
def isVali... | 37ece0a8e92a41ced2b4ce0f2d8dda3826b915ae | <|skeleton|>
class Solution1:
def isValid(self, nums, m, max_sum):
""":rtype: bool"""
<|body_0|>
def splitArray(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution1:
def isValid(self, nums, m, max_sum):
""":rtype: bool"""
count = 0
accumu = 0
for i in range(len(nums)):
accumu += nums[i]
if accumu > max_sum:
count += 1
if count >= m:
return False
... | the_stack_v2_python_sparse | Q410SplitArrayLargestSum.py | ShenTonyM/LeetCode-Learn | train | 0 | |
c5f43c8001094aab58258c9b4026f9f7a75d8b9f | [
"msg_header = msg.get_header()\nserialized_data = msg.get_data()\nreturn pickle.dumps({'header': msg_header, 'data': serialized_data})",
"data_dict = pickle.loads(serialized_byte_stream)\nif 'MSG_LEN|' in data_dict:\n msg_length = int(data_dict.split('|')[1])\n return msg_length\nmsg = Message(data=data_dic... | <|body_start_0|>
msg_header = msg.get_header()
serialized_data = msg.get_data()
return pickle.dumps({'header': msg_header, 'data': serialized_data})
<|end_body_0|>
<|body_start_1|>
data_dict = pickle.loads(serialized_byte_stream)
if 'MSG_LEN|' in data_dict:
msg_lengt... | Class for Pickle based serialization | PickleSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PickleSerializer:
"""Class for Pickle based serialization"""
def serialize(self, msg):
"""Serialize a message using pickle :param msg: message to serialize :type msg: `Message` :return: serialize byte stream :rtype: `b[]`"""
<|body_0|>
def deserialize(self, serialized_by... | stack_v2_sparse_classes_75kplus_train_004578 | 1,410 | permissive | [
{
"docstring": "Serialize a message using pickle :param msg: message to serialize :type msg: `Message` :return: serialize byte stream :rtype: `b[]`",
"name": "serialize",
"signature": "def serialize(self, msg)"
},
{
"docstring": "Deserialize a byte stream to a message :param serialized_byte_stre... | 2 | null | Implement the Python class `PickleSerializer` described below.
Class description:
Class for Pickle based serialization
Method signatures and docstrings:
- def serialize(self, msg): Serialize a message using pickle :param msg: message to serialize :type msg: `Message` :return: serialize byte stream :rtype: `b[]`
- def... | Implement the Python class `PickleSerializer` described below.
Class description:
Class for Pickle based serialization
Method signatures and docstrings:
- def serialize(self, msg): Serialize a message using pickle :param msg: message to serialize :type msg: `Message` :return: serialize byte stream :rtype: `b[]`
- def... | 64ffa2ee2e906b1bd6b3dd6aabcf6fc3de862608 | <|skeleton|>
class PickleSerializer:
"""Class for Pickle based serialization"""
def serialize(self, msg):
"""Serialize a message using pickle :param msg: message to serialize :type msg: `Message` :return: serialize byte stream :rtype: `b[]`"""
<|body_0|>
def deserialize(self, serialized_by... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PickleSerializer:
"""Class for Pickle based serialization"""
def serialize(self, msg):
"""Serialize a message using pickle :param msg: message to serialize :type msg: `Message` :return: serialize byte stream :rtype: `b[]`"""
msg_header = msg.get_header()
serialized_data = msg.get_... | the_stack_v2_python_sparse | debugging-constructs/ibmfl/message/pickle_serializer.py | SEED-VT/FedDebug | train | 8 |
e0ae544a730e81eee7ecc97803ee144a586ce760 | [
"self.graph = graph\nif not self._is_eulerian():\n raise ValueError('the graph is not eulerian')\nself.eulerian_cycle = list()\nself._graph_copy = self.graph.copy()",
"if source is None:\n source = next(self.graph.iternodes())\nnode = source\nwhile self._graph_copy.outdegree(node) > 0:\n for edge in list... | <|body_start_0|>
self.graph = graph
if not self._is_eulerian():
raise ValueError('the graph is not eulerian')
self.eulerian_cycle = list()
self._graph_copy = self.graph.copy()
<|end_body_0|>
<|body_start_1|>
if source is None:
source = next(self.graph.ite... | Fleury's algorithm for finding an Eulerian cycle (multigraphs). Complexity O(V*E). Attributes ---------- graph : input graph eulerian_cycle : list of edges (length |E|) _graph_copy : graph, private Notes ----- Based on the description from: https://en.wikipedia.org/wiki/Eulerian_path | FleuryBFSWithEdges | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FleuryBFSWithEdges:
"""Fleury's algorithm for finding an Eulerian cycle (multigraphs). Complexity O(V*E). Attributes ---------- graph : input graph eulerian_cycle : list of edges (length |E|) _graph_copy : graph, private Notes ----- Based on the description from: https://en.wikipedia.org/wiki/Eul... | stack_v2_sparse_classes_75kplus_train_004579 | 9,406 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self, source=None)"
},
{
"docstring": "Bridge test.",
"name": "_is_bridge",
"signa... | 4 | stack_v2_sparse_classes_30k_train_037897 | Implement the Python class `FleuryBFSWithEdges` described below.
Class description:
Fleury's algorithm for finding an Eulerian cycle (multigraphs). Complexity O(V*E). Attributes ---------- graph : input graph eulerian_cycle : list of edges (length |E|) _graph_copy : graph, private Notes ----- Based on the description ... | Implement the Python class `FleuryBFSWithEdges` described below.
Class description:
Fleury's algorithm for finding an Eulerian cycle (multigraphs). Complexity O(V*E). Attributes ---------- graph : input graph eulerian_cycle : list of edges (length |E|) _graph_copy : graph, private Notes ----- Based on the description ... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class FleuryBFSWithEdges:
"""Fleury's algorithm for finding an Eulerian cycle (multigraphs). Complexity O(V*E). Attributes ---------- graph : input graph eulerian_cycle : list of edges (length |E|) _graph_copy : graph, private Notes ----- Based on the description from: https://en.wikipedia.org/wiki/Eul... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FleuryBFSWithEdges:
"""Fleury's algorithm for finding an Eulerian cycle (multigraphs). Complexity O(V*E). Attributes ---------- graph : input graph eulerian_cycle : list of edges (length |E|) _graph_copy : graph, private Notes ----- Based on the description from: https://en.wikipedia.org/wiki/Eulerian_path"""... | the_stack_v2_python_sparse | graphtheory/eulerian/fleury.py | kgashok/graphs-dict | train | 0 |
ec07d5c5713bb83d50412c120871113a2e103d9b | [
"if root != None:\n sum_n = 0\nelse:\n sum_n = 1\nstack = [root]\nres = ''\nwhile stack.__len__() != 0 and stack.__len__() != sum_n:\n node = stack.pop(0)\n if node == None:\n sum_n += 1\n res += 'None/'\n stack.append(None)\n stack.append(None)\n else:\n if node.le... | <|body_start_0|>
if root != None:
sum_n = 0
else:
sum_n = 1
stack = [root]
res = ''
while stack.__len__() != 0 and stack.__len__() != sum_n:
node = stack.pop(0)
if node == None:
sum_n += 1
res += 'Non... | 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_004580 | 2,205 | 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_040148 | 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:... | a9fb28f7cfcae8d9c9a460462ec9ee8b5f3b40d8 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root != None:
sum_n = 0
else:
sum_n = 1
stack = [root]
res = ''
while stack.__len__() != 0 and stack.__len__() != sum_n:
... | the_stack_v2_python_sparse | code/Codec.py | 3wh1te/Leecode | train | 0 | |
6fc3b6c1cebdb778655ca2958f9cd242849a1e03 | [
"super().__init__()\nnew_users = dict()\nfor user in origin:\n new_users[user] = user.copy()\n self.add(new_users[user])\nfor user in origin:\n selected_people = user.get_selected_people()\n new_selected_people = [new_users[selected_user] for selected_user in selected_people]\n new_users[user]._selec... | <|body_start_0|>
super().__init__()
new_users = dict()
for user in origin:
new_users[user] = user.copy()
self.add(new_users[user])
for user in origin:
selected_people = user.get_selected_people()
new_selected_people = [new_users[selected_us... | Set of users. Intended to simplify work with users' sets, for example, to maintain connections between objects, when performing set reduction | UserSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSet:
"""Set of users. Intended to simplify work with users' sets, for example, to maintain connections between objects, when performing set reduction"""
def __init__(self, origin):
"""Creates set, containing only new User instances, based on given set :param users_set: Original u... | stack_v2_sparse_classes_75kplus_train_004581 | 1,803 | no_license | [
{
"docstring": "Creates set, containing only new User instances, based on given set :param users_set: Original user's set :return:",
"name": "__init__",
"signature": "def __init__(self, origin)"
},
{
"docstring": "Removes users from the set with given id :param id: Id of user, which we should de... | 4 | stack_v2_sparse_classes_30k_train_036531 | Implement the Python class `UserSet` described below.
Class description:
Set of users. Intended to simplify work with users' sets, for example, to maintain connections between objects, when performing set reduction
Method signatures and docstrings:
- def __init__(self, origin): Creates set, containing only new User i... | Implement the Python class `UserSet` described below.
Class description:
Set of users. Intended to simplify work with users' sets, for example, to maintain connections between objects, when performing set reduction
Method signatures and docstrings:
- def __init__(self, origin): Creates set, containing only new User i... | a80184ddea6c0c3e35255920297dc0b95c5a27c6 | <|skeleton|>
class UserSet:
"""Set of users. Intended to simplify work with users' sets, for example, to maintain connections between objects, when performing set reduction"""
def __init__(self, origin):
"""Creates set, containing only new User instances, based on given set :param users_set: Original u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserSet:
"""Set of users. Intended to simplify work with users' sets, for example, to maintain connections between objects, when performing set reduction"""
def __init__(self, origin):
"""Creates set, containing only new User instances, based on given set :param users_set: Original user's set :re... | the_stack_v2_python_sparse | utils/userset_utils.py | XomakNet/teambuilder | train | 0 |
39df0ae406684ac3ac5a3ffd7079d3d7d64d04d5 | [
"summand = 0\nt_occurs = target.count\no_occurs = other.count\ncontext = set(target.data.keys())\ncontext.update(other.data.keys())\nfor con in context:\n try:\n target_con = target.data[con] / t_occurs\n except:\n target_con = 0\n try:\n other_con = other.data[con] / o_occurs\n exc... | <|body_start_0|>
summand = 0
t_occurs = target.count
o_occurs = other.count
context = set(target.data.keys())
context.update(other.data.keys())
for con in context:
try:
target_con = target.data[con] / t_occurs
except:
... | sim_class | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sim_class:
def el_one(target, other):
"""compute L1 norm similiarity measure"""
<|body_0|>
def cos(target, other):
"""compute cosine similarity measure"""
<|body_1|>
def skew(target, other, alpha=0.99):
"""compute skew similarity measure"""
... | stack_v2_sparse_classes_75kplus_train_004582 | 7,560 | no_license | [
{
"docstring": "compute L1 norm similiarity measure",
"name": "el_one",
"signature": "def el_one(target, other)"
},
{
"docstring": "compute cosine similarity measure",
"name": "cos",
"signature": "def cos(target, other)"
},
{
"docstring": "compute skew similarity measure",
"n... | 3 | stack_v2_sparse_classes_30k_train_034125 | Implement the Python class `sim_class` described below.
Class description:
Implement the sim_class class.
Method signatures and docstrings:
- def el_one(target, other): compute L1 norm similiarity measure
- def cos(target, other): compute cosine similarity measure
- def skew(target, other, alpha=0.99): compute skew s... | Implement the Python class `sim_class` described below.
Class description:
Implement the sim_class class.
Method signatures and docstrings:
- def el_one(target, other): compute L1 norm similiarity measure
- def cos(target, other): compute cosine similarity measure
- def skew(target, other, alpha=0.99): compute skew s... | f7b1720a5597985e8432e783b88f42a770a05a1d | <|skeleton|>
class sim_class:
def el_one(target, other):
"""compute L1 norm similiarity measure"""
<|body_0|>
def cos(target, other):
"""compute cosine similarity measure"""
<|body_1|>
def skew(target, other, alpha=0.99):
"""compute skew similarity measure"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class sim_class:
def el_one(target, other):
"""compute L1 norm similiarity measure"""
summand = 0
t_occurs = target.count
o_occurs = other.count
context = set(target.data.keys())
context.update(other.data.keys())
for con in context:
try:
... | the_stack_v2_python_sparse | projects/nlp/prole_client.py | slacr/oslab-archive | train | 0 | |
d6eaf5636e6943d254a748340a539d936edf2780 | [
"conformations = {}\nfor conf in residue.disordered_get_id_list():\n if conf not in conformations:\n conformations[conf] = self.ConformationScore()\n conf_res = residue.disordered_get(conf)\n for atom in conf_res:\n weight = self.scores.get(atom.get_id(), self.default_score)\n conforma... | <|body_start_0|>
conformations = {}
for conf in residue.disordered_get_id_list():
if conf not in conformations:
conformations[conf] = self.ConformationScore()
conf_res = residue.disordered_get(conf)
for atom in conf_res:
weight = self.s... | For each point mutation in a PDB structure that is represented by an alternative location field, pick the mutation with the highest weighted population, breaking ties on occupancy and then b-factor. .. seealso:: :py:class:`phyre_engine.tools.conformation.PopulationConformationSelector` For a description of the selectio... | PopulationMutationSelector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PopulationMutationSelector:
"""For each point mutation in a PDB structure that is represented by an alternative location field, pick the mutation with the highest weighted population, breaking ties on occupancy and then b-factor. .. seealso:: :py:class:`phyre_engine.tools.conformation.PopulationC... | stack_v2_sparse_classes_75kplus_train_004583 | 11,813 | no_license | [
{
"docstring": "Returns a sorted list of tuples containing conformation IDs and scores.",
"name": "score_conformations",
"signature": "def score_conformations(self, residue)"
},
{
"docstring": "Pick the most-populated conformation.",
"name": "select",
"signature": "def select(self, chain... | 2 | null | Implement the Python class `PopulationMutationSelector` described below.
Class description:
For each point mutation in a PDB structure that is represented by an alternative location field, pick the mutation with the highest weighted population, breaking ties on occupancy and then b-factor. .. seealso:: :py:class:`phyr... | Implement the Python class `PopulationMutationSelector` described below.
Class description:
For each point mutation in a PDB structure that is represented by an alternative location field, pick the mutation with the highest weighted population, breaking ties on occupancy and then b-factor. .. seealso:: :py:class:`phyr... | b029078dd871c9b95573b4fc31ca7b25dcecbad9 | <|skeleton|>
class PopulationMutationSelector:
"""For each point mutation in a PDB structure that is represented by an alternative location field, pick the mutation with the highest weighted population, breaking ties on occupancy and then b-factor. .. seealso:: :py:class:`phyre_engine.tools.conformation.PopulationC... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PopulationMutationSelector:
"""For each point mutation in a PDB structure that is represented by an alternative location field, pick the mutation with the highest weighted population, breaking ties on occupancy and then b-factor. .. seealso:: :py:class:`phyre_engine.tools.conformation.PopulationConformationSe... | the_stack_v2_python_sparse | phyre_engine/tools/conformation.py | PhyreEngine/phyre_engine | train | 0 |
f68e8b19d2894bec38cf38127f2f74a1e3ff173b | [
"super().set_basic_params(**filter_locals(locals(), drop=['fallback_nokey', 'subscription_key', 'emperor_command_socket']))\nself._set_aliased('fallback-on-no-key', fallback_nokey, cast=bool)\nself._set_aliased('force-key', subscription_key)\nself._set_aliased('emperor-socket', emperor_command_socket)\nreturn self"... | <|body_start_0|>
super().set_basic_params(**filter_locals(locals(), drop=['fallback_nokey', 'subscription_key', 'emperor_command_socket']))
self._set_aliased('fallback-on-no-key', fallback_nokey, cast=bool)
self._set_aliased('force-key', subscription_key)
self._set_aliased('emperor-socke... | A proxy/load-balancer/router speaking the uwsgi protocol. You can put it between your webserver and real uWSGI instances to have more control over the routing of HTTP requests to your application servers. | RouterFast | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouterFast:
"""A proxy/load-balancer/router speaking the uwsgi protocol. You can put it between your webserver and real uWSGI instances to have more control over the routing of HTTP requests to your application servers."""
def set_basic_params(self, *, workers=None, zerg_server=None, fallbac... | stack_v2_sparse_classes_75kplus_train_004584 | 33,586 | permissive | [
{
"docstring": ":param int workers: Number of worker processes to spawn. :param str zerg_server: Attach the router to a zerg server. :param str fallback_node: Fallback to the specified node in case of error. :param int concurrent_events: Set the maximum number of concurrent events router can manage. Default: sy... | 5 | stack_v2_sparse_classes_30k_train_034363 | Implement the Python class `RouterFast` described below.
Class description:
A proxy/load-balancer/router speaking the uwsgi protocol. You can put it between your webserver and real uWSGI instances to have more control over the routing of HTTP requests to your application servers.
Method signatures and docstrings:
- d... | Implement the Python class `RouterFast` described below.
Class description:
A proxy/load-balancer/router speaking the uwsgi protocol. You can put it between your webserver and real uWSGI instances to have more control over the routing of HTTP requests to your application servers.
Method signatures and docstrings:
- d... | 1060d6c9e15695b65f1875df66128fb4ff1a5c0d | <|skeleton|>
class RouterFast:
"""A proxy/load-balancer/router speaking the uwsgi protocol. You can put it between your webserver and real uWSGI instances to have more control over the routing of HTTP requests to your application servers."""
def set_basic_params(self, *, workers=None, zerg_server=None, fallbac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RouterFast:
"""A proxy/load-balancer/router speaking the uwsgi protocol. You can put it between your webserver and real uWSGI instances to have more control over the routing of HTTP requests to your application servers."""
def set_basic_params(self, *, workers=None, zerg_server=None, fallback_node=None, ... | the_stack_v2_python_sparse | uwsgiconf/options/routing_routers.py | idlesign/uwsgiconf | train | 79 |
f64bcd3dbd53b90534bb61bf076b87d7a2ff7e93 | [
"def deco(fn):\n \"\"\"Decorate the function.\"\"\"\n if isinstance(prim, str):\n self[prim] = fn\n elif issubclass(prim, Primitive):\n self[id(prim)] = fn\n return fn\nreturn deco",
"fn = default\nif isinstance(prim_obj, str) and prim_obj in self:\n fn = self[prim_obj]\nelif isinstan... | <|body_start_0|>
def deco(fn):
"""Decorate the function."""
if isinstance(prim, str):
self[prim] = fn
elif issubclass(prim, Primitive):
self[id(prim)] = fn
return fn
return deco
<|end_body_0|>
<|body_start_1|>
fn = ... | Registry class for registry functions for grad and vm_impl on Primitive. | Registry | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-f... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Registry:
"""Registry class for registry functions for grad and vm_impl on Primitive."""
def register(self, prim):
"""register the function."""
<|body_0|>
def get(self, prim_obj, default):
"""Get the value by primitive."""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_004585 | 2,358 | permissive | [
{
"docstring": "register the function.",
"name": "register",
"signature": "def register(self, prim)"
},
{
"docstring": "Get the value by primitive.",
"name": "get",
"signature": "def get(self, prim_obj, default)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017296 | Implement the Python class `Registry` described below.
Class description:
Registry class for registry functions for grad and vm_impl on Primitive.
Method signatures and docstrings:
- def register(self, prim): register the function.
- def get(self, prim_obj, default): Get the value by primitive. | Implement the Python class `Registry` described below.
Class description:
Registry class for registry functions for grad and vm_impl on Primitive.
Method signatures and docstrings:
- def register(self, prim): register the function.
- def get(self, prim_obj, default): Get the value by primitive.
<|skeleton|>
class Re... | 54acb15d435533c815ee1bd9f6dc0b56b4d4cf83 | <|skeleton|>
class Registry:
"""Registry class for registry functions for grad and vm_impl on Primitive."""
def register(self, prim):
"""register the function."""
<|body_0|>
def get(self, prim_obj, default):
"""Get the value by primitive."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Registry:
"""Registry class for registry functions for grad and vm_impl on Primitive."""
def register(self, prim):
"""register the function."""
def deco(fn):
"""Decorate the function."""
if isinstance(prim, str):
self[prim] = fn
elif iss... | the_stack_v2_python_sparse | mindspore/python/mindspore/ops/_register_for_op.py | mindspore-ai/mindspore | train | 4,178 |
93c5fb079d87c95c1221032d38ee828c19516ebb | [
"super().__init__()\nself.total_duration = 0\nself.save_partial = True\nself.orb_tune_save_each_nrmeas = 10\nself.correct_orbit = True\nself.correct_orbit_nr_iters = 5\nself.get_tunes = True\nself.bpm_name = self.DEFAULT_BPMNAME\nself.bpm_attenuation = 14\nself.acquisition_timeout = 1\nself.acquisition_period = 3\n... | <|body_start_0|>
super().__init__()
self.total_duration = 0
self.save_partial = True
self.orb_tune_save_each_nrmeas = 10
self.correct_orbit = True
self.correct_orbit_nr_iters = 5
self.get_tunes = True
self.bpm_name = self.DEFAULT_BPMNAME
self.bpm_a... | . | MeasTouschekParams | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeasTouschekParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.total_duration = 0
self.save_partial = True
self.orb_tune_... | stack_v2_sparse_classes_75kplus_train_004586 | 34,435 | permissive | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ".",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050722 | Implement the Python class `MeasTouschekParams` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def __str__(self): . | Implement the Python class `MeasTouschekParams` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def __str__(self): .
<|skeleton|>
class MeasTouschekParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""... | 39644161d98964a3a3d80d63269201f0a1712e82 | <|skeleton|>
class MeasTouschekParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MeasTouschekParams:
"""."""
def __init__(self):
"""."""
super().__init__()
self.total_duration = 0
self.save_partial = True
self.orb_tune_save_each_nrmeas = 10
self.correct_orbit = True
self.correct_orbit_nr_iters = 5
self.get_tunes = True
... | the_stack_v2_python_sparse | apsuite/commisslib/meas_touschek_lifetime.py | lnls-fac/apsuite | train | 1 |
a6fbf3e62c9af79188fdaa2c9082038e79853502 | [
"validated_data['is_staff'] = True\nadmin = super().create(validated_data)\npassword = validated_data['password']\nadmin.set_password(password)\nadmin.save()\nreturn admin",
"user = super(AdminSerializer, self).update(instance, validated_data)\nuser.set_password(validated_data['password'])\nuser.save()\nreturn us... | <|body_start_0|>
validated_data['is_staff'] = True
admin = super().create(validated_data)
password = validated_data['password']
admin.set_password(password)
admin.save()
return admin
<|end_body_0|>
<|body_start_1|>
user = super(AdminSerializer, self).update(insta... | 权限序列化器 | AdminSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminSerializer:
"""权限序列化器"""
def create(self, validated_data):
"""重写保存数据方法"""
<|body_0|>
def update(self, instance, validated_data):
"""重写更新方法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
validated_data['is_staff'] = True
admin = sup... | stack_v2_sparse_classes_75kplus_train_004587 | 1,470 | no_license | [
{
"docstring": "重写保存数据方法",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "重写更新方法",
"name": "update",
"signature": "def update(self, instance, validated_data)"
}
] | 2 | null | Implement the Python class `AdminSerializer` described below.
Class description:
权限序列化器
Method signatures and docstrings:
- def create(self, validated_data): 重写保存数据方法
- def update(self, instance, validated_data): 重写更新方法 | Implement the Python class `AdminSerializer` described below.
Class description:
权限序列化器
Method signatures and docstrings:
- def create(self, validated_data): 重写保存数据方法
- def update(self, instance, validated_data): 重写更新方法
<|skeleton|>
class AdminSerializer:
"""权限序列化器"""
def create(self, validated_data):
... | e3976cbb9e96a1558f4e00abed1c61d887f915b1 | <|skeleton|>
class AdminSerializer:
"""权限序列化器"""
def create(self, validated_data):
"""重写保存数据方法"""
<|body_0|>
def update(self, instance, validated_data):
"""重写更新方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdminSerializer:
"""权限序列化器"""
def create(self, validated_data):
"""重写保存数据方法"""
validated_data['is_staff'] = True
admin = super().create(validated_data)
password = validated_data['password']
admin.set_password(password)
admin.save()
return admin
... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/meiduo_admin/serializers/admins.py | yi0506/meiduo | train | 0 |
ffca7a04f73ce195b3bbee0d905008f508027d75 | [
"start_g = [g for g in graph if g.label == start_label]\nif len(start_g) == 1:\n start_g[0].dist = 0\nelse:\n print('wrong')\n return\nfor curr_dist in range(len(graph)):\n for g in graph:\n if not g.known and g.dist == curr_dist:\n g.known = True\n for n in g.neighbors:\n ... | <|body_start_0|>
start_g = [g for g in graph if g.label == start_label]
if len(start_g) == 1:
start_g[0].dist = 0
else:
print('wrong')
return
for curr_dist in range(len(graph)):
for g in graph:
if not g.known and g.dist == c... | @param: graph: A list of Directed graph node @return: Any topological order for the given graph. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""@param: graph: A list of Directed graph node @return: Any topological order for the given graph."""
def shortest_path(self, graph, start_label):
"""start_label代表起始点的label值"""
<|body_0|>
def shortest_path1(self, graph, start_label):
"""bfs"""
... | stack_v2_sparse_classes_75kplus_train_004588 | 2,157 | no_license | [
{
"docstring": "start_label代表起始点的label值",
"name": "shortest_path",
"signature": "def shortest_path(self, graph, start_label)"
},
{
"docstring": "bfs",
"name": "shortest_path1",
"signature": "def shortest_path1(self, graph, start_label)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042695 | Implement the Python class `Solution` described below.
Class description:
@param: graph: A list of Directed graph node @return: Any topological order for the given graph.
Method signatures and docstrings:
- def shortest_path(self, graph, start_label): start_label代表起始点的label值
- def shortest_path1(self, graph, start_la... | Implement the Python class `Solution` described below.
Class description:
@param: graph: A list of Directed graph node @return: Any topological order for the given graph.
Method signatures and docstrings:
- def shortest_path(self, graph, start_label): start_label代表起始点的label值
- def shortest_path1(self, graph, start_la... | 857b8c7fccfe8216da59228c1cf3675444855673 | <|skeleton|>
class Solution:
"""@param: graph: A list of Directed graph node @return: Any topological order for the given graph."""
def shortest_path(self, graph, start_label):
"""start_label代表起始点的label值"""
<|body_0|>
def shortest_path1(self, graph, start_label):
"""bfs"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""@param: graph: A list of Directed graph node @return: Any topological order for the given graph."""
def shortest_path(self, graph, start_label):
"""start_label代表起始点的label值"""
start_g = [g for g in graph if g.label == start_label]
if len(start_g) == 1:
star... | the_stack_v2_python_sparse | algorithm/Single-source-shortest-paths-in-directed-acyclic-graphs.py | atashi/LLL | train | 0 |
48308291270a1693ece02d8d6807a5ef74f3caa5 | [
"new_block = ConvBlockGene('decode block', parent=self)\nself.children.append(new_block)\npass",
"encoder = self.root.children[0]\nn_encoder_blocks = encoder.hyperparam('n_blocks')\nn_children = n_encoder_blocks + 1\nn_children_now = len(self.children)\nd_n_children = n_children - n_children_now\nif d_n_children ... | <|body_start_0|>
new_block = ConvBlockGene('decode block', parent=self)
self.children.append(new_block)
pass
<|end_body_0|>
<|body_start_1|>
encoder = self.root.children[0]
n_encoder_blocks = encoder.hyperparam('n_blocks')
n_children = n_encoder_blocks + 1
n_chil... | Controls the creation of a decoder network module. A decoder network synthesizes an image (or something else?) from a collection of encoded features created by an encoder network. TODO Attributes: | DecoderGene | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderGene:
"""Controls the creation of a decoder network module. A decoder network synthesizes an image (or something else?) from a collection of encoded features created by an encoder network. TODO Attributes:"""
def add_child(self):
"""Add a child ConvBlockGene to this gene's chi... | stack_v2_sparse_classes_75kplus_train_004589 | 4,373 | no_license | [
{
"docstring": "Add a child ConvBlockGene to this gene's children. Returns: None",
"name": "add_child",
"signature": "def add_child(self)"
},
{
"docstring": "Set up child blocks. Returns: None",
"name": "setup_children",
"signature": "def setup_children(self)"
},
{
"docstring": "... | 5 | stack_v2_sparse_classes_30k_train_044494 | Implement the Python class `DecoderGene` described below.
Class description:
Controls the creation of a decoder network module. A decoder network synthesizes an image (or something else?) from a collection of encoded features created by an encoder network. TODO Attributes:
Method signatures and docstrings:
- def add_... | Implement the Python class `DecoderGene` described below.
Class description:
Controls the creation of a decoder network module. A decoder network synthesizes an image (or something else?) from a collection of encoded features created by an encoder network. TODO Attributes:
Method signatures and docstrings:
- def add_... | 6b78dc5e1e793a206ae3f4860d3a9ac887e663e5 | <|skeleton|>
class DecoderGene:
"""Controls the creation of a decoder network module. A decoder network synthesizes an image (or something else?) from a collection of encoded features created by an encoder network. TODO Attributes:"""
def add_child(self):
"""Add a child ConvBlockGene to this gene's chi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecoderGene:
"""Controls the creation of a decoder network module. A decoder network synthesizes an image (or something else?) from a collection of encoded features created by an encoder network. TODO Attributes:"""
def add_child(self):
"""Add a child ConvBlockGene to this gene's children. Return... | the_stack_v2_python_sparse | example3/src/_private/genenet/genes/DecoderGene.py | leapmanlab/examples | train | 1 |
effb00a0161be4d56d0591e9d61923133a70cce9 | [
"self.node = node\nself.connection_manager = manager\npb.PBClientFactory.__init__(self)",
"with self.connection_manager._lock:\n node = self.node\n node.ref = None\n for i in range(node.cores):\n w_key = '%s:%s:%i' % (node.host, node.port, i)\n del self.connection_manager.workers[w_key]\n ... | <|body_start_0|>
self.node = node
self.connection_manager = manager
pb.PBClientFactory.__init__(self)
<|end_body_0|>
<|body_start_1|>
with self.connection_manager._lock:
node = self.node
node.ref = None
for i in range(node.cores):
w_ke... | Subclassing of PBClientFactory to add auto-reconnect via Master's reconnection code. This factory is specific to the master acting as a client of a Node. | NodeClientFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeClientFactory:
"""Subclassing of PBClientFactory to add auto-reconnect via Master's reconnection code. This factory is specific to the master acting as a client of a Node."""
def __init__(self, node, manager):
"""@param node - node this factory is watching @param manager - manage... | stack_v2_sparse_classes_75kplus_train_004590 | 12,623 | no_license | [
{
"docstring": "@param node - node this factory is watching @param manager - manager that is tracking this node",
"name": "__init__",
"signature": "def __init__(self, node, manager)"
},
{
"docstring": "Called when self.node disconnects",
"name": "clientConnectionLost",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_021203 | Implement the Python class `NodeClientFactory` described below.
Class description:
Subclassing of PBClientFactory to add auto-reconnect via Master's reconnection code. This factory is specific to the master acting as a client of a Node.
Method signatures and docstrings:
- def __init__(self, node, manager): @param nod... | Implement the Python class `NodeClientFactory` described below.
Class description:
Subclassing of PBClientFactory to add auto-reconnect via Master's reconnection code. This factory is specific to the master acting as a client of a Node.
Method signatures and docstrings:
- def __init__(self, node, manager): @param nod... | 9696819fcebfc175969d680bbf58a70d615c4f07 | <|skeleton|>
class NodeClientFactory:
"""Subclassing of PBClientFactory to add auto-reconnect via Master's reconnection code. This factory is specific to the master acting as a client of a Node."""
def __init__(self, node, manager):
"""@param node - node this factory is watching @param manager - manage... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NodeClientFactory:
"""Subclassing of PBClientFactory to add auto-reconnect via Master's reconnection code. This factory is specific to the master acting as a client of a Node."""
def __init__(self, node, manager):
"""@param node - node this factory is watching @param manager - manager that is tra... | the_stack_v2_python_sparse | pydra/cluster/master/node_connection_manager.py | kreneskyp/Pydra | train | 2 |
099c3063bfc87406faa3a7789ea2c1d897b83d0f | [
"qualifier = rating_string[-2]\nnumber = int(rating_string[:-2])\nif qualifier == 'M':\n number *= 1000000\nelif qualifier == 'K':\n number *= 1000\nreturn number",
"trends_list = list()\nkeys = ('title', 'avatar', 'description', 'day')\ndate = req_json['date']\ntrends = req_json['trendingSearches']\nfor tr... | <|body_start_0|>
qualifier = rating_string[-2]
number = int(rating_string[:-2])
if qualifier == 'M':
number *= 1000000
elif qualifier == 'K':
number *= 1000
return number
<|end_body_0|>
<|body_start_1|>
trends_list = list()
keys = ('title'... | Subclass of TrendReq, implements it's own logic of parsing daily google trends | RealTrendReq | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RealTrendReq:
"""Subclass of TrendReq, implements it's own logic of parsing daily google trends"""
def rating_to_int(rating_string):
""":param rating_string: number of user requests in string format Convert google search measure of trend from string to integer :returns: trend rating ... | stack_v2_sparse_classes_75kplus_train_004591 | 2,566 | no_license | [
{
"docstring": ":param rating_string: number of user requests in string format Convert google search measure of trend from string to integer :returns: trend rating as integer",
"name": "rating_to_int",
"signature": "def rating_to_int(rating_string)"
},
{
"docstring": ":param req_json: part of js... | 3 | stack_v2_sparse_classes_30k_train_034160 | Implement the Python class `RealTrendReq` described below.
Class description:
Subclass of TrendReq, implements it's own logic of parsing daily google trends
Method signatures and docstrings:
- def rating_to_int(rating_string): :param rating_string: number of user requests in string format Convert google search measur... | Implement the Python class `RealTrendReq` described below.
Class description:
Subclass of TrendReq, implements it's own logic of parsing daily google trends
Method signatures and docstrings:
- def rating_to_int(rating_string): :param rating_string: number of user requests in string format Convert google search measur... | 39ef586228e02553be17bac79915d3de52d15b4b | <|skeleton|>
class RealTrendReq:
"""Subclass of TrendReq, implements it's own logic of parsing daily google trends"""
def rating_to_int(rating_string):
""":param rating_string: number of user requests in string format Convert google search measure of trend from string to integer :returns: trend rating ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RealTrendReq:
"""Subclass of TrendReq, implements it's own logic of parsing daily google trends"""
def rating_to_int(rating_string):
""":param rating_string: number of user requests in string format Convert google search measure of trend from string to integer :returns: trend rating as integer"""... | the_stack_v2_python_sparse | backend/trends/trends/clients/prefs.py | Darhild/trends | train | 0 |
4f65f17ebe58cf19ed40e665061044e828b6a84d | [
"self.dialogs = dialogs\nself.language = language\nself.styling = styling\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\ndialogs = idfy_rest_client.models.dialogs.Dialogs.from_dictionary(dictionary.get('dialogs')) if dictionary.get('dialogs') else None\nlanguage = ... | <|body_start_0|>
self.dialogs = dialogs
self.language = language
self.styling = styling
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
dialogs = idfy_rest_client.models.dialogs.Dialogs.fro... | Implementation of the 'UI' model. TODO: type model description here. Attributes: dialogs (Dialogs): You can create dialogs that will be showed to the signer in the signature process language (Language157): The signers preferred language, this setting is used when signing the document and in email/sms notifications.<spa... | UI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UI:
"""Implementation of the 'UI' model. TODO: type model description here. Attributes: dialogs (Dialogs): You can create dialogs that will be showed to the signer in the signature process language (Language157): The signers preferred language, this setting is used when signing the document and i... | stack_v2_sparse_classes_75kplus_train_004592 | 3,051 | permissive | [
{
"docstring": "Constructor for the UI class",
"name": "__init__",
"signature": "def __init__(self, dialogs=None, language=None, styling=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representat... | 2 | stack_v2_sparse_classes_30k_train_048587 | Implement the Python class `UI` described below.
Class description:
Implementation of the 'UI' model. TODO: type model description here. Attributes: dialogs (Dialogs): You can create dialogs that will be showed to the signer in the signature process language (Language157): The signers preferred language, this setting ... | Implement the Python class `UI` described below.
Class description:
Implementation of the 'UI' model. TODO: type model description here. Attributes: dialogs (Dialogs): You can create dialogs that will be showed to the signer in the signature process language (Language157): The signers preferred language, this setting ... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class UI:
"""Implementation of the 'UI' model. TODO: type model description here. Attributes: dialogs (Dialogs): You can create dialogs that will be showed to the signer in the signature process language (Language157): The signers preferred language, this setting is used when signing the document and i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UI:
"""Implementation of the 'UI' model. TODO: type model description here. Attributes: dialogs (Dialogs): You can create dialogs that will be showed to the signer in the signature process language (Language157): The signers preferred language, this setting is used when signing the document and in email/sms n... | the_stack_v2_python_sparse | idfy_rest_client/models/ui.py | dealflowteam/Idfy | train | 0 |
ba87b851b9224259391387b20fb6870ba0fb1f14 | [
"try:\n return db_session.query(dfa_models_v2.ProjectNameCache).filter_by(project_id=pid).one()\nexcept exc.NoResultFound:\n raise dexc.ProjectIdNotFound(project_id=pid)",
"db_session = db.get_session()\nwith db_session.begin(subtransactions=True):\n projid = proj_info['project_id']\n projname = proj_... | <|body_start_0|>
try:
return db_session.query(dfa_models_v2.ProjectNameCache).filter_by(project_id=pid).one()
except exc.NoResultFound:
raise dexc.ProjectIdNotFound(project_id=pid)
<|end_body_0|>
<|body_start_1|>
db_session = db.get_session()
with db_session.begi... | Project DB API. | ProjectsInfoCache | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectsInfoCache:
"""Project DB API."""
def _get_project_entry(self, db_session, pid):
"""Get a project entry from the table. :param db_session: database session object :param pid: project ID"""
<|body_0|>
def create_projects_cache_db(self, proj_info):
"""Create... | stack_v2_sparse_classes_75kplus_train_004593 | 3,360 | permissive | [
{
"docstring": "Get a project entry from the table. :param db_session: database session object :param pid: project ID",
"name": "_get_project_entry",
"signature": "def _get_project_entry(self, db_session, pid)"
},
{
"docstring": "Create an entry in the database. :param proj_info: dictionary that... | 6 | stack_v2_sparse_classes_30k_train_043879 | Implement the Python class `ProjectsInfoCache` described below.
Class description:
Project DB API.
Method signatures and docstrings:
- def _get_project_entry(self, db_session, pid): Get a project entry from the table. :param db_session: database session object :param pid: project ID
- def create_projects_cache_db(sel... | Implement the Python class `ProjectsInfoCache` described below.
Class description:
Project DB API.
Method signatures and docstrings:
- def _get_project_entry(self, db_session, pid): Get a project entry from the table. :param db_session: database session object :param pid: project ID
- def create_projects_cache_db(sel... | a1da17d0d63b3342a48c35da37984d6386ee1016 | <|skeleton|>
class ProjectsInfoCache:
"""Project DB API."""
def _get_project_entry(self, db_session, pid):
"""Get a project entry from the table. :param db_session: database session object :param pid: project ID"""
<|body_0|>
def create_projects_cache_db(self, proj_info):
"""Create... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectsInfoCache:
"""Project DB API."""
def _get_project_entry(self, db_session, pid):
"""Get a project entry from the table. :param db_session: database session object :param pid: project ID"""
try:
return db_session.query(dfa_models_v2.ProjectNameCache).filter_by(project_id... | the_stack_v2_python_sparse | neutron/plugins/ml2/drivers/cisco/dfa/projects_cache_db_v2.py | CingHu/neutron-ustack | train | 0 |
ee544876b8cc667ea4be09384f3a8058bef3930b | [
"ret = BaseUtils()\ntry:\n queryset = models.Course.objects.all()\n ser = CourseSerializer(instance=queryset, many=True)\n ret.data = ser.data\n ret.code = 1000\nexcept Exception as e:\n ret.code = 1001\n ret.error = '获取课程失败'\nreturn Response(ret.dict)",
"ret = {'code': 1000, 'data': None}\nset ... | <|body_start_0|>
ret = BaseUtils()
try:
queryset = models.Course.objects.all()
ser = CourseSerializer(instance=queryset, many=True)
ret.data = ser.data
ret.code = 1000
except Exception as e:
ret.code = 1001
ret.error = '获取课程... | CourseView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseView:
def list(self, request, *args, **kwargs):
"""课程列表 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建课程 :param request: :param args: :param kwargs: :return:"""
<|body_1|>
def retr... | stack_v2_sparse_classes_75kplus_train_004594 | 2,869 | no_license | [
{
"docstring": "课程列表 :param request: :param args: :param kwargs: :return:",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstring": "创建课程 :param request: :param args: :param kwargs: :return:",
"name": "post",
"signature": "def post(self, request, *args, ... | 4 | stack_v2_sparse_classes_30k_train_033389 | Implement the Python class `CourseView` described below.
Class description:
Implement the CourseView class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): 课程列表 :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): 创建课程 :param request: :param ar... | Implement the Python class `CourseView` described below.
Class description:
Implement the CourseView class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): 课程列表 :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): 创建课程 :param request: :param ar... | 306ce096537ac3e71ee7530ee58b43a9c3f25489 | <|skeleton|>
class CourseView:
def list(self, request, *args, **kwargs):
"""课程列表 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建课程 :param request: :param args: :param kwargs: :return:"""
<|body_1|>
def retr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CourseView:
def list(self, request, *args, **kwargs):
"""课程列表 :param request: :param args: :param kwargs: :return:"""
ret = BaseUtils()
try:
queryset = models.Course.objects.all()
ser = CourseSerializer(instance=queryset, many=True)
ret.data = ser.da... | the_stack_v2_python_sparse | luffapi/views/course.py | xxt123456/luffcity | train | 0 | |
b089d601996f79b6e22704815a0ae8a17e15d640 | [
"super().__init__(name='reward_predictor')\nself.model_size = model_size\nself.mlp = MLP(model_size=model_size, output_layer_size=None)\nself.reward_layer = RewardPredictorLayer(num_buckets=num_buckets, lower_bound=lower_bound, upper_bound=upper_bound)\ndl_type = tf.keras.mixed_precision.global_policy().compute_dty... | <|body_start_0|>
super().__init__(name='reward_predictor')
self.model_size = model_size
self.mlp = MLP(model_size=model_size, output_layer_size=None)
self.reward_layer = RewardPredictorLayer(num_buckets=num_buckets, lower_bound=lower_bound, upper_bound=upper_bound)
dl_type = tf.k... | Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. Predicted rewards are used to produce "dream data" to learn the policy in. | RewardPredictor | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RewardPredictor:
"""Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. Predicted rewards are used to produce "dream data" to learn the policy in."""
def __init__(self, *, model_size: Optional[str]='XS', num_buckets: int=255, lower_bound: float=-20.0, upper_bound:... | stack_v2_sparse_classes_75kplus_train_004595 | 4,202 | permissive | [
{
"docstring": "Initializes a RewardPredictor instance. Args: model_size: The \"Model Size\" used according to [1] Appendinx B. Determines the exact size of the underlying MLP. num_buckets: The number of buckets to create. Note that the number of possible symlog'd outcomes from the used distribution is `num_buc... | 2 | stack_v2_sparse_classes_30k_train_045781 | Implement the Python class `RewardPredictor` described below.
Class description:
Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. Predicted rewards are used to produce "dream data" to learn the policy in.
Method signatures and docstrings:
- def __init__(self, *, model_size: Optional[str... | Implement the Python class `RewardPredictor` described below.
Class description:
Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. Predicted rewards are used to produce "dream data" to learn the policy in.
Method signatures and docstrings:
- def __init__(self, *, model_size: Optional[str... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class RewardPredictor:
"""Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. Predicted rewards are used to produce "dream data" to learn the policy in."""
def __init__(self, *, model_size: Optional[str]='XS', num_buckets: int=255, lower_bound: float=-20.0, upper_bound:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RewardPredictor:
"""Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. Predicted rewards are used to produce "dream data" to learn the policy in."""
def __init__(self, *, model_size: Optional[str]='XS', num_buckets: int=255, lower_bound: float=-20.0, upper_bound: float=20.0):... | the_stack_v2_python_sparse | rllib/algorithms/dreamerv3/tf/models/components/reward_predictor.py | ray-project/ray | train | 29,482 |
aecebc78a40f65e7b4fc392bf28c27b4987133f7 | [
"keyword = self.request.query_params.get('keyword')\nif keyword == '' or keyword is None:\n return OrderInfo.objects.all()\nelse:\n return OrderInfo.objects.filter(order_id__contains=keyword)",
"try:\n order = OrderInfo.objects.get(order_id=order_id)\nexcept OrderInfo.DoesNotExist as e:\n logger.error... | <|body_start_0|>
keyword = self.request.query_params.get('keyword')
if keyword == '' or keyword is None:
return OrderInfo.objects.all()
else:
return OrderInfo.objects.filter(order_id__contains=keyword)
<|end_body_0|>
<|body_start_1|>
try:
order = Orde... | 订单信息管理 | OrdersView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrdersView:
"""订单信息管理"""
def get_queryset(self):
"""重写get_queryset方法,根据前端是否传递keyword值返回不同查询结果,得到查询集"""
<|body_0|>
def status(self, request, order_id):
"""修改订单状态"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
keyword = self.request.query_params.... | stack_v2_sparse_classes_75kplus_train_004596 | 1,741 | no_license | [
{
"docstring": "重写get_queryset方法,根据前端是否传递keyword值返回不同查询结果,得到查询集",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "修改订单状态",
"name": "status",
"signature": "def status(self, request, order_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042903 | Implement the Python class `OrdersView` described below.
Class description:
订单信息管理
Method signatures and docstrings:
- def get_queryset(self): 重写get_queryset方法,根据前端是否传递keyword值返回不同查询结果,得到查询集
- def status(self, request, order_id): 修改订单状态 | Implement the Python class `OrdersView` described below.
Class description:
订单信息管理
Method signatures and docstrings:
- def get_queryset(self): 重写get_queryset方法,根据前端是否传递keyword值返回不同查询结果,得到查询集
- def status(self, request, order_id): 修改订单状态
<|skeleton|>
class OrdersView:
"""订单信息管理"""
def get_queryset(self):
... | e3976cbb9e96a1558f4e00abed1c61d887f915b1 | <|skeleton|>
class OrdersView:
"""订单信息管理"""
def get_queryset(self):
"""重写get_queryset方法,根据前端是否传递keyword值返回不同查询结果,得到查询集"""
<|body_0|>
def status(self, request, order_id):
"""修改订单状态"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrdersView:
"""订单信息管理"""
def get_queryset(self):
"""重写get_queryset方法,根据前端是否传递keyword值返回不同查询结果,得到查询集"""
keyword = self.request.query_params.get('keyword')
if keyword == '' or keyword is None:
return OrderInfo.objects.all()
else:
return OrderInfo.obje... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/meiduo_admin/views/orders.py | yi0506/meiduo | train | 0 |
2a17eab2c353890a8d0aa428844decb4661e8efb | [
"direct_vec = np.zeros((11,))\nnext_direction = bp.Policy.TURNS[direction][action]\nnext_pos = head_pos.move(next_direction)\nboard_value = board[next_pos[0], next_pos[1]]\ndirect_vec[board_value + 1] = 1\nreturn direct_vec.tolist()",
"head_pos, direction = head\nvalues = np.zeros((11,))\nCustom.Feature.features_... | <|body_start_0|>
direct_vec = np.zeros((11,))
next_direction = bp.Policy.TURNS[direction][action]
next_pos = head_pos.move(next_direction)
board_value = board[next_pos[0], next_pos[1]]
direct_vec[board_value + 1] = 1
return direct_vec.tolist()
<|end_body_0|>
<|body_start... | A class that represent the features | Feature | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Feature:
"""A class that represent the features"""
def next_action_feature(head_pos, direction, action, board):
"""Checks what is the value in the cell of the next action and return a vector according to he value :param head_pos: head position :param direction: direction :param actio... | stack_v2_sparse_classes_75kplus_train_004597 | 16,456 | no_license | [
{
"docstring": "Checks what is the value in the cell of the next action and return a vector according to he value :param head_pos: head position :param direction: direction :param action: action :param board: board :return: zeros vector of size (11,) with 1 at the index of the value in the next position",
"... | 4 | null | Implement the Python class `Feature` described below.
Class description:
A class that represent the features
Method signatures and docstrings:
- def next_action_feature(head_pos, direction, action, board): Checks what is the value in the cell of the next action and return a vector according to he value :param head_po... | Implement the Python class `Feature` described below.
Class description:
A class that represent the features
Method signatures and docstrings:
- def next_action_feature(head_pos, direction, action, board): Checks what is the value in the cell of the next action and return a vector according to he value :param head_po... | d42d64300da96ac3c9c5378b1faba9693e93f14d | <|skeleton|>
class Feature:
"""A class that represent the features"""
def next_action_feature(head_pos, direction, action, board):
"""Checks what is the value in the cell of the next action and return a vector according to he value :param head_pos: head position :param direction: direction :param actio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Feature:
"""A class that represent the features"""
def next_action_feature(head_pos, direction, action, board):
"""Checks what is the value in the cell of the next action and return a vector according to he value :param head_pos: head position :param direction: direction :param action: action :pa... | the_stack_v2_python_sparse | policies/policy_Custom.py | LotanLevy/snake_game | train | 0 |
bfcd4da62a083bac86520a5ab26b870f4b86f7b9 | [
"def build(start, end):\n if start >= end:\n return 1\n if dp[start][end]:\n return dp[start][end]\n count = 0\n for root_val in range(start, end + 1):\n count += build(start, root_val - 1) * build(root_val + 1, end)\n dp[start][end] = count\n return count\ndp = [[0] * n for _... | <|body_start_0|>
def build(start, end):
if start >= end:
return 1
if dp[start][end]:
return dp[start][end]
count = 0
for root_val in range(start, end + 1):
count += build(start, root_val - 1) * build(root_val + 1, en... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numTrees(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numTrees_math(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def build(start, end):
if start >= end:
re... | stack_v2_sparse_classes_75kplus_train_004598 | 1,971 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "numTrees",
"signature": "def numTrees(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "numTrees_math",
"signature": "def numTrees_math(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numTrees(self, n): :type n: int :rtype: int
- def numTrees_math(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numTrees(self, n): :type n: int :rtype: int
- def numTrees_math(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def numTrees(self, n):
""":type ... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def numTrees(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numTrees_math(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numTrees(self, n):
""":type n: int :rtype: int"""
def build(start, end):
if start >= end:
return 1
if dp[start][end]:
return dp[start][end]
count = 0
for root_val in range(start, end + 1):
... | the_stack_v2_python_sparse | src/lt_96.py | oxhead/CodingYourWay | train | 0 | |
245e26466fbd216eda585cfef1abd3c865c92162 | [
"super(ValueChange, self).__init__(env, realign_fn)\nself.state_var = state_var\nself.normalize_by_steps = normalize_by_steps",
"history = self._extract_history(env)\ninitial_state = history[0].state\nfinal_state = history[-1].state\ndelta = getattr(final_state, self.state_var) - getattr(initial_state, self.state... | <|body_start_0|>
super(ValueChange, self).__init__(env, realign_fn)
self.state_var = state_var
self.normalize_by_steps = normalize_by_steps
<|end_body_0|>
<|body_start_1|>
history = self._extract_history(env)
initial_state = history[0].state
final_state = history[-1].sta... | Metric that returns how much a value has changed over the experiment. | ValueChange | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueChange:
"""Metric that returns how much a value has changed over the experiment."""
def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None):
"""Initializes the ValueChange metric. Args: env: A `core.FairnessEnv`. state_var: string name of a state variable to... | stack_v2_sparse_classes_75kplus_train_004599 | 7,087 | permissive | [
{
"docstring": "Initializes the ValueChange metric. Args: env: A `core.FairnessEnv`. state_var: string name of a state variable to track. normalize_by_steps: Whether to divide by number of steps to get an average change. realign_fn: Optional. If not None, defines how to realign history for use by a metric.",
... | 2 | stack_v2_sparse_classes_30k_train_030061 | Implement the Python class `ValueChange` described below.
Class description:
Metric that returns how much a value has changed over the experiment.
Method signatures and docstrings:
- def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None): Initializes the ValueChange metric. Args: env: A `core.Fa... | Implement the Python class `ValueChange` described below.
Class description:
Metric that returns how much a value has changed over the experiment.
Method signatures and docstrings:
- def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None): Initializes the ValueChange metric. Args: env: A `core.Fa... | 38eaf4514062892e0c3ce5d7cff4b4c1a7e49242 | <|skeleton|>
class ValueChange:
"""Metric that returns how much a value has changed over the experiment."""
def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None):
"""Initializes the ValueChange metric. Args: env: A `core.FairnessEnv`. state_var: string name of a state variable to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValueChange:
"""Metric that returns how much a value has changed over the experiment."""
def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None):
"""Initializes the ValueChange metric. Args: env: A `core.FairnessEnv`. state_var: string name of a state variable to track. norma... | the_stack_v2_python_sparse | metrics/value_tracking_metrics.py | google/ml-fairness-gym | train | 310 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.