blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a6332afc6bedaf9475623a46cd20ab564ad094dd | [
"with open(HTML5.JQUERY_LOAD_HELPER) as f:\n load_jquery_js = f.read()\ndriver.execute_async_script(load_jquery_js, jquery_url)",
"HTML5.__load_jquery(driver)\nwith open(HTML5.DRAG_AND_DROP_HELPER) as f:\n drag_and_drop_js = f.read()\ndrag_and_drop_command = \"$('{draggable}').simulateDragDrop({{ dropTarget... | <|body_start_0|>
with open(HTML5.JQUERY_LOAD_HELPER) as f:
load_jquery_js = f.read()
driver.execute_async_script(load_jquery_js, jquery_url)
<|end_body_0|>
<|body_start_1|>
HTML5.__load_jquery(driver)
with open(HTML5.DRAG_AND_DROP_HELPER) as f:
drag_and_drop_js =... | HTML5 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTML5:
def __load_jquery(driver, jquery_url=JQUERY_URL):
""":param driver: WebDriver object :param jquery_url: STRING, url from which to import jq :return: None"""
<|body_0|>
def drag_and_drop(driver, draggable, droppable):
""":param driver: WebDriver object :param d... | stack_v2_sparse_classes_36k_train_014900 | 2,733 | no_license | [
{
"docstring": ":param driver: WebDriver object :param jquery_url: STRING, url from which to import jq :return: None",
"name": "__load_jquery",
"signature": "def __load_jquery(driver, jquery_url=JQUERY_URL)"
},
{
"docstring": ":param driver: WebDriver object :param draggable: STRING, selector ht... | 2 | stack_v2_sparse_classes_30k_train_016976 | Implement the Python class `HTML5` described below.
Class description:
Implement the HTML5 class.
Method signatures and docstrings:
- def __load_jquery(driver, jquery_url=JQUERY_URL): :param driver: WebDriver object :param jquery_url: STRING, url from which to import jq :return: None
- def drag_and_drop(driver, dragg... | Implement the Python class `HTML5` described below.
Class description:
Implement the HTML5 class.
Method signatures and docstrings:
- def __load_jquery(driver, jquery_url=JQUERY_URL): :param driver: WebDriver object :param jquery_url: STRING, url from which to import jq :return: None
- def drag_and_drop(driver, dragg... | 44e6013622c5f09e0a390de6e7a94c9c253eb00f | <|skeleton|>
class HTML5:
def __load_jquery(driver, jquery_url=JQUERY_URL):
""":param driver: WebDriver object :param jquery_url: STRING, url from which to import jq :return: None"""
<|body_0|>
def drag_and_drop(driver, draggable, droppable):
""":param driver: WebDriver object :param d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HTML5:
def __load_jquery(driver, jquery_url=JQUERY_URL):
""":param driver: WebDriver object :param jquery_url: STRING, url from which to import jq :return: None"""
with open(HTML5.JQUERY_LOAD_HELPER) as f:
load_jquery_js = f.read()
driver.execute_async_script(load_jquery_js... | the_stack_v2_python_sparse | advance-selenium-1/test_drag_and_drop.py | lindafanglizhi/seleniumforpython | train | 0 | |
1dd6a6e0ad832b0ded2637de16293801525535a8 | [
"response = super(WorkflowDetail, self).retrieve(request, *args, **kwargs)\ntemplate_data = {'title': ''}\nreturn services.append_collection_template(response, template_data)",
"data = self.request.data\ndata.pop('previous_plugin_inst_id', None)\ndata.pop('nodes_info', None)\nreturn super(WorkflowDetail, self).up... | <|body_start_0|>
response = super(WorkflowDetail, self).retrieve(request, *args, **kwargs)
template_data = {'title': ''}
return services.append_collection_template(response, template_data)
<|end_body_0|>
<|body_start_1|>
data = self.request.data
data.pop('previous_plugin_inst_id... | A workflow view. | WorkflowDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowDetail:
"""A workflow view."""
def retrieve(self, request, *args, **kwargs):
"""Overriden to append a collection+json template to the response."""
<|body_0|>
def update(self, request, *args, **kwargs):
"""Overriden to remove descriptors that are not allow... | stack_v2_sparse_classes_36k_train_014901 | 9,518 | permissive | [
{
"docstring": "Overriden to append a collection+json template to the response.",
"name": "retrieve",
"signature": "def retrieve(self, request, *args, **kwargs)"
},
{
"docstring": "Overriden to remove descriptors that are not allowed to be updated before serializer validation.",
"name": "upd... | 3 | stack_v2_sparse_classes_30k_train_012016 | Implement the Python class `WorkflowDetail` described below.
Class description:
A workflow view.
Method signatures and docstrings:
- def retrieve(self, request, *args, **kwargs): Overriden to append a collection+json template to the response.
- def update(self, request, *args, **kwargs): Overriden to remove descripto... | Implement the Python class `WorkflowDetail` described below.
Class description:
A workflow view.
Method signatures and docstrings:
- def retrieve(self, request, *args, **kwargs): Overriden to append a collection+json template to the response.
- def update(self, request, *args, **kwargs): Overriden to remove descripto... | 20d3eedf20610af9182f6cca8db8f0b3546b5336 | <|skeleton|>
class WorkflowDetail:
"""A workflow view."""
def retrieve(self, request, *args, **kwargs):
"""Overriden to append a collection+json template to the response."""
<|body_0|>
def update(self, request, *args, **kwargs):
"""Overriden to remove descriptors that are not allow... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkflowDetail:
"""A workflow view."""
def retrieve(self, request, *args, **kwargs):
"""Overriden to append a collection+json template to the response."""
response = super(WorkflowDetail, self).retrieve(request, *args, **kwargs)
template_data = {'title': ''}
return service... | the_stack_v2_python_sparse | chris_backend/workflows/views.py | FNNDSC/ChRIS_ultron_backEnd | train | 36 |
b716380388a50b37db32a369709c0c49c1ad2e79 | [
"input_stream_ids = {f'input_{idx}': ik for idx, ik in enumerate(input_stream_keys)}\nassert 'new_shape' in config, \"BatchReshapeModule relies on 'new_shape' list.\\n Not found in config.\"\nsuper(BatchReshapeModule, self).__init__(id=id, type='BatchReshapeModule', config=config, input_stream_ids=in... | <|body_start_0|>
input_stream_ids = {f'input_{idx}': ik for idx, ik in enumerate(input_stream_keys)}
assert 'new_shape' in config, "BatchReshapeModule relies on 'new_shape' list.\n Not found in config."
super(BatchReshapeModule, self).__init__(id=id, type='BatchReshapeModule', con... | BatchReshapeModule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchReshapeModule:
def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]):
"""Reshape input streams data while keeping the batch dimension identical. :param config: Dict of parameters. Expectes: - "new_shape": List of Tuple/List/torch.Size representing the ... | stack_v2_sparse_classes_36k_train_014902 | 2,691 | permissive | [
{
"docstring": "Reshape input streams data while keeping the batch dimension identical. :param config: Dict of parameters. Expectes: - \"new_shape\": List of Tuple/List/torch.Size representing the new shape of each input stream, without mentionning the batch dimension. If multiple input streams are proposed but... | 2 | stack_v2_sparse_classes_30k_train_010171 | Implement the Python class `BatchReshapeModule` described below.
Class description:
Implement the BatchReshapeModule class.
Method signatures and docstrings:
- def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]): Reshape input streams data while keeping the batch dimension identical. ... | Implement the Python class `BatchReshapeModule` described below.
Class description:
Implement the BatchReshapeModule class.
Method signatures and docstrings:
- def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]): Reshape input streams data while keeping the batch dimension identical. ... | afe22da2ac20c0d24e93b4dbd1f1ad61374d1a6c | <|skeleton|>
class BatchReshapeModule:
def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]):
"""Reshape input streams data while keeping the batch dimension identical. :param config: Dict of parameters. Expectes: - "new_shape": List of Tuple/List/torch.Size representing the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchReshapeModule:
def __init__(self, id: str, config: Dict[str, object], input_stream_keys: List[str]):
"""Reshape input streams data while keeping the batch dimension identical. :param config: Dict of parameters. Expectes: - "new_shape": List of Tuple/List/torch.Size representing the new shape of e... | the_stack_v2_python_sparse | ReferentialGym/modules/batch_reshape_module.py | mk788/ReferentialGym | train | 0 | |
055c4d78c1de2906bc018d6082e9f7222fc16ab6 | [
"if not hasattr(self, '_dimensions_cache'):\n self._dimensions_cache = self.get_image_dimensions()\nreturn self._dimensions_cache",
"close = self.closed\ntry:\n self.open()\n image = willow.Image.open(self)\n return image.get_size()\nfinally:\n if close:\n self.close()\n else:\n se... | <|body_start_0|>
if not hasattr(self, '_dimensions_cache'):
self._dimensions_cache = self.get_image_dimensions()
return self._dimensions_cache
<|end_body_0|>
<|body_start_1|>
close = self.closed
try:
self.open()
image = willow.Image.open(self)
... | Override the ImageFieldFile in order to use Willow instead of Pillow. | WagtailImageFieldFile | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WagtailImageFieldFile:
"""Override the ImageFieldFile in order to use Willow instead of Pillow."""
def _get_image_dimensions(self):
"""override _get_image_dimensions to call our own get_image_dimensions."""
<|body_0|>
def get_image_dimensions(self):
"""The upstre... | stack_v2_sparse_classes_36k_train_014903 | 42,364 | permissive | [
{
"docstring": "override _get_image_dimensions to call our own get_image_dimensions.",
"name": "_get_image_dimensions",
"signature": "def _get_image_dimensions(self)"
},
{
"docstring": "The upstream ImageFieldFile calls a local function get_image_dimensions. In this implementation we've made get... | 2 | stack_v2_sparse_classes_30k_train_011176 | Implement the Python class `WagtailImageFieldFile` described below.
Class description:
Override the ImageFieldFile in order to use Willow instead of Pillow.
Method signatures and docstrings:
- def _get_image_dimensions(self): override _get_image_dimensions to call our own get_image_dimensions.
- def get_image_dimensi... | Implement the Python class `WagtailImageFieldFile` described below.
Class description:
Override the ImageFieldFile in order to use Willow instead of Pillow.
Method signatures and docstrings:
- def _get_image_dimensions(self): override _get_image_dimensions to call our own get_image_dimensions.
- def get_image_dimensi... | 06a7bc6124bf62675c09fbe0a4ed9bbac183e025 | <|skeleton|>
class WagtailImageFieldFile:
"""Override the ImageFieldFile in order to use Willow instead of Pillow."""
def _get_image_dimensions(self):
"""override _get_image_dimensions to call our own get_image_dimensions."""
<|body_0|>
def get_image_dimensions(self):
"""The upstre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WagtailImageFieldFile:
"""Override the ImageFieldFile in order to use Willow instead of Pillow."""
def _get_image_dimensions(self):
"""override _get_image_dimensions to call our own get_image_dimensions."""
if not hasattr(self, '_dimensions_cache'):
self._dimensions_cache = se... | the_stack_v2_python_sparse | wagtail/images/models.py | wagtail/wagtail | train | 12,974 |
3f9c738b7ac90cabdd435b0e95dd9f3db048d34e | [
"self.tracks = datareader.get_df_tracks()\nself.challenge_playlists = datareader.get_df_test_playlists()['pid'].as_matrix()\nkeys = list(self.tracks['tid'].as_matrix())\nvalues = list(self.tracks['track_uri'].as_matrix())\nself.dictionary = dict(zip(keys, values))",
"submission_list = []\nfor i in tqdm(range(len(... | <|body_start_0|>
self.tracks = datareader.get_df_tracks()
self.challenge_playlists = datareader.get_df_test_playlists()['pid'].as_matrix()
keys = list(self.tracks['tid'].as_matrix())
values = list(self.tracks['track_uri'].as_matrix())
self.dictionary = dict(zip(keys, values))
<|e... | Submitter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Submitter:
def __init__(self, datareader):
"""Initialize the submitter with Dataframes from csv files. :param datareader: a Datareader object properly initialized with the full dataset."""
<|body_0|>
def convert(self, recommendation_list):
"""Convert a numpy matrix o... | stack_v2_sparse_classes_36k_train_014904 | 3,469 | permissive | [
{
"docstring": "Initialize the submitter with Dataframes from csv files. :param datareader: a Datareader object properly initialized with the full dataset.",
"name": "__init__",
"signature": "def __init__(self, datareader)"
},
{
"docstring": "Convert a numpy matrix of recommendations into a Data... | 3 | null | Implement the Python class `Submitter` described below.
Class description:
Implement the Submitter class.
Method signatures and docstrings:
- def __init__(self, datareader): Initialize the submitter with Dataframes from csv files. :param datareader: a Datareader object properly initialized with the full dataset.
- de... | Implement the Python class `Submitter` described below.
Class description:
Implement the Submitter class.
Method signatures and docstrings:
- def __init__(self, datareader): Initialize the submitter with Dataframes from csv files. :param datareader: a Datareader object properly initialized with the full dataset.
- de... | 4077201ac7e4ed9da433bd10a92c183614182437 | <|skeleton|>
class Submitter:
def __init__(self, datareader):
"""Initialize the submitter with Dataframes from csv files. :param datareader: a Datareader object properly initialized with the full dataset."""
<|body_0|>
def convert(self, recommendation_list):
"""Convert a numpy matrix o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Submitter:
def __init__(self, datareader):
"""Initialize the submitter with Dataframes from csv files. :param datareader: a Datareader object properly initialized with the full dataset."""
self.tracks = datareader.get_df_tracks()
self.challenge_playlists = datareader.get_df_test_playli... | the_stack_v2_python_sparse | utils/submitter.py | edervishaj/spotify-recsys-challenge | train | 0 | |
29ff9fa4dcb930c7f08f205ff35455dcaa30b137 | [
"argparser = kwargs.get('argparser', '')\ntrack = kwargs.get('track', '')\nif not (track and argparser and argparser.osd):\n return\nartist = track.split(' - ')[0]\nalbum_art = AlbumArt()\nicon = album_art.get(artist)\nif sys.version_info.major == 2:\n track = track.encode('utf-8')\nif platform.system() == 'D... | <|body_start_0|>
argparser = kwargs.get('argparser', '')
track = kwargs.get('track', '')
if not (track and argparser and argparser.osd):
return
artist = track.split(' - ')[0]
album_art = AlbumArt()
icon = album_art.get(artist)
if sys.version_info.major... | OSD notification (osx + growl / Linux GI) | OSDNotification | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OSDNotification:
"""OSD notification (osx + growl / Linux GI)"""
def notify(cls, *args, **kwargs):
"""Notification dispatcher that calls platform specific method"""
<|body_0|>
def linux_notify(cls, message, icon):
"""Linux OSD using GI"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_014905 | 3,240 | permissive | [
{
"docstring": "Notification dispatcher that calls platform specific method",
"name": "notify",
"signature": "def notify(cls, *args, **kwargs)"
},
{
"docstring": "Linux OSD using GI",
"name": "linux_notify",
"signature": "def linux_notify(cls, message, icon)"
},
{
"docstring": "O... | 3 | stack_v2_sparse_classes_30k_train_011976 | Implement the Python class `OSDNotification` described below.
Class description:
OSD notification (osx + growl / Linux GI)
Method signatures and docstrings:
- def notify(cls, *args, **kwargs): Notification dispatcher that calls platform specific method
- def linux_notify(cls, message, icon): Linux OSD using GI
- def ... | Implement the Python class `OSDNotification` described below.
Class description:
OSD notification (osx + growl / Linux GI)
Method signatures and docstrings:
- def notify(cls, *args, **kwargs): Notification dispatcher that calls platform specific method
- def linux_notify(cls, message, icon): Linux OSD using GI
- def ... | 3e35a25cfcf982a3871cf0d819bae4374ee31ecf | <|skeleton|>
class OSDNotification:
"""OSD notification (osx + growl / Linux GI)"""
def notify(cls, *args, **kwargs):
"""Notification dispatcher that calls platform specific method"""
<|body_0|>
def linux_notify(cls, message, icon):
"""Linux OSD using GI"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OSDNotification:
"""OSD notification (osx + growl / Linux GI)"""
def notify(cls, *args, **kwargs):
"""Notification dispatcher that calls platform specific method"""
argparser = kwargs.get('argparser', '')
track = kwargs.get('track', '')
if not (track and argparser and argp... | the_stack_v2_python_sparse | voiceplay/player/hooks/osd.py | tb0hdan/voiceplay | train | 4 |
ac0b4069aaddb2b98353d623801f7800b2545b9f | [
"index = (y * framebuf.stride + x) // 8\noffset = 7 - x & 7\nframebuf.buf[index] = framebuf.buf[index] & ~(1 << offset) | (color != 0) << offset",
"index = (y * framebuf.stride + x) // 8\noffset = 7 - x & 7\nreturn framebuf.buf[index] >> offset & 1",
"for _x in range(x, x + width):\n offset = 7 - _x & 7\n ... | <|body_start_0|>
index = (y * framebuf.stride + x) // 8
offset = 7 - x & 7
framebuf.buf[index] = framebuf.buf[index] & ~(1 << offset) | (color != 0) << offset
<|end_body_0|>
<|body_start_1|>
index = (y * framebuf.stride + x) // 8
offset = 7 - x & 7
return framebuf.buf[in... | MHMSBFormat | MHMSBFormat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MHMSBFormat:
"""MHMSBFormat"""
def set_pixel(framebuf, x, y, color):
"""Set a given pixel to a color."""
<|body_0|>
def get_pixel(framebuf, x, y):
"""Get the color of a given pixel"""
<|body_1|>
def fill_rect(framebuf, x, y, width, height, color):
... | stack_v2_sparse_classes_36k_train_014906 | 10,632 | no_license | [
{
"docstring": "Set a given pixel to a color.",
"name": "set_pixel",
"signature": "def set_pixel(framebuf, x, y, color)"
},
{
"docstring": "Get the color of a given pixel",
"name": "get_pixel",
"signature": "def get_pixel(framebuf, x, y)"
},
{
"docstring": "Draw a rectangle at th... | 3 | stack_v2_sparse_classes_30k_train_017109 | Implement the Python class `MHMSBFormat` described below.
Class description:
MHMSBFormat
Method signatures and docstrings:
- def set_pixel(framebuf, x, y, color): Set a given pixel to a color.
- def get_pixel(framebuf, x, y): Get the color of a given pixel
- def fill_rect(framebuf, x, y, width, height, color): Draw a... | Implement the Python class `MHMSBFormat` described below.
Class description:
MHMSBFormat
Method signatures and docstrings:
- def set_pixel(framebuf, x, y, color): Set a given pixel to a color.
- def get_pixel(framebuf, x, y): Get the color of a given pixel
- def fill_rect(framebuf, x, y, width, height, color): Draw a... | 78cdde343961ba4a2f1b9e0833540f1b20b18bfc | <|skeleton|>
class MHMSBFormat:
"""MHMSBFormat"""
def set_pixel(framebuf, x, y, color):
"""Set a given pixel to a color."""
<|body_0|>
def get_pixel(framebuf, x, y):
"""Get the color of a given pixel"""
<|body_1|>
def fill_rect(framebuf, x, y, width, height, color):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MHMSBFormat:
"""MHMSBFormat"""
def set_pixel(framebuf, x, y, color):
"""Set a given pixel to a color."""
index = (y * framebuf.stride + x) // 8
offset = 7 - x & 7
framebuf.buf[index] = framebuf.buf[index] & ~(1 << offset) | (color != 0) << offset
def get_pixel(framebu... | the_stack_v2_python_sparse | led_matrix/framebuf.py | ben-64/led_matrix | train | 0 |
106f72fc320b7c2f5c3743091c3f0dfeb99a35b6 | [
"Version.objects.all().delete()\nTestModel.objects.all().delete()\nTestManyToManyModel.objects.all().delete()\nreversion.register(TestModel, follow=('testmanytomanymodel_set',))\nreversion.register(TestManyToManyModel, follow=('relations',))",
"with reversion.revision:\n test1 = TestModel.objects.create(name='... | <|body_start_0|>
Version.objects.all().delete()
TestModel.objects.all().delete()
TestManyToManyModel.objects.all().delete()
reversion.register(TestModel, follow=('testmanytomanymodel_set',))
reversion.register(TestManyToManyModel, follow=('relations',))
<|end_body_0|>
<|body_sta... | Tests the ManyToMany support. | ReversionManyToManyTest | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReversionManyToManyTest:
"""Tests the ManyToMany support."""
def setUp(self):
"""Sets up the TestModel."""
<|body_0|>
def testCanCreateRevision(self):
"""Tests that a revision containing both models is created."""
<|body_1|>
def testCanCreateRevision... | stack_v2_sparse_classes_36k_train_014907 | 24,355 | permissive | [
{
"docstring": "Sets up the TestModel.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests that a revision containing both models is created.",
"name": "testCanCreateRevision",
"signature": "def testCanCreateRevision(self)"
},
{
"docstring": "Tests that a r... | 6 | stack_v2_sparse_classes_30k_train_012539 | Implement the Python class `ReversionManyToManyTest` described below.
Class description:
Tests the ManyToMany support.
Method signatures and docstrings:
- def setUp(self): Sets up the TestModel.
- def testCanCreateRevision(self): Tests that a revision containing both models is created.
- def testCanCreateRevisionRela... | Implement the Python class `ReversionManyToManyTest` described below.
Class description:
Tests the ManyToMany support.
Method signatures and docstrings:
- def setUp(self): Sets up the TestModel.
- def testCanCreateRevision(self): Tests that a revision containing both models is created.
- def testCanCreateRevisionRela... | abc3fbfb34f791f84e9a9d4dc522966421778ab2 | <|skeleton|>
class ReversionManyToManyTest:
"""Tests the ManyToMany support."""
def setUp(self):
"""Sets up the TestModel."""
<|body_0|>
def testCanCreateRevision(self):
"""Tests that a revision containing both models is created."""
<|body_1|>
def testCanCreateRevision... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReversionManyToManyTest:
"""Tests the ManyToMany support."""
def setUp(self):
"""Sets up the TestModel."""
Version.objects.all().delete()
TestModel.objects.all().delete()
TestManyToManyModel.objects.all().delete()
reversion.register(TestModel, follow=('testmanytoma... | the_stack_v2_python_sparse | py/django_tools/django-reversion/src/reversion/tests.py | marceltoben/evandrix.github.com | train | 3 |
b1b8d50967a5bd2228333289c58ee2ec237ce790 | [
"self._wikinews_archive = wikinews_archive\nself._language = language\nself._filtered_no_text = []\nself._counter = collections.Counter()",
"logging.info('Extracting docs from [%s]', self._wikinews_archive)\nfile_list = glob.glob(self._wikinews_archive)\nassert file_list, self._wikinews_archive\nfor archive in fi... | <|body_start_0|>
self._wikinews_archive = wikinews_archive
self._language = language
self._filtered_no_text = []
self._counter = collections.Counter()
<|end_body_0|>
<|body_start_1|>
logging.info('Extracting docs from [%s]', self._wikinews_archive)
file_list = glob.glob(... | A class for extracting docs from preprocessed WikiNews archive. This targets the jsonl output of github.com/attardi/wikiextractor. | WikiNewsArchiveParser | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikiNewsArchiveParser:
"""A class for extracting docs from preprocessed WikiNews archive. This targets the jsonl output of github.com/attardi/wikiextractor."""
def __init__(self, wikinews_archive, language):
"""Constructor. Args: wikinews_archive: Glob pattern matching one or more bz... | stack_v2_sparse_classes_36k_train_014908 | 11,463 | permissive | [
{
"docstring": "Constructor. Args: wikinews_archive: Glob pattern matching one or more bzipped files containing jsonl records. language: Wikipedia-style language code used to produce document URLs.",
"name": "__init__",
"signature": "def __init__(self, wikinews_archive, language)"
},
{
"docstrin... | 2 | null | Implement the Python class `WikiNewsArchiveParser` described below.
Class description:
A class for extracting docs from preprocessed WikiNews archive. This targets the jsonl output of github.com/attardi/wikiextractor.
Method signatures and docstrings:
- def __init__(self, wikinews_archive, language): Constructor. Arg... | Implement the Python class `WikiNewsArchiveParser` described below.
Class description:
A class for extracting docs from preprocessed WikiNews archive. This targets the jsonl output of github.com/attardi/wikiextractor.
Method signatures and docstrings:
- def __init__(self, wikinews_archive, language): Constructor. Arg... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class WikiNewsArchiveParser:
"""A class for extracting docs from preprocessed WikiNews archive. This targets the jsonl output of github.com/attardi/wikiextractor."""
def __init__(self, wikinews_archive, language):
"""Constructor. Args: wikinews_archive: Glob pattern matching one or more bz... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WikiNewsArchiveParser:
"""A class for extracting docs from preprocessed WikiNews archive. This targets the jsonl output of github.com/attardi/wikiextractor."""
def __init__(self, wikinews_archive, language):
"""Constructor. Args: wikinews_archive: Glob pattern matching one or more bzipped files c... | the_stack_v2_python_sparse | dense_representations_for_entity_retrieval/mel/wikinews_extractor/common.py | Jimmy-INL/google-research | train | 1 |
09f79d5e8cfa003766ae978b8db607773fd1f5f6 | [
"if len(prices) == 0:\n return 0\nprofit = 0\nbuy = prices[0]\nfor i, price in enumerate(prices):\n if price < buy:\n buy = price\n if price - buy > profit:\n profit = price - buy\nreturn profit",
"prices_new = []\nfor i in range(len(prices) - 1):\n prices_new.append(prices[i + 1] - pric... | <|body_start_0|>
if len(prices) == 0:
return 0
profit = 0
buy = prices[0]
for i, price in enumerate(prices):
if price < buy:
buy = price
if price - buy > profit:
profit = price - buy
return profit
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfitLeetCode(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: in... | stack_v2_sparse_classes_36k_train_014909 | 2,482 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfitLeetCode",
"signature": "def maxProfitLeetCode(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type ... | 3 | stack_v2_sparse_classes_30k_train_008802 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfitLeetCode(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxSubArray(self, nums): :type n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfitLeetCode(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxSubArray(self, nums): :type n... | afdd6a6160abf51e25d747dd55aab48a2f87dcfe | <|skeleton|>
class Solution:
def maxProfitLeetCode(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfitLeetCode(self, prices):
""":type prices: List[int] :rtype: int"""
if len(prices) == 0:
return 0
profit = 0
buy = prices[0]
for i, price in enumerate(prices):
if price < buy:
buy = price
if price ... | the_stack_v2_python_sparse | 121_Best_Time_to_Buy_and_Sell_Stock.py | zhaoxuyan/LeetCode_Python | train | 0 | |
52d47ab43c7e71a4705ea400e688f412462cad1a | [
"if len(data) == 0:\n return False\nwhile data:\n n = 0\n if data[0] & 248 == 240:\n n = 4\n elif data[0] & 240 == 224:\n n = 3\n elif data[0] & 224 == 192:\n n = 2\n elif data[0] & 128 == 0:\n n = 1\n if n == 0 or len(data) < n:\n return False\n for j in x... | <|body_start_0|>
if len(data) == 0:
return False
while data:
n = 0
if data[0] & 248 == 240:
n = 4
elif data[0] & 240 == 224:
n = 3
elif data[0] & 224 == 192:
n = 2
elif data[0] & 128 =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validUtf8(self, data):
""":type data: List[int] :rtype: bool"""
<|body_0|>
def validUtf82(self, data):
""":type data: List[int] :rtype: bool"""
<|body_1|>
def validUtf83(self, data):
""":type data: List[int] :rtype: bool"""
... | stack_v2_sparse_classes_36k_train_014910 | 45,889 | no_license | [
{
"docstring": ":type data: List[int] :rtype: bool",
"name": "validUtf8",
"signature": "def validUtf8(self, data)"
},
{
"docstring": ":type data: List[int] :rtype: bool",
"name": "validUtf82",
"signature": "def validUtf82(self, data)"
},
{
"docstring": ":type data: List[int] :rty... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validUtf8(self, data): :type data: List[int] :rtype: bool
- def validUtf82(self, data): :type data: List[int] :rtype: bool
- def validUtf83(self, data): :type data: List[int]... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validUtf8(self, data): :type data: List[int] :rtype: bool
- def validUtf82(self, data): :type data: List[int] :rtype: bool
- def validUtf83(self, data): :type data: List[int]... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def validUtf8(self, data):
""":type data: List[int] :rtype: bool"""
<|body_0|>
def validUtf82(self, data):
""":type data: List[int] :rtype: bool"""
<|body_1|>
def validUtf83(self, data):
""":type data: List[int] :rtype: bool"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validUtf8(self, data):
""":type data: List[int] :rtype: bool"""
if len(data) == 0:
return False
while data:
n = 0
if data[0] & 248 == 240:
n = 4
elif data[0] & 240 == 224:
n = 3
el... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00393.UTF-8 Validation.py | roger6blog/LeetCode | train | 0 | |
24c0eca60e4b90b60e8991bbd27f5d587f97dfc2 | [
"pc = DotDict()\nf2jd = copy.deepcopy(cannonical_json_dump)\npc.upload_file_minidump_flash2 = DotDict()\npc.upload_file_minidump_flash2.json_dump = f2jd\npc.upload_file_minidump_flash2.json_dump['threads'][0]['frames'][1]['function'] = 'NtUserPeekMessage'\npc.upload_file_minidump_flash2.json_dump['threads'][0]['fra... | <|body_start_0|>
pc = DotDict()
f2jd = copy.deepcopy(cannonical_json_dump)
pc.upload_file_minidump_flash2 = DotDict()
pc.upload_file_minidump_flash2.json_dump = f2jd
pc.upload_file_minidump_flash2.json_dump['threads'][0]['frames'][1]['function'] = 'NtUserPeekMessage'
pc.u... | TestBug812318 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBug812318:
def test_action_case_1(self):
"""success - both targets found in top 5 frames of stack"""
<|body_0|>
def test_action_case_2(self):
"""success - only 1st target found in top 5 frames of stack"""
<|body_1|>
def test_action_case_3(self):
... | stack_v2_sparse_classes_36k_train_014911 | 27,276 | no_license | [
{
"docstring": "success - both targets found in top 5 frames of stack",
"name": "test_action_case_1",
"signature": "def test_action_case_1(self)"
},
{
"docstring": "success - only 1st target found in top 5 frames of stack",
"name": "test_action_case_2",
"signature": "def test_action_case... | 3 | stack_v2_sparse_classes_30k_val_000057 | Implement the Python class `TestBug812318` described below.
Class description:
Implement the TestBug812318 class.
Method signatures and docstrings:
- def test_action_case_1(self): success - both targets found in top 5 frames of stack
- def test_action_case_2(self): success - only 1st target found in top 5 frames of s... | Implement the Python class `TestBug812318` described below.
Class description:
Implement the TestBug812318 class.
Method signatures and docstrings:
- def test_action_case_1(self): success - both targets found in top 5 frames of stack
- def test_action_case_2(self): success - only 1st target found in top 5 frames of s... | 9c9b7701d7ddf9f3cbba1a4d0aa65758e8b49528 | <|skeleton|>
class TestBug812318:
def test_action_case_1(self):
"""success - both targets found in top 5 frames of stack"""
<|body_0|>
def test_action_case_2(self):
"""success - only 1st target found in top 5 frames of stack"""
<|body_1|>
def test_action_case_3(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestBug812318:
def test_action_case_1(self):
"""success - both targets found in top 5 frames of stack"""
pc = DotDict()
f2jd = copy.deepcopy(cannonical_json_dump)
pc.upload_file_minidump_flash2 = DotDict()
pc.upload_file_minidump_flash2.json_dump = f2jd
pc.uploa... | the_stack_v2_python_sparse | socorro/unittest/processor/test_skunk_classifiers.py | v1ka5/socorro | train | 0 | |
5b3fd235aa5fee6d8d90209c226fdf6f45968453 | [
"super().__init__(db, version, uuid)\nself.columns = get_table_columns(self.conn, 'ZADDITIONALASSETATTRIBUTES')\nself.table_name = 'ZADDITIONALASSETATTRIBUTES'",
"conn, cursor = self.db.get_db_connection()\nsql = f' SELECT ZADDITIONALASSETATTRIBUTES.*\\n FROM ZADDITIONALASSETATTRIBUTES\\n ... | <|body_start_0|>
super().__init__(db, version, uuid)
self.columns = get_table_columns(self.conn, 'ZADDITIONALASSETATTRIBUTES')
self.table_name = 'ZADDITIONALASSETATTRIBUTES'
<|end_body_0|>
<|body_start_1|>
conn, cursor = self.db.get_db_connection()
sql = f' SELECT ZADDITIONALAS... | ZADDITIONALASSETATTRIBUTES table. | AdditionalAttributesTable | [
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdditionalAttributesTable:
"""ZADDITIONALASSETATTRIBUTES table."""
def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str):
"""Create a Table object."""
<|body_0|>
def rows(self) -> list[tuple[Any]]:
"""Return rows for this photo from the ZADDITIONALA... | stack_v2_sparse_classes_36k_train_014912 | 8,828 | permissive | [
{
"docstring": "Create a Table object.",
"name": "__init__",
"signature": "def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str)"
},
{
"docstring": "Return rows for this photo from the ZADDITIONALASSETATTRIBUTES table.",
"name": "rows",
"signature": "def rows(self) -> list[... | 3 | null | Implement the Python class `AdditionalAttributesTable` described below.
Class description:
ZADDITIONALASSETATTRIBUTES table.
Method signatures and docstrings:
- def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str): Create a Table object.
- def rows(self) -> list[tuple[Any]]: Return rows for this photo ... | Implement the Python class `AdditionalAttributesTable` described below.
Class description:
ZADDITIONALASSETATTRIBUTES table.
Method signatures and docstrings:
- def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str): Create a Table object.
- def rows(self) -> list[tuple[Any]]: Return rows for this photo ... | 2cb5a4d18a27be6ccf68f5f35abd39418d238016 | <|skeleton|>
class AdditionalAttributesTable:
"""ZADDITIONALASSETATTRIBUTES table."""
def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str):
"""Create a Table object."""
<|body_0|>
def rows(self) -> list[tuple[Any]]:
"""Return rows for this photo from the ZADDITIONALA... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdditionalAttributesTable:
"""ZADDITIONALASSETATTRIBUTES table."""
def __init__(self, db: osxphotos.PhotosDB, version: int, uuid: str):
"""Create a Table object."""
super().__init__(db, version, uuid)
self.columns = get_table_columns(self.conn, 'ZADDITIONALASSETATTRIBUTES')
... | the_stack_v2_python_sparse | osxphotos/phototables.py | RhetTbull/osxphotos | train | 1,287 |
6b5564c2c0089331b30bec82dbf92a73bedf83f5 | [
"self.lr_scheds = [p.lr_step for p in self.phases]\nself.mom_scheds = [p.mom_step for p in self.phases]\nself.opt = self.learn.opt\nself.opt.lr, self.opt.mom = (self.lr_scheds[0].start, self.mom_scheds[0].start)\nself.idx_s = 0",
"if self.idx_s >= len(self.lr_scheds):\n return True\nself.opt.lr = self.lr_sched... | <|body_start_0|>
self.lr_scheds = [p.lr_step for p in self.phases]
self.mom_scheds = [p.mom_step for p in self.phases]
self.opt = self.learn.opt
self.opt.lr, self.opt.mom = (self.lr_scheds[0].start, self.mom_scheds[0].start)
self.idx_s = 0
<|end_body_0|>
<|body_start_1|>
... | Schedule multiple `TrainingPhase` for a `learner` | GeneralScheduler | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneralScheduler:
"""Schedule multiple `TrainingPhase` for a `learner`"""
def on_train_begin(self, n_epochs: int, **kwargs: Any) -> None:
"""Initialize our lr and mom schedules for training"""
<|body_0|>
def on_batch_end(self, **kwargs: Any) -> None:
"""Take a st... | stack_v2_sparse_classes_36k_train_014913 | 27,312 | permissive | [
{
"docstring": "Initialize our lr and mom schedules for training",
"name": "on_train_begin",
"signature": "def on_train_begin(self, n_epochs: int, **kwargs: Any) -> None"
},
{
"docstring": "Take a step in lr,mom sched, start next sched when current is complete",
"name": "on_batch_end",
"... | 2 | stack_v2_sparse_classes_30k_train_011680 | Implement the Python class `GeneralScheduler` described below.
Class description:
Schedule multiple `TrainingPhase` for a `learner`
Method signatures and docstrings:
- def on_train_begin(self, n_epochs: int, **kwargs: Any) -> None: Initialize our lr and mom schedules for training
- def on_batch_end(self, **kwargs: An... | Implement the Python class `GeneralScheduler` described below.
Class description:
Schedule multiple `TrainingPhase` for a `learner`
Method signatures and docstrings:
- def on_train_begin(self, n_epochs: int, **kwargs: Any) -> None: Initialize our lr and mom schedules for training
- def on_batch_end(self, **kwargs: An... | 7989b9721dda08fd1df146666f0855f1832e252e | <|skeleton|>
class GeneralScheduler:
"""Schedule multiple `TrainingPhase` for a `learner`"""
def on_train_begin(self, n_epochs: int, **kwargs: Any) -> None:
"""Initialize our lr and mom schedules for training"""
<|body_0|>
def on_batch_end(self, **kwargs: Any) -> None:
"""Take a st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneralScheduler:
"""Schedule multiple `TrainingPhase` for a `learner`"""
def on_train_begin(self, n_epochs: int, **kwargs: Any) -> None:
"""Initialize our lr and mom schedules for training"""
self.lr_scheds = [p.lr_step for p in self.phases]
self.mom_scheds = [p.mom_step for p in... | the_stack_v2_python_sparse | dev_nb/nb_004.py | EmbraceLife/fastai_docs | train | 3 |
bbe1acb5252debac8ad825d1a9f30965162b5b56 | [
"guide_map = deepcopy(manager.all())\nseen_ids = set(AssistantActivity.objects.filter(user_id=request.user.id).values_list('guide_id', flat=True))\nreturn Response([{'guide': key, 'seen': id in seen_ids} for key, id in guide_map.items()])",
"serializer = AssistantSerializer(data=request.data)\nif not serializer.i... | <|body_start_0|>
guide_map = deepcopy(manager.all())
seen_ids = set(AssistantActivity.objects.filter(user_id=request.user.id).values_list('guide_id', flat=True))
return Response([{'guide': key, 'seen': id in seen_ids} for key, id in guide_map.items()])
<|end_body_0|>
<|body_start_1|>
se... | AssistantEndpoint | [
"Apache-2.0",
"BUSL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssistantEndpoint:
def get(self, request: Request) -> Response:
"""Return all the guides with a 'seen' attribute if it has been 'viewed' or 'dismissed'."""
<|body_0|>
def put(self, request: Request):
"""Mark a guide as viewed or dismissed. Request is of the form { 'g... | stack_v2_sparse_classes_36k_train_014914 | 3,626 | permissive | [
{
"docstring": "Return all the guides with a 'seen' attribute if it has been 'viewed' or 'dismissed'.",
"name": "get",
"signature": "def get(self, request: Request) -> Response"
},
{
"docstring": "Mark a guide as viewed or dismissed. Request is of the form { 'guide_id': <guide_id> - OR - 'guide'... | 2 | null | Implement the Python class `AssistantEndpoint` described below.
Class description:
Implement the AssistantEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request) -> Response: Return all the guides with a 'seen' attribute if it has been 'viewed' or 'dismissed'.
- def put(self, request: Requ... | Implement the Python class `AssistantEndpoint` described below.
Class description:
Implement the AssistantEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request) -> Response: Return all the guides with a 'seen' attribute if it has been 'viewed' or 'dismissed'.
- def put(self, request: Requ... | d9dd4f382f96b5c4576b64cbf015db651556c18b | <|skeleton|>
class AssistantEndpoint:
def get(self, request: Request) -> Response:
"""Return all the guides with a 'seen' attribute if it has been 'viewed' or 'dismissed'."""
<|body_0|>
def put(self, request: Request):
"""Mark a guide as viewed or dismissed. Request is of the form { 'g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssistantEndpoint:
def get(self, request: Request) -> Response:
"""Return all the guides with a 'seen' attribute if it has been 'viewed' or 'dismissed'."""
guide_map = deepcopy(manager.all())
seen_ids = set(AssistantActivity.objects.filter(user_id=request.user.id).values_list('guide_id... | the_stack_v2_python_sparse | src/sentry/api/endpoints/assistant.py | nagyist/sentry | train | 0 | |
bfdeb5361db702beebbe017c4450f5f4e094b533 | [
"if logdir is None:\n raise ValueError('A logdir is required')\nif directory_loader_factory is None:\n raise ValueError('A directory loader factory is required')\nself._logdir = logdir\nself._directory_loader_factory = directory_loader_factory\nself._directory_loaders = {}",
"logger.info('Starting logdir tr... | <|body_start_0|>
if logdir is None:
raise ValueError('A logdir is required')
if directory_loader_factory is None:
raise ValueError('A directory loader factory is required')
self._logdir = logdir
self._directory_loader_factory = directory_loader_factory
sel... | Loader for a root log directory, maintaining multiple DirectoryLoaders. This class takes a root log directory and a factory for DirectoryLoaders, and maintains one DirectoryLoader per "logdir subdirectory" of the root logdir. Note that this class is not thread-safe. | LogdirLoader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogdirLoader:
"""Loader for a root log directory, maintaining multiple DirectoryLoaders. This class takes a root log directory and a factory for DirectoryLoaders, and maintains one DirectoryLoader per "logdir subdirectory" of the root logdir. Note that this class is not thread-safe."""
def _... | stack_v2_sparse_classes_36k_train_014915 | 4,418 | permissive | [
{
"docstring": "Constructs a new LogdirLoader. Args: logdir: The root log directory to load from. directory_loader_factory: A factory for creating DirectoryLoaders. The factory should take a path and return a DirectoryLoader. Raises: ValueError: If logdir or directory_loader_factory are None.",
"name": "__i... | 4 | stack_v2_sparse_classes_30k_train_003171 | Implement the Python class `LogdirLoader` described below.
Class description:
Loader for a root log directory, maintaining multiple DirectoryLoaders. This class takes a root log directory and a factory for DirectoryLoaders, and maintains one DirectoryLoader per "logdir subdirectory" of the root logdir. Note that this ... | Implement the Python class `LogdirLoader` described below.
Class description:
Loader for a root log directory, maintaining multiple DirectoryLoaders. This class takes a root log directory and a factory for DirectoryLoaders, and maintains one DirectoryLoader per "logdir subdirectory" of the root logdir. Note that this ... | 5961c76dca0fb9bb40d146f5ce13834ac29d8ddb | <|skeleton|>
class LogdirLoader:
"""Loader for a root log directory, maintaining multiple DirectoryLoaders. This class takes a root log directory and a factory for DirectoryLoaders, and maintains one DirectoryLoader per "logdir subdirectory" of the root logdir. Note that this class is not thread-safe."""
def _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogdirLoader:
"""Loader for a root log directory, maintaining multiple DirectoryLoaders. This class takes a root log directory and a factory for DirectoryLoaders, and maintains one DirectoryLoader per "logdir subdirectory" of the root logdir. Note that this class is not thread-safe."""
def __init__(self,... | the_stack_v2_python_sparse | tensorboard/uploader/logdir_loader.py | tensorflow/tensorboard | train | 6,766 |
296ce7a9b959bb0cc8cc6b75363359ec614be1d1 | [
"with role_lock, db.session.begin_nested():\n if db.session.query(Role).filter(Role.person == self.external_object and Role.external_object == movie).first() is None:\n db.session.merge(Role(person=self.external_object, external_object=movie, role=role))",
"if key != 'gender':\n raise InvalidMetadata... | <|body_start_0|>
with role_lock, db.session.begin_nested():
if db.session.query(Role).filter(Role.person == self.external_object and Role.external_object == movie).first() is None:
db.session.merge(Role(person=self.external_object, external_object=movie, role=role))
<|end_body_0|>
<... | Represents a person. | Person | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Person:
"""Represents a person."""
def add_role(self, movie, role):
"""Add a role to a person. Raises ------ NotImplementedError Not implemented"""
<|body_0|>
def add_meta(self, key, content):
"""Add a metadata to the object. See :func:`ExternalObjectMetaMixin.ad... | stack_v2_sparse_classes_36k_train_014916 | 38,954 | no_license | [
{
"docstring": "Add a role to a person. Raises ------ NotImplementedError Not implemented",
"name": "add_role",
"signature": "def add_role(self, movie, role)"
},
{
"docstring": "Add a metadata to the object. See :func:`ExternalObjectMetaMixin.add_meta`",
"name": "add_meta",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_002292 | Implement the Python class `Person` described below.
Class description:
Represents a person.
Method signatures and docstrings:
- def add_role(self, movie, role): Add a role to a person. Raises ------ NotImplementedError Not implemented
- def add_meta(self, key, content): Add a metadata to the object. See :func:`Exter... | Implement the Python class `Person` described below.
Class description:
Represents a person.
Method signatures and docstrings:
- def add_role(self, movie, role): Add a role to a person. Raises ------ NotImplementedError Not implemented
- def add_meta(self, key, content): Add a metadata to the object. See :func:`Exter... | 5f4493bedb36c29e80740676bbb179901272d91e | <|skeleton|>
class Person:
"""Represents a person."""
def add_role(self, movie, role):
"""Add a role to a person. Raises ------ NotImplementedError Not implemented"""
<|body_0|>
def add_meta(self, key, content):
"""Add a metadata to the object. See :func:`ExternalObjectMetaMixin.ad... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Person:
"""Represents a person."""
def add_role(self, movie, role):
"""Add a role to a person. Raises ------ NotImplementedError Not implemented"""
with role_lock, db.session.begin_nested():
if db.session.query(Role).filter(Role.person == self.external_object and Role.external... | the_stack_v2_python_sparse | matcher/scheme/object.py | sandhose/obs-matcher | train | 2 |
e0487270a3bd5c3a5a2aa74ff0726e1758f4ae4b | [
"features = []\ncount = len(request.feature) - 1\nwhile count >= 0:\n features.append(str(request.feature[count]))\n count -= 1\nprepped_features = Pairwise.prepare_features(request.cohort_id, features)\noutputs = Pairwise.run_pairwise(prepped_features)\nresults = PairwiseResults(result_vectors=[], filter_mes... | <|body_start_0|>
features = []
count = len(request.feature) - 1
while count >= 0:
features.append(str(request.feature[count]))
count -= 1
prepped_features = Pairwise.prepare_features(request.cohort_id, features)
outputs = Pairwise.run_pairwise(prepped_feat... | Pairwise API v1 | PairwiseApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PairwiseApi:
"""Pairwise API v1"""
def run_job(self, request):
"""Used by the web application."""
<|body_0|>
def precomputed_results(self, request):
"""Used by the web application."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
features = []
... | stack_v2_sparse_classes_36k_train_014917 | 7,340 | permissive | [
{
"docstring": "Used by the web application.",
"name": "run_job",
"signature": "def run_job(self, request)"
},
{
"docstring": "Used by the web application.",
"name": "precomputed_results",
"signature": "def precomputed_results(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001825 | Implement the Python class `PairwiseApi` described below.
Class description:
Pairwise API v1
Method signatures and docstrings:
- def run_job(self, request): Used by the web application.
- def precomputed_results(self, request): Used by the web application. | Implement the Python class `PairwiseApi` described below.
Class description:
Pairwise API v1
Method signatures and docstrings:
- def run_job(self, request): Used by the web application.
- def precomputed_results(self, request): Used by the web application.
<|skeleton|>
class PairwiseApi:
"""Pairwise API v1"""
... | 1c1809eb5b3ab7ec8a7d028df878ce8b0de9854f | <|skeleton|>
class PairwiseApi:
"""Pairwise API v1"""
def run_job(self, request):
"""Used by the web application."""
<|body_0|>
def precomputed_results(self, request):
"""Used by the web application."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PairwiseApi:
"""Pairwise API v1"""
def run_job(self, request):
"""Used by the web application."""
features = []
count = len(request.feature) - 1
while count >= 0:
features.append(str(request.feature[count]))
count -= 1
prepped_features = Pai... | the_stack_v2_python_sparse | api/pairwise_api.py | Angiotension/ISB-CGC-Webapp | train | 0 |
f85a7a71c03b07f4f79b3887f7c854bc20eff067 | [
"self.config = config\nself.time_step = config['model']['time_step']\nself.batch_size = config['model']['batch_size']\nself.n_neg = config['model']['n_neg']\nself.model = TVBR(config['model'])\nuser_fea = torch.tensor(config['user_fea'], requires_grad=False, device=config['model']['device_str'], dtype=torch.float32... | <|body_start_0|>
self.config = config
self.time_step = config['model']['time_step']
self.batch_size = config['model']['batch_size']
self.n_neg = config['model']['n_neg']
self.model = TVBR(config['model'])
user_fea = torch.tensor(config['user_fea'], requires_grad=False, de... | Model Engine For TVBR. Args: ModelEngine ([type]): [description] | TVBREngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TVBREngine:
"""Model Engine For TVBR. Args: ModelEngine ([type]): [description]"""
def __init__(self, config):
"""Initialize configs. Args: config ([type]): [description]"""
<|body_0|>
def train_single_batch(self, batch_data, ratings=None):
"""Train a single batc... | stack_v2_sparse_classes_36k_train_014918 | 19,594 | permissive | [
{
"docstring": "Initialize configs. Args: config ([type]): [description]",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Train a single batch. Args: batch_data ([type]): [description] ratings ([type], optional): [description]. Defaults to None. Returns: [type]:... | 3 | stack_v2_sparse_classes_30k_val_000874 | Implement the Python class `TVBREngine` described below.
Class description:
Model Engine For TVBR. Args: ModelEngine ([type]): [description]
Method signatures and docstrings:
- def __init__(self, config): Initialize configs. Args: config ([type]): [description]
- def train_single_batch(self, batch_data, ratings=None)... | Implement the Python class `TVBREngine` described below.
Class description:
Model Engine For TVBR. Args: ModelEngine ([type]): [description]
Method signatures and docstrings:
- def __init__(self, config): Initialize configs. Args: config ([type]): [description]
- def train_single_batch(self, batch_data, ratings=None)... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class TVBREngine:
"""Model Engine For TVBR. Args: ModelEngine ([type]): [description]"""
def __init__(self, config):
"""Initialize configs. Args: config ([type]): [description]"""
<|body_0|>
def train_single_batch(self, batch_data, ratings=None):
"""Train a single batc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TVBREngine:
"""Model Engine For TVBR. Args: ModelEngine ([type]): [description]"""
def __init__(self, config):
"""Initialize configs. Args: config ([type]): [description]"""
self.config = config
self.time_step = config['model']['time_step']
self.batch_size = config['model'... | the_stack_v2_python_sparse | beta_rec/models/tvbr.py | beta-team/beta-recsys | train | 156 |
dac7dec441206cb14720c5a43535d3eda92e3282 | [
"self.s11 = s11\nself.s12 = s12\nself.s21 = s21\nself.s22 = s22",
"assert self.s22.shape == A.s11.shape\nN = self.s22.shape[0]\nX = inv(np.eye(N) - np.dot(A.s11, self.s22))\nY = inv(np.eye(N) - np.dot(self.s22, A.s11))\ns11 = self.s11 + np.dot(self.s12, np.dot(X, np.dot(A.s11, self.s21)))\ns12 = np.dot(self.s12, ... | <|body_start_0|>
self.s11 = s11
self.s12 = s12
self.s21 = s21
self.s22 = s22
<|end_body_0|>
<|body_start_1|>
assert self.s22.shape == A.s11.shape
N = self.s22.shape[0]
X = inv(np.eye(N) - np.dot(A.s11, self.s22))
Y = inv(np.eye(N) - np.dot(self.s22, A.s11... | GenericElement represents basic class for mode matching technique. It has generic constructor which builds generalized S matrix and defines a way to "multiply" S matrices (i.e. to cascade networks) | GenericElement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericElement:
"""GenericElement represents basic class for mode matching technique. It has generic constructor which builds generalized S matrix and defines a way to "multiply" S matrices (i.e. to cascade networks)"""
def __init__(self, s11, s12, s21, s22):
"""Initialize S matrix f... | stack_v2_sparse_classes_36k_train_014919 | 1,125 | no_license | [
{
"docstring": "Initialize S matrix from its bloc elements",
"name": "__init__",
"signature": "def __init__(self, s11, s12, s21, s22)"
},
{
"docstring": "Embed current element S matrix with element A S matrix",
"name": "__mul__",
"signature": "def __mul__(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014418 | Implement the Python class `GenericElement` described below.
Class description:
GenericElement represents basic class for mode matching technique. It has generic constructor which builds generalized S matrix and defines a way to "multiply" S matrices (i.e. to cascade networks)
Method signatures and docstrings:
- def ... | Implement the Python class `GenericElement` described below.
Class description:
GenericElement represents basic class for mode matching technique. It has generic constructor which builds generalized S matrix and defines a way to "multiply" S matrices (i.e. to cascade networks)
Method signatures and docstrings:
- def ... | 3cd67879ca6c649866e51b4d7892aa835f1e68c7 | <|skeleton|>
class GenericElement:
"""GenericElement represents basic class for mode matching technique. It has generic constructor which builds generalized S matrix and defines a way to "multiply" S matrices (i.e. to cascade networks)"""
def __init__(self, s11, s12, s21, s22):
"""Initialize S matrix f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenericElement:
"""GenericElement represents basic class for mode matching technique. It has generic constructor which builds generalized S matrix and defines a way to "multiply" S matrices (i.e. to cascade networks)"""
def __init__(self, s11, s12, s21, s22):
"""Initialize S matrix from its bloc ... | the_stack_v2_python_sparse | mode_matching/mode_matching/GenericElement.py | dmitrodem/pier_filter | train | 0 |
73480324bcf82c6fc6ded0ea5c746acbc8253db3 | [
"self.maxSize = maxSize\nself.arr = []\nself.inc = maxSize * [0]",
"if len(self.arr) == self.maxSize:\n return\nself.arr.append(x)",
"if len(self.arr) == 0:\n return -1\ni = len(self.arr) - 1\nif i > 0:\n self.inc[i - 1] += self.inc[i]\nres = self.arr.pop() + self.inc[i]\nself.inc[i] = 0\nreturn res",
... | <|body_start_0|>
self.maxSize = maxSize
self.arr = []
self.inc = maxSize * [0]
<|end_body_0|>
<|body_start_1|>
if len(self.arr) == self.maxSize:
return
self.arr.append(x)
<|end_body_1|>
<|body_start_2|>
if len(self.arr) == 0:
return -1
i ... | CustomStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomStack:
def __init__(self, maxSize):
""":type maxSize: int"""
<|body_0|>
def push(self, x):
""":type x: int :rtype: None"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def increment(self, k, val):
""":type k: ... | stack_v2_sparse_classes_36k_train_014920 | 2,610 | no_license | [
{
"docstring": ":type maxSize: int",
"name": "__init__",
"signature": "def __init__(self, maxSize)"
},
{
"docstring": ":type x: int :rtype: None",
"name": "push",
"signature": "def push(self, x)"
},
{
"docstring": ":rtype: int",
"name": "pop",
"signature": "def pop(self)"... | 4 | null | Implement the Python class `CustomStack` described below.
Class description:
Implement the CustomStack class.
Method signatures and docstrings:
- def __init__(self, maxSize): :type maxSize: int
- def push(self, x): :type x: int :rtype: None
- def pop(self): :rtype: int
- def increment(self, k, val): :type k: int :typ... | Implement the Python class `CustomStack` described below.
Class description:
Implement the CustomStack class.
Method signatures and docstrings:
- def __init__(self, maxSize): :type maxSize: int
- def push(self, x): :type x: int :rtype: None
- def pop(self): :rtype: int
- def increment(self, k, val): :type k: int :typ... | 1bd17e867d1d557a6ebbbd99f693d5fbd9f5b61e | <|skeleton|>
class CustomStack:
def __init__(self, maxSize):
""":type maxSize: int"""
<|body_0|>
def push(self, x):
""":type x: int :rtype: None"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def increment(self, k, val):
""":type k: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomStack:
def __init__(self, maxSize):
""":type maxSize: int"""
self.maxSize = maxSize
self.arr = []
self.inc = maxSize * [0]
def push(self, x):
""":type x: int :rtype: None"""
if len(self.arr) == self.maxSize:
return
self.arr.append(... | the_stack_v2_python_sparse | leetcode/1381-design-a-stack-with-increment-operation/main.py | shriharshs/AlgoDaily | train | 0 | |
3f1ba51335236df24394d6d94972c6d8e6dc7d31 | [
"tika_import.check()\nsuper().__init__(remove_numeric_tables=remove_numeric_tables, valid_languages=valid_languages, id_hash_keys=id_hash_keys)\nping = requests.get(tika_url, timeout=timeout)\nif ping.status_code != 200:\n raise Exception(f\"Apache Tika server is not reachable at the URL '{tika_url}'. To run it ... | <|body_start_0|>
tika_import.check()
super().__init__(remove_numeric_tables=remove_numeric_tables, valid_languages=valid_languages, id_hash_keys=id_hash_keys)
ping = requests.get(tika_url, timeout=timeout)
if ping.status_code != 200:
raise Exception(f"Apache Tika server is no... | TikaConverter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TikaConverter:
def __init__(self, tika_url: str='http://localhost:9998/tika', remove_numeric_tables: bool=False, valid_languages: Optional[List[str]]=None, id_hash_keys: Optional[List[str]]=None, timeout: Union[float, Tuple[float, float]]=10.0):
""":param tika_url: URL of the Tika server... | stack_v2_sparse_classes_36k_train_014921 | 9,174 | permissive | [
{
"docstring": ":param tika_url: URL of the Tika server :param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables. The tabular structures in documents might be noise for the reader model if it does not have table parsing capability for finding answers. However, tables may ... | 2 | null | Implement the Python class `TikaConverter` described below.
Class description:
Implement the TikaConverter class.
Method signatures and docstrings:
- def __init__(self, tika_url: str='http://localhost:9998/tika', remove_numeric_tables: bool=False, valid_languages: Optional[List[str]]=None, id_hash_keys: Optional[List... | Implement the Python class `TikaConverter` described below.
Class description:
Implement the TikaConverter class.
Method signatures and docstrings:
- def __init__(self, tika_url: str='http://localhost:9998/tika', remove_numeric_tables: bool=False, valid_languages: Optional[List[str]]=None, id_hash_keys: Optional[List... | 5f1256ac7e5734c2ea481e72cb7e02c34baf8c43 | <|skeleton|>
class TikaConverter:
def __init__(self, tika_url: str='http://localhost:9998/tika', remove_numeric_tables: bool=False, valid_languages: Optional[List[str]]=None, id_hash_keys: Optional[List[str]]=None, timeout: Union[float, Tuple[float, float]]=10.0):
""":param tika_url: URL of the Tika server... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TikaConverter:
def __init__(self, tika_url: str='http://localhost:9998/tika', remove_numeric_tables: bool=False, valid_languages: Optional[List[str]]=None, id_hash_keys: Optional[List[str]]=None, timeout: Union[float, Tuple[float, float]]=10.0):
""":param tika_url: URL of the Tika server :param remove... | the_stack_v2_python_sparse | haystack/nodes/file_converter/tika.py | deepset-ai/haystack | train | 10,599 | |
0e68a2594dc66fa9cf8c9491b0f8d6dafc876ca6 | [
"extra = ctypes.c_ulong(0)\nii_ = Input_I()\nii_.ki = KeyBdInput(keyCode, 72, 0, 0, ctypes.pointer(extra))\nx = Input(ctypes.c_ulong(1), ii_)\nSendInput(1, ctypes.pointer(x), ctypes.sizeof(x))",
"extra = ctypes.c_ulong(0)\nii_ = Input_I()\nii_.ki = KeyBdInput(keyCode, 72, 2, 0, ctypes.pointer(extra))\nx = Input(c... | <|body_start_0|>
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(keyCode, 72, 0, 0, ctypes.pointer(extra))
x = Input(ctypes.c_ulong(1), ii_)
SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
<|end_body_0|>
<|body_start_1|>
extra = ctypes.c_ulong(0)
... | Class Keyboard :author: Paradoxis <luke@paradoxis.nl> :description: Keyboard methods to trigger fake key events | Keyboard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Keyboard:
"""Class Keyboard :author: Paradoxis <luke@paradoxis.nl> :description: Keyboard methods to trigger fake key events"""
def keyDown(keyCode):
"""Key down wrapper :param keyCode: int :return: void"""
<|body_0|>
def keyUp(keyCode):
"""Key up wrapper :param ... | stack_v2_sparse_classes_36k_train_014922 | 5,030 | no_license | [
{
"docstring": "Key down wrapper :param keyCode: int :return: void",
"name": "keyDown",
"signature": "def keyDown(keyCode)"
},
{
"docstring": "Key up wrapper :param keyCode: int :return: void",
"name": "keyUp",
"signature": "def keyUp(keyCode)"
},
{
"docstring": "Type a key :para... | 3 | stack_v2_sparse_classes_30k_train_014251 | Implement the Python class `Keyboard` described below.
Class description:
Class Keyboard :author: Paradoxis <luke@paradoxis.nl> :description: Keyboard methods to trigger fake key events
Method signatures and docstrings:
- def keyDown(keyCode): Key down wrapper :param keyCode: int :return: void
- def keyUp(keyCode): K... | Implement the Python class `Keyboard` described below.
Class description:
Class Keyboard :author: Paradoxis <luke@paradoxis.nl> :description: Keyboard methods to trigger fake key events
Method signatures and docstrings:
- def keyDown(keyCode): Key down wrapper :param keyCode: int :return: void
- def keyUp(keyCode): K... | 5c03f77893ae98a49805fb15fbf48fed688dc714 | <|skeleton|>
class Keyboard:
"""Class Keyboard :author: Paradoxis <luke@paradoxis.nl> :description: Keyboard methods to trigger fake key events"""
def keyDown(keyCode):
"""Key down wrapper :param keyCode: int :return: void"""
<|body_0|>
def keyUp(keyCode):
"""Key up wrapper :param ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Keyboard:
"""Class Keyboard :author: Paradoxis <luke@paradoxis.nl> :description: Keyboard methods to trigger fake key events"""
def keyDown(keyCode):
"""Key down wrapper :param keyCode: int :return: void"""
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(keyC... | the_stack_v2_python_sparse | software/non_ai/systemcontrols/keyboard.py | SGNetworksIndia/J.A.R.V.I.S | train | 7 |
e5cb7e9827d9baa3b5468665610161d64aec31a8 | [
"self.model_dir = os.path.join(self.directory, 'webpage')\nself.conf_file = 'slda.conf'\nself.__engine = InferenceEngine(self.model_dir, self.conf_file)\nself.vocab_path = os.path.join(self.model_dir, 'vocab_info.txt')\nlac = hub.Module(name='lac')\nself.__tokenizer = LACTokenizer(self.vocab_path, lac)\nself.vocabu... | <|body_start_0|>
self.model_dir = os.path.join(self.directory, 'webpage')
self.conf_file = 'slda.conf'
self.__engine = InferenceEngine(self.model_dir, self.conf_file)
self.vocab_path = os.path.join(self.model_dir, 'vocab_info.txt')
lac = hub.Module(name='lac')
self.__toke... | TopicModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopicModel:
def _initialize(self):
"""Initialize with the necessary elements."""
<|body_0|>
def infer_doc_topic_distribution(self, document):
"""This interface infers the topic distribution of document. Args: document(str): the input document text. Returns: results(l... | stack_v2_sparse_classes_36k_train_014923 | 3,571 | permissive | [
{
"docstring": "Initialize with the necessary elements.",
"name": "_initialize",
"signature": "def _initialize(self)"
},
{
"docstring": "This interface infers the topic distribution of document. Args: document(str): the input document text. Returns: results(list): returns the topic distribution ... | 3 | stack_v2_sparse_classes_30k_train_002386 | Implement the Python class `TopicModel` described below.
Class description:
Implement the TopicModel class.
Method signatures and docstrings:
- def _initialize(self): Initialize with the necessary elements.
- def infer_doc_topic_distribution(self, document): This interface infers the topic distribution of document. A... | Implement the Python class `TopicModel` described below.
Class description:
Implement the TopicModel class.
Method signatures and docstrings:
- def _initialize(self): Initialize with the necessary elements.
- def infer_doc_topic_distribution(self, document): This interface infers the topic distribution of document. A... | b402610a6f0b382a978e82473b541ea1fc6cf09a | <|skeleton|>
class TopicModel:
def _initialize(self):
"""Initialize with the necessary elements."""
<|body_0|>
def infer_doc_topic_distribution(self, document):
"""This interface infers the topic distribution of document. Args: document(str): the input document text. Returns: results(l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopicModel:
def _initialize(self):
"""Initialize with the necessary elements."""
self.model_dir = os.path.join(self.directory, 'webpage')
self.conf_file = 'slda.conf'
self.__engine = InferenceEngine(self.model_dir, self.conf_file)
self.vocab_path = os.path.join(self.mod... | the_stack_v2_python_sparse | modules/text/language_model/slda_webpage/module.py | PaddlePaddle/PaddleHub | train | 12,914 | |
24990deb51601d4e7764f618b8c5881e1bdda358 | [
"self.arr = []\nself.dict = {}\nself.realSet = set()\nself.removeItem = set()",
"if val not in self.dict:\n self.arr.append(val)\n self.dict[val] = len(self.arr) - 1\nif val in self.removeItem:\n self.removeItem.remove(val)\nif val not in self.realSet:\n self.realSet.add(val)\n return True\nreturn ... | <|body_start_0|>
self.arr = []
self.dict = {}
self.realSet = set()
self.removeItem = set()
<|end_body_0|>
<|body_start_1|>
if val not in self.dict:
self.arr.append(val)
self.dict[val] = len(self.arr) - 1
if val in self.removeItem:
self... | RandomizedSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val: int) -> bool:
"""Inserts a value to the set. Returns true if the set did not already contain the specified element."""
<|body_1|>
def remove(se... | stack_v2_sparse_classes_36k_train_014924 | 1,822 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the set. Returns true if the set did not already contain the specified element.",
"name": "insert",
"signature": "def insert(self, val: int) ... | 4 | null | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val: int) -> bool: Inserts a value to the set. Returns true if the set did not already conta... | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val: int) -> bool: Inserts a value to the set. Returns true if the set did not already conta... | a47ffee11a23f96d3c20da97379dd279392ebd86 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val: int) -> bool:
"""Inserts a value to the set. Returns true if the set did not already contain the specified element."""
<|body_1|>
def remove(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
self.arr = []
self.dict = {}
self.realSet = set()
self.removeItem = set()
def insert(self, val: int) -> bool:
"""Inserts a value to the set. Returns true if the set did not alread... | the_stack_v2_python_sparse | LeetCode/Medium/380. Insert Delete GetRandom O(1).py | AlfredKai/KaiCodingNotes | train | 0 | |
95f78468fe1ec0aa3371467e6b3d89ae58b5cc31 | [
"super(Encoder, self).__init__()\nresnet = _load_resnet101_model()\nmodules = list(resnet.children())[:-1]\nself.resnet = nn.Sequential(*modules)\nself.embed = nn.Linear(resnet.fc.in_features, embed_size)\nfor param in self.resnet.parameters():\n param.requires_grad = False",
"features = self.resnet(imgs)\nfea... | <|body_start_0|>
super(Encoder, self).__init__()
resnet = _load_resnet101_model()
modules = list(resnet.children())[:-1]
self.resnet = nn.Sequential(*modules)
self.embed = nn.Linear(resnet.fc.in_features, embed_size)
for param in self.resnet.parameters():
para... | CNN encoder. | Encoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""CNN encoder."""
def __init__(self, embed_size):
"""Initialize encoder. Args: encoded_img_size (int): Output size."""
<|body_0|>
def forward(self, imgs):
"""Forward propagation. Args: imgs (torch.Tensor): A tensor of dimension (batch_size, 3, img_size,... | stack_v2_sparse_classes_36k_train_014925 | 4,057 | permissive | [
{
"docstring": "Initialize encoder. Args: encoded_img_size (int): Output size.",
"name": "__init__",
"signature": "def __init__(self, embed_size)"
},
{
"docstring": "Forward propagation. Args: imgs (torch.Tensor): A tensor of dimension (batch_size, 3, img_size, img_size). Returns: Embedded image... | 3 | stack_v2_sparse_classes_30k_val_000622 | Implement the Python class `Encoder` described below.
Class description:
CNN encoder.
Method signatures and docstrings:
- def __init__(self, embed_size): Initialize encoder. Args: encoded_img_size (int): Output size.
- def forward(self, imgs): Forward propagation. Args: imgs (torch.Tensor): A tensor of dimension (bat... | Implement the Python class `Encoder` described below.
Class description:
CNN encoder.
Method signatures and docstrings:
- def __init__(self, embed_size): Initialize encoder. Args: encoded_img_size (int): Output size.
- def forward(self, imgs): Forward propagation. Args: imgs (torch.Tensor): A tensor of dimension (bat... | fdebb153ae6d5dc9ed61968e474949f4d067e6e4 | <|skeleton|>
class Encoder:
"""CNN encoder."""
def __init__(self, embed_size):
"""Initialize encoder. Args: encoded_img_size (int): Output size."""
<|body_0|>
def forward(self, imgs):
"""Forward propagation. Args: imgs (torch.Tensor): A tensor of dimension (batch_size, 3, img_size,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""CNN encoder."""
def __init__(self, embed_size):
"""Initialize encoder. Args: encoded_img_size (int): Output size."""
super(Encoder, self).__init__()
resnet = _load_resnet101_model()
modules = list(resnet.children())[:-1]
self.resnet = nn.Sequential(*mod... | the_stack_v2_python_sparse | models/encoder.py | SarahAlkhateeb/Image-Captioning-with-Different-Decoders | train | 0 |
127b536d18395e0b543d55cd05265cf700cf6b83 | [
"ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(_build_enforcement_target_attr, domain_id=domain_id, user_id=user_id, role_id=role_id))\nPROVIDERS.assignment_api.get_grant(domain_id=domain_id, user_id=user_id, role_id=role_id, inherited_to_projects=True)\nreturn (None, http_clie... | <|body_start_0|>
ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(_build_enforcement_target_attr, domain_id=domain_id, user_id=user_id, role_id=role_id))
PROVIDERS.assignment_api.get_grant(domain_id=domain_id, user_id=user_id, role_id=role_id, inherited_to_projects=Tru... | OSInheritDomainUserRolesResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OSInheritDomainUserRolesResource:
def get(self, domain_id, user_id, role_id):
"""Check for an inherited grant for a user on a domain. GET/HEAD /OS-INHERIT/domains/{domain_id}/users/{user_id}/roles /{role_id}/inherited_to_projects"""
<|body_0|>
def put(self, domain_id, user_i... | stack_v2_sparse_classes_36k_train_014926 | 19,022 | permissive | [
{
"docstring": "Check for an inherited grant for a user on a domain. GET/HEAD /OS-INHERIT/domains/{domain_id}/users/{user_id}/roles /{role_id}/inherited_to_projects",
"name": "get",
"signature": "def get(self, domain_id, user_id, role_id)"
},
{
"docstring": "Create an inherited grant for a user ... | 3 | stack_v2_sparse_classes_30k_train_007654 | Implement the Python class `OSInheritDomainUserRolesResource` described below.
Class description:
Implement the OSInheritDomainUserRolesResource class.
Method signatures and docstrings:
- def get(self, domain_id, user_id, role_id): Check for an inherited grant for a user on a domain. GET/HEAD /OS-INHERIT/domains/{dom... | Implement the Python class `OSInheritDomainUserRolesResource` described below.
Class description:
Implement the OSInheritDomainUserRolesResource class.
Method signatures and docstrings:
- def get(self, domain_id, user_id, role_id): Check for an inherited grant for a user on a domain. GET/HEAD /OS-INHERIT/domains/{dom... | 03a0a8146a78682ede9eca12a5a7fdacde2035c8 | <|skeleton|>
class OSInheritDomainUserRolesResource:
def get(self, domain_id, user_id, role_id):
"""Check for an inherited grant for a user on a domain. GET/HEAD /OS-INHERIT/domains/{domain_id}/users/{user_id}/roles /{role_id}/inherited_to_projects"""
<|body_0|>
def put(self, domain_id, user_i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OSInheritDomainUserRolesResource:
def get(self, domain_id, user_id, role_id):
"""Check for an inherited grant for a user on a domain. GET/HEAD /OS-INHERIT/domains/{domain_id}/users/{user_id}/roles /{role_id}/inherited_to_projects"""
ENFORCER.enforce_call(action='identity:check_grant', build_ta... | the_stack_v2_python_sparse | keystone/api/os_inherit.py | sapcc/keystone | train | 0 | |
d487f0b323bea9fa4ec7b82480628a234af134c5 | [
"self.actions = ACTIONS\nself.args = {'q1': {'n_h1': 200, 'n_h2': 200, 'batch_size': 1000, 'opt': dy.AdamTrainer, 'activation': dy.rectify}, 'q2': {'n_h1': 400, 'n_h2': 400, 'batch_size': 1000, 'opt': dy.AdamTrainer, 'activation': dy.rectify}, 'q3': {'n_h1': 400, 'n_h2': 400, 'batch_size': 1000, 'opt': dy.AdamTrain... | <|body_start_0|>
self.actions = ACTIONS
self.args = {'q1': {'n_h1': 200, 'n_h2': 200, 'batch_size': 1000, 'opt': dy.AdamTrainer, 'activation': dy.rectify}, 'q2': {'n_h1': 400, 'n_h2': 400, 'batch_size': 1000, 'opt': dy.AdamTrainer, 'activation': dy.rectify}, 'q3': {'n_h1': 400, 'n_h2': 400, 'batch_size'... | DepModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DepModel:
def __init__(self, which, model):
"""You can add more arguments for examples actions and model paths. You need to load your model here. actions: provides indices for actions. it has the same order as the data/vocabs.actions file."""
<|body_0|>
def score(self, str_f... | stack_v2_sparse_classes_36k_train_014927 | 1,849 | no_license | [
{
"docstring": "You can add more arguments for examples actions and model paths. You need to load your model here. actions: provides indices for actions. it has the same order as the data/vocabs.actions file.",
"name": "__init__",
"signature": "def __init__(self, which, model)"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_010685 | Implement the Python class `DepModel` described below.
Class description:
Implement the DepModel class.
Method signatures and docstrings:
- def __init__(self, which, model): You can add more arguments for examples actions and model paths. You need to load your model here. actions: provides indices for actions. it has... | Implement the Python class `DepModel` described below.
Class description:
Implement the DepModel class.
Method signatures and docstrings:
- def __init__(self, which, model): You can add more arguments for examples actions and model paths. You need to load your model here. actions: provides indices for actions. it has... | a3fb300a3197432edfbb1da461330a9a3ef44d45 | <|skeleton|>
class DepModel:
def __init__(self, which, model):
"""You can add more arguments for examples actions and model paths. You need to load your model here. actions: provides indices for actions. it has the same order as the data/vocabs.actions file."""
<|body_0|>
def score(self, str_f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DepModel:
def __init__(self, which, model):
"""You can add more arguments for examples actions and model paths. You need to load your model here. actions: provides indices for actions. it has the same order as the data/vocabs.actions file."""
self.actions = ACTIONS
self.args = {'q1': {... | the_stack_v2_python_sparse | pset4/src/depModel.py | sanghal/coms-w4705 | train | 0 | |
d90fb4143d58d7c3603199effbd3d60c9cfb6caf | [
"sequence = cls._evaluate_env_var(sequence)\nsequence = cls._evaluate_custom_var(sequence, spec_vars)\nreturn CodeEvaluator.evaluate(sequence, spec_vars, is_a_test_case)",
"matches = cls.variable_pattern.finditer(sequence)\nfor match in matches:\n variable_name = match.group('variable')\n if any((letter.isl... | <|body_start_0|>
sequence = cls._evaluate_env_var(sequence)
sequence = cls._evaluate_custom_var(sequence, spec_vars)
return CodeEvaluator.evaluate(sequence, spec_vars, is_a_test_case)
<|end_body_0|>
<|body_start_1|>
matches = cls.variable_pattern.finditer(sequence)
for match in ... | Class that handles environment and custom variables evaluation. It replaces every occurrence with ```${customVariable}``` or ```${ENV}``` pattern. | StringEvaluator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringEvaluator:
"""Class that handles environment and custom variables evaluation. It replaces every occurrence with ```${customVariable}``` or ```${ENV}``` pattern."""
def evaluate(cls, sequence, spec_vars, is_a_test_case=False):
"""Receives a sequence of characters and evaluates a... | stack_v2_sparse_classes_36k_train_014928 | 4,041 | permissive | [
{
"docstring": "Receives a sequence of characters and evaluates any custom or environment variables present on it Args: sequence[string]: sequence of characters to be evaluated spec_vars[dict]: dictionary containing the SpecEvaluator variables is_a_test_case[bool]: indicator for checking if the given evaluation... | 4 | stack_v2_sparse_classes_30k_train_017138 | Implement the Python class `StringEvaluator` described below.
Class description:
Class that handles environment and custom variables evaluation. It replaces every occurrence with ```${customVariable}``` or ```${ENV}``` pattern.
Method signatures and docstrings:
- def evaluate(cls, sequence, spec_vars, is_a_test_case=... | Implement the Python class `StringEvaluator` described below.
Class description:
Class that handles environment and custom variables evaluation. It replaces every occurrence with ```${customVariable}``` or ```${ENV}``` pattern.
Method signatures and docstrings:
- def evaluate(cls, sequence, spec_vars, is_a_test_case=... | 1e419f29364585123cb1bc14c2d7ebd2c9b117b7 | <|skeleton|>
class StringEvaluator:
"""Class that handles environment and custom variables evaluation. It replaces every occurrence with ```${customVariable}``` or ```${ENV}``` pattern."""
def evaluate(cls, sequence, spec_vars, is_a_test_case=False):
"""Receives a sequence of characters and evaluates a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringEvaluator:
"""Class that handles environment and custom variables evaluation. It replaces every occurrence with ```${customVariable}``` or ```${ENV}``` pattern."""
def evaluate(cls, sequence, spec_vars, is_a_test_case=False):
"""Receives a sequence of characters and evaluates any custom or ... | the_stack_v2_python_sparse | scanapi/evaluators/string_evaluator.py | scanapi/scanapi | train | 1,330 |
1b16f4f995578ff78b2109db5fe1ced3ecf1aba5 | [
"serial = []\n\ndef preorder(node):\n if not node:\n return\n serial.append(str(node.val))\n for child in node.children:\n preorder(child)\n serial.append('#')\npreorder(root)\nreturn ' '.join(serial)",
"if not data:\n return None\ntokens = deque(data.split())\nroot = Node(int(tokens.... | <|body_start_0|>
serial = []
def preorder(node):
if not node:
return
serial.append(str(node.val))
for child in node.children:
preorder(child)
serial.append('#')
preorder(root)
return ' '.join(serial)
<|end_b... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_014929 | 2,443 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def deserialize(self, ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | 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: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | 05e0beff0047f0ad399d0b46d625bb8d3459814e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
serial = []
def preorder(node):
if not node:
return
serial.append(str(node.val))
for child in node.children:
preo... | the_stack_v2_python_sparse | python_1_to_1000/428_Serialize_and_Deserialize_N-ary_Tree.py | jakehoare/leetcode | train | 58 | |
642b7921733b8fb0d4bed8b8f52e0d57d135ef9b | [
"n = len(arr)\ndp = [0] * n\ndp[0] = 1\nres = 1\nfor i in range(1, n):\n if dp[i - 1] == 1:\n if arr[i] != arr[i - 1]:\n dp[i] = dp[i - 1] + 1\n else:\n dp[i] = 1\n elif arr[i - 1] > arr[i] and arr[i - 2] < arr[i - 1] or (arr[i - 1] < arr[i] and arr[i - 2] > arr[i - 1]):\n ... | <|body_start_0|>
n = len(arr)
dp = [0] * n
dp[0] = 1
res = 1
for i in range(1, n):
if dp[i - 1] == 1:
if arr[i] != arr[i - 1]:
dp[i] = dp[i - 1] + 1
else:
dp[i] = 1
elif arr[i - 1] > a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxTurbulenceSize(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def maxTurbulenceSizeO1Space(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
def maxTurbulenceSizeO1SpaceFaster(self, arr):
""":type arr: ... | stack_v2_sparse_classes_36k_train_014930 | 3,331 | no_license | [
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "maxTurbulenceSize",
"signature": "def maxTurbulenceSize(self, arr)"
},
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "maxTurbulenceSizeO1Space",
"signature": "def maxTurbulenceSizeO1Space(self, arr)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_010695 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxTurbulenceSize(self, arr): :type arr: List[int] :rtype: int
- def maxTurbulenceSizeO1Space(self, arr): :type arr: List[int] :rtype: int
- def maxTurbulenceSizeO1SpaceFaste... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxTurbulenceSize(self, arr): :type arr: List[int] :rtype: int
- def maxTurbulenceSizeO1Space(self, arr): :type arr: List[int] :rtype: int
- def maxTurbulenceSizeO1SpaceFaste... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def maxTurbulenceSize(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def maxTurbulenceSizeO1Space(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
def maxTurbulenceSizeO1SpaceFaster(self, arr):
""":type arr: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxTurbulenceSize(self, arr):
""":type arr: List[int] :rtype: int"""
n = len(arr)
dp = [0] * n
dp[0] = 1
res = 1
for i in range(1, n):
if dp[i - 1] == 1:
if arr[i] != arr[i - 1]:
dp[i] = dp[i - 1] + 1... | the_stack_v2_python_sparse | L/LongestTurbulentSubarray.py | bssrdf/pyleet | train | 2 | |
e3d85df34b0a5fedd9f2565fd3055c3174b890d0 | [
"try:\n self.sqlhandler = None\n if self.getTeaList():\n self.write(self.teaList)\n self.finish()\n else:\n raise RuntimeError\nexcept Exception:\n self.write('error')\n self.finish()\nfinally:\n if self.sqlhandler is not None:\n self.sqlhandler.closeMySql()\n tornad... | <|body_start_0|>
try:
self.sqlhandler = None
if self.getTeaList():
self.write(self.teaList)
self.finish()
else:
raise RuntimeError
except Exception:
self.write('error')
self.finish()
final... | AdmGetTeaListRequestHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdmGetTeaListRequestHandler:
def get(self):
"""从数据库获取老师列表返回给管理员"""
<|body_0|>
def getTeaList(self):
"""从数据库读取老师列表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
self.sqlhandler = None
if self.getTeaList():
... | stack_v2_sparse_classes_36k_train_014931 | 1,561 | no_license | [
{
"docstring": "从数据库获取老师列表返回给管理员",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "从数据库读取老师列表",
"name": "getTeaList",
"signature": "def getTeaList(self)"
}
] | 2 | null | Implement the Python class `AdmGetTeaListRequestHandler` described below.
Class description:
Implement the AdmGetTeaListRequestHandler class.
Method signatures and docstrings:
- def get(self): 从数据库获取老师列表返回给管理员
- def getTeaList(self): 从数据库读取老师列表 | Implement the Python class `AdmGetTeaListRequestHandler` described below.
Class description:
Implement the AdmGetTeaListRequestHandler class.
Method signatures and docstrings:
- def get(self): 从数据库获取老师列表返回给管理员
- def getTeaList(self): 从数据库读取老师列表
<|skeleton|>
class AdmGetTeaListRequestHandler:
def get(self):
... | b28eb4163b02bd0a931653b94851592f2654b199 | <|skeleton|>
class AdmGetTeaListRequestHandler:
def get(self):
"""从数据库获取老师列表返回给管理员"""
<|body_0|>
def getTeaList(self):
"""从数据库读取老师列表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdmGetTeaListRequestHandler:
def get(self):
"""从数据库获取老师列表返回给管理员"""
try:
self.sqlhandler = None
if self.getTeaList():
self.write(self.teaList)
self.finish()
else:
raise RuntimeError
except Exception:
... | the_stack_v2_python_sparse | app/src/main/pythonWork/AdmGetTeaListRequestHandler.py | lyh-ADT/edu-app | train | 1 | |
85e8d112bd234641d7e2e89f9c46f3f62a558d34 | [
"from __builtin__ import reduce\nif '' == digits:\n return []\nkvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\nreturn reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])",
"from __builtin__ import reduce\nif '' == dig... | <|body_start_0|>
from __builtin__ import reduce
if '' == digits:
return []
kvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])
<... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def rewrite(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
def rewrite2(self, digits):
""":type digits: str :rtype: List[str... | stack_v2_sparse_classes_36k_train_014932 | 2,869 | no_license | [
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits)"
},
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "rewrite",
"signature": "def rewrite(self, digits)"
},
{
"docstring": ":type di... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def rewrite(self, digits): :type digits: str :rtype: List[str]
- def rewrite2(self, digits): :type dig... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def rewrite(self, digits): :type digits: str :rtype: List[str]
- def rewrite2(self, digits): :type dig... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def rewrite(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
def rewrite2(self, digits):
""":type digits: str :rtype: List[str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
from __builtin__ import reduce
if '' == digits:
return []
kvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
re... | the_stack_v2_python_sparse | co_ms/17_Letter_Combinations_of_a_Phone_Number.py | vsdrun/lc_public | train | 6 | |
04b84cc12bb94823da217e1768ad3e9306f01982 | [
"self.R_a = 6378137.0\nself.R_b = 6356752.3142\nself.lon0_bmp = lon0_bmp\nself.lat0_bmp = lat0_bmp\nself.angle0_bmp = angle0_bmp\nself.R_bmp, _ = cv2.Rodrigues(np.array([0, 0, self.angle0_bmp * np.pi / 180]))\nself.R_bmp_inv = np.linalg.inv(self.R_bmp)",
"x = (lonlat[:, 0] - self.lon0_bmp) * np.pi / 180 * self.R_... | <|body_start_0|>
self.R_a = 6378137.0
self.R_b = 6356752.3142
self.lon0_bmp = lon0_bmp
self.lat0_bmp = lat0_bmp
self.angle0_bmp = angle0_bmp
self.R_bmp, _ = cv2.Rodrigues(np.array([0, 0, self.angle0_bmp * np.pi / 180]))
self.R_bmp_inv = np.linalg.inv(self.R_bmp)
<... | 经纬度与m坐标系相互转换 | Lon_Lat_Meter_Transform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lon_Lat_Meter_Transform:
"""经纬度与m坐标系相互转换"""
def __init__(self, lon0_bmp, lat0_bmp, angle0_bmp):
"""初始化 @param: lon0_bmp,lat0_bmp,angle0_bmp:用于绘图时的粗标的经纬度及夹角"""
<|body_0|>
def lonlat_to_xy_of_draw(self, lonlat):
"""经纬度转到画车道图的激光雷达m坐标系下 @param: lon_lat:(-1,2) np.arra... | stack_v2_sparse_classes_36k_train_014933 | 15,912 | no_license | [
{
"docstring": "初始化 @param: lon0_bmp,lat0_bmp,angle0_bmp:用于绘图时的粗标的经纬度及夹角",
"name": "__init__",
"signature": "def __init__(self, lon0_bmp, lat0_bmp, angle0_bmp)"
},
{
"docstring": "经纬度转到画车道图的激光雷达m坐标系下 @param: lon_lat:(-1,2) np.array @return: xy:(-1,2) np.array",
"name": "lonlat_to_xy_of_draw"... | 3 | null | Implement the Python class `Lon_Lat_Meter_Transform` described below.
Class description:
经纬度与m坐标系相互转换
Method signatures and docstrings:
- def __init__(self, lon0_bmp, lat0_bmp, angle0_bmp): 初始化 @param: lon0_bmp,lat0_bmp,angle0_bmp:用于绘图时的粗标的经纬度及夹角
- def lonlat_to_xy_of_draw(self, lonlat): 经纬度转到画车道图的激光雷达m坐标系下 @param: l... | Implement the Python class `Lon_Lat_Meter_Transform` described below.
Class description:
经纬度与m坐标系相互转换
Method signatures and docstrings:
- def __init__(self, lon0_bmp, lat0_bmp, angle0_bmp): 初始化 @param: lon0_bmp,lat0_bmp,angle0_bmp:用于绘图时的粗标的经纬度及夹角
- def lonlat_to_xy_of_draw(self, lonlat): 经纬度转到画车道图的激光雷达m坐标系下 @param: l... | 31918e28fa3390390c4ea6208132d48164f95f73 | <|skeleton|>
class Lon_Lat_Meter_Transform:
"""经纬度与m坐标系相互转换"""
def __init__(self, lon0_bmp, lat0_bmp, angle0_bmp):
"""初始化 @param: lon0_bmp,lat0_bmp,angle0_bmp:用于绘图时的粗标的经纬度及夹角"""
<|body_0|>
def lonlat_to_xy_of_draw(self, lonlat):
"""经纬度转到画车道图的激光雷达m坐标系下 @param: lon_lat:(-1,2) np.arra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lon_Lat_Meter_Transform:
"""经纬度与m坐标系相互转换"""
def __init__(self, lon0_bmp, lat0_bmp, angle0_bmp):
"""初始化 @param: lon0_bmp,lat0_bmp,angle0_bmp:用于绘图时的粗标的经纬度及夹角"""
self.R_a = 6378137.0
self.R_b = 6356752.3142
self.lon0_bmp = lon0_bmp
self.lat0_bmp = lat0_bmp
sel... | the_stack_v2_python_sparse | new_soft/Common/CommonParam.py | 841661831/perception | train | 1 |
1bac291c14a42c3902d6925bc876dd9beaa4106f | [
"print(f'\\nRole __init__ ()')\nfor key, value in kwargs.items():\n print(f'>{key} = {value}')\nsuper().__init__(**kwargs)",
"if re.sub('[(){}<> .!?,;]', '', text_) == '':\n return\ntts = gTTS(text=text_, lang=self.lang)\ntf = NamedTemporaryFile(delete=False)\ntmp_file = tf.name\ntts.save(tmp_file)\nsound =... | <|body_start_0|>
print(f'\nRole __init__ ()')
for key, value in kwargs.items():
print(f'>{key} = {value}')
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
if re.sub('[(){}<> .!?,;]', '', text_) == '':
return
tts = gTTS(text=text_, lang=self.lan... | Definition of Role object and dialogue | Role | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Role:
"""Definition of Role object and dialogue"""
def __init__(self, **kwargs):
"""define Role object"""
<|body_0|>
def speak(self, text_):
"""Convert text to AudioSegment (sound) object"""
<|body_1|>
def do(self, **kwargs):
"""Do Role objec... | stack_v2_sparse_classes_36k_train_014934 | 4,505 | permissive | [
{
"docstring": "define Role object",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Convert text to AudioSegment (sound) object",
"name": "speak",
"signature": "def speak(self, text_)"
},
{
"docstring": "Do Role object call :param kwargs: overr... | 3 | stack_v2_sparse_classes_30k_train_011072 | Implement the Python class `Role` described below.
Class description:
Definition of Role object and dialogue
Method signatures and docstrings:
- def __init__(self, **kwargs): define Role object
- def speak(self, text_): Convert text to AudioSegment (sound) object
- def do(self, **kwargs): Do Role object call :param k... | Implement the Python class `Role` described below.
Class description:
Definition of Role object and dialogue
Method signatures and docstrings:
- def __init__(self, **kwargs): define Role object
- def speak(self, text_): Convert text to AudioSegment (sound) object
- def do(self, **kwargs): Do Role object call :param k... | 194bc6c7b899bb4ab61966af3ba1e619fc74c20c | <|skeleton|>
class Role:
"""Definition of Role object and dialogue"""
def __init__(self, **kwargs):
"""define Role object"""
<|body_0|>
def speak(self, text_):
"""Convert text to AudioSegment (sound) object"""
<|body_1|>
def do(self, **kwargs):
"""Do Role objec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Role:
"""Definition of Role object and dialogue"""
def __init__(self, **kwargs):
"""define Role object"""
print(f'\nRole __init__ ()')
for key, value in kwargs.items():
print(f'>{key} = {value}')
super().__init__(**kwargs)
def speak(self, text_):
"... | the_stack_v2_python_sparse | manuscript/Jemma/x_actions/role.py | anterokangas/ManuscriptManagerOld | train | 0 |
fc7494ac563806f38d2c287148f89ffc0f7d1147 | [
"profile_form = ProfileEditForm()\nkyc_form = KYCUploadForm()\ncontext = {'profile_form': profile_form, 'kyc_form': kyc_form, 'timezones': pytz.common_timezones}\nreturn render(request, self.template_name, context)",
"profile_form = ProfileEditForm(request.POST, request.FILES)\nkyc_form = KYCUploadForm(request.PO... | <|body_start_0|>
profile_form = ProfileEditForm()
kyc_form = KYCUploadForm()
context = {'profile_form': profile_form, 'kyc_form': kyc_form, 'timezones': pytz.common_timezones}
return render(request, self.template_name, context)
<|end_body_0|>
<|body_start_1|>
profile_form = Prof... | KYCUploadView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KYCUploadView:
def get(self, request, *args, **kwargs):
"""provide kyc forms to provide kyc details"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""kyc details uploading verifing the data and reconfirm by user"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_014935 | 39,823 | no_license | [
{
"docstring": "provide kyc forms to provide kyc details",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "kyc details uploading verifing the data and reconfirm by user",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
... | 2 | stack_v2_sparse_classes_30k_train_000515 | Implement the Python class `KYCUploadView` described below.
Class description:
Implement the KYCUploadView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): provide kyc forms to provide kyc details
- def post(self, request, *args, **kwargs): kyc details uploading verifing the data an... | Implement the Python class `KYCUploadView` described below.
Class description:
Implement the KYCUploadView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): provide kyc forms to provide kyc details
- def post(self, request, *args, **kwargs): kyc details uploading verifing the data an... | 778d9a8fb95c8fe3214a8423905553c71ed7234a | <|skeleton|>
class KYCUploadView:
def get(self, request, *args, **kwargs):
"""provide kyc forms to provide kyc details"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""kyc details uploading verifing the data and reconfirm by user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KYCUploadView:
def get(self, request, *args, **kwargs):
"""provide kyc forms to provide kyc details"""
profile_form = ProfileEditForm()
kyc_form = KYCUploadForm()
context = {'profile_form': profile_form, 'kyc_form': kyc_form, 'timezones': pytz.common_timezones}
return r... | the_stack_v2_python_sparse | apps/authentication/views.py | devmaster54/tixon | train | 0 | |
e2d1391eff573fe26fd5516eb0193e828ab44107 | [
"self.typology = 'Area'\nself.source_id = identifier\nself.name = name\nself.tectonic_region_type = tectonic_region\nself.aspect_ratio = aspect_ratio\nself.mfd = None\nself.msr = None\nif upper_depth < 0.0:\n raise ValueError('Upper Depth Must be Non Negative')\nself.upper_depth = upper_depth\nif lower_depth and... | <|body_start_0|>
self.typology = 'Area'
self.source_id = identifier
self.name = name
self.tectonic_region_type = tectonic_region
self.aspect_ratio = aspect_ratio
self.mfd = None
self.msr = None
if upper_depth < 0.0:
raise ValueError('Upper Dept... | New class to describe the mtkAreaSource object | mtkAreaSource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mtkAreaSource:
"""New class to describe the mtkAreaSource object"""
def __init__(self, identifier, name, tectonic_region, aspect_ratio, input_geometry, upper_depth=0.0, lower_depth=None):
"""Instantiate class with just the basic attributes :param identifier: Integer ID code for the s... | stack_v2_sparse_classes_36k_train_014936 | 5,217 | no_license | [
{
"docstring": "Instantiate class with just the basic attributes :param identifier: Integer ID code for the source :param name: Source Name (string) :param tectonic_region: Tectonic Region Type (String) :param aspect_ratio: Ratio of along-strike length to down-dip width (float) :param input_geometry: Input geom... | 2 | stack_v2_sparse_classes_30k_train_000772 | Implement the Python class `mtkAreaSource` described below.
Class description:
New class to describe the mtkAreaSource object
Method signatures and docstrings:
- def __init__(self, identifier, name, tectonic_region, aspect_ratio, input_geometry, upper_depth=0.0, lower_depth=None): Instantiate class with just the basi... | Implement the Python class `mtkAreaSource` described below.
Class description:
New class to describe the mtkAreaSource object
Method signatures and docstrings:
- def __init__(self, identifier, name, tectonic_region, aspect_ratio, input_geometry, upper_depth=0.0, lower_depth=None): Instantiate class with just the basi... | cb98126555d54548f8e6ff8305eef15328930310 | <|skeleton|>
class mtkAreaSource:
"""New class to describe the mtkAreaSource object"""
def __init__(self, identifier, name, tectonic_region, aspect_ratio, input_geometry, upper_depth=0.0, lower_depth=None):
"""Instantiate class with just the basic attributes :param identifier: Integer ID code for the s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mtkAreaSource:
"""New class to describe the mtkAreaSource object"""
def __init__(self, identifier, name, tectonic_region, aspect_ratio, input_geometry, upper_depth=0.0, lower_depth=None):
"""Instantiate class with just the basic attributes :param identifier: Integer ID code for the source :param ... | the_stack_v2_python_sparse | seismicity_modeller/mtk/sources/mtk_area.py | g-weatherill/prototype_code | train | 0 |
e9297151bd31b8478efe2aa9f54f0842f2642211 | [
"self._params = {}\nself._feature_keys = feature_keys\nself._vocab_sizes = vocab_sizes\ndummy_emb = tf.zeros([1, embedding_size], dtype=tf.float32)\nfor feature_key in feature_keys:\n vocab_size = self._vocab_sizes[feature_key]\n emb = tf.get_variable(feature_key, shape=(vocab_size, embedding_size), dtype=tf.... | <|body_start_0|>
self._params = {}
self._feature_keys = feature_keys
self._vocab_sizes = vocab_sizes
dummy_emb = tf.zeros([1, embedding_size], dtype=tf.float32)
for feature_key in feature_keys:
vocab_size = self._vocab_sizes[feature_key]
emb = tf.get_varia... | This class is used to convert SparseTensor inputs to dense Tensors. This class is used to convert raw features to their vector representations. It takes in a dictionary, where the key is the name of a feature (e.g. diagnosis_id) and the value is a SparseTensor of integers (i.e. lookup IDs), then retrieves corresponding... | FeatureEmbedder | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureEmbedder:
"""This class is used to convert SparseTensor inputs to dense Tensors. This class is used to convert raw features to their vector representations. It takes in a dictionary, where the key is the name of a feature (e.g. diagnosis_id) and the value is a SparseTensor of integers (i.e... | stack_v2_sparse_classes_36k_train_014937 | 32,334 | permissive | [
{
"docstring": "Init function. Args: vocab_sizes: A dictionary of vocabularize sizes for each feature. feature_keys: A list of feature names you want to use. embedding_size: The dimension size of the feature representation vector.",
"name": "__init__",
"signature": "def __init__(self, vocab_sizes, featu... | 2 | stack_v2_sparse_classes_30k_train_004396 | Implement the Python class `FeatureEmbedder` described below.
Class description:
This class is used to convert SparseTensor inputs to dense Tensors. This class is used to convert raw features to their vector representations. It takes in a dictionary, where the key is the name of a feature (e.g. diagnosis_id) and the v... | Implement the Python class `FeatureEmbedder` described below.
Class description:
This class is used to convert SparseTensor inputs to dense Tensors. This class is used to convert raw features to their vector representations. It takes in a dictionary, where the key is the name of a feature (e.g. diagnosis_id) and the v... | 0672299d78a24a7c299499d4a79102a7e1192cd9 | <|skeleton|>
class FeatureEmbedder:
"""This class is used to convert SparseTensor inputs to dense Tensors. This class is used to convert raw features to their vector representations. It takes in a dictionary, where the key is the name of a feature (e.g. diagnosis_id) and the value is a SparseTensor of integers (i.e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureEmbedder:
"""This class is used to convert SparseTensor inputs to dense Tensors. This class is used to convert raw features to their vector representations. It takes in a dictionary, where the key is the name of a feature (e.g. diagnosis_id) and the value is a SparseTensor of integers (i.e. lookup IDs)... | the_stack_v2_python_sparse | graph-convolutional-transformer/graph_convolutional_transformer.py | drskaf/Graph-Convolutional-Transformer | train | 0 |
cd76153b589e06b93b985cd73f9e03ea429ee04a | [
"args = parser.parse_args()\ntry:\n if not all([args['platform_id'], args['vm_uuid']]):\n raise Exception('Parameter error')\n data = control.disks.get_disk_by_vm_uuid(platform_id=args['platform_id'], vm_uuid=args['vm_uuid'])\nexcept Exception as e:\n return (set_return_val(False, [], str(e), 1529),... | <|body_start_0|>
args = parser.parse_args()
try:
if not all([args['platform_id'], args['vm_uuid']]):
raise Exception('Parameter error')
data = control.disks.get_disk_by_vm_uuid(platform_id=args['platform_id'], vm_uuid=args['vm_uuid'])
except Exception as e... | DiskManage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiskManage:
def get(self):
"""获取vCenter vm_disk 信息 --- tags: - vCenter disk parameters: - in: query name: platform_id type: integer required: true - in: query name: vm_uuid type: string required: true responses: 200: description: vCenter disk 信息 schema: properties: ok: type: boolean desc... | stack_v2_sparse_classes_36k_train_014938 | 8,504 | no_license | [
{
"docstring": "获取vCenter vm_disk 信息 --- tags: - vCenter disk parameters: - in: query name: platform_id type: integer required: true - in: query name: vm_uuid type: string required: true responses: 200: description: vCenter disk 信息 schema: properties: ok: type: boolean description: status code: type: \"integer\... | 3 | stack_v2_sparse_classes_30k_val_000858 | Implement the Python class `DiskManage` described below.
Class description:
Implement the DiskManage class.
Method signatures and docstrings:
- def get(self): 获取vCenter vm_disk 信息 --- tags: - vCenter disk parameters: - in: query name: platform_id type: integer required: true - in: query name: vm_uuid type: string req... | Implement the Python class `DiskManage` described below.
Class description:
Implement the DiskManage class.
Method signatures and docstrings:
- def get(self): 获取vCenter vm_disk 信息 --- tags: - vCenter disk parameters: - in: query name: platform_id type: integer required: true - in: query name: vm_uuid type: string req... | d25871dc66dfbd9f04e3d4d95843e39de286cfc8 | <|skeleton|>
class DiskManage:
def get(self):
"""获取vCenter vm_disk 信息 --- tags: - vCenter disk parameters: - in: query name: platform_id type: integer required: true - in: query name: vm_uuid type: string required: true responses: 200: description: vCenter disk 信息 schema: properties: ok: type: boolean desc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiskManage:
def get(self):
"""获取vCenter vm_disk 信息 --- tags: - vCenter disk parameters: - in: query name: platform_id type: integer required: true - in: query name: vm_uuid type: string required: true responses: 200: description: vCenter disk 信息 schema: properties: ok: type: boolean description: statu... | the_stack_v2_python_sparse | app/main/vcenter/apis/disks.py | zcl-organization/naguan | train | 0 | |
c90fcecec2eff172d8b01235dddd8db5105b0e5b | [
"type_detector_list = ['истребитель', 'штурмовик', 'бомбардировщик', 'гражданский транспортный', 'гражданский пассажирский']\nif object_type not in type_detector_list:\n raise ValueError('Мне передали некорректный тип самолета, что дальше?')\nif flight_altitude > altitude_max:\n flight_altitude = altitude_max... | <|body_start_0|>
type_detector_list = ['истребитель', 'штурмовик', 'бомбардировщик', 'гражданский транспортный', 'гражданский пассажирский']
if object_type not in type_detector_list:
raise ValueError('Мне передали некорректный тип самолета, что дальше?')
if flight_altitude > altitude... | Дочерний класс самолет | PlaneClass | [
"WTFPL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaneClass:
"""Дочерний класс самолет"""
def __init__(self, name, price, object_type, flight_altitude, producing_country, owner_country, speed, weapon_type, altitude_max, fuel, fuel_max, fuel_consumption):
"""Общие поля с Aircraft: Название, цена, тип объекта, высота полета, страна п... | stack_v2_sparse_classes_36k_train_014939 | 11,707 | permissive | [
{
"docstring": "Общие поля с Aircraft: Название, цена, тип объекта, высота полета, страна производитель, страна владелец Различные поля с Aicraft: Скорость,тип вооружения, максимальная высота полета, запас топлива в баке, максимальный запас топлива, расход топлива",
"name": "__init__",
"signature": "def... | 5 | null | Implement the Python class `PlaneClass` described below.
Class description:
Дочерний класс самолет
Method signatures and docstrings:
- def __init__(self, name, price, object_type, flight_altitude, producing_country, owner_country, speed, weapon_type, altitude_max, fuel, fuel_max, fuel_consumption): Общие поля с Aircr... | Implement the Python class `PlaneClass` described below.
Class description:
Дочерний класс самолет
Method signatures and docstrings:
- def __init__(self, name, price, object_type, flight_altitude, producing_country, owner_country, speed, weapon_type, altitude_max, fuel, fuel_max, fuel_consumption): Общие поля с Aircr... | 9575c43fa01c261ea1ed573df9b5686b5a6f4211 | <|skeleton|>
class PlaneClass:
"""Дочерний класс самолет"""
def __init__(self, name, price, object_type, flight_altitude, producing_country, owner_country, speed, weapon_type, altitude_max, fuel, fuel_max, fuel_consumption):
"""Общие поля с Aircraft: Название, цена, тип объекта, высота полета, страна п... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlaneClass:
"""Дочерний класс самолет"""
def __init__(self, name, price, object_type, flight_altitude, producing_country, owner_country, speed, weapon_type, altitude_max, fuel, fuel_max, fuel_consumption):
"""Общие поля с Aircraft: Название, цена, тип объекта, высота полета, страна производитель,... | the_stack_v2_python_sparse | Course_I/Алгоритмы Python/Part2/семинары/control1/airclass_module.py | GeorgiyDemo/FA | train | 46 |
8beb911f5a654a74b00dcf2975f5188507b67993 | [
"if associate_with.internal_id is None:\n raise ValueError('Model to associate with must have an internal ID: %s' % associate_with)\nif isinstance(associate, InternalIdModel):\n associate = [associate]\nsession = self._database_connector.create_session()\nsqlalchemy_associated_with_type = get_equivalent_sqlal... | <|body_start_0|>
if associate_with.internal_id is None:
raise ValueError('Model to associate with must have an internal ID: %s' % associate_with)
if isinstance(associate, InternalIdModel):
associate = [associate]
session = self._database_connector.create_session()
... | SQLAlchemy metadata_mapper that deals with models that can be associated with other models via a join table. | SQLAssociationMapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLAssociationMapper:
"""SQLAlchemy metadata_mapper that deals with models that can be associated with other models via a join table."""
def _set_association(self, associate: Union[InternalIdModel, Iterable[InternalIdModel]], associate_with: InternalIdModel, relationship_property_name: str):... | stack_v2_sparse_classes_36k_train_014940 | 10,822 | permissive | [
{
"docstring": "Associates the given models to another model, linked to via the specified relationship property. :param associate: the models to associate :param associate_with: the model to associate with :param relationship_property_name: the property on `associate_with` in which the relationship is expressed... | 2 | stack_v2_sparse_classes_30k_train_005931 | Implement the Python class `SQLAssociationMapper` described below.
Class description:
SQLAlchemy metadata_mapper that deals with models that can be associated with other models via a join table.
Method signatures and docstrings:
- def _set_association(self, associate: Union[InternalIdModel, Iterable[InternalIdModel]]... | Implement the Python class `SQLAssociationMapper` described below.
Class description:
SQLAlchemy metadata_mapper that deals with models that can be associated with other models via a join table.
Method signatures and docstrings:
- def _set_association(self, associate: Union[InternalIdModel, Iterable[InternalIdModel]]... | d998016f44c54666f76f90d8d3efa90e12730fff | <|skeleton|>
class SQLAssociationMapper:
"""SQLAlchemy metadata_mapper that deals with models that can be associated with other models via a join table."""
def _set_association(self, associate: Union[InternalIdModel, Iterable[InternalIdModel]], associate_with: InternalIdModel, relationship_property_name: str):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SQLAssociationMapper:
"""SQLAlchemy metadata_mapper that deals with models that can be associated with other models via a join table."""
def _set_association(self, associate: Union[InternalIdModel, Iterable[InternalIdModel]], associate_with: InternalIdModel, relationship_property_name: str):
"""A... | the_stack_v2_python_sparse | subrepos/wtsi-hgi.python-sequencescape-db/sequencescape/_sqlalchemy/mappers.py | wtsi-hgi/openstack-tenant-cleaner | train | 0 |
2e64c33ea1ad47a28c474caa851ed66d5ed4b676 | [
"if not is_phonenumber_valid(attrs['phone_number']):\n raise serializers.ValidationError('Invalid phone number')\nreturn attrs",
"user = User()\nuser.email = validated_data.get('email')\nuser.first_name = validated_data.get('first_name')\nuser.last_name = validated_data.get('last_name')\nuser.set_password(vali... | <|body_start_0|>
if not is_phonenumber_valid(attrs['phone_number']):
raise serializers.ValidationError('Invalid phone number')
return attrs
<|end_body_0|>
<|body_start_1|>
user = User()
user.email = validated_data.get('email')
user.first_name = validated_data.get('fi... | UserSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSerializer:
def validate(self, attrs):
"""Add custom validations"""
<|body_0|>
def create(self, validated_data):
"""Create and return user instance, given validate data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not is_phonenumber_valid(... | stack_v2_sparse_classes_36k_train_014941 | 1,873 | no_license | [
{
"docstring": "Add custom validations",
"name": "validate",
"signature": "def validate(self, attrs)"
},
{
"docstring": "Create and return user instance, given validate data",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004148 | Implement the Python class `UserSerializer` described below.
Class description:
Implement the UserSerializer class.
Method signatures and docstrings:
- def validate(self, attrs): Add custom validations
- def create(self, validated_data): Create and return user instance, given validate data | Implement the Python class `UserSerializer` described below.
Class description:
Implement the UserSerializer class.
Method signatures and docstrings:
- def validate(self, attrs): Add custom validations
- def create(self, validated_data): Create and return user instance, given validate data
<|skeleton|>
class UserSer... | 4a10587cedf7cef216dfb3b225ca5acb6f23cba2 | <|skeleton|>
class UserSerializer:
def validate(self, attrs):
"""Add custom validations"""
<|body_0|>
def create(self, validated_data):
"""Create and return user instance, given validate data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSerializer:
def validate(self, attrs):
"""Add custom validations"""
if not is_phonenumber_valid(attrs['phone_number']):
raise serializers.ValidationError('Invalid phone number')
return attrs
def create(self, validated_data):
"""Create and return user instan... | the_stack_v2_python_sparse | authentication/serializers.py | tech-cent/momo_bank_api | train | 3 | |
1594477157a934f635f1b286347b458cc4e5d0df | [
"self.quit = False\nself.add = False\nself.delete = False\nself.item = None",
"print('[command] [item] (command: a to add, d to delete, q to quit).')\nline = input()\ncommand = line[:1]\nself.item = line[2:]\nif command == 'a':\n self.add = True\nelif command == 'q':\n self.quit = True\nelif command == 'd':... | <|body_start_0|>
self.quit = False
self.add = False
self.delete = False
self.item = None
<|end_body_0|>
<|body_start_1|>
print('[command] [item] (command: a to add, d to delete, q to quit).')
line = input()
command = line[:1]
self.item = line[2:]
... | Order class. | Order | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Order:
"""Order class."""
def __init__(self):
"""Initializing the order."""
<|body_0|>
def get_input(self):
"""Retrieve the order."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.quit = False
self.add = False
self.delete = F... | stack_v2_sparse_classes_36k_train_014942 | 630 | permissive | [
{
"docstring": "Initializing the order.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Retrieve the order.",
"name": "get_input",
"signature": "def get_input(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014395 | Implement the Python class `Order` described below.
Class description:
Order class.
Method signatures and docstrings:
- def __init__(self): Initializing the order.
- def get_input(self): Retrieve the order. | Implement the Python class `Order` described below.
Class description:
Order class.
Method signatures and docstrings:
- def __init__(self): Initializing the order.
- def get_input(self): Retrieve the order.
<|skeleton|>
class Order:
"""Order class."""
def __init__(self):
"""Initializing the order.""... | fa58835d532126c4cfb0baf4cb8d9d8a0e2703d2 | <|skeleton|>
class Order:
"""Order class."""
def __init__(self):
"""Initializing the order."""
<|body_0|>
def get_input(self):
"""Retrieve the order."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Order:
"""Order class."""
def __init__(self):
"""Initializing the order."""
self.quit = False
self.add = False
self.delete = False
self.item = None
def get_input(self):
"""Retrieve the order."""
print('[command] [item] (command: a to add, d to ... | the_stack_v2_python_sparse | sales/shopping_order.py | carlb15/Python | train | 2 |
866d4d13f17b33cf028656e07c3c8a2d55e490c8 | [
"self.sess = sess\nself.model = model\nself.config = config\nself.data_loader = data_loader\nself.cur_iterration = 0\nself.train_writer = tf.summary.FileWriter(self.config.summary_dir, sess.graph)\nself.init = tf.global_variables_initializer()\nself.sess.run(self.init)\nif self.config.load:\n self.model.load(sel... | <|body_start_0|>
self.sess = sess
self.model = model
self.config = config
self.data_loader = data_loader
self.cur_iterration = 0
self.train_writer = tf.summary.FileWriter(self.config.summary_dir, sess.graph)
self.init = tf.global_variables_initializer()
se... | Trainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trainer:
def __init__(self, sess, model, data_loader, config, is_training=True):
"""Initilization of train Arguments: sess {[type]} -- [description] model {[type]} -- [description] config {[type]} -- [description] logger {[type]} -- [description] data_loader {[type]} -- [description]"""
... | stack_v2_sparse_classes_36k_train_014943 | 2,992 | no_license | [
{
"docstring": "Initilization of train Arguments: sess {[type]} -- [description] model {[type]} -- [description] config {[type]} -- [description] logger {[type]} -- [description] data_loader {[type]} -- [description]",
"name": "__init__",
"signature": "def __init__(self, sess, model, data_loader, config... | 4 | stack_v2_sparse_classes_30k_train_005313 | Implement the Python class `Trainer` described below.
Class description:
Implement the Trainer class.
Method signatures and docstrings:
- def __init__(self, sess, model, data_loader, config, is_training=True): Initilization of train Arguments: sess {[type]} -- [description] model {[type]} -- [description] config {[ty... | Implement the Python class `Trainer` described below.
Class description:
Implement the Trainer class.
Method signatures and docstrings:
- def __init__(self, sess, model, data_loader, config, is_training=True): Initilization of train Arguments: sess {[type]} -- [description] model {[type]} -- [description] config {[ty... | 6d91ba88c12568cf296d583a2e176f6853961ad6 | <|skeleton|>
class Trainer:
def __init__(self, sess, model, data_loader, config, is_training=True):
"""Initilization of train Arguments: sess {[type]} -- [description] model {[type]} -- [description] config {[type]} -- [description] logger {[type]} -- [description] data_loader {[type]} -- [description]"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trainer:
def __init__(self, sess, model, data_loader, config, is_training=True):
"""Initilization of train Arguments: sess {[type]} -- [description] model {[type]} -- [description] config {[type]} -- [description] logger {[type]} -- [description] data_loader {[type]} -- [description]"""
self.s... | the_stack_v2_python_sparse | triplet_learning/stage_6/trainer/trainer.py | shangliy/SL_Model_Methods | train | 0 | |
08c9906e28c71a08573f63ac1ca033955c508d8b | [
"self._addModelVariable(model, 'base_frequency', long, ModelVariableFormat.DECIMAL)\nself._addModelVariable(model, 'xtal_frequency', int, ModelVariableFormat.DECIMAL)\nself._addModelVariable(model, 'channel_spacing', int, ModelVariableFormat.DECIMAL)",
"model.vars.xtal_frequency.value = int(model.vars.xtal_freque... | <|body_start_0|>
self._addModelVariable(model, 'base_frequency', long, ModelVariableFormat.DECIMAL)
self._addModelVariable(model, 'xtal_frequency', int, ModelVariableFormat.DECIMAL)
self._addModelVariable(model, 'channel_spacing', int, ModelVariableFormat.DECIMAL)
<|end_body_0|>
<|body_start_1|... | CALC_Profile_Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CALC_Profile_Base:
def buildVariables(self, model):
"""Populates a list of needed variables for this calculator Args: model (ModelRoot) : Builds the variables specific to this calculator"""
<|body_0|>
def calc_map_inputs(self, model):
"""the following function maps r... | stack_v2_sparse_classes_36k_train_014944 | 1,496 | no_license | [
{
"docstring": "Populates a list of needed variables for this calculator Args: model (ModelRoot) : Builds the variables specific to this calculator",
"name": "buildVariables",
"signature": "def buildVariables(self, model)"
},
{
"docstring": "the following function maps renamed variables into the... | 2 | stack_v2_sparse_classes_30k_train_016368 | Implement the Python class `CALC_Profile_Base` described below.
Class description:
Implement the CALC_Profile_Base class.
Method signatures and docstrings:
- def buildVariables(self, model): Populates a list of needed variables for this calculator Args: model (ModelRoot) : Builds the variables specific to this calcul... | Implement the Python class `CALC_Profile_Base` described below.
Class description:
Implement the CALC_Profile_Base class.
Method signatures and docstrings:
- def buildVariables(self, model): Populates a list of needed variables for this calculator Args: model (ModelRoot) : Builds the variables specific to this calcul... | 9f84e3b5a1397998dfea5287949fa5b1f4c209a6 | <|skeleton|>
class CALC_Profile_Base:
def buildVariables(self, model):
"""Populates a list of needed variables for this calculator Args: model (ModelRoot) : Builds the variables specific to this calculator"""
<|body_0|>
def calc_map_inputs(self, model):
"""the following function maps r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CALC_Profile_Base:
def buildVariables(self, model):
"""Populates a list of needed variables for this calculator Args: model (ModelRoot) : Builds the variables specific to this calculator"""
self._addModelVariable(model, 'base_frequency', long, ModelVariableFormat.DECIMAL)
self._addMode... | the_stack_v2_python_sparse | .closet/jython.configurator.efr32/1.0.0.201606231656-435/pyradioconfig/parts/common/calculators/calc_profile_base_beta1.py | acvilla/Sundial-Beta | train | 1 | |
9084a2d3826675a055b2cc24306d5c2061e26cc3 | [
"super(Tar, self).__init__()\nself.dry_run = dry_run\nself.verbose = verbose",
"path = os.path.dirname(file_path)\nif path == '':\n path = '.'\nfolder_name = os.path.basename(file_path)\ntar_filename = '%s.tar.gz' % folder_name\ntar_filename = os.path.join(path, tar_filename)\nextra_tar_options = ''\nif self.v... | <|body_start_0|>
super(Tar, self).__init__()
self.dry_run = dry_run
self.verbose = verbose
<|end_body_0|>
<|body_start_1|>
path = os.path.dirname(file_path)
if path == '':
path = '.'
folder_name = os.path.basename(file_path)
tar_filename = '%s.tar.gz'... | Tar Class. | Tar | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tar:
"""Tar Class."""
def __init__(self, dry_run=False, verbose=False):
"""Init."""
<|body_0|>
def create(self, file_path):
"""Create TAR file."""
<|body_1|>
def extract(self, file_path):
"""Extract TAR file."""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k_train_014945 | 1,535 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, dry_run=False, verbose=False)"
},
{
"docstring": "Create TAR file.",
"name": "create",
"signature": "def create(self, file_path)"
},
{
"docstring": "Extract TAR file.",
"name": "extract",
"signat... | 3 | stack_v2_sparse_classes_30k_train_003810 | Implement the Python class `Tar` described below.
Class description:
Tar Class.
Method signatures and docstrings:
- def __init__(self, dry_run=False, verbose=False): Init.
- def create(self, file_path): Create TAR file.
- def extract(self, file_path): Extract TAR file. | Implement the Python class `Tar` described below.
Class description:
Tar Class.
Method signatures and docstrings:
- def __init__(self, dry_run=False, verbose=False): Init.
- def create(self, file_path): Create TAR file.
- def extract(self, file_path): Extract TAR file.
<|skeleton|>
class Tar:
"""Tar Class."""
... | 19ab8b09985d8c19f235feea348e3a2b0dae890a | <|skeleton|>
class Tar:
"""Tar Class."""
def __init__(self, dry_run=False, verbose=False):
"""Init."""
<|body_0|>
def create(self, file_path):
"""Create TAR file."""
<|body_1|>
def extract(self, file_path):
"""Extract TAR file."""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tar:
"""Tar Class."""
def __init__(self, dry_run=False, verbose=False):
"""Init."""
super(Tar, self).__init__()
self.dry_run = dry_run
self.verbose = verbose
def create(self, file_path):
"""Create TAR file."""
path = os.path.dirname(file_path)
... | the_stack_v2_python_sparse | gerrit_backup_tool/tar/Tar.py | ZhangYaxu/gerrit_backup_tool | train | 0 |
445b61fe55f97317eb96b9d6f4bf3c7b05c4fccf | [
"users_lessons = cls.select().where(LessonStudent.student_id == user_id)\nlessons = [Lesson.get(Lesson.id == lesson.lesson_id) for lesson in users_lessons]\nreturn lessons",
"users_school = User.get(User.user_id == user_id).school_id\nfor lesson_id in lesson_ids:\n lesson = Lesson.get(Lesson.id == lesson_id)\n... | <|body_start_0|>
users_lessons = cls.select().where(LessonStudent.student_id == user_id)
lessons = [Lesson.get(Lesson.id == lesson.lesson_id) for lesson in users_lessons]
return lessons
<|end_body_0|>
<|body_start_1|>
users_school = User.get(User.user_id == user_id).school_id
fo... | Model representing a user attending a lesson in a specific year and semester | LessonStudent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LessonStudent:
"""Model representing a user attending a lesson in a specific year and semester"""
def get_attended_lessons(cls, user_id):
"""Class method to get all the Lessons a user is currently attending"""
<|body_0|>
def attend(cls, user_id, lesson_ids):
"""C... | stack_v2_sparse_classes_36k_train_014946 | 3,410 | no_license | [
{
"docstring": "Class method to get all the Lessons a user is currently attending",
"name": "get_attended_lessons",
"signature": "def get_attended_lessons(cls, user_id)"
},
{
"docstring": "Class method to create LessonStudent objects for every lesson a user wants to attend",
"name": "attend"... | 2 | stack_v2_sparse_classes_30k_train_012307 | Implement the Python class `LessonStudent` described below.
Class description:
Model representing a user attending a lesson in a specific year and semester
Method signatures and docstrings:
- def get_attended_lessons(cls, user_id): Class method to get all the Lessons a user is currently attending
- def attend(cls, us... | Implement the Python class `LessonStudent` described below.
Class description:
Model representing a user attending a lesson in a specific year and semester
Method signatures and docstrings:
- def get_attended_lessons(cls, user_id): Class method to get all the Lessons a user is currently attending
- def attend(cls, us... | 43b797c0d1e78a00e63907797e8336674153fb6b | <|skeleton|>
class LessonStudent:
"""Model representing a user attending a lesson in a specific year and semester"""
def get_attended_lessons(cls, user_id):
"""Class method to get all the Lessons a user is currently attending"""
<|body_0|>
def attend(cls, user_id, lesson_ids):
"""C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LessonStudent:
"""Model representing a user attending a lesson in a specific year and semester"""
def get_attended_lessons(cls, user_id):
"""Class method to get all the Lessons a user is currently attending"""
users_lessons = cls.select().where(LessonStudent.student_id == user_id)
... | the_stack_v2_python_sparse | app/lesson/models.py | eperegrine/beatthecurve | train | 1 |
251f7dfe66fe5ffbaf3be2ea02ed81b84c5b0c4e | [
"self.cp = ConfigParser()\nif os.path.isabs(file_name):\n self.cp.read(file_name, encoding='utf-8')\n self.file_name = file_name\nelse:\n self.p = dirname(dirname(abspath(__file__)))\n sys.path.insert(0, self.p)\n self.file_name = self.p + '\\\\' + file_name\n self.cp.read(self.file_name, encoding... | <|body_start_0|>
self.cp = ConfigParser()
if os.path.isabs(file_name):
self.cp.read(file_name, encoding='utf-8')
self.file_name = file_name
else:
self.p = dirname(dirname(abspath(__file__)))
sys.path.insert(0, self.p)
self.file_name = s... | ConfigAction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigAction:
def __init__(self, file_name):
"""初始化操作,读取文件内容 :param file_name:"""
<|body_0|>
def modify(self, sec, key_, val):
"""修改配置信息 :param sec: :param opt: :param val: :return:"""
<|body_1|>
def get(self, section_, key_=None):
"""获取配置信息 :par... | stack_v2_sparse_classes_36k_train_014947 | 3,222 | no_license | [
{
"docstring": "初始化操作,读取文件内容 :param file_name:",
"name": "__init__",
"signature": "def __init__(self, file_name)"
},
{
"docstring": "修改配置信息 :param sec: :param opt: :param val: :return:",
"name": "modify",
"signature": "def modify(self, sec, key_, val)"
},
{
"docstring": "获取配置信息 :... | 5 | stack_v2_sparse_classes_30k_train_011382 | Implement the Python class `ConfigAction` described below.
Class description:
Implement the ConfigAction class.
Method signatures and docstrings:
- def __init__(self, file_name): 初始化操作,读取文件内容 :param file_name:
- def modify(self, sec, key_, val): 修改配置信息 :param sec: :param opt: :param val: :return:
- def get(self, sect... | Implement the Python class `ConfigAction` described below.
Class description:
Implement the ConfigAction class.
Method signatures and docstrings:
- def __init__(self, file_name): 初始化操作,读取文件内容 :param file_name:
- def modify(self, sec, key_, val): 修改配置信息 :param sec: :param opt: :param val: :return:
- def get(self, sect... | 41eab8a5c3b5c4c38efe418bc4f333abf7940d81 | <|skeleton|>
class ConfigAction:
def __init__(self, file_name):
"""初始化操作,读取文件内容 :param file_name:"""
<|body_0|>
def modify(self, sec, key_, val):
"""修改配置信息 :param sec: :param opt: :param val: :return:"""
<|body_1|>
def get(self, section_, key_=None):
"""获取配置信息 :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigAction:
def __init__(self, file_name):
"""初始化操作,读取文件内容 :param file_name:"""
self.cp = ConfigParser()
if os.path.isabs(file_name):
self.cp.read(file_name, encoding='utf-8')
self.file_name = file_name
else:
self.p = dirname(dirname(abspat... | the_stack_v2_python_sparse | pyBase/config_action.py | fangdong1990/IMRoute-ApiTest | train | 0 | |
9e3d3cfd491d98cc28042f02a8b7422c3819d7b6 | [
"schema = BusinessSchema()\nbusiness = Business.get_by_id(business_id)\nif not business:\n return (dict(status='fail', message=f'Business with id {business_id} not found'), 404)\nbusiness_data, errors = schema.dumps(business)\nif errors:\n return (dict(status='fail', message=errors), 500)\nreturn (dict(status... | <|body_start_0|>
schema = BusinessSchema()
business = Business.get_by_id(business_id)
if not business:
return (dict(status='fail', message=f'Business with id {business_id} not found'), 404)
business_data, errors = schema.dumps(business)
if errors:
return (... | BusinessDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BusinessDetailView:
def get(self, business_id):
"""Getting individual business"""
<|body_0|>
def patch(self, business_id):
"""Update a single business"""
<|body_1|>
def delete(self, business_id):
"""Delete a single business"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_014948 | 3,207 | no_license | [
{
"docstring": "Getting individual business",
"name": "get",
"signature": "def get(self, business_id)"
},
{
"docstring": "Update a single business",
"name": "patch",
"signature": "def patch(self, business_id)"
},
{
"docstring": "Delete a single business",
"name": "delete",
... | 3 | stack_v2_sparse_classes_30k_train_009133 | Implement the Python class `BusinessDetailView` described below.
Class description:
Implement the BusinessDetailView class.
Method signatures and docstrings:
- def get(self, business_id): Getting individual business
- def patch(self, business_id): Update a single business
- def delete(self, business_id): Delete a sin... | Implement the Python class `BusinessDetailView` described below.
Class description:
Implement the BusinessDetailView class.
Method signatures and docstrings:
- def get(self, business_id): Getting individual business
- def patch(self, business_id): Update a single business
- def delete(self, business_id): Delete a sin... | 015d70b8f79df6c1a5629add35767cee52f424f5 | <|skeleton|>
class BusinessDetailView:
def get(self, business_id):
"""Getting individual business"""
<|body_0|>
def patch(self, business_id):
"""Update a single business"""
<|body_1|>
def delete(self, business_id):
"""Delete a single business"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BusinessDetailView:
def get(self, business_id):
"""Getting individual business"""
schema = BusinessSchema()
business = Business.get_by_id(business_id)
if not business:
return (dict(status='fail', message=f'Business with id {business_id} not found'), 404)
bus... | the_stack_v2_python_sparse | app/controllers/business.py | MutegekiHenry/project-cohort-backend | train | 0 | |
80b7654cc0fb801091e38653b10c2342086ae260 | [
"self.doors = ['a', 'b', 'c']\nself.wins = 0\nself.total = 0",
"prize = random.choice(self.doors)\nempty = (set(self.doors) - {prize, chosen}).pop()\nself.total += 1\nif strategy(self.doors, chosen, empty) == prize:\n self.wins += 1\n return True\nreturn False",
"for i in xrange(n):\n self.play(strateg... | <|body_start_0|>
self.doors = ['a', 'b', 'c']
self.wins = 0
self.total = 0
<|end_body_0|>
<|body_start_1|>
prize = random.choice(self.doors)
empty = (set(self.doors) - {prize, chosen}).pop()
self.total += 1
if strategy(self.doors, chosen, empty) == prize:
... | Monty | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Monty:
def __init__(self):
"""Initialize instance variables: doors: list of strings wins: integer total: integer"""
<|body_0|>
def play(self, strategy, chosen='a'):
"""INPUT: function, string OUTPUT: Boolean Play the Monty Hall game once. The first choice is given by... | stack_v2_sparse_classes_36k_train_014949 | 1,547 | no_license | [
{
"docstring": "Initialize instance variables: doors: list of strings wins: integer total: integer",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "INPUT: function, string OUTPUT: Boolean Play the Monty Hall game once. The first choice is given by the argument chosen. R... | 3 | stack_v2_sparse_classes_30k_train_011005 | Implement the Python class `Monty` described below.
Class description:
Implement the Monty class.
Method signatures and docstrings:
- def __init__(self): Initialize instance variables: doors: list of strings wins: integer total: integer
- def play(self, strategy, chosen='a'): INPUT: function, string OUTPUT: Boolean P... | Implement the Python class `Monty` described below.
Class description:
Implement the Monty class.
Method signatures and docstrings:
- def __init__(self): Initialize instance variables: doors: list of strings wins: integer total: integer
- def play(self, strategy, chosen='a'): INPUT: function, string OUTPUT: Boolean P... | 560334017c5748aa29431fa918ed7a35e8f2699c | <|skeleton|>
class Monty:
def __init__(self):
"""Initialize instance variables: doors: list of strings wins: integer total: integer"""
<|body_0|>
def play(self, strategy, chosen='a'):
"""INPUT: function, string OUTPUT: Boolean Play the Monty Hall game once. The first choice is given by... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Monty:
def __init__(self):
"""Initialize instance variables: doors: list of strings wins: integer total: integer"""
self.doors = ['a', 'b', 'c']
self.wins = 0
self.total = 0
def play(self, strategy, chosen='a'):
"""INPUT: function, string OUTPUT: Boolean Play the M... | the_stack_v2_python_sparse | power-bayesian/monty.py | knakamor/projects | train | 1 | |
55d11f4d7bfc88f75f76ef987123562308529ad9 | [
"cache = {0: 0, 1: 1, 2: 2}\nfor i in range(3, n + 1):\n cache[i] = cache[i - 1] + cache[i - 2]\nreturn cache[n]",
"cache = {}\n\ndef dfs(i):\n if i <= 2:\n cache[i] = i\n return i\n if i in cache:\n return cache[i]\n cache[i] = dfs(i - 1) + dfs(i - 2)\n return cache[i]\nreturn... | <|body_start_0|>
cache = {0: 0, 1: 1, 2: 2}
for i in range(3, n + 1):
cache[i] = cache[i - 1] + cache[i - 2]
return cache[n]
<|end_body_0|>
<|body_start_1|>
cache = {}
def dfs(i):
if i <= 2:
cache[i] = i
return i
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cache = {0: 0, 1: 1, 2: 2}
for i in range(3, n + 1):
... | stack_v2_sparse_classes_36k_train_014950 | 713 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002021 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): :type n: int :rtype: int
- def climbStairs(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 climbStairs(self, n): :type n: int :rtype: int
- def climbStairs(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def climbStairs(self, n):
""":t... | 2a29426be1d690b6f90bc45b437900deee46d832 | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
cache = {0: 0, 1: 1, 2: 2}
for i in range(3, n + 1):
cache[i] = cache[i - 1] + cache[i - 2]
return cache[n]
def climbStairs(self, n):
""":type n: int :rtype: int"""
cache = {}
... | the_stack_v2_python_sparse | src/leet/70-climbing-stairs.py | sevenseablue/leetcode | train | 0 | |
7e766aacfad92a5527b3fcebb8cd70b350e09244 | [
"base_path = Path('gungame')\ntry:\n folder = valid_plugins.get_plugin_type(name) + '_plugins'\n file_path = base_path / folder / name\n cvar_prefix = name + '_'\nexcept ValueError:\n folder = 'core'\n file_path = base_path / name + '_settings'\n cvar_prefix = 'gg_{plugin_name}_'.format(plugin_nam... | <|body_start_0|>
base_path = Path('gungame')
try:
folder = valid_plugins.get_plugin_type(name) + '_plugins'
file_path = base_path / folder / name
cvar_prefix = name + '_'
except ValueError:
folder = 'core'
file_path = base_path / name +... | Class used to create GunGame configuration files. | GunGameConfigManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GunGameConfigManager:
"""Class used to create GunGame configuration files."""
def __init__(self, name):
"""Add 'gungame' to the path before initializing the instance."""
<|body_0|>
def cvar(self, name, default=0, description=None, flags=0, min_value=None, max_value=None,... | stack_v2_sparse_classes_36k_train_014951 | 4,371 | no_license | [
{
"docstring": "Add 'gungame' to the path before initializing the instance.",
"name": "__init__",
"signature": "def __init__(self, name)"
},
{
"docstring": "Override cvar method to add cvar as _GunGameCvarManager object.",
"name": "cvar",
"signature": "def cvar(self, name, default=0, des... | 2 | null | Implement the Python class `GunGameConfigManager` described below.
Class description:
Class used to create GunGame configuration files.
Method signatures and docstrings:
- def __init__(self, name): Add 'gungame' to the path before initializing the instance.
- def cvar(self, name, default=0, description=None, flags=0,... | Implement the Python class `GunGameConfigManager` described below.
Class description:
Class used to create GunGame configuration files.
Method signatures and docstrings:
- def __init__(self, name): Add 'gungame' to the path before initializing the instance.
- def cvar(self, name, default=0, description=None, flags=0,... | dd76d1f581a1a8aff18c2194834665fa66a82aab | <|skeleton|>
class GunGameConfigManager:
"""Class used to create GunGame configuration files."""
def __init__(self, name):
"""Add 'gungame' to the path before initializing the instance."""
<|body_0|>
def cvar(self, name, default=0, description=None, flags=0, min_value=None, max_value=None,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GunGameConfigManager:
"""Class used to create GunGame configuration files."""
def __init__(self, name):
"""Add 'gungame' to the path before initializing the instance."""
base_path = Path('gungame')
try:
folder = valid_plugins.get_plugin_type(name) + '_plugins'
... | the_stack_v2_python_sparse | addons/source-python/plugins/gungame/core/config/manager.py | Hackmastr/GunGame-SP | train | 0 |
20fa1ec185c23badede4c5226874d120ce80d8cc | [
"self.languages = {}\nif data is not None:\n self.update(data)",
"result = None\nsrc = []\nprio = 1e+99\nfor lang in self.languages.values():\n lang_src = lang.get_source_files(file_list)\n if (len(lang_src), lang.priority) > (len(src), prio):\n result = lang\n src = lang_src\n prio ... | <|body_start_0|>
self.languages = {}
if data is not None:
self.update(data)
<|end_body_0|>
<|body_start_1|>
result = None
src = []
prio = 1e+99
for lang in self.languages.values():
lang_src = lang.get_source_files(file_list)
if (len(la... | A set of languages. | Languages | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Languages:
"""A set of languages."""
def __init__(self, data=None):
"""Create a set of languages from a dict. Args: data (dict): dictonary containing configuration. If None, resulting set of languages is empty. See documentation of update() method below for details."""
<|body... | stack_v2_sparse_classes_36k_train_014952 | 8,369 | permissive | [
{
"docstring": "Create a set of languages from a dict. Args: data (dict): dictonary containing configuration. If None, resulting set of languages is empty. See documentation of update() method below for details.",
"name": "__init__",
"signature": "def __init__(self, data=None)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_005075 | Implement the Python class `Languages` described below.
Class description:
A set of languages.
Method signatures and docstrings:
- def __init__(self, data=None): Create a set of languages from a dict. Args: data (dict): dictonary containing configuration. If None, resulting set of languages is empty. See documentatio... | Implement the Python class `Languages` described below.
Class description:
A set of languages.
Method signatures and docstrings:
- def __init__(self, data=None): Create a set of languages from a dict. Args: data (dict): dictonary containing configuration. If None, resulting set of languages is empty. See documentatio... | 307d417056e8dc8581db96572e945868e0559454 | <|skeleton|>
class Languages:
"""A set of languages."""
def __init__(self, data=None):
"""Create a set of languages from a dict. Args: data (dict): dictonary containing configuration. If None, resulting set of languages is empty. See documentation of update() method below for details."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Languages:
"""A set of languages."""
def __init__(self, data=None):
"""Create a set of languages from a dict. Args: data (dict): dictonary containing configuration. If None, resulting set of languages is empty. See documentation of update() method below for details."""
self.languages = {}... | the_stack_v2_python_sparse | problemtools/languages.py | Kattis/problemtools | train | 95 |
87bd5b6aa00433aa56a83a0ca2e03b02c93e1ac9 | [
"self.astar_fore = AStarLookup(grid, start, goal)\nself.astar_back = AStarLookup(grid, goal, start)\nself.expanded_nodes = 0\nself.len_optimal = 0",
"while not self.astar_fore.is_found and (not self.astar_back.is_found):\n self.astar_fore.next_move(self.astar_back.best)\n if self.astar_fore.is_found:\n ... | <|body_start_0|>
self.astar_fore = AStarLookup(grid, start, goal)
self.astar_back = AStarLookup(grid, goal, start)
self.expanded_nodes = 0
self.len_optimal = 0
<|end_body_0|>
<|body_start_1|>
while not self.astar_fore.is_found and (not self.astar_back.is_found):
self... | ============================================================================ Description: Bi-Directional A* (one turn each direction). ============================================================================ | AStarBi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AStarBi:
"""============================================================================ Description: Bi-Directional A* (one turn each direction). ============================================================================"""
def __init__(self, grid, start, goal):
"""===============... | stack_v2_sparse_classes_36k_train_014953 | 2,415 | no_license | [
{
"docstring": "======================================================================== Description: Constructor (inits the attributes). ======================================================================== Arguments: ------------------------------------------------------------------------ 1. grid : Grid. 2... | 3 | stack_v2_sparse_classes_30k_train_002864 | Implement the Python class `AStarBi` described below.
Class description:
============================================================================ Description: Bi-Directional A* (one turn each direction). ============================================================================
Method signatures and docstrings:... | Implement the Python class `AStarBi` described below.
Class description:
============================================================================ Description: Bi-Directional A* (one turn each direction). ============================================================================
Method signatures and docstrings:... | ef4d6218bc48d3c988f287187e6e3feec05d88cd | <|skeleton|>
class AStarBi:
"""============================================================================ Description: Bi-Directional A* (one turn each direction). ============================================================================"""
def __init__(self, grid, start, goal):
"""===============... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AStarBi:
"""============================================================================ Description: Bi-Directional A* (one turn each direction). ============================================================================"""
def __init__(self, grid, start, goal):
"""============================... | the_stack_v2_python_sparse | f_astar/c_astar_bi.py | valdas1966/old | train | 0 |
c512fea2319e3bb9f5a3963ac9424e8dd08e50ba | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | AccountGrants assign a resource directly to an account, giving the account the permission to connect to that resource. | AccountGrantsServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountGrantsServicer:
"""AccountGrants assign a resource directly to an account, giving the account the permission to connect to that resource."""
def Create(self, request, context):
"""Create registers a new AccountGrant."""
<|body_0|>
def Get(self, request, context):
... | stack_v2_sparse_classes_36k_train_014954 | 7,980 | permissive | [
{
"docstring": "Create registers a new AccountGrant.",
"name": "Create",
"signature": "def Create(self, request, context)"
},
{
"docstring": "Get reads one AccountGrant by ID.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Delete removes a Acco... | 4 | stack_v2_sparse_classes_30k_train_008422 | Implement the Python class `AccountGrantsServicer` described below.
Class description:
AccountGrants assign a resource directly to an account, giving the account the permission to connect to that resource.
Method signatures and docstrings:
- def Create(self, request, context): Create registers a new AccountGrant.
- d... | Implement the Python class `AccountGrantsServicer` described below.
Class description:
AccountGrants assign a resource directly to an account, giving the account the permission to connect to that resource.
Method signatures and docstrings:
- def Create(self, request, context): Create registers a new AccountGrant.
- d... | 1f3a53ef8c404e64d9324f9fd13f5c39c71eaca5 | <|skeleton|>
class AccountGrantsServicer:
"""AccountGrants assign a resource directly to an account, giving the account the permission to connect to that resource."""
def Create(self, request, context):
"""Create registers a new AccountGrant."""
<|body_0|>
def Get(self, request, context):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountGrantsServicer:
"""AccountGrants assign a resource directly to an account, giving the account the permission to connect to that resource."""
def Create(self, request, context):
"""Create registers a new AccountGrant."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
contex... | the_stack_v2_python_sparse | strongdm/account_grants_pb2_grpc.py | strongdm/strongdm-sdk-python | train | 9 |
6640f260e798560bc00fd29d4fe7c8c85ec54676 | [
"if data is None:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\n else:\n self.lambtha = float(lambtha)\nelse:\n if type(data) is not list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple ... | <|body_start_0|>
if data is None:
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
else:
self.lambtha = float(lambtha)
else:
if type(data) is not list:
raise TypeError('data must be a list')
... | Represents an exponential distribution | Exponential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exponential:
"""Represents an exponential distribution"""
def __init__(self, data=None, lambtha=1.0):
"""Class constructor - 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"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_014955 | 1,434 | no_license | [
{
"docstring": "Class constructor - 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)"
},
{
"docstring": "Calculates the value of t... | 3 | stack_v2_sparse_classes_30k_train_016906 | Implement the Python class `Exponential` described below.
Class description:
Represents an exponential distribution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Class constructor - data is a list of the data to be used to estimate the distribution - lambtha is the expected number of... | Implement the Python class `Exponential` described below.
Class description:
Represents an exponential distribution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Class constructor - data is a list of the data to be used to estimate the distribution - lambtha is the expected number of... | 161e33b23d398d7d01ad0d7740b78dda3f27e787 | <|skeleton|>
class Exponential:
"""Represents an exponential distribution"""
def __init__(self, data=None, lambtha=1.0):
"""Class constructor - 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"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Exponential:
"""Represents an exponential distribution"""
def __init__(self, data=None, lambtha=1.0):
"""Class constructor - 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"""
if data is None:
... | the_stack_v2_python_sparse | math/0x03-probability/exponential.py | felipeserna/holbertonschool-machine_learning | train | 0 |
f8a63997dcdb6c3e20c089ff5ff2ab99692e9ead | [
"self.host = host\nself.user = user\nself.password = password\nself.port = 22",
"ssh = paramiko.SSHClient()\nssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\ntry:\n ssh.connect(self.host, self.port, self.user, self.password, timeout=10)\n return ssh\nexcept Exception as e:\n pass",
"ssh = sel... | <|body_start_0|>
self.host = host
self.user = user
self.password = password
self.port = 22
<|end_body_0|>
<|body_start_1|>
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(self.host, self.port, self... | SSH login remote host for exec command | SSH | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSH:
"""SSH login remote host for exec command"""
def __init__(self, host, user, password):
"""init host, user, password, and port default 22"""
<|body_0|>
def connect(self):
"""Connect remote host ,return ssh object, or None"""
<|body_1|>
def run(se... | stack_v2_sparse_classes_36k_train_014956 | 8,680 | no_license | [
{
"docstring": "init host, user, password, and port default 22",
"name": "__init__",
"signature": "def __init__(self, host, user, password)"
},
{
"docstring": "Connect remote host ,return ssh object, or None",
"name": "connect",
"signature": "def connect(self)"
},
{
"docstring": ... | 3 | null | Implement the Python class `SSH` described below.
Class description:
SSH login remote host for exec command
Method signatures and docstrings:
- def __init__(self, host, user, password): init host, user, password, and port default 22
- def connect(self): Connect remote host ,return ssh object, or None
- def run(self, ... | Implement the Python class `SSH` described below.
Class description:
SSH login remote host for exec command
Method signatures and docstrings:
- def __init__(self, host, user, password): init host, user, password, and port default 22
- def connect(self): Connect remote host ,return ssh object, or None
- def run(self, ... | c77c8c4795f2b9359106836a4d2af38aafbf025c | <|skeleton|>
class SSH:
"""SSH login remote host for exec command"""
def __init__(self, host, user, password):
"""init host, user, password, and port default 22"""
<|body_0|>
def connect(self):
"""Connect remote host ,return ssh object, or None"""
<|body_1|>
def run(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSH:
"""SSH login remote host for exec command"""
def __init__(self, host, user, password):
"""init host, user, password, and port default 22"""
self.host = host
self.user = user
self.password = password
self.port = 22
def connect(self):
"""Connect rem... | the_stack_v2_python_sparse | Day10/src/myFabric.py | wenchong2008/learning | train | 0 |
c3ee8a38a79865f238b73b5f83c3a60b50f50629 | [
"self.icon = icon\nself.label = label\nself.default_params = kwargs\nself.default_params.setdefault('type', 'button')\nif tooltip:\n self.default_params.setdefault('data-toggle', 'tooltip')\n self.default_params.setdefault('title', tooltip)\nsuper(ButtonWidget, self).__init__()",
"params = self.default_para... | <|body_start_0|>
self.icon = icon
self.label = label
self.default_params = kwargs
self.default_params.setdefault('type', 'button')
if tooltip:
self.default_params.setdefault('data-toggle', 'tooltip')
self.default_params.setdefault('title', tooltip)
... | Implement Bootstrap HTML5 button. | ButtonWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ButtonWidget:
"""Implement Bootstrap HTML5 button."""
def __init__(self, label='', tooltip=None, icon=None, **kwargs):
"""Initialize button widget. .. note:: the icons assume use of Twitter Bootstrap, Font Awesome or some other icon library, that allows inserting icons with a <i>-tag... | stack_v2_sparse_classes_36k_train_014957 | 15,429 | no_license | [
{
"docstring": "Initialize button widget. .. note:: the icons assume use of Twitter Bootstrap, Font Awesome or some other icon library, that allows inserting icons with a <i>-tag. :param tooltip: str, Tooltip text for the button. :param icon: str, Name of an icon, e.g. icon-barcode.",
"name": "__init__",
... | 2 | null | Implement the Python class `ButtonWidget` described below.
Class description:
Implement Bootstrap HTML5 button.
Method signatures and docstrings:
- def __init__(self, label='', tooltip=None, icon=None, **kwargs): Initialize button widget. .. note:: the icons assume use of Twitter Bootstrap, Font Awesome or some other... | Implement the Python class `ButtonWidget` described below.
Class description:
Implement Bootstrap HTML5 button.
Method signatures and docstrings:
- def __init__(self, label='', tooltip=None, icon=None, **kwargs): Initialize button widget. .. note:: the icons assume use of Twitter Bootstrap, Font Awesome or some other... | 90032ba4825c6c4dda78c9c2b1d3edf18692b9dc | <|skeleton|>
class ButtonWidget:
"""Implement Bootstrap HTML5 button."""
def __init__(self, label='', tooltip=None, icon=None, **kwargs):
"""Initialize button widget. .. note:: the icons assume use of Twitter Bootstrap, Font Awesome or some other icon library, that allows inserting icons with a <i>-tag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ButtonWidget:
"""Implement Bootstrap HTML5 button."""
def __init__(self, label='', tooltip=None, icon=None, **kwargs):
"""Initialize button widget. .. note:: the icons assume use of Twitter Bootstrap, Font Awesome or some other icon library, that allows inserting icons with a <i>-tag. :param tool... | the_stack_v2_python_sparse | inspirehep/modules/forms/field_widgets.py | spirosdelviniotis/inspire-next | train | 1 |
99f833cb28529c5808e13b07fab3f82097a5f5dc | [
"self.BATCH_SIZE = self.IMAGES_PER_GPU * self.GPU_COUNT\nself.LR_BASE = self.LR_BASE_BASE * (float(self.BATCH_SIZE) / 16)\nif self.IMAGE_RESIZE_MODE == 'crop':\n self.IMAGE_SHAPE = np.array([self.IMAGE_MIN_DIM, self.IMAGE_MIN_DIM, 3])\nelse:\n self.IMAGE_SHAPE = np.array([self.IMAGE_MAX_DIM, self.IMAGE_MAX_DI... | <|body_start_0|>
self.BATCH_SIZE = self.IMAGES_PER_GPU * self.GPU_COUNT
self.LR_BASE = self.LR_BASE_BASE * (float(self.BATCH_SIZE) / 16)
if self.IMAGE_RESIZE_MODE == 'crop':
self.IMAGE_SHAPE = np.array([self.IMAGE_MIN_DIM, self.IMAGE_MIN_DIM, 3])
else:
self.IMAGE_... | Base configuration class. For custom configurations, create a sub-class that inherits from this one and override properties that need to be changed. | Config | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""Base configuration class. For custom configurations, create a sub-class that inherits from this one and override properties that need to be changed."""
def __init__(self):
"""Set values of computed attributes."""
<|body_0|>
def display(self):
"""Displa... | stack_v2_sparse_classes_36k_train_014958 | 5,348 | permissive | [
{
"docstring": "Set values of computed attributes.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Display Configuration values.",
"name": "display",
"signature": "def display(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016907 | Implement the Python class `Config` described below.
Class description:
Base configuration class. For custom configurations, create a sub-class that inherits from this one and override properties that need to be changed.
Method signatures and docstrings:
- def __init__(self): Set values of computed attributes.
- def ... | Implement the Python class `Config` described below.
Class description:
Base configuration class. For custom configurations, create a sub-class that inherits from this one and override properties that need to be changed.
Method signatures and docstrings:
- def __init__(self): Set values of computed attributes.
- def ... | cbe701ecd586860ff3444f4ad5aea25e209260ea | <|skeleton|>
class Config:
"""Base configuration class. For custom configurations, create a sub-class that inherits from this one and override properties that need to be changed."""
def __init__(self):
"""Set values of computed attributes."""
<|body_0|>
def display(self):
"""Displa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
"""Base configuration class. For custom configurations, create a sub-class that inherits from this one and override properties that need to be changed."""
def __init__(self):
"""Set values of computed attributes."""
self.BATCH_SIZE = self.IMAGES_PER_GPU * self.GPU_COUNT
se... | the_stack_v2_python_sparse | semantic-segmentation/libraries/semantic/config.py | shenqiang-Yuan/hdxfag | train | 0 |
f35cbaa151008ea37d1de73e3bfb032c82b16d03 | [
"if not root:\n return ''\nq = [root]\nres = []\nwhile q:\n node = q.pop(0)\n if node == None:\n res.append('None')\n continue\n res.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\nwhile res[-1] == 'None':\n res.pop()\nreturn ','.join(res)",
"if data == '':\n... | <|body_start_0|>
if not root:
return ''
q = [root]
res = []
while q:
node = q.pop(0)
if node == None:
res.append('None')
continue
res.append(str(node.val))
q.append(node.left)
q.append... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_014959 | 1,833 | 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_013418 | 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:... | cd23bddc7766d13a9896356b177caeb533f2f433 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
q = [root]
res = []
while q:
node = q.pop(0)
if node == None:
res.append('None')
... | the_stack_v2_python_sparse | leetcode/209_Serialize_and_Deserialize_Binary_Tree.py | aasthaagrawal/Algorithms_and_Data_Structures | train | 1 | |
f253ab8ff8d84bcd66755d1830066a25aa219732 | [
"tag1 = -1\nfor i in range(len(nums) - 2, -1, -1):\n if nums[i] < nums[i + 1]:\n tag1 = i\n break\nif tag1 != -1:\n for i in range(len(nums) - 1, -1, -1):\n if nums[tag1] < nums[i]:\n tmp = nums[tag1]\n nums[tag1] = nums[i]\n nums[i] = tmp\n bre... | <|body_start_0|>
tag1 = -1
for i in range(len(nums) - 2, -1, -1):
if nums[i] < nums[i + 1]:
tag1 = i
break
if tag1 != -1:
for i in range(len(nums) - 1, -1, -1):
if nums[tag1] < nums[i]:
tmp = nums[tag1]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_014960 | 1,183 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "nextPermutation",
"signature": "def nextPermutation(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permute",
"signature": "def per... | 2 | stack_v2_sparse_classes_30k_train_005740 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextPermutation(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def permute(self, nums): :type nums: List[int] :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextPermutation(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def permute(self, nums): :type nums: List[int] :rtype:... | c2b01374942dcba7fbbe7865d13d7599bbc083f3 | <|skeleton|>
class Solution:
def nextPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
tag1 = -1
for i in range(len(nums) - 2, -1, -1):
if nums[i] < nums[i + 1]:
tag1 = i
break
if tag... | the_stack_v2_python_sparse | P0046.py | chenjiahui1991/LeetCode | train | 0 | |
bd7855f8fc2e7c4da04643f226b6a4226cf1da9f | [
"SystemController.__init__(self)\nself.global_scenario = None\nself.global_optimizer = None\nself.global_scheduler = None\nself.monitor = None\nself._global_control_input = None",
"SystemController.init_params(self)\nif self.global_scheduler is None:\n self.global_scheduler = GlobalPeriodicScheduler()\nself.gl... | <|body_start_0|>
SystemController.__init__(self)
self.global_scenario = None
self.global_optimizer = None
self.global_scheduler = None
self.monitor = None
self._global_control_input = None
<|end_body_0|>
<|body_start_1|>
SystemController.init_params(self)
... | Hierarchical System Controller Attributes: global_scenario (GlobalScenario): global scenario global_scheduler (GlobalScheduler): global scheduler monitor (sp.simulator.monitor.monitor.Monitor): simulator's monitor | HierarchicalSystemController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HierarchicalSystemController:
"""Hierarchical System Controller Attributes: global_scenario (GlobalScenario): global scenario global_scheduler (GlobalScheduler): global scheduler monitor (sp.simulator.monitor.monitor.Monitor): simulator's monitor"""
def __init__(self):
"""Initializat... | stack_v2_sparse_classes_36k_train_014961 | 3,902 | no_license | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Initialize simulation parameters",
"name": "init_params",
"signature": "def init_params(self)"
},
{
"docstring": "Clear simulation parameters",
"name": "clear_params",
... | 4 | stack_v2_sparse_classes_30k_train_009078 | Implement the Python class `HierarchicalSystemController` described below.
Class description:
Hierarchical System Controller Attributes: global_scenario (GlobalScenario): global scenario global_scheduler (GlobalScheduler): global scheduler monitor (sp.simulator.monitor.monitor.Monitor): simulator's monitor
Method sig... | Implement the Python class `HierarchicalSystemController` described below.
Class description:
Hierarchical System Controller Attributes: global_scenario (GlobalScenario): global scenario global_scheduler (GlobalScheduler): global scheduler monitor (sp.simulator.monitor.monitor.Monitor): simulator's monitor
Method sig... | ce7045918f60c92ce1ed5ca4389b969bf28e6b82 | <|skeleton|>
class HierarchicalSystemController:
"""Hierarchical System Controller Attributes: global_scenario (GlobalScenario): global scenario global_scheduler (GlobalScheduler): global scheduler monitor (sp.simulator.monitor.monitor.Monitor): simulator's monitor"""
def __init__(self):
"""Initializat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HierarchicalSystemController:
"""Hierarchical System Controller Attributes: global_scenario (GlobalScenario): global scenario global_scheduler (GlobalScheduler): global scheduler monitor (sp.simulator.monitor.monitor.Monitor): simulator's monitor"""
def __init__(self):
"""Initialization"""
... | the_stack_v2_python_sparse | sp/hierarchical_controller/system_controller.py | adysonmaia/phd-sp-dynamic | train | 0 |
54d1253f18e0dc7e44e62048337951004877d150 | [
"http_method = str(request_raw['method']).lower()\ntemp_url = str(request_raw['url']).strip()\ntemp_headers = http_util.header_to_lowercase(json.loads(request_raw['headers']))\ncontent_type = temp_headers['content-type'] if temp_headers is not None and http_util.ContentType.NAME.lower() in temp_headers else None\nt... | <|body_start_0|>
http_method = str(request_raw['method']).lower()
temp_url = str(request_raw['url']).strip()
temp_headers = http_util.header_to_lowercase(json.loads(request_raw['headers']))
content_type = temp_headers['content-type'] if temp_headers is not None and http_util.ContentType.... | Checker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Checker:
def check_logic(self, request_raw):
"""检测响应中是否泄漏身份证 :param request_raw: :return:"""
<|body_0|>
def init_plugin_info(self):
"""初始化信息 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
http_method = str(request_raw['method']).lower()
... | stack_v2_sparse_classes_36k_train_014962 | 3,661 | permissive | [
{
"docstring": "检测响应中是否泄漏身份证 :param request_raw: :return:",
"name": "check_logic",
"signature": "def check_logic(self, request_raw)"
},
{
"docstring": "初始化信息 :return:",
"name": "init_plugin_info",
"signature": "def init_plugin_info(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007556 | Implement the Python class `Checker` described below.
Class description:
Implement the Checker class.
Method signatures and docstrings:
- def check_logic(self, request_raw): 检测响应中是否泄漏身份证 :param request_raw: :return:
- def init_plugin_info(self): 初始化信息 :return: | Implement the Python class `Checker` described below.
Class description:
Implement the Checker class.
Method signatures and docstrings:
- def check_logic(self, request_raw): 检测响应中是否泄漏身份证 :param request_raw: :return:
- def init_plugin_info(self): 初始化信息 :return:
<|skeleton|>
class Checker:
def check_logic(self, r... | 4ee5cca8dc5fc5d7e631e935517bd0f493c30a37 | <|skeleton|>
class Checker:
def check_logic(self, request_raw):
"""检测响应中是否泄漏身份证 :param request_raw: :return:"""
<|body_0|>
def init_plugin_info(self):
"""初始化信息 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Checker:
def check_logic(self, request_raw):
"""检测响应中是否泄漏身份证 :param request_raw: :return:"""
http_method = str(request_raw['method']).lower()
temp_url = str(request_raw['url']).strip()
temp_headers = http_util.header_to_lowercase(json.loads(request_raw['headers']))
cont... | the_stack_v2_python_sparse | HunterAdminApi/plugins/owasp/identity_leak.py | a1kaid/hunter | train | 0 | |
7452019c38dd9c91762ac1114da73c8d37488d0a | [
"for link in self.all():\n text = link.markup_to_html(text)\nreturn text",
"for link in self.all():\n text = link.insert_url(text)\nreturn text"
] | <|body_start_0|>
for link in self.all():
text = link.markup_to_html(text)
return text
<|end_body_0|>
<|body_start_1|>
for link in self.all():
text = link.insert_url(text)
return text
<|end_body_1|>
| InlineLinkManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InlineLinkManager:
def markup_to_html(self, text):
"""replace markup version of tag with html version"""
<|body_0|>
def insert_urls(self, text):
"""insert url as reference in link"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for link in self.all(... | stack_v2_sparse_classes_36k_train_014963 | 10,045 | permissive | [
{
"docstring": "replace markup version of tag with html version",
"name": "markup_to_html",
"signature": "def markup_to_html(self, text)"
},
{
"docstring": "insert url as reference in link",
"name": "insert_urls",
"signature": "def insert_urls(self, text)"
}
] | 2 | null | Implement the Python class `InlineLinkManager` described below.
Class description:
Implement the InlineLinkManager class.
Method signatures and docstrings:
- def markup_to_html(self, text): replace markup version of tag with html version
- def insert_urls(self, text): insert url as reference in link | Implement the Python class `InlineLinkManager` described below.
Class description:
Implement the InlineLinkManager class.
Method signatures and docstrings:
- def markup_to_html(self, text): replace markup version of tag with html version
- def insert_urls(self, text): insert url as reference in link
<|skeleton|>
cla... | 911a2541c77eca522ba5a723f175786f4f9eb481 | <|skeleton|>
class InlineLinkManager:
def markup_to_html(self, text):
"""replace markup version of tag with html version"""
<|body_0|>
def insert_urls(self, text):
"""insert url as reference in link"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InlineLinkManager:
def markup_to_html(self, text):
"""replace markup version of tag with html version"""
for link in self.all():
text = link.markup_to_html(text)
return text
def insert_urls(self, text):
"""insert url as reference in link"""
for link in ... | the_stack_v2_python_sparse | django/apps/stories/models/links.py | universitas/universitas.no | train | 19 | |
20666abb1b47f877da668f4cc41ae5db09b00e04 | [
"a, b = (q, p)\nwhile not (a & 1 or b & 1):\n a >>= 1\n b >>= 1\nif not a & 1:\n return 0\nelif b & 1:\n return 1\nelse:\n return 2",
"g = gcd(p, q)\na, b = (q // g, p // g)\nif not a & 1:\n return 0\nelif b & 1:\n return 1\nelse:\n return 2"
] | <|body_start_0|>
a, b = (q, p)
while not (a & 1 or b & 1):
a >>= 1
b >>= 1
if not a & 1:
return 0
elif b & 1:
return 1
else:
return 2
<|end_body_0|>
<|body_start_1|>
g = gcd(p, q)
a, b = (q // g, p // g)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
"""Extend the original box to mutiple boxes in order to simulate the reflections as follows (p = 3, q = 2): See pics/mirror_reflection.png. So in the end the ray will meet the point where ap == bq. The easiest match is to set a... | stack_v2_sparse_classes_36k_train_014964 | 1,515 | no_license | [
{
"docstring": "Extend the original box to mutiple boxes in order to simulate the reflections as follows (p = 3, q = 2): See pics/mirror_reflection.png. So in the end the ray will meet the point where ap == bq. The easiest match is to set a = q and b = p to match the above equation. Now consider the following c... | 2 | stack_v2_sparse_classes_30k_train_008721 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mirrorReflection(self, p: int, q: int) -> int: Extend the original box to mutiple boxes in order to simulate the reflections as follows (p = 3, q = 2): See pics/mirror_reflec... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mirrorReflection(self, p: int, q: int) -> int: Extend the original box to mutiple boxes in order to simulate the reflections as follows (p = 3, q = 2): See pics/mirror_reflec... | edb870f83f0c4568cce0cacec04ee70cf6b545bf | <|skeleton|>
class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
"""Extend the original box to mutiple boxes in order to simulate the reflections as follows (p = 3, q = 2): See pics/mirror_reflection.png. So in the end the ray will meet the point where ap == bq. The easiest match is to set a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
"""Extend the original box to mutiple boxes in order to simulate the reflections as follows (p = 3, q = 2): See pics/mirror_reflection.png. So in the end the ray will meet the point where ap == bq. The easiest match is to set a = q and b = p... | the_stack_v2_python_sparse | 2020/mirror_reflection.py | eronekogin/leetcode | train | 0 | |
ce47da395d34b7fd435444b94e89037cedaa693f | [
"self.assertEqual(True, yourtest.reverse_boolean(False))\nself.assertEqual(False, yourtest.reverse_boolean(True))\nself.assertEqual(False, yourtest.reverse_boolean(123))\nself.assertEqual(True, yourtest.reverse_boolean(0))\nself.assertEqual(True, yourtest.reverse_boolean([]))\nself.assertEqual(False, yourtest.rever... | <|body_start_0|>
self.assertEqual(True, yourtest.reverse_boolean(False))
self.assertEqual(False, yourtest.reverse_boolean(True))
self.assertEqual(False, yourtest.reverse_boolean(123))
self.assertEqual(True, yourtest.reverse_boolean(0))
self.assertEqual(True, yourtest.reverse_bool... | 기본적인 함수 사용법을 배웁니다. | BasicFunctionTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicFunctionTest:
"""기본적인 함수 사용법을 배웁니다."""
def test_reverse_boolean(self):
"""True, False의 각각의 반대값을 리턴시켜라."""
<|body_0|>
def test_create_function(self):
"""Lambda 함수 또는.. Wrapper 함수를 사용하여 다음의 결과물을 리턴시키는 함수를 만드세요."""
<|body_1|>
def test_calculate_mea... | stack_v2_sparse_classes_36k_train_014965 | 3,512 | no_license | [
{
"docstring": "True, False의 각각의 반대값을 리턴시켜라.",
"name": "test_reverse_boolean",
"signature": "def test_reverse_boolean(self)"
},
{
"docstring": "Lambda 함수 또는.. Wrapper 함수를 사용하여 다음의 결과물을 리턴시키는 함수를 만드세요.",
"name": "test_create_function",
"signature": "def test_create_function(self)"
},
... | 6 | stack_v2_sparse_classes_30k_train_012329 | Implement the Python class `BasicFunctionTest` described below.
Class description:
기본적인 함수 사용법을 배웁니다.
Method signatures and docstrings:
- def test_reverse_boolean(self): True, False의 각각의 반대값을 리턴시켜라.
- def test_create_function(self): Lambda 함수 또는.. Wrapper 함수를 사용하여 다음의 결과물을 리턴시키는 함수를 만드세요.
- def test_calculate_mean(se... | Implement the Python class `BasicFunctionTest` described below.
Class description:
기본적인 함수 사용법을 배웁니다.
Method signatures and docstrings:
- def test_reverse_boolean(self): True, False의 각각의 반대값을 리턴시켜라.
- def test_create_function(self): Lambda 함수 또는.. Wrapper 함수를 사용하여 다음의 결과물을 리턴시키는 함수를 만드세요.
- def test_calculate_mean(se... | eafbeddc7a7706377478282252806de3a56cc5bb | <|skeleton|>
class BasicFunctionTest:
"""기본적인 함수 사용법을 배웁니다."""
def test_reverse_boolean(self):
"""True, False의 각각의 반대값을 리턴시켜라."""
<|body_0|>
def test_create_function(self):
"""Lambda 함수 또는.. Wrapper 함수를 사용하여 다음의 결과물을 리턴시키는 함수를 만드세요."""
<|body_1|>
def test_calculate_mea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicFunctionTest:
"""기본적인 함수 사용법을 배웁니다."""
def test_reverse_boolean(self):
"""True, False의 각각의 반대값을 리턴시켜라."""
self.assertEqual(True, yourtest.reverse_boolean(False))
self.assertEqual(False, yourtest.reverse_boolean(True))
self.assertEqual(False, yourtest.reverse_boolean(1... | the_stack_v2_python_sparse | 010_function/functions.py | AndersonJo/python-lab | train | 0 |
4e5481eb3fc93e65a41731a58f352d68de49604b | [
"config_builder.add(CommonStoreKeys.OP_ID.key, None)\nconfig_builder.add(CommonStoreKeys.EXECUTION_ID.key, None)\nconfig_builder.add(CommonStoreKeys.ATTEMPT_ID.key, None)",
"op_id = context.configuration.get_value(CommonStoreKeys.OP_ID.key)\nexecution_id = context.configuration.get_value(CommonStoreKeys.EXECUTION... | <|body_start_0|>
config_builder.add(CommonStoreKeys.OP_ID.key, None)
config_builder.add(CommonStoreKeys.EXECUTION_ID.key, None)
config_builder.add(CommonStoreKeys.ATTEMPT_ID.key, None)
<|end_body_0|>
<|body_start_1|>
op_id = context.configuration.get_value(CommonStoreKeys.OP_ID.key)
... | Initialize in the StateStore common runtime attributes | RuntimeStateInitializePlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RuntimeStateInitializePlugin:
"""Initialize in the StateStore common runtime attributes"""
def vdk_configure(self, config_builder: ConfigurationBuilder) -> None:
"""Some job attributes like op_id can be passed externally as configuration."""
<|body_0|>
def vdk_initialize... | stack_v2_sparse_classes_36k_train_014966 | 4,888 | permissive | [
{
"docstring": "Some job attributes like op_id can be passed externally as configuration.",
"name": "vdk_configure",
"signature": "def vdk_configure(self, config_builder: ConfigurationBuilder) -> None"
},
{
"docstring": "Setup common state attributes of the app (CommonStoreKeys). Configuration c... | 2 | stack_v2_sparse_classes_30k_train_020856 | Implement the Python class `RuntimeStateInitializePlugin` described below.
Class description:
Initialize in the StateStore common runtime attributes
Method signatures and docstrings:
- def vdk_configure(self, config_builder: ConfigurationBuilder) -> None: Some job attributes like op_id can be passed externally as con... | Implement the Python class `RuntimeStateInitializePlugin` described below.
Class description:
Initialize in the StateStore common runtime attributes
Method signatures and docstrings:
- def vdk_configure(self, config_builder: ConfigurationBuilder) -> None: Some job attributes like op_id can be passed externally as con... | 9ac18145c6a32e0c3ae035b99796e87184a53522 | <|skeleton|>
class RuntimeStateInitializePlugin:
"""Initialize in the StateStore common runtime attributes"""
def vdk_configure(self, config_builder: ConfigurationBuilder) -> None:
"""Some job attributes like op_id can be passed externally as configuration."""
<|body_0|>
def vdk_initialize... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RuntimeStateInitializePlugin:
"""Initialize in the StateStore common runtime attributes"""
def vdk_configure(self, config_builder: ConfigurationBuilder) -> None:
"""Some job attributes like op_id can be passed externally as configuration."""
config_builder.add(CommonStoreKeys.OP_ID.key, N... | the_stack_v2_python_sparse | projects/vdk-core/src/vdk/internal/builtin_plugins/builtin_hook_impl.py | savadev/versatile-data-kit | train | 0 |
70b34531957cc37b45d09a78acf08a617d0b9997 | [
"super(FunctionComponent, self).__init__(opts)\nself.opts = opts\nself.options = opts.get(STAXX_SECTION, {})\nself.staxx_ip = self.options.get('staxx_ip')\nself.staxx_port = self.options.get('staxx_port')\nself.staxx_user = self.options.get('staxx_user')\nself.staxx_password = self.options.get('staxx_password')",
... | <|body_start_0|>
super(FunctionComponent, self).__init__(opts)
self.opts = opts
self.options = opts.get(STAXX_SECTION, {})
self.staxx_ip = self.options.get('staxx_ip')
self.staxx_port = self.options.get('staxx_port')
self.staxx_user = self.options.get('staxx_user')
... | Component that implements Resilient function(s) | FunctionComponent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionComponent:
"""Component that implements Resilient function(s)"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _send_to_staxx_function(self, event, *args, **kwargs):
"""Function:"""
<|body_... | stack_v2_sparse_classes_36k_train_014967 | 5,546 | permissive | [
{
"docstring": "constructor provides access to the configuration options",
"name": "__init__",
"signature": "def __init__(self, opts)"
},
{
"docstring": "Function:",
"name": "_send_to_staxx_function",
"signature": "def _send_to_staxx_function(self, event, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements Resilient function(s)
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _send_to_staxx_function(self, event, *args, **kwargs): Functio... | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements Resilient function(s)
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _send_to_staxx_function(self, event, *args, **kwargs): Functio... | 6878c78b94eeca407998a41ce8db2cc00f2b6758 | <|skeleton|>
class FunctionComponent:
"""Component that implements Resilient function(s)"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _send_to_staxx_function(self, event, *args, **kwargs):
"""Function:"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FunctionComponent:
"""Component that implements Resilient function(s)"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
super(FunctionComponent, self).__init__(opts)
self.opts = opts
self.options = opts.get(STAXX_SECTION, {})
... | the_stack_v2_python_sparse | fn_anomali_staxx/fn_anomali_staxx/components/funct_staxx_import.py | ibmresilient/resilient-community-apps | train | 81 |
dcb6183f960faaf186f21ccad580cba644c5a288 | [
"obj = Invoice.objects.select_for_update().filter(slug=slug).first()\nif obj is None:\n raise Http404()\nclient_ip, is_routable = get_client_ip(self.request)\nself.check_object_permissions(request, obj)\nserializer = InvoiceRetrieveUpdateSerializer(obj, many=False)\nreturn Response(data=serializer.data, status=s... | <|body_start_0|>
obj = Invoice.objects.select_for_update().filter(slug=slug).first()
if obj is None:
raise Http404()
client_ip, is_routable = get_client_ip(self.request)
self.check_object_permissions(request, obj)
serializer = InvoiceRetrieveUpdateSerializer(obj, many... | InvoiceRetrieveDestroyAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvoiceRetrieveDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
<|body_0|>
def put(self, request, pk=None):
"""Update"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj = Invoice.objects.select_for_update().filter(slug=slug).first(... | stack_v2_sparse_classes_36k_train_014968 | 7,213 | permissive | [
{
"docstring": "Retrieve",
"name": "get",
"signature": "def get(self, request, slug=None)"
},
{
"docstring": "Update",
"name": "put",
"signature": "def put(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011952 | Implement the Python class `InvoiceRetrieveDestroyAPIView` described below.
Class description:
Implement the InvoiceRetrieveDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, slug=None): Retrieve
- def put(self, request, pk=None): Update | Implement the Python class `InvoiceRetrieveDestroyAPIView` described below.
Class description:
Implement the InvoiceRetrieveDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, slug=None): Retrieve
- def put(self, request, pk=None): Update
<|skeleton|>
class InvoiceRetrieveDestroyAPIView:... | 98e1ff8bab7dda3492e5ff637bf5aafd111c840c | <|skeleton|>
class InvoiceRetrieveDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
<|body_0|>
def put(self, request, pk=None):
"""Update"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InvoiceRetrieveDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
obj = Invoice.objects.select_for_update().filter(slug=slug).first()
if obj is None:
raise Http404()
client_ip, is_routable = get_client_ip(self.request)
self.check_object_permis... | the_stack_v2_python_sparse | mikaponics/ecommerce/views/resources/invoice_views.py | mikaponics/mikaponics-back | train | 4 | |
a97f1c5445294929db91c9d84e62fc4f12a29e94 | [
"self.feat_len = feat_len\nself.extended_fingers = np.zeros((self.feat_len, 5))\nself.finger_lengths = np.zeros((self.feat_len, 5))\nself.inner_distances = np.zeros((feat_len, 10))\nself.palm_direction = np.zeros((feat_len, 3))\nself.palm_radius = np.zeros((feat_len, 1))\nself.palm_grab = np.zeros((feat_len, 1))\ns... | <|body_start_0|>
self.feat_len = feat_len
self.extended_fingers = np.zeros((self.feat_len, 5))
self.finger_lengths = np.zeros((self.feat_len, 5))
self.inner_distances = np.zeros((feat_len, 10))
self.palm_direction = np.zeros((feat_len, 3))
self.palm_radius = np.zeros((fea... | Features | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Features:
def __init__(self, feat_len, reps):
""":param feat_len: Number of frames collected, before averaging and appending features. Used as number of rows for a given feature matrix :type feat_len: int :param reps: Number of repetitions to be performed. Used for :type reps: int"""
... | stack_v2_sparse_classes_36k_train_014969 | 1,535 | no_license | [
{
"docstring": ":param feat_len: Number of frames collected, before averaging and appending features. Used as number of rows for a given feature matrix :type feat_len: int :param reps: Number of repetitions to be performed. Used for :type reps: int",
"name": "__init__",
"signature": "def __init__(self, ... | 2 | stack_v2_sparse_classes_30k_train_009645 | Implement the Python class `Features` described below.
Class description:
Implement the Features class.
Method signatures and docstrings:
- def __init__(self, feat_len, reps): :param feat_len: Number of frames collected, before averaging and appending features. Used as number of rows for a given feature matrix :type ... | Implement the Python class `Features` described below.
Class description:
Implement the Features class.
Method signatures and docstrings:
- def __init__(self, feat_len, reps): :param feat_len: Number of frames collected, before averaging and appending features. Used as number of rows for a given feature matrix :type ... | 1d51ad72859479ee4ca5fc90bf13f1a58f8116a9 | <|skeleton|>
class Features:
def __init__(self, feat_len, reps):
""":param feat_len: Number of frames collected, before averaging and appending features. Used as number of rows for a given feature matrix :type feat_len: int :param reps: Number of repetitions to be performed. Used for :type reps: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Features:
def __init__(self, feat_len, reps):
""":param feat_len: Number of frames collected, before averaging and appending features. Used as number of rows for a given feature matrix :type feat_len: int :param reps: Number of repetitions to be performed. Used for :type reps: int"""
self.feat... | the_stack_v2_python_sparse | prototyping/backend/features2.py | atah1991/ASLA | train | 0 | |
c7dd6d09117cc8686eddbd1a7ea10d88a5909a25 | [
"transactions = get_transactions_by_ids(transaction_ids=None)\nresult = TransactionSchema(many=True).dump(transactions).data\nreturn (result, 200)",
"transactions = get_transactions_by_ids(request.json['transaction_ids'])\nresult = TransactionSchema(many=True).dump(transactions).data\nreturn (result, 200)"
] | <|body_start_0|>
transactions = get_transactions_by_ids(transaction_ids=None)
result = TransactionSchema(many=True).dump(transactions).data
return (result, 200)
<|end_body_0|>
<|body_start_1|>
transactions = get_transactions_by_ids(request.json['transaction_ids'])
result = Trans... | Flask-RESTful resource endpoints for TransactionModel by ID's. | TransactionsByIds | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransactionsByIds:
"""Flask-RESTful resource endpoints for TransactionModel by ID's."""
def get(self):
"""Simple endpoint to retrieve all rows from table."""
<|body_0|>
def post(self):
"""Simple endpoint to return several rows from table given a list of ID's."""
... | stack_v2_sparse_classes_36k_train_014970 | 4,727 | no_license | [
{
"docstring": "Simple endpoint to retrieve all rows from table.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Simple endpoint to return several rows from table given a list of ID's.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `TransactionsByIds` described below.
Class description:
Flask-RESTful resource endpoints for TransactionModel by ID's.
Method signatures and docstrings:
- def get(self): Simple endpoint to retrieve all rows from table.
- def post(self): Simple endpoint to return several rows from table give... | Implement the Python class `TransactionsByIds` described below.
Class description:
Flask-RESTful resource endpoints for TransactionModel by ID's.
Method signatures and docstrings:
- def get(self): Simple endpoint to retrieve all rows from table.
- def post(self): Simple endpoint to return several rows from table give... | d5ffcc5d276692d1578cea704125b1b3952beb1c | <|skeleton|>
class TransactionsByIds:
"""Flask-RESTful resource endpoints for TransactionModel by ID's."""
def get(self):
"""Simple endpoint to retrieve all rows from table."""
<|body_0|>
def post(self):
"""Simple endpoint to return several rows from table given a list of ID's."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransactionsByIds:
"""Flask-RESTful resource endpoints for TransactionModel by ID's."""
def get(self):
"""Simple endpoint to retrieve all rows from table."""
transactions = get_transactions_by_ids(transaction_ids=None)
result = TransactionSchema(many=True).dump(transactions).data
... | the_stack_v2_python_sparse | application/resources/transaction.py | transreductionist/API-Project-1 | train | 0 |
25a88cbaf5aa09785dd617093a0c36a81844132d | [
"super(JSONParser, self).__init__(*args, **kwargs)\nself.pretty = kwargs.get('pretty', False)\nself.indent = kwargs.get('indent', self.TAB_WIDTH)",
"super(JSONParser, self)._set_argparser_options()\nself._outparser.add_argument('-P', '--outfile-pretty', action='store_true', dest='pretty', help='A flag to indicate... | <|body_start_0|>
super(JSONParser, self).__init__(*args, **kwargs)
self.pretty = kwargs.get('pretty', False)
self.indent = kwargs.get('indent', self.TAB_WIDTH)
<|end_body_0|>
<|body_start_1|>
super(JSONParser, self)._set_argparser_options()
self._outparser.add_argument('-P', '--... | JSONParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONParser:
def __init__(self, *args, **kwargs):
""":option pretty [bool]: Make JSON human-readable"""
<|body_0|>
def _set_argparse_options(self):
"""Creates an ArgumentParser with the parser's allowed arguments."""
<|body_1|>
def write(self, fileobj):
... | stack_v2_sparse_classes_36k_train_014971 | 1,517 | no_license | [
{
"docstring": ":option pretty [bool]: Make JSON human-readable",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Creates an ArgumentParser with the parser's allowed arguments.",
"name": "_set_argparse_options",
"signature": "def _set_argparse_op... | 3 | stack_v2_sparse_classes_30k_train_016516 | Implement the Python class `JSONParser` described below.
Class description:
Implement the JSONParser class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): :option pretty [bool]: Make JSON human-readable
- def _set_argparse_options(self): Creates an ArgumentParser with the parser's allowed ar... | Implement the Python class `JSONParser` described below.
Class description:
Implement the JSONParser class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): :option pretty [bool]: Make JSON human-readable
- def _set_argparse_options(self): Creates an ArgumentParser with the parser's allowed ar... | d0b69daf20e230bded3b814d02ee08ca6c39f612 | <|skeleton|>
class JSONParser:
def __init__(self, *args, **kwargs):
""":option pretty [bool]: Make JSON human-readable"""
<|body_0|>
def _set_argparse_options(self):
"""Creates an ArgumentParser with the parser's allowed arguments."""
<|body_1|>
def write(self, fileobj):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JSONParser:
def __init__(self, *args, **kwargs):
""":option pretty [bool]: Make JSON human-readable"""
super(JSONParser, self).__init__(*args, **kwargs)
self.pretty = kwargs.get('pretty', False)
self.indent = kwargs.get('indent', self.TAB_WIDTH)
def _set_argparse_options(s... | the_stack_v2_python_sparse | csvutils/parsers/builtins/json.py | hhubbell/polytab | train | 0 | |
b62173335183be65b5f41cc1779a5b84b3e2cbfb | [
"super(DRQN, self).__init__()\nobs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))\nif head_hidden_size is None:\n head_hidden_size = encoder_hidden_size_list[-1]\nif isinstance(obs_shape, int) or len(obs_shape) == 1:\n self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, activation... | <|body_start_0|>
super(DRQN, self).__init__()
obs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))
if head_hidden_size is None:
head_hidden_size = encoder_hidden_size_list[-1]
if isinstance(obs_shape, int) or len(obs_shape) == 1:
self.encoder = FC... | Overview: DQN + RNN = DRQN | DRQN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DRQN:
"""Overview: DQN + RNN = DRQN"""
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size: Optional[int]=None, head_layer_num: int=1, lstm_type: Optional[s... | stack_v2_sparse_classes_36k_train_014972 | 30,380 | permissive | [
{
"docstring": "Overview: Init the DRQN Model according to arguments. Arguments: - obs_shape (:obj:`Union[int, SequenceType]`): Observation's space. - action_shape (:obj:`Union[int, SequenceType]`): Action's space. - encoder_hidden_size_list (:obj:`SequenceType`): Collection of ``hidden_size`` to pass to ``Enco... | 2 | stack_v2_sparse_classes_30k_train_007046 | Implement the Python class `DRQN` described below.
Class description:
Overview: DQN + RNN = DRQN
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_si... | Implement the Python class `DRQN` described below.
Class description:
Overview: DQN + RNN = DRQN
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_si... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class DRQN:
"""Overview: DQN + RNN = DRQN"""
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size: Optional[int]=None, head_layer_num: int=1, lstm_type: Optional[s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DRQN:
"""Overview: DQN + RNN = DRQN"""
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], dueling: bool=True, head_hidden_size: Optional[int]=None, head_layer_num: int=1, lstm_type: Optional[str]='normal',... | the_stack_v2_python_sparse | ding/model/template/q_learning.py | shengxuesun/DI-engine | train | 1 |
3d02f5488f6dffaadffb0f97c6ebf8a446595497 | [
"self.snake = collections.deque([(0, 0)])\nself.dirs = {'U': (1, 0), 'D': (-1, 0), 'R': (0, 1), 'L': (0, -1)}\nself.width = width\nself.height = height\nself.food_p = 0\nself.snake_set = set([(0, 0)])\nself.food = food",
"new_row = self.snake[0][0] + self.dirs[direction][0]\nnew_col = self.snake[0][1] + self.dirs... | <|body_start_0|>
self.snake = collections.deque([(0, 0)])
self.dirs = {'U': (1, 0), 'D': (-1, 0), 'R': (0, 1), 'L': (0, -1)}
self.width = width
self.height = height
self.food_p = 0
self.snake_set = set([(0, 0)])
self.food = food
<|end_body_0|>
<|body_start_1|>
... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_36k_train_014973 | 2,003 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_003735 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | 14d973b09e6add87320900c34379667c93d9b538 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | 353.py | HONGWENHT/LeetCode | train | 0 | |
8e73fe7b8dd0aceaaa4c0739085c488d2649a286 | [
"new_category = SpecificationCategory(name=validated_data.get('name'), car=validated_data.get('car'))\nnew_category.save()\nreturn new_category",
"instance.name = validated_data.get('name', instance.name)\ninstance.car = validated_data.get('car', instance.car)\ninstance.save()\nreturn instance"
] | <|body_start_0|>
new_category = SpecificationCategory(name=validated_data.get('name'), car=validated_data.get('car'))
new_category.save()
return new_category
<|end_body_0|>
<|body_start_1|>
instance.name = validated_data.get('name', instance.name)
instance.car = validated_data.g... | SpecificationCategorySerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecificationCategorySerializer:
def create(self, validated_data):
"""create and return new 'SpecificationCategory' instance"""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `SpecificationCategory` instance"""
<|body_... | stack_v2_sparse_classes_36k_train_014974 | 6,342 | no_license | [
{
"docstring": "create and return new 'SpecificationCategory' instance",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Update and return an existing `SpecificationCategory` instance",
"name": "update",
"signature": "def update(self, instance, valida... | 2 | stack_v2_sparse_classes_30k_train_005605 | Implement the Python class `SpecificationCategorySerializer` described below.
Class description:
Implement the SpecificationCategorySerializer class.
Method signatures and docstrings:
- def create(self, validated_data): create and return new 'SpecificationCategory' instance
- def update(self, instance, validated_data... | Implement the Python class `SpecificationCategorySerializer` described below.
Class description:
Implement the SpecificationCategorySerializer class.
Method signatures and docstrings:
- def create(self, validated_data): create and return new 'SpecificationCategory' instance
- def update(self, instance, validated_data... | dba8d1fdb96889e41328e792816a4968cbeb1ed4 | <|skeleton|>
class SpecificationCategorySerializer:
def create(self, validated_data):
"""create and return new 'SpecificationCategory' instance"""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `SpecificationCategory` instance"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpecificationCategorySerializer:
def create(self, validated_data):
"""create and return new 'SpecificationCategory' instance"""
new_category = SpecificationCategory(name=validated_data.get('name'), car=validated_data.get('car'))
new_category.save()
return new_category
def ... | the_stack_v2_python_sparse | cars_web/cars_app/serializers.py | Ignisor/cars_scrapper | train | 0 | |
d64d509554643fc585988153e0e87b869228657d | [
"if not prices:\n return 0\nn = len(prices)\ndp = [[0, 0] for _ in range(n)]\ndp[0][0] = -prices[0]\nfor i in range(1, n):\n dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i])\n dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])\nreturn dp[-1][1]",
"n = len(prices)\nres = 0\nfor i in range(1, n):... | <|body_start_0|>
if not prices:
return 0
n = len(prices)
dp = [[0, 0] for _ in range(n)]
dp[0][0] = -prices[0]
for i in range(1, n):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i])
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit1(self, prices: List[int]) -> int:
"""思路:每次记录两个状态:买入和卖出,每次计算这两个操作的最大收益"""
<|body_0|>
def maxProfit2(self, prices: List[int]) -> int:
"""1. 扫描一遍 只要后一天比前一天大 就把这两天的差值加一下 2. 这种说法是正确的。因为 [1, 3, 4], 4-1 = (3-1) + (4-3)"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_014975 | 2,663 | no_license | [
{
"docstring": "思路:每次记录两个状态:买入和卖出,每次计算这两个操作的最大收益",
"name": "maxProfit1",
"signature": "def maxProfit1(self, prices: List[int]) -> int"
},
{
"docstring": "1. 扫描一遍 只要后一天比前一天大 就把这两天的差值加一下 2. 这种说法是正确的。因为 [1, 3, 4], 4-1 = (3-1) + (4-3)",
"name": "maxProfit2",
"signature": "def maxProfit2(self... | 2 | stack_v2_sparse_classes_30k_train_007843 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit1(self, prices: List[int]) -> int: 思路:每次记录两个状态:买入和卖出,每次计算这两个操作的最大收益
- def maxProfit2(self, prices: List[int]) -> int: 1. 扫描一遍 只要后一天比前一天大 就把这两天的差值加一下 2. 这种说法是正确的。因为 [... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit1(self, prices: List[int]) -> int: 思路:每次记录两个状态:买入和卖出,每次计算这两个操作的最大收益
- def maxProfit2(self, prices: List[int]) -> int: 1. 扫描一遍 只要后一天比前一天大 就把这两天的差值加一下 2. 这种说法是正确的。因为 [... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def maxProfit1(self, prices: List[int]) -> int:
"""思路:每次记录两个状态:买入和卖出,每次计算这两个操作的最大收益"""
<|body_0|>
def maxProfit2(self, prices: List[int]) -> int:
"""1. 扫描一遍 只要后一天比前一天大 就把这两天的差值加一下 2. 这种说法是正确的。因为 [1, 3, 4], 4-1 = (3-1) + (4-3)"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit1(self, prices: List[int]) -> int:
"""思路:每次记录两个状态:买入和卖出,每次计算这两个操作的最大收益"""
if not prices:
return 0
n = len(prices)
dp = [[0, 0] for _ in range(n)]
dp[0][0] = -prices[0]
for i in range(1, n):
dp[i][0] = max(dp[i - 1][... | the_stack_v2_python_sparse | LeetCode/股票购买专题/122. 买卖股票的最佳时机 II.py | yiming1012/MyLeetCode | train | 2 | |
aef55c16cc79287d41b593690d8e063cf6e15142 | [
"logger.debug(f'Creating video with name {name}. Format: {fmt}, size: {size}, save folder: {save_fld}')\nself.scene = scene\nself.save_fld = Path(save_fld)\nself.save_fld.mkdir(exist_ok=True)\nself.save_name = name\nself.video_format = fmt\nself.size = size\nif 'mp4' not in self.video_format:\n raise NotImplemen... | <|body_start_0|>
logger.debug(f'Creating video with name {name}. Format: {fmt}, size: {size}, save folder: {save_fld}')
self.scene = scene
self.save_fld = Path(save_fld)
self.save_fld.mkdir(exist_ok=True)
self.save_name = name
self.video_format = fmt
self.size = s... | VideoMaker | [
"BSD-3-Clause",
"GPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoMaker:
def __init__(self, scene, save_fld, name, fmt='mp4', size='1620x1050', make_frame_func=None):
"""Creates a video by animating a scene and saving a sequence of screenshots. :param scene: the instance of Scene to be animated :param save_fld: str, Path. Where the video will be s... | stack_v2_sparse_classes_36k_train_014976 | 13,632 | permissive | [
{
"docstring": "Creates a video by animating a scene and saving a sequence of screenshots. :param scene: the instance of Scene to be animated :param save_fld: str, Path. Where the video will be savd :param save_name: str, name of the video :param fmt: str. Video format (e.g. 'mp4') :param make_frame_func: None,... | 5 | stack_v2_sparse_classes_30k_train_014491 | Implement the Python class `VideoMaker` described below.
Class description:
Implement the VideoMaker class.
Method signatures and docstrings:
- def __init__(self, scene, save_fld, name, fmt='mp4', size='1620x1050', make_frame_func=None): Creates a video by animating a scene and saving a sequence of screenshots. :para... | Implement the Python class `VideoMaker` described below.
Class description:
Implement the VideoMaker class.
Method signatures and docstrings:
- def __init__(self, scene, save_fld, name, fmt='mp4', size='1620x1050', make_frame_func=None): Creates a video by animating a scene and saving a sequence of screenshots. :para... | a14ead80c1dbc75f20a145a49394dc467c4f7bf1 | <|skeleton|>
class VideoMaker:
def __init__(self, scene, save_fld, name, fmt='mp4', size='1620x1050', make_frame_func=None):
"""Creates a video by animating a scene and saving a sequence of screenshots. :param scene: the instance of Scene to be animated :param save_fld: str, Path. Where the video will be s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VideoMaker:
def __init__(self, scene, save_fld, name, fmt='mp4', size='1620x1050', make_frame_func=None):
"""Creates a video by animating a scene and saving a sequence of screenshots. :param scene: the instance of Scene to be animated :param save_fld: str, Path. Where the video will be savd :param sav... | the_stack_v2_python_sparse | brainrender/video.py | brainglobe/brainrender | train | 345 | |
7a9c3c5330b5ab073bf78a4fd772d103e1e351b7 | [
"configDict = configDict or {}\nconfigDict.setdefault('endpoint', url)\nconfigDict.setdefault('cacheduration', 1)\nconfigDict.setdefault('accept_type', 'application/json')\nconfigDict.setdefault('content_type', 'application/json')\nconfigDict['logger'] = logger if logger else logging.getLogger()\nsuper(RucioConMon,... | <|body_start_0|>
configDict = configDict or {}
configDict.setdefault('endpoint', url)
configDict.setdefault('cacheduration', 1)
configDict.setdefault('accept_type', 'application/json')
configDict.setdefault('content_type', 'application/json')
configDict['logger'] = logger... | API for dealing with retrieving information from Rucio Consistency Monitor | RucioConMon | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RucioConMon:
"""API for dealing with retrieving information from Rucio Consistency Monitor"""
def __init__(self, url, logger=None, configDict=None):
"""Init method for the RucioConMon Class"""
<|body_0|>
def _getResult(self, uri, callname='', clearCache=False, args=None,... | stack_v2_sparse_classes_36k_train_014977 | 5,244 | permissive | [
{
"docstring": "Init method for the RucioConMon Class",
"name": "__init__",
"signature": "def __init__(self, url, logger=None, configDict=None)"
},
{
"docstring": "Either fetch data from the cache file or query the data-service :param uri: The endpoint uri :param callname: alias for caller funct... | 5 | null | Implement the Python class `RucioConMon` described below.
Class description:
API for dealing with retrieving information from Rucio Consistency Monitor
Method signatures and docstrings:
- def __init__(self, url, logger=None, configDict=None): Init method for the RucioConMon Class
- def _getResult(self, uri, callname=... | Implement the Python class `RucioConMon` described below.
Class description:
API for dealing with retrieving information from Rucio Consistency Monitor
Method signatures and docstrings:
- def __init__(self, url, logger=None, configDict=None): Init method for the RucioConMon Class
- def _getResult(self, uri, callname=... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class RucioConMon:
"""API for dealing with retrieving information from Rucio Consistency Monitor"""
def __init__(self, url, logger=None, configDict=None):
"""Init method for the RucioConMon Class"""
<|body_0|>
def _getResult(self, uri, callname='', clearCache=False, args=None,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RucioConMon:
"""API for dealing with retrieving information from Rucio Consistency Monitor"""
def __init__(self, url, logger=None, configDict=None):
"""Init method for the RucioConMon Class"""
configDict = configDict or {}
configDict.setdefault('endpoint', url)
configDict.... | the_stack_v2_python_sparse | src/python/WMCore/Services/RucioConMon/RucioConMon.py | vkuznet/WMCore | train | 0 |
b56a033581dd529f285a21ea85b11b295499f7c2 | [
"if self.request.user.is_authenticated():\n referer_view = self.get_referer_view(self.request)\n return HttpResponseRedirect(referer_view)\nelse:\n data = {'msg': {'content': self.cls_default_msgs['not_signed_in']}}\n template = self.engine.get_template('authentication/login.html')\n context = Reques... | <|body_start_0|>
if self.request.user.is_authenticated():
referer_view = self.get_referer_view(self.request)
return HttpResponseRedirect(referer_view)
else:
data = {'msg': {'content': self.cls_default_msgs['not_signed_in']}}
template = self.engine.get_temp... | This class allows a user to login to his/her account. Attributes: engine: the static reference of the template engine. cls_default_msgs: a dictionary of messages representing the current user status. | UserLoginView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserLoginView:
"""This class allows a user to login to his/her account. Attributes: engine: the static reference of the template engine. cls_default_msgs: a dictionary of messages representing the current user status."""
def get(self, *args, **kwargs):
"""Handles the get request to t... | stack_v2_sparse_classes_36k_train_014978 | 17,941 | permissive | [
{
"docstring": "Handles the get request to the 'login' named route. Returns: A HttpResponse with an authentication login template",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Handles the POST request to the 'login' named route. Expects that an email/username ... | 3 | null | Implement the Python class `UserLoginView` described below.
Class description:
This class allows a user to login to his/her account. Attributes: engine: the static reference of the template engine. cls_default_msgs: a dictionary of messages representing the current user status.
Method signatures and docstrings:
- def... | Implement the Python class `UserLoginView` described below.
Class description:
This class allows a user to login to his/her account. Attributes: engine: the static reference of the template engine. cls_default_msgs: a dictionary of messages representing the current user status.
Method signatures and docstrings:
- def... | 3704cbe6e69ba3e4c53401d3bbc339208e9ebccd | <|skeleton|>
class UserLoginView:
"""This class allows a user to login to his/her account. Attributes: engine: the static reference of the template engine. cls_default_msgs: a dictionary of messages representing the current user status."""
def get(self, *args, **kwargs):
"""Handles the get request to t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserLoginView:
"""This class allows a user to login to his/her account. Attributes: engine: the static reference of the template engine. cls_default_msgs: a dictionary of messages representing the current user status."""
def get(self, *args, **kwargs):
"""Handles the get request to the 'login' na... | the_stack_v2_python_sparse | troupon/authentication/views.py | morristech/troupon | train | 0 |
4b0a6f23347bb26e3f4c2b10e24567773a8d16ae | [
"m, res = (abs(n), 1.0)\nwhile m:\n if m % 2 == 1:\n res *= x\n x *= x\n m //= 2\nreturn res if n > 0 else 1 / res",
"m, res = (abs(n), 1.0)\nwhile m:\n if m & 1:\n res *= x\n x *= x\n m >>= 1\nreturn res if n > 0 else 1 / res"
] | <|body_start_0|>
m, res = (abs(n), 1.0)
while m:
if m % 2 == 1:
res *= x
x *= x
m //= 2
return res if n > 0 else 1 / res
<|end_body_0|>
<|body_start_1|>
m, res = (abs(n), 1.0)
while m:
if m & 1:
res ... | Power | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Power:
def of_x_and_n(self, x: float, n: int) -> float:
"""Approach: Time Complexity: Space Complexity: :param x: :param n: :return:"""
<|body_0|>
def of_x_and_n_(self, x: float, n: int) -> float:
"""Approach: Time Complexity: Space Complexity: :param x: :param n: :r... | stack_v2_sparse_classes_36k_train_014979 | 984 | no_license | [
{
"docstring": "Approach: Time Complexity: Space Complexity: :param x: :param n: :return:",
"name": "of_x_and_n",
"signature": "def of_x_and_n(self, x: float, n: int) -> float"
},
{
"docstring": "Approach: Time Complexity: Space Complexity: :param x: :param n: :return:",
"name": "of_x_and_n_... | 2 | null | Implement the Python class `Power` described below.
Class description:
Implement the Power class.
Method signatures and docstrings:
- def of_x_and_n(self, x: float, n: int) -> float: Approach: Time Complexity: Space Complexity: :param x: :param n: :return:
- def of_x_and_n_(self, x: float, n: int) -> float: Approach:... | Implement the Python class `Power` described below.
Class description:
Implement the Power class.
Method signatures and docstrings:
- def of_x_and_n(self, x: float, n: int) -> float: Approach: Time Complexity: Space Complexity: :param x: :param n: :return:
- def of_x_and_n_(self, x: float, n: int) -> float: Approach:... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Power:
def of_x_and_n(self, x: float, n: int) -> float:
"""Approach: Time Complexity: Space Complexity: :param x: :param n: :return:"""
<|body_0|>
def of_x_and_n_(self, x: float, n: int) -> float:
"""Approach: Time Complexity: Space Complexity: :param x: :param n: :r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Power:
def of_x_and_n(self, x: float, n: int) -> float:
"""Approach: Time Complexity: Space Complexity: :param x: :param n: :return:"""
m, res = (abs(n), 1.0)
while m:
if m % 2 == 1:
res *= x
x *= x
m //= 2
return res if n > 0... | the_stack_v2_python_sparse | goldman_sachs/pow_xn.py | Shiv2157k/leet_code | train | 1 | |
e6fcededbfd5e5af9392bc246fc7de3efdcfaff1 | [
"strategy = Strategy.objects.get(pk=pk)\nstrategy = Strategy.describe_strategies([strategy], verbose=Strategy.MAX_VERBOSE)[0]\nreturn Response({'data': {'strategy': strategy}})",
"strategy = Strategy.objects.get(pk=pk)\nserializer = StrategyCreateUpdateSerializer(strategy, data=request.data, partial=True, context... | <|body_start_0|>
strategy = Strategy.objects.get(pk=pk)
strategy = Strategy.describe_strategies([strategy], verbose=Strategy.MAX_VERBOSE)[0]
return Response({'data': {'strategy': strategy}})
<|end_body_0|>
<|body_start_1|>
strategy = Strategy.objects.get(pk=pk)
serializer = Stra... | SingleStrategyAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleStrategyAPIView:
def get(request, pk):
"""获取策略详情"""
<|body_0|>
def put(request, pk):
"""修改策略"""
<|body_1|>
def delete(request, pk):
"""删除策略"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
strategy = Strategy.objects.get(pk... | stack_v2_sparse_classes_36k_train_014980 | 9,461 | no_license | [
{
"docstring": "获取策略详情",
"name": "get",
"signature": "def get(request, pk)"
},
{
"docstring": "修改策略",
"name": "put",
"signature": "def put(request, pk)"
},
{
"docstring": "删除策略",
"name": "delete",
"signature": "def delete(request, pk)"
}
] | 3 | stack_v2_sparse_classes_30k_train_015988 | Implement the Python class `SingleStrategyAPIView` described below.
Class description:
Implement the SingleStrategyAPIView class.
Method signatures and docstrings:
- def get(request, pk): 获取策略详情
- def put(request, pk): 修改策略
- def delete(request, pk): 删除策略 | Implement the Python class `SingleStrategyAPIView` described below.
Class description:
Implement the SingleStrategyAPIView class.
Method signatures and docstrings:
- def get(request, pk): 获取策略详情
- def put(request, pk): 修改策略
- def delete(request, pk): 删除策略
<|skeleton|>
class SingleStrategyAPIView:
def get(reques... | bb85b52598d68956bde8756c8321ade7b8479ba7 | <|skeleton|>
class SingleStrategyAPIView:
def get(request, pk):
"""获取策略详情"""
<|body_0|>
def put(request, pk):
"""修改策略"""
<|body_1|>
def delete(request, pk):
"""删除策略"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleStrategyAPIView:
def get(request, pk):
"""获取策略详情"""
strategy = Strategy.objects.get(pk=pk)
strategy = Strategy.describe_strategies([strategy], verbose=Strategy.MAX_VERBOSE)[0]
return Response({'data': {'strategy': strategy}})
def put(request, pk):
"""修改策略"""
... | the_stack_v2_python_sparse | curd_test/configure/views.py | huiiiuh/huihuiproject | train | 0 | |
6d7a2eb11cf2f14d3092f0d9a0d0d4afd66740c3 | [
"super().__init__()\nself.encoder = ESPNet_Encoder(num_classes, p, q)\nif encoderFile != None:\n self.encoder.load_state_dict(torch.load(encoderFile))\n print('Encoder loaded!')\nself.en_modules = []\nfor i, m in enumerate(self.encoder.children()):\n self.en_modules.append(m)\nself.level3_C = C(128 + 3, nu... | <|body_start_0|>
super().__init__()
self.encoder = ESPNet_Encoder(num_classes, p, q)
if encoderFile != None:
self.encoder.load_state_dict(torch.load(encoderFile))
print('Encoder loaded!')
self.en_modules = []
for i, m in enumerate(self.encoder.children()):... | This class defines the ESPNet network | ESPNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESPNet:
"""This class defines the ESPNet network"""
def __init__(self, num_classes=19, p=2, q=3, encoderFile=None):
""":param num_classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier :param encoderFile: pret... | stack_v2_sparse_classes_36k_train_014981 | 15,567 | permissive | [
{
"docstring": ":param num_classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier :param encoderFile: pretrained encoder weights. Recall that we first trained the ESPNet-C and then attached the RUM-based light weight decoder. See paper f... | 2 | null | Implement the Python class `ESPNet` described below.
Class description:
This class defines the ESPNet network
Method signatures and docstrings:
- def __init__(self, num_classes=19, p=2, q=3, encoderFile=None): :param num_classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multi... | Implement the Python class `ESPNet` described below.
Class description:
This class defines the ESPNet network
Method signatures and docstrings:
- def __init__(self, num_classes=19, p=2, q=3, encoderFile=None): :param num_classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multi... | f2993d3ce73a2f7ddba05da3891defb08547d504 | <|skeleton|>
class ESPNet:
"""This class defines the ESPNet network"""
def __init__(self, num_classes=19, p=2, q=3, encoderFile=None):
""":param num_classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier :param encoderFile: pret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ESPNet:
"""This class defines the ESPNet network"""
def __init__(self, num_classes=19, p=2, q=3, encoderFile=None):
""":param num_classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier :param encoderFile: pretrained encode... | the_stack_v2_python_sparse | pytorch/pytorchcv/models/others/oth_espnet.py | osmr/imgclsmob | train | 3,017 |
e4d6dd4dbc02b686cda11ab6c27defb8ea75215c | [
"super().highlightBlock(text)\nself.setCurrentBlockState(0)\nif not self.match_multiline(text, *TRI_SINGLE):\n self.match_multiline(text, *TRI_DOUBLE)",
"if self.previousBlockState() == in_state:\n start = 0\n add = 0\nelse:\n match = delimiter.match(text)\n if not match.hasMatch():\n return... | <|body_start_0|>
super().highlightBlock(text)
self.setCurrentBlockState(0)
if not self.match_multiline(text, *TRI_SINGLE):
self.match_multiline(text, *TRI_DOUBLE)
<|end_body_0|>
<|body_start_1|>
if self.previousBlockState() == in_state:
start = 0
add ... | Syntax highlighter for the Python language. | PythonHighlighter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PythonHighlighter:
"""Syntax highlighter for the Python language."""
def highlightBlock(self, text: str):
"""Apply syntax highlighting to the given block of text."""
<|body_0|>
def match_multiline(self, text: str, delimiter: core.RegularExpression, in_state: int, style: ... | stack_v2_sparse_classes_36k_train_014982 | 4,856 | permissive | [
{
"docstring": "Apply syntax highlighting to the given block of text.",
"name": "highlightBlock",
"signature": "def highlightBlock(self, text: str)"
},
{
"docstring": "Do highlighting of multi-line strings. ``delimiter`` should be a ``core.RegExp`` for triple-single-quotes or triple-double-quote... | 2 | null | Implement the Python class `PythonHighlighter` described below.
Class description:
Syntax highlighter for the Python language.
Method signatures and docstrings:
- def highlightBlock(self, text: str): Apply syntax highlighting to the given block of text.
- def match_multiline(self, text: str, delimiter: core.RegularEx... | Implement the Python class `PythonHighlighter` described below.
Class description:
Syntax highlighter for the Python language.
Method signatures and docstrings:
- def highlightBlock(self, text: str): Apply syntax highlighting to the given block of text.
- def match_multiline(self, text: str, delimiter: core.RegularEx... | f00500d992d1befb0f2c2ae62fd2a8aafba7fd45 | <|skeleton|>
class PythonHighlighter:
"""Syntax highlighter for the Python language."""
def highlightBlock(self, text: str):
"""Apply syntax highlighting to the given block of text."""
<|body_0|>
def match_multiline(self, text: str, delimiter: core.RegularExpression, in_state: int, style: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PythonHighlighter:
"""Syntax highlighter for the Python language."""
def highlightBlock(self, text: str):
"""Apply syntax highlighting to the given block of text."""
super().highlightBlock(text)
self.setCurrentBlockState(0)
if not self.match_multiline(text, *TRI_SINGLE):
... | the_stack_v2_python_sparse | prettyqt/syntaxhighlighters/pythonhighlighter.py | phil65/PrettyQt | train | 17 |
1ac632160995bb15da92f686cbdd2d493f46e787 | [
"self._canceller = type(self)._canceller_function\nself.future = future\nself.check = check\nself.event = event\nself.target = target\nself._timeouter = Timeouter(self, timeout)\nevent.append(target, self)",
"try:\n result = self.check(*args)\nexcept BaseException as err:\n self.future.set_exception_if_pend... | <|body_start_0|>
self._canceller = type(self)._canceller_function
self.future = future
self.check = check
self.event = event
self.target = target
self._timeouter = Timeouter(self, timeout)
event.append(target, self)
<|end_body_0|>
<|body_start_1|>
try:
... | Waits for the given event and if the check returns `True` called with the received parameters, then passes them to it's waiter future. If check return anything else than `False`, then passes that as well to the future. Attributes ----------- _canceller : `None`, `function` The canceller function of the ``WaitAndContinu... | WaitAndContinue | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WaitAndContinue:
"""Waits for the given event and if the check returns `True` called with the received parameters, then passes them to it's waiter future. If check return anything else than `False`, then passes that as well to the future. Attributes ----------- _canceller : `None`, `function` The... | stack_v2_sparse_classes_36k_train_014983 | 8,320 | permissive | [
{
"docstring": "Creates a new ``WaitAndContinue`` with the given parameters. Parameters ---------- future : ``Future` The waiter future `what's result will be set when the check returns non `False` value. check : `callable` The check what is called with the received parameters whenever an event is received. tar... | 4 | null | Implement the Python class `WaitAndContinue` described below.
Class description:
Waits for the given event and if the check returns `True` called with the received parameters, then passes them to it's waiter future. If check return anything else than `False`, then passes that as well to the future. Attributes --------... | Implement the Python class `WaitAndContinue` described below.
Class description:
Waits for the given event and if the check returns `True` called with the received parameters, then passes them to it's waiter future. If check return anything else than `False`, then passes that as well to the future. Attributes --------... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class WaitAndContinue:
"""Waits for the given event and if the check returns `True` called with the received parameters, then passes them to it's waiter future. If check return anything else than `False`, then passes that as well to the future. Attributes ----------- _canceller : `None`, `function` The... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WaitAndContinue:
"""Waits for the given event and if the check returns `True` called with the received parameters, then passes them to it's waiter future. If check return anything else than `False`, then passes that as well to the future. Attributes ----------- _canceller : `None`, `function` The canceller fu... | the_stack_v2_python_sparse | hata/ext/command_utils/waiters.py | HuyaneMatsu/hata | train | 3 |
ba29255d800fcc456a99366c46265846b507eff6 | [
"if request.method in permissions.SAFE_METHODS:\n return True\nreturn request.user.is_staff",
"if request.method in permissions.SAFE_METHODS:\n return True\nreturn request.user.is_staff"
] | <|body_start_0|>
if request.method in permissions.SAFE_METHODS:
return True
return request.user.is_staff
<|end_body_0|>
<|body_start_1|>
if request.method in permissions.SAFE_METHODS:
return True
return request.user.is_staff
<|end_body_1|>
| IsAdminOrReadOnly | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsAdminOrReadOnly:
def has_permission(self, request, view):
"""Admin/Staff are allowed to Write. Others can only Read."""
<|body_0|>
def has_object_permission(self, request, view, obj):
"""Admin/Staff are allowed to Update/Delete. Others can only Retrieve."""
... | stack_v2_sparse_classes_36k_train_014984 | 677 | permissive | [
{
"docstring": "Admin/Staff are allowed to Write. Others can only Read.",
"name": "has_permission",
"signature": "def has_permission(self, request, view)"
},
{
"docstring": "Admin/Staff are allowed to Update/Delete. Others can only Retrieve.",
"name": "has_object_permission",
"signature"... | 2 | stack_v2_sparse_classes_30k_test_000352 | Implement the Python class `IsAdminOrReadOnly` described below.
Class description:
Implement the IsAdminOrReadOnly class.
Method signatures and docstrings:
- def has_permission(self, request, view): Admin/Staff are allowed to Write. Others can only Read.
- def has_object_permission(self, request, view, obj): Admin/St... | Implement the Python class `IsAdminOrReadOnly` described below.
Class description:
Implement the IsAdminOrReadOnly class.
Method signatures and docstrings:
- def has_permission(self, request, view): Admin/Staff are allowed to Write. Others can only Read.
- def has_object_permission(self, request, view, obj): Admin/St... | 755e4b4f10aa7b1918b260a5823900fb41bfff1b | <|skeleton|>
class IsAdminOrReadOnly:
def has_permission(self, request, view):
"""Admin/Staff are allowed to Write. Others can only Read."""
<|body_0|>
def has_object_permission(self, request, view, obj):
"""Admin/Staff are allowed to Update/Delete. Others can only Retrieve."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IsAdminOrReadOnly:
def has_permission(self, request, view):
"""Admin/Staff are allowed to Write. Others can only Read."""
if request.method in permissions.SAFE_METHODS:
return True
return request.user.is_staff
def has_object_permission(self, request, view, obj):
... | the_stack_v2_python_sparse | recipe_blog/categories/permissions.py | hossshakiba/recipe-blog-api | train | 3 | |
f04b963678034be216f3d1ca4e27e56e795926cb | [
"for track_data_sample in data_samples:\n video_data_samples = track_data_sample['video_data_samples']\n ori_video_len = video_data_samples[0].ori_video_length\n if ori_video_len == len(video_data_samples):\n self.process_video(video_data_samples)\n else:\n self.process_image(video_data_sa... | <|body_start_0|>
for track_data_sample in data_samples:
video_data_samples = track_data_sample['video_data_samples']
ori_video_len = video_data_samples[0].ori_video_length
if ori_video_len == len(video_data_samples):
self.process_video(video_data_samples)
... | Base class for a metric in video task. The metric first processes each batch of data_samples and predictions, and appends the processed results to the results list. Then it collects all results together from all ranks if distributed training is used. Finally, it computes the metrics of the entire dataset. A subclass of... | BaseVideoMetric | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseVideoMetric:
"""Base class for a metric in video task. The metric first processes each batch of data_samples and predictions, and appends the processed results to the results list. Then it collects all results together from all ranks if distributed training is used. Finally, it computes the m... | stack_v2_sparse_classes_36k_train_014985 | 6,513 | permissive | [
{
"docstring": "Process one batch of data samples and predictions. The processed results should be stored in ``self.results``, which will be used to compute the metrics when all batches have been processed. Args: data_batch (dict): A batch of data from the dataloader. data_samples (Sequence[dict]): A batch of d... | 2 | stack_v2_sparse_classes_30k_train_001817 | Implement the Python class `BaseVideoMetric` described below.
Class description:
Base class for a metric in video task. The metric first processes each batch of data_samples and predictions, and appends the processed results to the results list. Then it collects all results together from all ranks if distributed train... | Implement the Python class `BaseVideoMetric` described below.
Class description:
Base class for a metric in video task. The metric first processes each batch of data_samples and predictions, and appends the processed results to the results list. Then it collects all results together from all ranks if distributed train... | f78af7785ada87f1ced75a2313746e4ba3149760 | <|skeleton|>
class BaseVideoMetric:
"""Base class for a metric in video task. The metric first processes each batch of data_samples and predictions, and appends the processed results to the results list. Then it collects all results together from all ranks if distributed training is used. Finally, it computes the m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseVideoMetric:
"""Base class for a metric in video task. The metric first processes each batch of data_samples and predictions, and appends the processed results to the results list. Then it collects all results together from all ranks if distributed training is used. Finally, it computes the metrics of the... | the_stack_v2_python_sparse | mmdet/evaluation/metrics/base_video_metric.py | wencheng256/mmdetection | train | 0 |
10f707af482e820a63be44a512f78fb29db16c4c | [
"super().__init__()\nself.channels = channels\nself.size = presize\nself.buffer = self.generate(presize)",
"if size <= self.size:\n return self.buffer[:size]\nself.buffer = self.generate(size)\nreturn self.buffer",
"pos = tf.range(size)\ni = tf.range(0, self.channels, 2)\ndenom = tf.exp(-np.log(10000) * tf.c... | <|body_start_0|>
super().__init__()
self.channels = channels
self.size = presize
self.buffer = self.generate(presize)
<|end_body_0|>
<|body_start_1|>
if size <= self.size:
return self.buffer[:size]
self.buffer = self.generate(size)
return self.buffer
... | Sinusoidal positional encoding generator. | PositionalEncodings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncodings:
"""Sinusoidal positional encoding generator."""
def __init__(self, channels: int, presize: int=128):
"""Initializer. Args: channels: size of the channels. presize: initial pe cache size."""
<|body_0|>
def call(self, size: int) -> tf.Tensor:
"... | stack_v2_sparse_classes_36k_train_014986 | 1,682 | permissive | [
{
"docstring": "Initializer. Args: channels: size of the channels. presize: initial pe cache size.",
"name": "__init__",
"signature": "def __init__(self, channels: int, presize: int=128)"
},
{
"docstring": "Return cached positional encodings. Args: size: length of the pe. Returns: [tf.float32; [... | 3 | stack_v2_sparse_classes_30k_train_019726 | Implement the Python class `PositionalEncodings` described below.
Class description:
Sinusoidal positional encoding generator.
Method signatures and docstrings:
- def __init__(self, channels: int, presize: int=128): Initializer. Args: channels: size of the channels. presize: initial pe cache size.
- def call(self, si... | Implement the Python class `PositionalEncodings` described below.
Class description:
Sinusoidal positional encoding generator.
Method signatures and docstrings:
- def __init__(self, channels: int, presize: int=128): Initializer. Args: channels: size of the channels. presize: initial pe cache size.
- def call(self, si... | c9df591d339eb998daf4f1e5a922a61309b6363d | <|skeleton|>
class PositionalEncodings:
"""Sinusoidal positional encoding generator."""
def __init__(self, channels: int, presize: int=128):
"""Initializer. Args: channels: size of the channels. presize: initial pe cache size."""
<|body_0|>
def call(self, size: int) -> tf.Tensor:
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PositionalEncodings:
"""Sinusoidal positional encoding generator."""
def __init__(self, channels: int, presize: int=128):
"""Initializer. Args: channels: size of the channels. presize: initial pe cache size."""
super().__init__()
self.channels = channels
self.size = presiz... | the_stack_v2_python_sparse | glowtts/transformer/pe.py | ishine/tf-glow-tts | train | 0 |
367c6b7691400f21c9726c2d449c3be198ba40a4 | [
"params = request.body\njsonParams = json.loads(params)\nuser = User_Info.objects.filter(email__exact=jsonParams.get('email'))\nif user.exists():\n return JsonResponse({'status': False, 'err': '邮箱已经被注册'}, status=401)\nuser = User_Info.objects.filter(nickname__exact=jsonParams.get('nickname'))\nif user.exists():\... | <|body_start_0|>
params = request.body
jsonParams = json.loads(params)
user = User_Info.objects.filter(email__exact=jsonParams.get('email'))
if user.exists():
return JsonResponse({'status': False, 'err': '邮箱已经被注册'}, status=401)
user = User_Info.objects.filter(nickname... | RegisterView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterView:
def post(self, request):
"""注册账户"""
<|body_0|>
def randomID(self):
"""生成随机不重复的id :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
params = request.body
jsonParams = json.loads(params)
user = User_Info.objects.fi... | stack_v2_sparse_classes_36k_train_014987 | 2,017 | no_license | [
{
"docstring": "注册账户",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "生成随机不重复的id :return:",
"name": "randomID",
"signature": "def randomID(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002412 | Implement the Python class `RegisterView` described below.
Class description:
Implement the RegisterView class.
Method signatures and docstrings:
- def post(self, request): 注册账户
- def randomID(self): 生成随机不重复的id :return: | Implement the Python class `RegisterView` described below.
Class description:
Implement the RegisterView class.
Method signatures and docstrings:
- def post(self, request): 注册账户
- def randomID(self): 生成随机不重复的id :return:
<|skeleton|>
class RegisterView:
def post(self, request):
"""注册账户"""
<|body_... | 526dea540048fc92260bce611c520c50af744e0b | <|skeleton|>
class RegisterView:
def post(self, request):
"""注册账户"""
<|body_0|>
def randomID(self):
"""生成随机不重复的id :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterView:
def post(self, request):
"""注册账户"""
params = request.body
jsonParams = json.loads(params)
user = User_Info.objects.filter(email__exact=jsonParams.get('email'))
if user.exists():
return JsonResponse({'status': False, 'err': '邮箱已经被注册'}, status=40... | the_stack_v2_python_sparse | apps/account/views/bashInfo/register.py | DICKQI/ALGYunXS | train | 0 | |
60f460d3550fe6c7fb2b6ede0d4ada8e8bb210db | [
"IO_files = {}\nfile_names = set()\nfor fl in in_dir.files:\n if self.name not in fl.users:\n if utils.splitext(fl.name)[-1] in self.input_types:\n IO_files['-!i'] = os.path.join(in_dir.path, fl.name)\n command_ids = [utils.infer_path_id(IO_files['-!i'])]\n in_dir.use_file... | <|body_start_0|>
IO_files = {}
file_names = set()
for fl in in_dir.files:
if self.name not in fl.users:
if utils.splitext(fl.name)[-1] in self.input_types:
IO_files['-!i'] = os.path.join(in_dir.path, fl.name)
command_ids = [util... | Class for indexing .vcf files with bgzip & tabix. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name of the function. input_type: Inp... | bgzip | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class bgzip:
"""Class for indexing .vcf files with bgzip & tabix. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name... | stack_v2_sparse_classes_36k_train_014988 | 10,695 | permissive | [
{
"docstring": "Infers the input and output file paths. This method must keep the directory objects up to date of the file edits! Parameters: in_cmd: A dict containing the command line. in_dir: Input directory (instance of filetypes.Directory). out_dir: Output directory (instance of filetypes.Directory). Return... | 2 | stack_v2_sparse_classes_30k_train_001247 | Implement the Python class `bgzip` described below.
Class description:
Class for indexing .vcf files with bgzip & tabix. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date a... | Implement the Python class `bgzip` described below.
Class description:
Class for indexing .vcf files with bgzip & tabix. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date a... | fd83eee4be0bb78c67a111fd1c1c1dff4c16aefe | <|skeleton|>
class bgzip:
"""Class for indexing .vcf files with bgzip & tabix. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class bgzip:
"""Class for indexing .vcf files with bgzip & tabix. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name of the funct... | the_stack_v2_python_sparse | modules/tabix.py | tyrmi/STAPLER | train | 4 |
4717a6a43f8f3ca38a38e78a6f7ce3fa1a603939 | [
"session_id = super().create_session(user_id=user_id)\nif session_id:\n user_session = UserSession(user_id=user_id, session_id=session_id)\n user_session.save()\n return session_id",
"if session_id:\n UserSession.load_from_file()\n user_session_list = UserSession.search({'session_id': session_id})\... | <|body_start_0|>
session_id = super().create_session(user_id=user_id)
if session_id:
user_session = UserSession(user_id=user_id, session_id=session_id)
user_session.save()
return session_id
<|end_body_0|>
<|body_start_1|>
if session_id:
UserSessio... | session authentication that's being save in a database | SessionDBAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionDBAuth:
"""session authentication that's being save in a database"""
def create_session(self, user_id=None):
"""overloads parents create_session. Creates a UserSession Object and saves it in the database :param user_id: :return:"""
<|body_0|>
def user_id_for_sessi... | stack_v2_sparse_classes_36k_train_014989 | 2,476 | no_license | [
{
"docstring": "overloads parents create_session. Creates a UserSession Object and saves it in the database :param user_id: :return:",
"name": "create_session",
"signature": "def create_session(self, user_id=None)"
},
{
"docstring": "overloads from parent. looks for user_id in the database and r... | 3 | stack_v2_sparse_classes_30k_train_006963 | Implement the Python class `SessionDBAuth` described below.
Class description:
session authentication that's being save in a database
Method signatures and docstrings:
- def create_session(self, user_id=None): overloads parents create_session. Creates a UserSession Object and saves it in the database :param user_id: ... | Implement the Python class `SessionDBAuth` described below.
Class description:
session authentication that's being save in a database
Method signatures and docstrings:
- def create_session(self, user_id=None): overloads parents create_session. Creates a UserSession Object and saves it in the database :param user_id: ... | f6728ac558d8bce58701d47fe7ec2258524b6803 | <|skeleton|>
class SessionDBAuth:
"""session authentication that's being save in a database"""
def create_session(self, user_id=None):
"""overloads parents create_session. Creates a UserSession Object and saves it in the database :param user_id: :return:"""
<|body_0|>
def user_id_for_sessi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionDBAuth:
"""session authentication that's being save in a database"""
def create_session(self, user_id=None):
"""overloads parents create_session. Creates a UserSession Object and saves it in the database :param user_id: :return:"""
session_id = super().create_session(user_id=user_i... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_db_auth.py | jhonatang1988/holbertonschool-web_back_end | train | 0 |
b859e66503c61efd0f8e98519c9b0474425c6400 | [
"self.cbb = DpFile(cbb_file)\nself.wbb = DpFile(wbb_file)\nself.sam = DpFile(sam_file)\nself.plate = plate\nself.model = self.sam.model\nif not dwr_file == None:\n self.dwr = DpFile(dwr_file)\nelse:\n self.dwr = None\nself._calibrate_measurement()",
"cold_blackbody = bb_radiance(self.cbb.header.cbb_temperat... | <|body_start_0|>
self.cbb = DpFile(cbb_file)
self.wbb = DpFile(wbb_file)
self.sam = DpFile(sam_file)
self.plate = plate
self.model = self.sam.model
if not dwr_file == None:
self.dwr = DpFile(dwr_file)
else:
self.dwr = None
self._cal... | A class that holds the information relavent to a complete measurement taken with a D&P Instruments Model 103F MicroFT or Model 202 TurboFT. Attributes: cbb - A DpFile instance holding the cold blackbody information. wbb - A DpFile instance holding the warm blackbody information. sam - A DpFile instance holding the samp... | DpMeasurement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DpMeasurement:
"""A class that holds the information relavent to a complete measurement taken with a D&P Instruments Model 103F MicroFT or Model 202 TurboFT. Attributes: cbb - A DpFile instance holding the cold blackbody information. wbb - A DpFile instance holding the warm blackbody information.... | stack_v2_sparse_classes_36k_train_014990 | 4,023 | no_license | [
{
"docstring": "DpMeasurement instance constructor. Arguments: cbb_file - The cold blackbody filename. wbb_file - The warm blackbody filename. sam_file - The sample filename. dwr_file - The downwelling filename. plate - The plate emissivity.",
"name": "__init__",
"signature": "def __init__(self, cbb_fil... | 3 | stack_v2_sparse_classes_30k_train_017850 | Implement the Python class `DpMeasurement` described below.
Class description:
A class that holds the information relavent to a complete measurement taken with a D&P Instruments Model 103F MicroFT or Model 202 TurboFT. Attributes: cbb - A DpFile instance holding the cold blackbody information. wbb - A DpFile instance ... | Implement the Python class `DpMeasurement` described below.
Class description:
A class that holds the information relavent to a complete measurement taken with a D&P Instruments Model 103F MicroFT or Model 202 TurboFT. Attributes: cbb - A DpFile instance holding the cold blackbody information. wbb - A DpFile instance ... | 743167940f700374755ea273b90da66befae1ba4 | <|skeleton|>
class DpMeasurement:
"""A class that holds the information relavent to a complete measurement taken with a D&P Instruments Model 103F MicroFT or Model 202 TurboFT. Attributes: cbb - A DpFile instance holding the cold blackbody information. wbb - A DpFile instance holding the warm blackbody information.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DpMeasurement:
"""A class that holds the information relavent to a complete measurement taken with a D&P Instruments Model 103F MicroFT or Model 202 TurboFT. Attributes: cbb - A DpFile instance holding the cold blackbody information. wbb - A DpFile instance holding the warm blackbody information. sam - A DpFi... | the_stack_v2_python_sparse | tes/models/dp_models/dp_measurement.py | max19951001/TES | train | 0 |
440fa2c0cfcf6e5b4875dc700c31c61af8210bf7 | [
"context = super(LogInFormView, self).get_context_data(**kwargs)\ncontext['title'] = 'Login'\nreturn context",
"username = form.cleaned_data['username']\npassword = form.cleaned_data['password']\ncontext = self.get_context_data()\nuser = authenticate(self.request, username=username, password=password)\nif user is... | <|body_start_0|>
context = super(LogInFormView, self).get_context_data(**kwargs)
context['title'] = 'Login'
return context
<|end_body_0|>
<|body_start_1|>
username = form.cleaned_data['username']
password = form.cleaned_data['password']
context = self.get_context_data()
... | A class of FormView to logged in the user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_valid(form): Logged in the user | LogInFormView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogInFormView:
"""A class of FormView to logged in the user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_valid(... | stack_v2_sparse_classes_36k_train_014991 | 9,386 | no_license | [
{
"docstring": "Call the original method of the view and add the title on the context Parameters ---------- kwargs : str Some argument that Django are passing, need when call the original method of the view Returns ------- dict a dict of the context of the page",
"name": "get_context_data",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_010462 | Implement the Python class `LogInFormView` described below.
Class description:
A class of FormView to logged in the user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): ... | Implement the Python class `LogInFormView` described below.
Class description:
A class of FormView to logged in the user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): ... | 939245d046974fabf33fa540b4c3b6d077100ff5 | <|skeleton|>
class LogInFormView:
"""A class of FormView to logged in the user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_valid(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogInFormView:
"""A class of FormView to logged in the user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_valid(form): Logged... | the_stack_v2_python_sparse | purebeurre/views/user.py | M0l42/P08_PureBeurre | train | 1 |
2d67e3ceb5cae9c1f58d9d1fd330756782fc519f | [
"Frame.__init__(self, master)\nself.pack()\nself.createArtistWidgets()",
"Artist_Frame = Frame(self)\nGenre_Frame = Frame(self)\nself.labelInputArtist = Label(Artist_Frame, text='Artist Name')\nself.labelInputGenre = Label(Genre_Frame, text='Artist Genre')\nself.text_in_Artist = Entry(Artist_Frame)\nself.text_in_... | <|body_start_0|>
Frame.__init__(self, master)
self.pack()
self.createArtistWidgets()
<|end_body_0|>
<|body_start_1|>
Artist_Frame = Frame(self)
Genre_Frame = Frame(self)
self.labelInputArtist = Label(Artist_Frame, text='Artist Name')
self.labelInputGenre = Label(... | Application main window class. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createArtistWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_36k_train_014992 | 2,375 | no_license | [
{
"docstring": "Main frame initialization (mostly delegated)",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Add all the widgets to the main frame.",
"name": "createArtistWidgets",
"signature": "def createArtistWidgets(self)"
},
{
"docstrin... | 3 | null | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createArtistWidgets(self): Add all the widgets to the main frame.
- def handle(self): Hand... | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createArtistWidgets(self): Add all the widgets to the main frame.
- def handle(self): Hand... | 2dba11861f91e4bdc1ef28279132a6d8dd4ccf54 | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createArtistWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
Frame.__init__(self, master)
self.pack()
self.createArtistWidgets()
def createArtistWidgets(self):
"""Add all the widgets to t... | the_stack_v2_python_sparse | Mux_Gui/Add_Artist_Gui.py | rduvalwa5/Mux | train | 0 |
dee29fa7db02c6dce5694df7a2e2ae9ea9e8f6dd | [
"self.state_list = state_list\nself.state = self.state_list[state - 1]\nself.mod_type = mod_type",
"S1_codewords = self._get_3b4b_S1_codewords()\nS2_codewords = self._get_3b4b_S2_codewords()\nif x is not None:\n if self.state.name == 'S1':\n return S1_codewords[x]\n elif self.state.name == 'S2':\n ... | <|body_start_0|>
self.state_list = state_list
self.state = self.state_list[state - 1]
self.mod_type = mod_type
<|end_body_0|>
<|body_start_1|>
S1_codewords = self._get_3b4b_S1_codewords()
S2_codewords = self._get_3b4b_S2_codewords()
if x is not None:
if self.... | EncoderFsmClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderFsmClass:
def __init__(self, state_list, state, mod_type):
"""Encoder state machine for reverse link modulation Args: state_list: A list of BasicStateClass objects state: List index for start state"""
<|body_0|>
def get_output_symbol(self, x=None):
"""Return t... | stack_v2_sparse_classes_36k_train_014993 | 36,290 | no_license | [
{
"docstring": "Encoder state machine for reverse link modulation Args: state_list: A list of BasicStateClass objects state: List index for start state",
"name": "__init__",
"signature": "def __init__(self, state_list, state, mod_type)"
},
{
"docstring": "Return the symbol, sampled at 2 smpls/sy... | 5 | stack_v2_sparse_classes_30k_train_013971 | Implement the Python class `EncoderFsmClass` described below.
Class description:
Implement the EncoderFsmClass class.
Method signatures and docstrings:
- def __init__(self, state_list, state, mod_type): Encoder state machine for reverse link modulation Args: state_list: A list of BasicStateClass objects state: List i... | Implement the Python class `EncoderFsmClass` described below.
Class description:
Implement the EncoderFsmClass class.
Method signatures and docstrings:
- def __init__(self, state_list, state, mod_type): Encoder state machine for reverse link modulation Args: state_list: A list of BasicStateClass objects state: List i... | cc7ea7eae78bcc3709117ede81f89ed23d756e26 | <|skeleton|>
class EncoderFsmClass:
def __init__(self, state_list, state, mod_type):
"""Encoder state machine for reverse link modulation Args: state_list: A list of BasicStateClass objects state: List index for start state"""
<|body_0|>
def get_output_symbol(self, x=None):
"""Return t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderFsmClass:
def __init__(self, state_list, state, mod_type):
"""Encoder state machine for reverse link modulation Args: state_list: A list of BasicStateClass objects state: List index for start state"""
self.state_list = state_list
self.state = self.state_list[state - 1]
s... | the_stack_v2_python_sparse | systems_r700/model/src/tag/tag_waveforms.py | NopMicrowave/Impinj_R700_Indy_Reader_Chip_and_Speedway_Reader_Simulation | train | 0 | |
3b52212878ff18675a653607ff83a84ffad6da1d | [
"import queue\nq = queue.Queue()\nq.put(root)\nans = []\nwhile q.qsize():\n n = q.qsize()\n for _ in range(n):\n node: TreeNode = q.get()\n if node is None:\n ans.append('null')\n else:\n ans.append(str(node.val))\n q.put(node.left)\n q.put(node... | <|body_start_0|>
import queue
q = queue.Queue()
q.put(root)
ans = []
while q.qsize():
n = q.qsize()
for _ in range(n):
node: TreeNode = q.get()
if node is None:
ans.append('null')
else:
... | 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, s):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_014994 | 3,230 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, s): Decodes your encoded data to tree. :type data: str :rtype: Tr... | 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, s): Decodes your encoded data to tree. :type data: str :rtype: Tr... | 5ce829760205674965eae81b191a364022b80ae2 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, s):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
import queue
q = queue.Queue()
q.put(root)
ans = []
while q.qsize():
n = q.qsize()
for _ in range(n):
node: TreeNo... | the_stack_v2_python_sparse | src/297.二叉树的序列化与反序列化.py | gwy15/leetcode | train | 3 | |
a890a710795911300e8995c27eb5de813b0d9a44 | [
"super().__init__(ad, name, logging, args, config, app_config, global_vars)\nself.period = 30\nself.timer_handle = None\nself.heart_beat = 0\nself.my_mqtt = None",
"self.heart_beat = 0\nself.my_mqtt = self.get_plugin_api('MQTT')\nif 'period' in self.args:\n self.period = self.args['period']\nelse:\n self.pe... | <|body_start_0|>
super().__init__(ad, name, logging, args, config, app_config, global_vars)
self.period = 30
self.timer_handle = None
self.heart_beat = 0
self.my_mqtt = None
<|end_body_0|>
<|body_start_1|>
self.heart_beat = 0
self.my_mqtt = self.get_plugin_api('M... | HeartBeat Class / APP | HeartBeat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeartBeat:
"""HeartBeat Class / APP"""
def __init__(self, ad: AppDaemon, name, logging, args, config, app_config, global_vars):
"""Class constructor"""
<|body_0|>
def initialize(self):
"""Initialization function of the appdeamon app"""
<|body_1|>
def... | stack_v2_sparse_classes_36k_train_014995 | 3,836 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, ad: AppDaemon, name, logging, args, config, app_config, global_vars)"
},
{
"docstring": "Initialization function of the appdeamon app",
"name": "initialize",
"signature": "def initialize(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_015961 | Implement the Python class `HeartBeat` described below.
Class description:
HeartBeat Class / APP
Method signatures and docstrings:
- def __init__(self, ad: AppDaemon, name, logging, args, config, app_config, global_vars): Class constructor
- def initialize(self): Initialization function of the appdeamon app
- def hea... | Implement the Python class `HeartBeat` described below.
Class description:
HeartBeat Class / APP
Method signatures and docstrings:
- def __init__(self, ad: AppDaemon, name, logging, args, config, app_config, global_vars): Class constructor
- def initialize(self): Initialization function of the appdeamon app
- def hea... | aaa9c1f854abeb76a7e9f12bbfc724d77f226940 | <|skeleton|>
class HeartBeat:
"""HeartBeat Class / APP"""
def __init__(self, ad: AppDaemon, name, logging, args, config, app_config, global_vars):
"""Class constructor"""
<|body_0|>
def initialize(self):
"""Initialization function of the appdeamon app"""
<|body_1|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeartBeat:
"""HeartBeat Class / APP"""
def __init__(self, ad: AppDaemon, name, logging, args, config, app_config, global_vars):
"""Class constructor"""
super().__init__(ad, name, logging, args, config, app_config, global_vars)
self.period = 30
self.timer_handle = None
... | the_stack_v2_python_sparse | src/appdaemon/apps/heart_beat.py | winkste/ha_config | train | 0 |
7ec5cd52046185fbfd59427550b45b1e4b4e78a2 | [
"if not isinstance(label_key, (int, str)):\n raise TypeError('label_key must be int or str, but is %s' % type(label_key))\nsuper(ClassifierWithState, self).__init__()\nself.lossfun = lossfun\nself.y = None\nself.loss = None\nself.label_key = label_key\nself.predictor = predictor",
"if isinstance(self.label_key... | <|body_start_0|>
if not isinstance(label_key, (int, str)):
raise TypeError('label_key must be int or str, but is %s' % type(label_key))
super(ClassifierWithState, self).__init__()
self.lossfun = lossfun
self.y = None
self.loss = None
self.label_key = label_key... | A wrapper for pytorch RNNLM. | ClassifierWithState | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassifierWithState:
"""A wrapper for pytorch RNNLM."""
def __init__(self, predictor, lossfun=nn.CrossEntropyLoss(reduction='none'), label_key=-1):
"""Initialize class. :param torch.nn.Module predictor : The RNNLM :param function lossfun : The loss function to use :param int/str labe... | stack_v2_sparse_classes_36k_train_014996 | 14,561 | permissive | [
{
"docstring": "Initialize class. :param torch.nn.Module predictor : The RNNLM :param function lossfun : The loss function to use :param int/str label_key :",
"name": "__init__",
"signature": "def __init__(self, predictor, lossfun=nn.CrossEntropyLoss(reduction='none'), label_key=-1)"
},
{
"docst... | 5 | null | Implement the Python class `ClassifierWithState` described below.
Class description:
A wrapper for pytorch RNNLM.
Method signatures and docstrings:
- def __init__(self, predictor, lossfun=nn.CrossEntropyLoss(reduction='none'), label_key=-1): Initialize class. :param torch.nn.Module predictor : The RNNLM :param functi... | Implement the Python class `ClassifierWithState` described below.
Class description:
A wrapper for pytorch RNNLM.
Method signatures and docstrings:
- def __init__(self, predictor, lossfun=nn.CrossEntropyLoss(reduction='none'), label_key=-1): Initialize class. :param torch.nn.Module predictor : The RNNLM :param functi... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class ClassifierWithState:
"""A wrapper for pytorch RNNLM."""
def __init__(self, predictor, lossfun=nn.CrossEntropyLoss(reduction='none'), label_key=-1):
"""Initialize class. :param torch.nn.Module predictor : The RNNLM :param function lossfun : The loss function to use :param int/str labe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassifierWithState:
"""A wrapper for pytorch RNNLM."""
def __init__(self, predictor, lossfun=nn.CrossEntropyLoss(reduction='none'), label_key=-1):
"""Initialize class. :param torch.nn.Module predictor : The RNNLM :param function lossfun : The loss function to use :param int/str label_key :"""
... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/lm/default.py | espnet/espnet | train | 7,242 |
18eceee99817d73e366bad4af4c594a24d725dfb | [
"self.width = width\nself.heigth = heigth\nself.button = pygame.Surface((self.width, self.heigth))\nself.pos = self.button.get_rect(center=pos)\nself.color_unclicked = color_unclicked\nself.color_click = color_click\nself.on_button = False\nself.fontsize = fontsize\nself.betutip = pygame.font.Font(None, self.fontsi... | <|body_start_0|>
self.width = width
self.heigth = heigth
self.button = pygame.Surface((self.width, self.heigth))
self.pos = self.button.get_rect(center=pos)
self.color_unclicked = color_unclicked
self.color_click = color_click
self.on_button = False
self.f... | Az éppen aktuális menüablakon található gombok attribútumait tartalmazó osztály. Használja a Window() és a Mouse() osztályok egy-egy példányát is. | Button | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Button:
"""Az éppen aktuális menüablakon található gombok attribútumait tartalmazó osztály. Használja a Window() és a Mouse() osztályok egy-egy példányát is."""
def __init__(self, window, mouse, width=100, heigth=50, pos=(312.5, 337.5), color_unclicked=(255, 0, 0), color_click=(0, 255, 0), t... | stack_v2_sparse_classes_36k_train_014997 | 9,743 | no_license | [
{
"docstring": "A Button() osztály konstruktor függvénye. Attribútuma a gomb szélessége és hossza, a gomb felülete amin majd a gomb megjelenik a képernyőn, a pozíciója, a gomb színét amikor nincs rajta illetve mikor rajta van a kurzor. A gomb feliratának betűtipusát, annak szövegét és a szöveg pozícióját (ami m... | 3 | stack_v2_sparse_classes_30k_train_011768 | Implement the Python class `Button` described below.
Class description:
Az éppen aktuális menüablakon található gombok attribútumait tartalmazó osztály. Használja a Window() és a Mouse() osztályok egy-egy példányát is.
Method signatures and docstrings:
- def __init__(self, window, mouse, width=100, heigth=50, pos=(31... | Implement the Python class `Button` described below.
Class description:
Az éppen aktuális menüablakon található gombok attribútumait tartalmazó osztály. Használja a Window() és a Mouse() osztályok egy-egy példányát is.
Method signatures and docstrings:
- def __init__(self, window, mouse, width=100, heigth=50, pos=(31... | 1c1501be032c1b5a1aee3f3e6fe5363eaab3abdc | <|skeleton|>
class Button:
"""Az éppen aktuális menüablakon található gombok attribútumait tartalmazó osztály. Használja a Window() és a Mouse() osztályok egy-egy példányát is."""
def __init__(self, window, mouse, width=100, heigth=50, pos=(312.5, 337.5), color_unclicked=(255, 0, 0), color_click=(0, 255, 0), t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Button:
"""Az éppen aktuális menüablakon található gombok attribútumait tartalmazó osztály. Használja a Window() és a Mouse() osztályok egy-egy példányát is."""
def __init__(self, window, mouse, width=100, heigth=50, pos=(312.5, 337.5), color_unclicked=(255, 0, 0), color_click=(0, 255, 0), text='Start', ... | the_stack_v2_python_sparse | menu_functions.py | tothpeti96/Snake | train | 0 |
49d9eba4735e50bfd3f353f548e0f99e64bb7e5a | [
"if not start_bracket or not end_bracket:\n raise ValueError('Attempted to construct Bracketed segment without specifying brackets.')\nself.start_bracket = start_bracket\nself.end_bracket = end_bracket\nsuper().__init__(segments=segments, pos_marker=pos_marker, uuid=uuid)",
"start_brackets = [start_bracket for... | <|body_start_0|>
if not start_bracket or not end_bracket:
raise ValueError('Attempted to construct Bracketed segment without specifying brackets.')
self.start_bracket = start_bracket
self.end_bracket = end_bracket
super().__init__(segments=segments, pos_marker=pos_marker, uui... | A segment containing a bracketed expression. | BracketedSegment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BracketedSegment:
"""A segment containing a bracketed expression."""
def __init__(self, segments: Tuple['BaseSegment', ...], start_bracket: Tuple[BaseSegment], end_bracket: Tuple[BaseSegment], pos_marker: Optional[PositionMarker]=None, uuid: Optional[UUID]=None):
"""Stash the bracket... | stack_v2_sparse_classes_36k_train_014998 | 2,905 | permissive | [
{
"docstring": "Stash the bracket segments for later.",
"name": "__init__",
"signature": "def __init__(self, segments: Tuple['BaseSegment', ...], start_bracket: Tuple[BaseSegment], end_bracket: Tuple[BaseSegment], pos_marker: Optional[PositionMarker]=None, uuid: Optional[UUID]=None)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_002210 | Implement the Python class `BracketedSegment` described below.
Class description:
A segment containing a bracketed expression.
Method signatures and docstrings:
- def __init__(self, segments: Tuple['BaseSegment', ...], start_bracket: Tuple[BaseSegment], end_bracket: Tuple[BaseSegment], pos_marker: Optional[PositionMa... | Implement the Python class `BracketedSegment` described below.
Class description:
A segment containing a bracketed expression.
Method signatures and docstrings:
- def __init__(self, segments: Tuple['BaseSegment', ...], start_bracket: Tuple[BaseSegment], end_bracket: Tuple[BaseSegment], pos_marker: Optional[PositionMa... | a66da908907ee1eaf09d88a731025da29e7fca07 | <|skeleton|>
class BracketedSegment:
"""A segment containing a bracketed expression."""
def __init__(self, segments: Tuple['BaseSegment', ...], start_bracket: Tuple[BaseSegment], end_bracket: Tuple[BaseSegment], pos_marker: Optional[PositionMarker]=None, uuid: Optional[UUID]=None):
"""Stash the bracket... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BracketedSegment:
"""A segment containing a bracketed expression."""
def __init__(self, segments: Tuple['BaseSegment', ...], start_bracket: Tuple[BaseSegment], end_bracket: Tuple[BaseSegment], pos_marker: Optional[PositionMarker]=None, uuid: Optional[UUID]=None):
"""Stash the bracket segments for... | the_stack_v2_python_sparse | src/sqlfluff/core/parser/segments/bracketed.py | sqlfluff/sqlfluff | train | 5,931 |
892cbc07a1524f47caaf9eddeb1e1485bb79c915 | [
"data = form.cleaned_data\nself.success_url = reverse('compile_results', kwargs={'level': int(data['level']), 'semester': int(data['semester'])})\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['title_text'] = 'Choose Results To Compile'\ncontext['detail_text'] = 'Please ... | <|body_start_0|>
data = form.cleaned_data
self.success_url = reverse('compile_results', kwargs={'level': int(data['level']), 'semester': int(data['semester'])})
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context['... | View for choosing which semester result to compile. Check that the user has necessary permissions (Lecturer) and that account is still active. Redirects to compile_results view on form valid. | CompileResultView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompileResultView:
"""View for choosing which semester result to compile. Check that the user has necessary permissions (Lecturer) and that account is still active. Redirects to compile_results view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call sup... | stack_v2_sparse_classes_36k_train_014999 | 29,759 | no_license | [
{
"docstring": "Compute the success URL and call super.form_valid()",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Return the data used in the templates rendering.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
... | 2 | stack_v2_sparse_classes_30k_train_007309 | Implement the Python class `CompileResultView` described below.
Class description:
View for choosing which semester result to compile. Check that the user has necessary permissions (Lecturer) and that account is still active. Redirects to compile_results view on form valid.
Method signatures and docstrings:
- def for... | Implement the Python class `CompileResultView` described below.
Class description:
View for choosing which semester result to compile. Check that the user has necessary permissions (Lecturer) and that account is still active. Redirects to compile_results view on form valid.
Method signatures and docstrings:
- def for... | 06bc577d01d3dbf6c425e03dcb903977a38e377c | <|skeleton|>
class CompileResultView:
"""View for choosing which semester result to compile. Check that the user has necessary permissions (Lecturer) and that account is still active. Redirects to compile_results view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call sup... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompileResultView:
"""View for choosing which semester result to compile. Check that the user has necessary permissions (Lecturer) and that account is still active. Redirects to compile_results view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid... | the_stack_v2_python_sparse | cbt/views.py | Festusali/CBTest | train | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.