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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
447a5ffcda44bfc1c757ac8da2f22c0d3253cb1d | [
"if model._meta.app_label in settings.DATABASE_APPS_MAPPING:\n return settings.DATABASE_APPS_MAPPING[model._meta.app_label]\nreturn None",
"if model._meta.app_label in settings.DATABASE_APPS_MAPPING:\n return settings.DATABASE_APPS_MAPPING[model._meta.app_label]\nreturn None",
"db1 = settings.DATABASE_APP... | <|body_start_0|>
if model._meta.app_label in settings.DATABASE_APPS_MAPPING:
return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label in settings.DATABASE_APPS_MAPPING:
return settings.DATABASE_APPS... | A router to control all database operations on models in the supplier application. | SupplierMgrRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupplierMgrRouter:
"""A router to control all database operations on models in the supplier application."""
def db_for_read(self, model, **hints):
"""Attempts to read supplier_mgr models go to supplier_mgr."""
<|body_0|>
def db_for_write(self, model, **hints):
""... | stack_v2_sparse_classes_36k_train_023600 | 2,162 | no_license | [
{
"docstring": "Attempts to read supplier_mgr models go to supplier_mgr.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write supplier_mgr models go to supplier_mgr.",
"name": "db_for_write",
"signature": "def db_for_write(sel... | 4 | stack_v2_sparse_classes_30k_test_000103 | Implement the Python class `SupplierMgrRouter` described below.
Class description:
A router to control all database operations on models in the supplier application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read supplier_mgr models go to supplier_mgr.
- def db_for_write(s... | Implement the Python class `SupplierMgrRouter` described below.
Class description:
A router to control all database operations on models in the supplier application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read supplier_mgr models go to supplier_mgr.
- def db_for_write(s... | b57173d445b4ecce282a7035e8ffdd42e5d79959 | <|skeleton|>
class SupplierMgrRouter:
"""A router to control all database operations on models in the supplier application."""
def db_for_read(self, model, **hints):
"""Attempts to read supplier_mgr models go to supplier_mgr."""
<|body_0|>
def db_for_write(self, model, **hints):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SupplierMgrRouter:
"""A router to control all database operations on models in the supplier application."""
def db_for_read(self, model, **hints):
"""Attempts to read supplier_mgr models go to supplier_mgr."""
if model._meta.app_label in settings.DATABASE_APPS_MAPPING:
return ... | the_stack_v2_python_sparse | apps/db_router.py | cpf1993/assist_test | train | 1 |
a42227a53e0dfb62b537e0755bb28a18c9a0cf09 | [
"self.name = name\nself.class_name = class_name\nself.model_name = model_name\nself.direct_import: List[str] = []\nself.typing_import: List[str] = []\nself.model_import: List[str] = []\nself.type = self.parse_type(class_name)",
"if class_name.startswith('list['):\n self.typing_import.append('List')\n sub_cl... | <|body_start_0|>
self.name = name
self.class_name = class_name
self.model_name = model_name
self.direct_import: List[str] = []
self.typing_import: List[str] = []
self.model_import: List[str] = []
self.type = self.parse_type(class_name)
<|end_body_0|>
<|body_start... | Represents parsed state of kubernetes client model attribute. | Attribute | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attribute:
"""Represents parsed state of kubernetes client model attribute."""
def __init__(self, name: str, class_name: str, model_name: str) -> None:
"""Parse attribute parameters."""
<|body_0|>
def parse_type(self, class_name: str) -> str:
"""Get attribute typ... | stack_v2_sparse_classes_36k_train_023601 | 6,267 | permissive | [
{
"docstring": "Parse attribute parameters.",
"name": "__init__",
"signature": "def __init__(self, name: str, class_name: str, model_name: str) -> None"
},
{
"docstring": "Get attribute type from its class name.",
"name": "parse_type",
"signature": "def parse_type(self, class_name: str) ... | 2 | null | Implement the Python class `Attribute` described below.
Class description:
Represents parsed state of kubernetes client model attribute.
Method signatures and docstrings:
- def __init__(self, name: str, class_name: str, model_name: str) -> None: Parse attribute parameters.
- def parse_type(self, class_name: str) -> s... | Implement the Python class `Attribute` described below.
Class description:
Represents parsed state of kubernetes client model attribute.
Method signatures and docstrings:
- def __init__(self, name: str, class_name: str, model_name: str) -> None: Parse attribute parameters.
- def parse_type(self, class_name: str) -> s... | 82995b008daf551a4fe11660018d9c08c69f9e6e | <|skeleton|>
class Attribute:
"""Represents parsed state of kubernetes client model attribute."""
def __init__(self, name: str, class_name: str, model_name: str) -> None:
"""Parse attribute parameters."""
<|body_0|>
def parse_type(self, class_name: str) -> str:
"""Get attribute typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Attribute:
"""Represents parsed state of kubernetes client model attribute."""
def __init__(self, name: str, class_name: str, model_name: str) -> None:
"""Parse attribute parameters."""
self.name = name
self.class_name = class_name
self.model_name = model_name
self... | the_stack_v2_python_sparse | scripts/typeddictgen.py | gordonbondon/kubernetes-typed | train | 24 |
86b4d576315d9603c2b98d08eb40655ff2e2695b | [
"if type(self.value) is not str:\n raise ValidationError('Validation Error: Secret Custom Setting should be a String')\nif self.value == '' and self.required:\n raise ValidationError('Required.')\nif self.value != '':\n self.value = secrets_signed_unsigned_value(self.name, self.value, self.tethys_app.packa... | <|body_start_0|>
if type(self.value) is not str:
raise ValidationError('Validation Error: Secret Custom Setting should be a String')
if self.value == '' and self.required:
raise ValidationError('Required.')
if self.value != '':
self.value = secrets_signed_unsi... | Used to define a Custom Secret Setting. Attributes: name(str): Unique name used to identify the setting. description(str): Short description of the setting. required(bool): A value will be required if True. **Example:** :: from tethys_sdk.app_settings import SecretCustomSetting default_name_setting = SecretCustomSettin... | SecretCustomSetting | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecretCustomSetting:
"""Used to define a Custom Secret Setting. Attributes: name(str): Unique name used to identify the setting. description(str): Short description of the setting. required(bool): A value will be required if True. **Example:** :: from tethys_sdk.app_settings import SecretCustomSe... | stack_v2_sparse_classes_36k_train_023602 | 45,827 | permissive | [
{
"docstring": "Validate prior to saving changes.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Get the value",
"name": "get_value",
"signature": "def get_value(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018989 | Implement the Python class `SecretCustomSetting` described below.
Class description:
Used to define a Custom Secret Setting. Attributes: name(str): Unique name used to identify the setting. description(str): Short description of the setting. required(bool): A value will be required if True. **Example:** :: from tethys... | Implement the Python class `SecretCustomSetting` described below.
Class description:
Used to define a Custom Secret Setting. Attributes: name(str): Unique name used to identify the setting. description(str): Short description of the setting. required(bool): A value will be required if True. **Example:** :: from tethys... | e9365fa55ec25d7658a75ca7fb0632013374d876 | <|skeleton|>
class SecretCustomSetting:
"""Used to define a Custom Secret Setting. Attributes: name(str): Unique name used to identify the setting. description(str): Short description of the setting. required(bool): A value will be required if True. **Example:** :: from tethys_sdk.app_settings import SecretCustomSe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SecretCustomSetting:
"""Used to define a Custom Secret Setting. Attributes: name(str): Unique name used to identify the setting. description(str): Short description of the setting. required(bool): A value will be required if True. **Example:** :: from tethys_sdk.app_settings import SecretCustomSetting default... | the_stack_v2_python_sparse | tethys_apps/models.py | tethysplatform/tethys | train | 95 |
2176476bd36a670fd4c2dd3318b45a5b2972d229 | [
"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... | Missing associated documentation comment in .proto file. | LoggingServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggingServiceServicer:
"""Missing associated documentation comment in .proto file."""
def addLogEvent(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def getLogEvents(self, request, context):
"""Missing associat... | stack_v2_sparse_classes_36k_train_023603 | 7,376 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "addLogEvent",
"signature": "def addLogEvent(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "getLogEvents",
"signature": "def getLogEvents(se... | 4 | stack_v2_sparse_classes_30k_train_001346 | Implement the Python class `LoggingServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def addLogEvent(self, request, context): Missing associated documentation comment in .proto file.
- def getLogEvents(self, request, conte... | Implement the Python class `LoggingServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def addLogEvent(self, request, context): Missing associated documentation comment in .proto file.
- def getLogEvents(self, request, conte... | dc1ea0b58f92429ec8e7b54a8f23525abe024ba9 | <|skeleton|>
class LoggingServiceServicer:
"""Missing associated documentation comment in .proto file."""
def addLogEvent(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def getLogEvents(self, request, context):
"""Missing associat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoggingServiceServicer:
"""Missing associated documentation comment in .proto file."""
def addLogEvent(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemente... | the_stack_v2_python_sparse | custos-client-sdks/custos-python-sdk/custos/server/core/LoggingService_pb2_grpc.py | apache/airavata-custos | train | 12 |
026b68c5c1fc852c2147f7eaca2235770b17bf0f | [
"data = parser.parse_args()\nif data['file'] == None:\n return json.dumps({'data': '', 'message': 'No File Found', 'status': 'error'})\nraw_file = data['file']\nif raw_file:\n extension = raw_file.filename.split('.')[-1]\n if extension == 'csv':\n raw_file.save(os.path.join(_folderPath, 'raw' + '.' ... | <|body_start_0|>
data = parser.parse_args()
if data['file'] == None:
return json.dumps({'data': '', 'message': 'No File Found', 'status': 'error'})
raw_file = data['file']
if raw_file:
extension = raw_file.filename.split('.')[-1]
if extension == 'csv':... | Files | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Files:
def post(self):
""""Upload data"""
<|body_0|>
def delete(self):
""""Delete data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = parser.parse_args()
if data['file'] == None:
return json.dumps({'data': '', 'message': ... | stack_v2_sparse_classes_36k_train_023604 | 2,186 | no_license | [
{
"docstring": "\"Upload data",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "\"Delete data",
"name": "delete",
"signature": "def delete(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006244 | Implement the Python class `Files` described below.
Class description:
Implement the Files class.
Method signatures and docstrings:
- def post(self): "Upload data
- def delete(self): "Delete data | Implement the Python class `Files` described below.
Class description:
Implement the Files class.
Method signatures and docstrings:
- def post(self): "Upload data
- def delete(self): "Delete data
<|skeleton|>
class Files:
def post(self):
""""Upload data"""
<|body_0|>
def delete(self):
... | 62b9e5fd4b7cb32e2a319447c2131905ddd17d4c | <|skeleton|>
class Files:
def post(self):
""""Upload data"""
<|body_0|>
def delete(self):
""""Delete data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Files:
def post(self):
""""Upload data"""
data = parser.parse_args()
if data['file'] == None:
return json.dumps({'data': '', 'message': 'No File Found', 'status': 'error'})
raw_file = data['file']
if raw_file:
extension = raw_file.filename.split(... | the_stack_v2_python_sparse | api/resources/files.py | rakumairu/Flow-App-Server | train | 0 | |
69cc0b61d83b54ff2507ecf58441f73b8def71a9 | [
"super(DaffyTrackPlotHelper, self).__init__(usage_string=usage_string)\nself.shade_lines_by_intensity = shadeLines\nself.decorate_map()\nif draw_nature_track:\n self.draw_nature_run_track(axes=axes)",
"log.debug('plotting nature run data')\nnature_data = self.cfg.truth_track.tracker_entries\nnrLats = [x.lat fo... | <|body_start_0|>
super(DaffyTrackPlotHelper, self).__init__(usage_string=usage_string)
self.shade_lines_by_intensity = shadeLines
self.decorate_map()
if draw_nature_track:
self.draw_nature_run_track(axes=axes)
<|end_body_0|>
<|body_start_1|>
log.debug('plotting natur... | Provides routines for plotting tracks. Note that this is a subclass of DaffyMapHelper, since it utilizes a lot of the options from that class. | DaffyTrackPlotHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DaffyTrackPlotHelper:
"""Provides routines for plotting tracks. Note that this is a subclass of DaffyMapHelper, since it utilizes a lot of the options from that class."""
def __init__(self, usage_string=None, draw_nature_track=True, shadeLines=True, axes=plt.gca()):
"""Instantiate a ... | stack_v2_sparse_classes_36k_train_023605 | 27,841 | no_license | [
{
"docstring": "Instantiate a DaffyTrackPlotHelper @param shadeLines If True, the shade of the line will be intensified according to the max wind speed @param axes Axes object to use to dra the nature run track. TODO: This is not a good place to plot the nature run track since the axes on which the tracks will ... | 3 | stack_v2_sparse_classes_30k_train_010135 | Implement the Python class `DaffyTrackPlotHelper` described below.
Class description:
Provides routines for plotting tracks. Note that this is a subclass of DaffyMapHelper, since it utilizes a lot of the options from that class.
Method signatures and docstrings:
- def __init__(self, usage_string=None, draw_nature_tra... | Implement the Python class `DaffyTrackPlotHelper` described below.
Class description:
Provides routines for plotting tracks. Note that this is a subclass of DaffyMapHelper, since it utilizes a lot of the options from that class.
Method signatures and docstrings:
- def __init__(self, usage_string=None, draw_nature_tra... | ea02c68f30a61b8a8048b7801f3d0433b9adecc9 | <|skeleton|>
class DaffyTrackPlotHelper:
"""Provides routines for plotting tracks. Note that this is a subclass of DaffyMapHelper, since it utilizes a lot of the options from that class."""
def __init__(self, usage_string=None, draw_nature_track=True, shadeLines=True, axes=plt.gca()):
"""Instantiate a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DaffyTrackPlotHelper:
"""Provides routines for plotting tracks. Note that this is a subclass of DaffyMapHelper, since it utilizes a lot of the options from that class."""
def __init__(self, usage_string=None, draw_nature_track=True, shadeLines=True, axes=plt.gca()):
"""Instantiate a DaffyTrackPlo... | the_stack_v2_python_sparse | daffy_plot/plot_helper.py | JavierDelgadoNoaa/daffyplot | train | 0 |
298d7fae408e3d76a018d0e77e7ce4d3c641d651 | [
"try:\n import jpype\n self._backend = 'jpype'\nexcept ImportError:\n self._backend = 'subprocess'\nself.lemmatizer = lemmatizer\nself.__sd = StanfordDependencies.get_instance(backend=self._backend)\nself.representation = representation\nself.universal = universal",
"if self._backend == 'jpype':\n dep... | <|body_start_0|>
try:
import jpype
self._backend = 'jpype'
except ImportError:
self._backend = 'subprocess'
self.lemmatizer = lemmatizer
self.__sd = StanfordDependencies.get_instance(backend=self._backend)
self.representation = representation
... | Convert ptb trees to universal dependencies | Ptb2DepConverter | [
"LicenseRef-scancode-us-govt-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ptb2DepConverter:
"""Convert ptb trees to universal dependencies"""
def __init__(self, lemmatizer, representation='CCprocessed', universal=False):
"""Args: representation(str): Currently supported representations are 'basic', 'collapsed', 'CCprocessed', and 'collapsedTree' universal(... | stack_v2_sparse_classes_36k_train_023606 | 7,295 | permissive | [
{
"docstring": "Args: representation(str): Currently supported representations are 'basic', 'collapsed', 'CCprocessed', and 'collapsedTree' universal(bool): if True, use universal dependencies if they're available",
"name": "__init__",
"signature": "def __init__(self, lemmatizer, representation='CCproce... | 2 | stack_v2_sparse_classes_30k_train_009052 | Implement the Python class `Ptb2DepConverter` described below.
Class description:
Convert ptb trees to universal dependencies
Method signatures and docstrings:
- def __init__(self, lemmatizer, representation='CCprocessed', universal=False): Args: representation(str): Currently supported representations are 'basic', '... | Implement the Python class `Ptb2DepConverter` described below.
Class description:
Convert ptb trees to universal dependencies
Method signatures and docstrings:
- def __init__(self, lemmatizer, representation='CCprocessed', universal=False): Args: representation(str): Currently supported representations are 'basic', '... | 073199e2792824740e89844a59c13d3d40ce4d23 | <|skeleton|>
class Ptb2DepConverter:
"""Convert ptb trees to universal dependencies"""
def __init__(self, lemmatizer, representation='CCprocessed', universal=False):
"""Args: representation(str): Currently supported representations are 'basic', 'collapsed', 'CCprocessed', and 'collapsedTree' universal(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ptb2DepConverter:
"""Convert ptb trees to universal dependencies"""
def __init__(self, lemmatizer, representation='CCprocessed', universal=False):
"""Args: representation(str): Currently supported representations are 'basic', 'collapsed', 'CCprocessed', and 'collapsedTree' universal(bool): if Tru... | the_stack_v2_python_sparse | negbio/pipeline/ptb2ud.py | ncbi-nlp/NegBio | train | 142 |
7a4a1d916037a2cbcb25ab03d0278358ded29b7a | [
"super().__init__()\nself.winWidth = winWidth\nself.winHeight = winHeight\nself.speed = [3, 3]\nself.image = pygame.Surface((30, 30))\nself.image.set_colorkey((255, 255, 255))\nself.rect = self.image.get_rect()\nself.rect.centerx = self.rect.width // 2\nself.rect.centery = self.winHeight // 2",
"if self.rect.left... | <|body_start_0|>
super().__init__()
self.winWidth = winWidth
self.winHeight = winHeight
self.speed = [3, 3]
self.image = pygame.Surface((30, 30))
self.image.set_colorkey((255, 255, 255))
self.rect = self.image.get_rect()
self.rect.centerx = self.rect.width... | Ball | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ball:
def __init__(self, winWidth, winHeight):
"""Constructor of Ball class Inputs: 1) Window's width 2) Window's height"""
<|body_0|>
def moveStep(self):
"""Moves ball and change direction if it collides with top or sides of window"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_023607 | 11,251 | no_license | [
{
"docstring": "Constructor of Ball class Inputs: 1) Window's width 2) Window's height",
"name": "__init__",
"signature": "def __init__(self, winWidth, winHeight)"
},
{
"docstring": "Moves ball and change direction if it collides with top or sides of window",
"name": "moveStep",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_013673 | Implement the Python class `Ball` described below.
Class description:
Implement the Ball class.
Method signatures and docstrings:
- def __init__(self, winWidth, winHeight): Constructor of Ball class Inputs: 1) Window's width 2) Window's height
- def moveStep(self): Moves ball and change direction if it collides with ... | Implement the Python class `Ball` described below.
Class description:
Implement the Ball class.
Method signatures and docstrings:
- def __init__(self, winWidth, winHeight): Constructor of Ball class Inputs: 1) Window's width 2) Window's height
- def moveStep(self): Moves ball and change direction if it collides with ... | d38a8cb5f7c9accd8aed07455191205c4aad30c0 | <|skeleton|>
class Ball:
def __init__(self, winWidth, winHeight):
"""Constructor of Ball class Inputs: 1) Window's width 2) Window's height"""
<|body_0|>
def moveStep(self):
"""Moves ball and change direction if it collides with top or sides of window"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ball:
def __init__(self, winWidth, winHeight):
"""Constructor of Ball class Inputs: 1) Window's width 2) Window's height"""
super().__init__()
self.winWidth = winWidth
self.winHeight = winHeight
self.speed = [3, 3]
self.image = pygame.Surface((30, 30))
s... | the_stack_v2_python_sparse | Python Programs Into to CS/finalProject.py | gadeuneo/Python | train | 0 | |
634378481c29fdfb7f88b9a40665ae45694634af | [
"start_date = date.today()\nexp_date = date.today() + timedelta(days=30)\ne = Employee(first_name='John', last_name='Gamlet', email='gamlet@example.com', contract_start_date=start_date, contract_exp_date=exp_date)\nself.assertEqual(e.full_name(), 'Gamlet John')",
"start_date = date.today()\nexp_date = date.today(... | <|body_start_0|>
start_date = date.today()
exp_date = date.today() + timedelta(days=30)
e = Employee(first_name='John', last_name='Gamlet', email='gamlet@example.com', contract_start_date=start_date, contract_exp_date=exp_date)
self.assertEqual(e.full_name(), 'Gamlet John')
<|end_body_0|... | EmployeeMethodTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmployeeMethodTests:
def test_full_name_with_valid_employee(self):
"""the full_name method should return joined (' ') first_name and last_name"""
<|body_0|>
def test_create_new_employee_with_empty_attributes(self):
"""saving employee without all required data should ... | stack_v2_sparse_classes_36k_train_023608 | 27,946 | no_license | [
{
"docstring": "the full_name method should return joined (' ') first_name and last_name",
"name": "test_full_name_with_valid_employee",
"signature": "def test_full_name_with_valid_employee(self)"
},
{
"docstring": "saving employee without all required data should be aborted",
"name": "test_... | 2 | stack_v2_sparse_classes_30k_train_019305 | Implement the Python class `EmployeeMethodTests` described below.
Class description:
Implement the EmployeeMethodTests class.
Method signatures and docstrings:
- def test_full_name_with_valid_employee(self): the full_name method should return joined (' ') first_name and last_name
- def test_create_new_employee_with_e... | Implement the Python class `EmployeeMethodTests` described below.
Class description:
Implement the EmployeeMethodTests class.
Method signatures and docstrings:
- def test_full_name_with_valid_employee(self): the full_name method should return joined (' ') first_name and last_name
- def test_create_new_employee_with_e... | aa82ab2cb219617c1fa9a18970b2a4d27c573191 | <|skeleton|>
class EmployeeMethodTests:
def test_full_name_with_valid_employee(self):
"""the full_name method should return joined (' ') first_name and last_name"""
<|body_0|>
def test_create_new_employee_with_empty_attributes(self):
"""saving employee without all required data should ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmployeeMethodTests:
def test_full_name_with_valid_employee(self):
"""the full_name method should return joined (' ') first_name and last_name"""
start_date = date.today()
exp_date = date.today() + timedelta(days=30)
e = Employee(first_name='John', last_name='Gamlet', email='ga... | the_stack_v2_python_sparse | employees/tests.py | Code-Poets/polish-lody | train | 0 | |
6c952ce6ef498b3213542d60cb26c72a2df90e6d | [
"self.X = X\nself.fs = fs\nself.N = N\nself.K = K\nif self.K == None:\n self.K = int(len(X) / 2) - 1",
"x = np.zeros(self.N)\nfor n in range(self.N):\n x[n] = 1 / np.sqrt(self.N) * self.X[0] * np.exp(1j * 2 * cmath.pi * 0 * n / self.N)\n for k in range(1, self.K + 1):\n x[n] = x[n] + 1 / np.sqrt(s... | <|body_start_0|>
self.X = X
self.fs = fs
self.N = N
self.K = K
if self.K == None:
self.K = int(len(X) / 2) - 1
<|end_body_0|>
<|body_start_1|>
x = np.zeros(self.N)
for n in range(self.N):
x[n] = 1 / np.sqrt(self.N) * self.X[0] * np.exp(1j ... | idft Inverse Discrete Fourier transform. | idft | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class idft:
"""idft Inverse Discrete Fourier transform."""
def __init__(self, X, fs, N, K=None):
""":param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param N: The number of total signal samples N :param K: Input positive integer that determines the number of ... | stack_v2_sparse_classes_36k_train_023609 | 25,417 | no_license | [
{
"docstring": ":param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param N: The number of total signal samples N :param K: Input positive integer that determines the number of coeffients used to calculate the iDFT.",
"name": "__init__",
"signature": "def __init__(self, X, f... | 3 | stack_v2_sparse_classes_30k_train_012813 | Implement the Python class `idft` described below.
Class description:
idft Inverse Discrete Fourier transform.
Method signatures and docstrings:
- def __init__(self, X, fs, N, K=None): :param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param N: The number of total signal samples N :param... | Implement the Python class `idft` described below.
Class description:
idft Inverse Discrete Fourier transform.
Method signatures and docstrings:
- def __init__(self, X, fs, N, K=None): :param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param N: The number of total signal samples N :param... | b72322cfc6d81c996117cea2160ee312da62d3ed | <|skeleton|>
class idft:
"""idft Inverse Discrete Fourier transform."""
def __init__(self, X, fs, N, K=None):
""":param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param N: The number of total signal samples N :param K: Input positive integer that determines the number of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class idft:
"""idft Inverse Discrete Fourier transform."""
def __init__(self, X, fs, N, K=None):
""":param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param N: The number of total signal samples N :param K: Input positive integer that determines the number of coeffients us... | the_stack_v2_python_sparse | Inverse Discrete Fourier Transform/iDFT_main.py | FG-14/Signals-and-Information-Processing-DSP- | train | 0 |
cd6a17c59a192b74c35039e7d709358552edee49 | [
"num_schools_elementary_laval_xpath = '//*[@id=\"MainContent\"]/div[1]/p[2]/a/@href'\nnum_schools_secondary_laval_xpath = '//*[@id=\"MainContent\"]/div[1]/p[4]/a/@href'\nnum_schools_elementary_lanaudiere1_xpath = '//*[@id=\"MainContent\"]/div[1]/p[8]/a/@href'\nnum_schools_secondary_lanaudiere1_xpath = '//*[@id=\"Ma... | <|body_start_0|>
num_schools_elementary_laval_xpath = '//*[@id="MainContent"]/div[1]/p[2]/a/@href'
num_schools_secondary_laval_xpath = '//*[@id="MainContent"]/div[1]/p[4]/a/@href'
num_schools_elementary_lanaudiere1_xpath = '//*[@id="MainContent"]/div[1]/p[8]/a/@href'
num_schools_secondar... | a scrapy spider to crawl swlauriersb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found | MontrealSwlauriersbSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MontrealSwlauriersbSpider:
"""a scrapy spider to crawl swlauriersb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found"""
def parse(self, response):
... | stack_v2_sparse_classes_36k_train_023610 | 6,134 | no_license | [
{
"docstring": "parse the start urls to get a list of schools urls for all schools types and cities",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "get required information for each school this method is called once for each school page",
"name": "parse_school_... | 3 | stack_v2_sparse_classes_30k_train_010852 | Implement the Python class `MontrealSwlauriersbSpider` described below.
Class description:
a scrapy spider to crawl swlauriersb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found
Met... | Implement the Python class `MontrealSwlauriersbSpider` described below.
Class description:
a scrapy spider to crawl swlauriersb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found
Met... | 350264cf6da323692c2838d8cb235ef61085851b | <|skeleton|>
class MontrealSwlauriersbSpider:
"""a scrapy spider to crawl swlauriersb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found"""
def parse(self, response):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MontrealSwlauriersbSpider:
"""a scrapy spider to crawl swlauriersb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found"""
def parse(self, response):
"""parse the ... | the_stack_v2_python_sparse | school_scraping/spiders/montreal_swlauriersb.py | ramadanmostafa/canada_school_scraping | train | 0 |
70f558bb745f952980e493d930e815bf2081db3e | [
"self.game_active = False\nself.al_settings = al_settings\nself.reset_stats()\nself.high_score = 0",
"self.ships_left = self.al_settings.ship_limit\nself.score = 0\nself.level = 1"
] | <|body_start_0|>
self.game_active = False
self.al_settings = al_settings
self.reset_stats()
self.high_score = 0
<|end_body_0|>
<|body_start_1|>
self.ships_left = self.al_settings.ship_limit
self.score = 0
self.level = 1
<|end_body_1|>
| 跟踪游戏的统计信息 | GameStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, al_settings):
"""初始化统计信息"""
<|body_0|>
def reset_stats(self):
"""初始化在游戏运行期间可能改变的统计信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.game_active = False
self.al_settings = al_settings
... | stack_v2_sparse_classes_36k_train_023611 | 594 | no_license | [
{
"docstring": "初始化统计信息",
"name": "__init__",
"signature": "def __init__(self, al_settings)"
},
{
"docstring": "初始化在游戏运行期间可能改变的统计信息",
"name": "reset_stats",
"signature": "def reset_stats(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011430 | Implement the Python class `GameStats` described below.
Class description:
跟踪游戏的统计信息
Method signatures and docstrings:
- def __init__(self, al_settings): 初始化统计信息
- def reset_stats(self): 初始化在游戏运行期间可能改变的统计信息 | Implement the Python class `GameStats` described below.
Class description:
跟踪游戏的统计信息
Method signatures and docstrings:
- def __init__(self, al_settings): 初始化统计信息
- def reset_stats(self): 初始化在游戏运行期间可能改变的统计信息
<|skeleton|>
class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, al_settings):
"""初始化统计信息"""
... | bef0e99939b9fd4885b25ffea360b5745e7cc809 | <|skeleton|>
class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, al_settings):
"""初始化统计信息"""
<|body_0|>
def reset_stats(self):
"""初始化在游戏运行期间可能改变的统计信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameStats:
"""跟踪游戏的统计信息"""
def __init__(self, al_settings):
"""初始化统计信息"""
self.game_active = False
self.al_settings = al_settings
self.reset_stats()
self.high_score = 0
def reset_stats(self):
"""初始化在游戏运行期间可能改变的统计信息"""
self.ships_left = self.al_... | the_stack_v2_python_sparse | game_stats.py | ssf-czh/alien_invision | train | 0 |
5d2952fdb3e3a244e6f74a4d211a9caf0d835208 | [
"super(Zero, self).__init__()\nself.stride = desc.stride\nself.data_format = desc.data_format",
"if self.stride == 1:\n return tf.zeros_like(x)\nif self.data_format == 'channels_first':\n return tf.zeros_like(x)[:, :, ::self.stride, ::self.stride]\nelse:\n return tf.zeros_like(x)[:, ::self.stride, ::self... | <|body_start_0|>
super(Zero, self).__init__()
self.stride = desc.stride
self.data_format = desc.data_format
<|end_body_0|>
<|body_start_1|>
if self.stride == 1:
return tf.zeros_like(x)
if self.data_format == 'channels_first':
return tf.zeros_like(x)[:, :,... | Class of Zero operation. :param desc: description of Zero :type desc: Config | Zero | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Zero:
"""Class of Zero operation. :param desc: description of Zero :type desc: Config"""
def __init__(self, desc):
"""Init Zero."""
<|body_0|>
def __call__(self, x):
"""Forward Function fo Zero."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
su... | stack_v2_sparse_classes_36k_train_023612 | 7,938 | permissive | [
{
"docstring": "Init Zero.",
"name": "__init__",
"signature": "def __init__(self, desc)"
},
{
"docstring": "Forward Function fo Zero.",
"name": "__call__",
"signature": "def __call__(self, x)"
}
] | 2 | null | Implement the Python class `Zero` described below.
Class description:
Class of Zero operation. :param desc: description of Zero :type desc: Config
Method signatures and docstrings:
- def __init__(self, desc): Init Zero.
- def __call__(self, x): Forward Function fo Zero. | Implement the Python class `Zero` described below.
Class description:
Class of Zero operation. :param desc: description of Zero :type desc: Config
Method signatures and docstrings:
- def __init__(self, desc): Init Zero.
- def __call__(self, x): Forward Function fo Zero.
<|skeleton|>
class Zero:
"""Class of Zero ... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class Zero:
"""Class of Zero operation. :param desc: description of Zero :type desc: Config"""
def __init__(self, desc):
"""Init Zero."""
<|body_0|>
def __call__(self, x):
"""Forward Function fo Zero."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Zero:
"""Class of Zero operation. :param desc: description of Zero :type desc: Config"""
def __init__(self, desc):
"""Init Zero."""
super(Zero, self).__init__()
self.stride = desc.stride
self.data_format = desc.data_format
def __call__(self, x):
"""Forward Fun... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/tensorflow/blocks/operations.py | Huawei-Ascend/modelzoo | train | 1 |
9c62560105cc0cce95532315a357d22d164ece7d | [
"queryset = HostCategory.objects.filter(parent=None)\nserializer = HostCategoryChildrenSerializer(queryset, many=True, context={'request': request})\nreturn Response(serializer.data)",
"queryset = HostCategory.objects.all()\ncategory = get_object_or_404(queryset, pk=pk)\nserializer = HostCategoryChildrenSerialize... | <|body_start_0|>
queryset = HostCategory.objects.filter(parent=None)
serializer = HostCategoryChildrenSerializer(queryset, many=True, context={'request': request})
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
queryset = HostCategory.objects.all()
category = g... | HostCategoryViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostCategoryViewSet:
def list(self, request):
"""Returns the tree of all host categories via GET. Allows any."""
<|body_0|>
def retrieve(self, request, pk):
"""Returns a particular branch of host categories via GET. Allows any."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_023613 | 9,571 | no_license | [
{
"docstring": "Returns the tree of all host categories via GET. Allows any.",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Returns a particular branch of host categories via GET. Allows any.",
"name": "retrieve",
"signature": "def retrieve(self, request, pk)... | 2 | stack_v2_sparse_classes_30k_train_008693 | Implement the Python class `HostCategoryViewSet` described below.
Class description:
Implement the HostCategoryViewSet class.
Method signatures and docstrings:
- def list(self, request): Returns the tree of all host categories via GET. Allows any.
- def retrieve(self, request, pk): Returns a particular branch of host... | Implement the Python class `HostCategoryViewSet` described below.
Class description:
Implement the HostCategoryViewSet class.
Method signatures and docstrings:
- def list(self, request): Returns the tree of all host categories via GET. Allows any.
- def retrieve(self, request, pk): Returns a particular branch of host... | 78ef668111d7552c98795c8aa07698b642cf09a5 | <|skeleton|>
class HostCategoryViewSet:
def list(self, request):
"""Returns the tree of all host categories via GET. Allows any."""
<|body_0|>
def retrieve(self, request, pk):
"""Returns a particular branch of host categories via GET. Allows any."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HostCategoryViewSet:
def list(self, request):
"""Returns the tree of all host categories via GET. Allows any."""
queryset = HostCategory.objects.filter(parent=None)
serializer = HostCategoryChildrenSerializer(queryset, many=True, context={'request': request})
return Response(se... | the_stack_v2_python_sparse | backend/core/views.py | lawrencejberry/bridge | train | 0 | |
6ada7e6a372141e8298143bc570d154c73ae0dad | [
"try:\n return DataSourceToken.get_by_id(id)\nexcept DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND, 'Token with id {} does not exist'.format(id))",
"user: User = None\ndata_source: DataSource = None\ntry:\n if user_id:\n user = _UserService.get_user_by_id(self, user_id)\nexcept Exception:\... | <|body_start_0|>
try:
return DataSourceToken.get_by_id(id)
except DoesNotExist:
raise ValueError(HTTPStatus.NOT_FOUND, 'Token with id {} does not exist'.format(id))
<|end_body_0|>
<|body_start_1|>
user: User = None
data_source: DataSource = None
try:
... | DataSourceTokenService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSourceTokenService:
def get_token_by_id(self, id: int):
"""Retrieves data source token by id Arguments: id {int} -- data source token id Raises: ValueError: Id does not exist Returns: DataSourceToken -- DataSourceToken object"""
<|body_0|>
def create_token_for_data_sourc... | stack_v2_sparse_classes_36k_train_023614 | 5,886 | no_license | [
{
"docstring": "Retrieves data source token by id Arguments: id {int} -- data source token id Raises: ValueError: Id does not exist Returns: DataSourceToken -- DataSourceToken object",
"name": "get_token_by_id",
"signature": "def get_token_by_id(self, id: int)"
},
{
"docstring": "Creates a JWT f... | 5 | stack_v2_sparse_classes_30k_train_005732 | Implement the Python class `DataSourceTokenService` described below.
Class description:
Implement the DataSourceTokenService class.
Method signatures and docstrings:
- def get_token_by_id(self, id: int): Retrieves data source token by id Arguments: id {int} -- data source token id Raises: ValueError: Id does not exis... | Implement the Python class `DataSourceTokenService` described below.
Class description:
Implement the DataSourceTokenService class.
Method signatures and docstrings:
- def get_token_by_id(self, id: int): Retrieves data source token by id Arguments: id {int} -- data source token id Raises: ValueError: Id does not exis... | f73de5dd356b680ee8efe1d1914266d5523084d2 | <|skeleton|>
class DataSourceTokenService:
def get_token_by_id(self, id: int):
"""Retrieves data source token by id Arguments: id {int} -- data source token id Raises: ValueError: Id does not exist Returns: DataSourceToken -- DataSourceToken object"""
<|body_0|>
def create_token_for_data_sourc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataSourceTokenService:
def get_token_by_id(self, id: int):
"""Retrieves data source token by id Arguments: id {int} -- data source token id Raises: ValueError: Id does not exist Returns: DataSourceToken -- DataSourceToken object"""
try:
return DataSourceToken.get_by_id(id)
... | the_stack_v2_python_sparse | api/services/data_source_token.py | CalvinHuynh/project-olympic | train | 0 | |
4d733c4aefc460de5b36fbc0fb046509e030af71 | [
"alloy_type = alloy_model.AlloyType.objects.only('id', 'type').filter(is_delete=False, id=alloy_type_id)\nif alloy_type:\n data = {'alloy_type': alloy_type}\n return render(request, 'admin/alloy/alloy_type_edit.html', context=data)\nelse:\n logger.info('id为<{}>合金类型不存在'.format(alloy_type_id))\n return to... | <|body_start_0|>
alloy_type = alloy_model.AlloyType.objects.only('id', 'type').filter(is_delete=False, id=alloy_type_id)
if alloy_type:
data = {'alloy_type': alloy_type}
return render(request, 'admin/alloy/alloy_type_edit.html', context=data)
else:
logger.info... | 合金类型修改 | AlloyTypeEdit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlloyTypeEdit:
"""合金类型修改"""
def get(self, request, alloy_type_id):
"""指定合金类型查询展示 :param request: :param alloy_type_id: :return:"""
<|body_0|>
def put(self, request, alloy_type_id):
"""指定合金类型修改 :param request: :param alloy_type_id: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_023615 | 11,849 | no_license | [
{
"docstring": "指定合金类型查询展示 :param request: :param alloy_type_id: :return:",
"name": "get",
"signature": "def get(self, request, alloy_type_id)"
},
{
"docstring": "指定合金类型修改 :param request: :param alloy_type_id: :return:",
"name": "put",
"signature": "def put(self, request, alloy_type_id)"... | 3 | stack_v2_sparse_classes_30k_train_017265 | Implement the Python class `AlloyTypeEdit` described below.
Class description:
合金类型修改
Method signatures and docstrings:
- def get(self, request, alloy_type_id): 指定合金类型查询展示 :param request: :param alloy_type_id: :return:
- def put(self, request, alloy_type_id): 指定合金类型修改 :param request: :param alloy_type_id: :return:
- ... | Implement the Python class `AlloyTypeEdit` described below.
Class description:
合金类型修改
Method signatures and docstrings:
- def get(self, request, alloy_type_id): 指定合金类型查询展示 :param request: :param alloy_type_id: :return:
- def put(self, request, alloy_type_id): 指定合金类型修改 :param request: :param alloy_type_id: :return:
- ... | 063332d2a5e2ddabf800817f02074b4f5c162ade | <|skeleton|>
class AlloyTypeEdit:
"""合金类型修改"""
def get(self, request, alloy_type_id):
"""指定合金类型查询展示 :param request: :param alloy_type_id: :return:"""
<|body_0|>
def put(self, request, alloy_type_id):
"""指定合金类型修改 :param request: :param alloy_type_id: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlloyTypeEdit:
"""合金类型修改"""
def get(self, request, alloy_type_id):
"""指定合金类型查询展示 :param request: :param alloy_type_id: :return:"""
alloy_type = alloy_model.AlloyType.objects.only('id', 'type').filter(is_delete=False, id=alloy_type_id)
if alloy_type:
data = {'alloy_type... | the_stack_v2_python_sparse | sfs/apps/alloy/views.py | Hx-someone/sfs-1 | train | 0 |
4736ecbe066a91e5d125ffcbf5b422f8a8125a60 | [
"super().__init__()\nself.losses = []\nself.acc = []\nself.embed_layer = nn.Embedding(10, 32)\nm2m = {'RNN': nn.RNN, 'LSTM': nn.LSTM, 'GRU': nn.GRU}\nself.rnn = m2m[model](64, 64, layers, batch_first=True)\nself.dense = nn.Linear(64, 10)",
"num1 = self.embed_layer(num1)\nnum2 = self.embed_layer(num2)\ntemp = torc... | <|body_start_0|>
super().__init__()
self.losses = []
self.acc = []
self.embed_layer = nn.Embedding(10, 32)
m2m = {'RNN': nn.RNN, 'LSTM': nn.LSTM, 'GRU': nn.GRU}
self.rnn = m2m[model](64, 64, layers, batch_first=True)
self.dense = nn.Linear(64, 10)
<|end_body_0|>
... | myAdvPTRNNModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class myAdvPTRNNModel:
def __init__(self, layers=2, model='RNN'):
"""Please finish your code here."""
<|body_0|>
def forward(self, num1, num2):
"""Please finish your code here."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
sel... | stack_v2_sparse_classes_36k_train_023616 | 7,633 | no_license | [
{
"docstring": "Please finish your code here.",
"name": "__init__",
"signature": "def __init__(self, layers=2, model='RNN')"
},
{
"docstring": "Please finish your code here.",
"name": "forward",
"signature": "def forward(self, num1, num2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014721 | Implement the Python class `myAdvPTRNNModel` described below.
Class description:
Implement the myAdvPTRNNModel class.
Method signatures and docstrings:
- def __init__(self, layers=2, model='RNN'): Please finish your code here.
- def forward(self, num1, num2): Please finish your code here. | Implement the Python class `myAdvPTRNNModel` described below.
Class description:
Implement the myAdvPTRNNModel class.
Method signatures and docstrings:
- def __init__(self, layers=2, model='RNN'): Please finish your code here.
- def forward(self, num1, num2): Please finish your code here.
<|skeleton|>
class myAdvPTR... | 4064a13958b39b8fae2e47fe4e9629b23b30e33d | <|skeleton|>
class myAdvPTRNNModel:
def __init__(self, layers=2, model='RNN'):
"""Please finish your code here."""
<|body_0|>
def forward(self, num1, num2):
"""Please finish your code here."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class myAdvPTRNNModel:
def __init__(self, layers=2, model='RNN'):
"""Please finish your code here."""
super().__init__()
self.losses = []
self.acc = []
self.embed_layer = nn.Embedding(10, 32)
m2m = {'RNN': nn.RNN, 'LSTM': nn.LSTM, 'GRU': nn.GRU}
self.rnn = m2m... | the_stack_v2_python_sparse | assignment-2/17307130118/handout/pt.py | gkzhb/PRML-Spring20-FDU | train | 0 | |
810445ac6c111be7c5d414f21a6a863256a4a092 | [
"answer = i = j = 0\nseen = dict()\nwhile j < len(s):\n if s[j] in seen:\n i = max(i, seen[s[j]] + 1)\n answer = max(answer, j - i + 1)\n seen[s[j]] = j\n j += 1\nreturn answer",
"longest = 0\ni = 0\nj = 0\nseen = dict()\nwhile i < len(s) and j < len(s):\n if s[j] in seen:\n del seen[... | <|body_start_0|>
answer = i = j = 0
seen = dict()
while j < len(s):
if s[j] in seen:
i = max(i, seen[s[j]] + 1)
answer = max(answer, j - i + 1)
seen[s[j]] = j
j += 1
return answer
<|end_body_0|>
<|body_start_1|>
lon... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def length_of_longest_substring(s: str) -> int:
"""[summary] Arguments: s {str} -- [description] Returns: int -- [description]"""
<|body_0|>
def length_of_longest_substring_2(s: str) -> int:
"""Using sliding window. Arguments: s {str} -- [description] Retur... | stack_v2_sparse_classes_36k_train_023617 | 1,610 | permissive | [
{
"docstring": "[summary] Arguments: s {str} -- [description] Returns: int -- [description]",
"name": "length_of_longest_substring",
"signature": "def length_of_longest_substring(s: str) -> int"
},
{
"docstring": "Using sliding window. Arguments: s {str} -- [description] Returns: int -- [descrip... | 2 | stack_v2_sparse_classes_30k_train_017855 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def length_of_longest_substring(s: str) -> int: [summary] Arguments: s {str} -- [description] Returns: int -- [description]
- def length_of_longest_substring_2(s: str) -> int: Us... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def length_of_longest_substring(s: str) -> int: [summary] Arguments: s {str} -- [description] Returns: int -- [description]
- def length_of_longest_substring_2(s: str) -> int: Us... | 85a0dd4b32c2b7a293d0622ac3dac140d70bc5b1 | <|skeleton|>
class Solution:
def length_of_longest_substring(s: str) -> int:
"""[summary] Arguments: s {str} -- [description] Returns: int -- [description]"""
<|body_0|>
def length_of_longest_substring_2(s: str) -> int:
"""Using sliding window. Arguments: s {str} -- [description] Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def length_of_longest_substring(s: str) -> int:
"""[summary] Arguments: s {str} -- [description] Returns: int -- [description]"""
answer = i = j = 0
seen = dict()
while j < len(s):
if s[j] in seen:
i = max(i, seen[s[j]] + 1)
ans... | the_stack_v2_python_sparse | python/string/length_of_longest_substring.py | aqd14/daily-coding | train | 0 | |
374602f9bc51ce386d2457609ed274f9e4b6d624 | [
"super().__init__(observation_spec)\nself._update_mode = update_mode\nself._clipping = float(clipping)\nself._fields = fields\nif fields is not None:\n observation_spec = dict([(field, alf.nest.get_field(observation_spec, field)) for field in fields])\nif mode == 'adaptive':\n self._normalizer = AdaptiveNorma... | <|body_start_0|>
super().__init__(observation_spec)
self._update_mode = update_mode
self._clipping = float(clipping)
self._fields = fields
if fields is not None:
observation_spec = dict([(field, alf.nest.get_field(observation_spec, field)) for field in fields])
... | ObservationNormalizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObservationNormalizer:
def __init__(self, observation_spec, fields=None, clipping=0.0, window_size=10000, update_rate=0.0001, speed=8.0, zero_mean=True, update_mode='replay', mode='adaptive'):
"""Create an observation normalizer with optional value clipping to be used as the ``data_trans... | stack_v2_sparse_classes_36k_train_023618 | 40,444 | permissive | [
{
"docstring": "Create an observation normalizer with optional value clipping to be used as the ``data_transformer`` of an algorithm. It will be called before both ``rollout_step()`` and ``train_step()``. The normalizer by default doesn't automatically update the mean and std. Instead, it will check when ``self... | 2 | stack_v2_sparse_classes_30k_val_000553 | Implement the Python class `ObservationNormalizer` described below.
Class description:
Implement the ObservationNormalizer class.
Method signatures and docstrings:
- def __init__(self, observation_spec, fields=None, clipping=0.0, window_size=10000, update_rate=0.0001, speed=8.0, zero_mean=True, update_mode='replay', ... | Implement the Python class `ObservationNormalizer` described below.
Class description:
Implement the ObservationNormalizer class.
Method signatures and docstrings:
- def __init__(self, observation_spec, fields=None, clipping=0.0, window_size=10000, update_rate=0.0001, speed=8.0, zero_mean=True, update_mode='replay', ... | b00ff2fa5e660de31020338ba340263183fbeaa4 | <|skeleton|>
class ObservationNormalizer:
def __init__(self, observation_spec, fields=None, clipping=0.0, window_size=10000, update_rate=0.0001, speed=8.0, zero_mean=True, update_mode='replay', mode='adaptive'):
"""Create an observation normalizer with optional value clipping to be used as the ``data_trans... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObservationNormalizer:
def __init__(self, observation_spec, fields=None, clipping=0.0, window_size=10000, update_rate=0.0001, speed=8.0, zero_mean=True, update_mode='replay', mode='adaptive'):
"""Create an observation normalizer with optional value clipping to be used as the ``data_transformer`` of an... | the_stack_v2_python_sparse | alf/algorithms/data_transformer.py | HorizonRobotics/alf | train | 288 | |
7fb48a88f253f5fb8237f7129c7f08bc903c8dd4 | [
"self._n_classes = n_classes\nself._mode = mode\nself._normalization = normalization",
"skip_128 = input_block(inputs=features, out_channels=32, normalization=self._normalization, mode=self._mode)\nskip_64 = downsample_block(inputs=skip_128, out_channels=64, normalization=self._normalization, mode=self._mode)\nsk... | <|body_start_0|>
self._n_classes = n_classes
self._mode = mode
self._normalization = normalization
<|end_body_0|>
<|body_start_1|>
skip_128 = input_block(inputs=features, out_channels=32, normalization=self._normalization, mode=self._mode)
skip_64 = downsample_block(inputs=skip_... | Model builder | Builder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Builder:
"""Model builder"""
def __init__(self, n_classes, mode, normalization='none'):
"""Configure the unet3d builder :param n_classes: Number of output channels :param mode: Estimator's execution mode :param normalization: Name of the normalization layer"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_023619 | 3,800 | permissive | [
{
"docstring": "Configure the unet3d builder :param n_classes: Number of output channels :param mode: Estimator's execution mode :param normalization: Name of the normalization layer",
"name": "__init__",
"signature": "def __init__(self, n_classes, mode, normalization='none')"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_020541 | Implement the Python class `Builder` described below.
Class description:
Model builder
Method signatures and docstrings:
- def __init__(self, n_classes, mode, normalization='none'): Configure the unet3d builder :param n_classes: Number of output channels :param mode: Estimator's execution mode :param normalization: N... | Implement the Python class `Builder` described below.
Class description:
Model builder
Method signatures and docstrings:
- def __init__(self, n_classes, mode, normalization='none'): Configure the unet3d builder :param n_classes: Number of output channels :param mode: Estimator's execution mode :param normalization: N... | a5388a45f71a949639b35cc5b990bd130d2d8164 | <|skeleton|>
class Builder:
"""Model builder"""
def __init__(self, n_classes, mode, normalization='none'):
"""Configure the unet3d builder :param n_classes: Number of output channels :param mode: Estimator's execution mode :param normalization: Name of the normalization layer"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Builder:
"""Model builder"""
def __init__(self, n_classes, mode, normalization='none'):
"""Configure the unet3d builder :param n_classes: Number of output channels :param mode: Estimator's execution mode :param normalization: Name of the normalization layer"""
self._n_classes = n_classes
... | the_stack_v2_python_sparse | TensorFlow/Segmentation/UNet_3D_Medical/model/unet3d.py | NVIDIA/DeepLearningExamples | train | 11,838 |
20ea00ae97c2606337ef98005649db73c71547c2 | [
"resource_args.AddStreamObjectResourceArg(parser)\nobject_identifier_parser = parser.add_group(required=True, mutex=True)\nso_flags.AddOracleObjectIdentifier(object_identifier_parser)\nso_flags.AddMysqlObjectIdentifier(object_identifier_parser)\nso_flags.AddPostgresqlObjectIdentifier(object_identifier_parser)",
"... | <|body_start_0|>
resource_args.AddStreamObjectResourceArg(parser)
object_identifier_parser = parser.add_group(required=True, mutex=True)
so_flags.AddOracleObjectIdentifier(object_identifier_parser)
so_flags.AddMysqlObjectIdentifier(object_identifier_parser)
so_flags.AddPostgresql... | Lookup a Datastream stream object. | Lookup | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lookup:
"""Lookup a Datastream stream object."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed."... | stack_v2_sparse_classes_36k_train_023620 | 3,006 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring"... | 2 | null | Implement the Python class `Lookup` described below.
Class description:
Lookup a Datastream stream object.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command li... | Implement the Python class `Lookup` described below.
Class description:
Lookup a Datastream stream object.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command li... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Lookup:
"""Lookup a Datastream stream object."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lookup:
"""Lookup a Datastream stream object."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed."""
re... | the_stack_v2_python_sparse | lib/surface/datastream/objects/lookup.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
91bc08739a94ee07872811b6f25477d7b6f76648 | [
"if value < 5:\n raise serializers.ValidationError('amount must be at least 5$')\nreturn value",
"amount = data['amount']\nresponse = stripe.Charge.create(amount=amount, currency='usd', source=data['stripeToken'], description='Donation')\ndatabase_amount = amount * 10\nif response.paid:\n return Donation.ob... | <|body_start_0|>
if value < 5:
raise serializers.ValidationError('amount must be at least 5$')
return value
<|end_body_0|>
<|body_start_1|>
amount = data['amount']
response = stripe.Charge.create(amount=amount, currency='usd', source=data['stripeToken'], description='Donatio... | Donation create serializer. | DonationCreateSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DonationCreateSerializer:
"""Donation create serializer."""
def validate_amount(self, value):
"""Ammount validator."""
<|body_0|>
def create(self, data):
"""Handle creation."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if value < 5:
... | stack_v2_sparse_classes_36k_train_023621 | 1,445 | no_license | [
{
"docstring": "Ammount validator.",
"name": "validate_amount",
"signature": "def validate_amount(self, value)"
},
{
"docstring": "Handle creation.",
"name": "create",
"signature": "def create(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003536 | Implement the Python class `DonationCreateSerializer` described below.
Class description:
Donation create serializer.
Method signatures and docstrings:
- def validate_amount(self, value): Ammount validator.
- def create(self, data): Handle creation. | Implement the Python class `DonationCreateSerializer` described below.
Class description:
Donation create serializer.
Method signatures and docstrings:
- def validate_amount(self, value): Ammount validator.
- def create(self, data): Handle creation.
<|skeleton|>
class DonationCreateSerializer:
"""Donation create... | e2f4557e2a85405838c6c9f65f1cb8a5f60a35ba | <|skeleton|>
class DonationCreateSerializer:
"""Donation create serializer."""
def validate_amount(self, value):
"""Ammount validator."""
<|body_0|>
def create(self, data):
"""Handle creation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DonationCreateSerializer:
"""Donation create serializer."""
def validate_amount(self, value):
"""Ammount validator."""
if value < 5:
raise serializers.ValidationError('amount must be at least 5$')
return value
def create(self, data):
"""Handle creation."""... | the_stack_v2_python_sparse | apps/donations/serializers/donations.py | HebertFerrer/WebMaster-back-end | train | 0 |
a83b782a2d028aeeb4ba26be36d0761443a344a4 | [
"zipURI = src + '.zip'\nif not os.path.isdir(src):\n raise 'MokaUtils.file.writeZip: The argument ' + \"'%s' must be a directory.\" % src\n return\nwith closing(zipfile.ZipFile(zipURI, 'w', zipfile.ZIP_DEFLATED)) as z:\n for root, dirs, files in os.walk(src):\n for fileName in files:\n ab... | <|body_start_0|>
zipURI = src + '.zip'
if not os.path.isdir(src):
raise 'MokaUtils.file.writeZip: The argument ' + "'%s' must be a directory." % src
return
with closing(zipfile.ZipFile(zipURI, 'w', zipfile.ZIP_DEFLATED)) as z:
for root, dirs, files in os.walk(... | A subclass of MokaUtils pertaining to 'file' objects. | file | [
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class file:
"""A subclass of MokaUtils pertaining to 'file' objects."""
def writeZip(src, dst=None, deleteFolders=False):
"""Writes a given path to a zip file based on the basename of the 'src' argument. from: http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-... | stack_v2_sparse_classes_36k_train_023622 | 41,263 | permissive | [
{
"docstring": "Writes a given path to a zip file based on the basename of the 'src' argument. from: http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5 @param src: The source directory of the zip files. @type src: string @param dst: (Optional) The dst uri of... | 3 | stack_v2_sparse_classes_30k_train_020930 | Implement the Python class `file` described below.
Class description:
A subclass of MokaUtils pertaining to 'file' objects.
Method signatures and docstrings:
- def writeZip(src, dst=None, deleteFolders=False): Writes a given path to a zip file based on the basename of the 'src' argument. from: http://stackoverflow.co... | Implement the Python class `file` described below.
Class description:
A subclass of MokaUtils pertaining to 'file' objects.
Method signatures and docstrings:
- def writeZip(src, dst=None, deleteFolders=False): Writes a given path to a zip file based on the basename of the 'src' argument. from: http://stackoverflow.co... | 06867037842e2a074ae5ed3b0bdf4bf016a231a5 | <|skeleton|>
class file:
"""A subclass of MokaUtils pertaining to 'file' objects."""
def writeZip(src, dst=None, deleteFolders=False):
"""Writes a given path to a zip file based on the basename of the 'src' argument. from: http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class file:
"""A subclass of MokaUtils pertaining to 'file' objects."""
def writeZip(src, dst=None, deleteFolders=False):
"""Writes a given path to a zip file based on the basename of the 'src' argument. from: http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-... | the_stack_v2_python_sparse | XNATSlicer/XnatSlicerLib/ext/MokaUtils/MokaUtils.py | NrgXnat/XNATSlicer | train | 4 |
d1efc6a03da83c827ce76bd0a58ed308bc84639b | [
"ast = parse(contrast)\nn_buffers, cells_in_contrast = _t_contrast_rel_properties(ast)\npcells, mcells = _t_contrast_rel_expand_cells(cells_in_contrast, cells)\nself.contrast = contrast\nself.indexes = indexes\nself._ast = ast\nself._pcells = pcells\nself._mcells = mcells\nself._n_buffers = n_buffers\nself._buffer_... | <|body_start_0|>
ast = parse(contrast)
n_buffers, cells_in_contrast = _t_contrast_rel_properties(ast)
pcells, mcells = _t_contrast_rel_expand_cells(cells_in_contrast, cells)
self.contrast = contrast
self.indexes = indexes
self._ast = ast
self._pcells = pcells
... | Parse a contrast expression and expose methods to apply it | TContrastRel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TContrastRel:
"""Parse a contrast expression and expose methods to apply it"""
def __init__(self, contrast, cells, indexes):
"""Parse a contrast expression and expose methods to apply it Parameters ---------- contrast : str Contrast specification. cells : tuple of cells Cells that oc... | stack_v2_sparse_classes_36k_train_023623 | 6,256 | permissive | [
{
"docstring": "Parse a contrast expression and expose methods to apply it Parameters ---------- contrast : str Contrast specification. cells : tuple of cells Cells that occur in the contrast (each cell is represented by a str or a tuple of str). indexes : dict {cell: index} Indexes for the data of every cell."... | 3 | null | Implement the Python class `TContrastRel` described below.
Class description:
Parse a contrast expression and expose methods to apply it
Method signatures and docstrings:
- def __init__(self, contrast, cells, indexes): Parse a contrast expression and expose methods to apply it Parameters ---------- contrast : str Con... | Implement the Python class `TContrastRel` described below.
Class description:
Parse a contrast expression and expose methods to apply it
Method signatures and docstrings:
- def __init__(self, contrast, cells, indexes): Parse a contrast expression and expose methods to apply it Parameters ---------- contrast : str Con... | feb9bdec2a99aca3077e44f318aef1c85a2e4730 | <|skeleton|>
class TContrastRel:
"""Parse a contrast expression and expose methods to apply it"""
def __init__(self, contrast, cells, indexes):
"""Parse a contrast expression and expose methods to apply it Parameters ---------- contrast : str Contrast specification. cells : tuple of cells Cells that oc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TContrastRel:
"""Parse a contrast expression and expose methods to apply it"""
def __init__(self, contrast, cells, indexes):
"""Parse a contrast expression and expose methods to apply it Parameters ---------- contrast : str Contrast specification. cells : tuple of cells Cells that occur in the co... | the_stack_v2_python_sparse | eelbrain/_stats/t_contrast.py | weilongzheng/Eelbrain | train | 0 |
46d79c460f85c8f96d0ed6dbe2353d41c01558c9 | [
"super(NOAAWCOSS, self).__init__(False, False, DO_NOT_SET, name, name + '.ncep.noaa.gov')\nself._phase = phase\nself._production = None\nself._lastprod = 0\nself._prod_cache_time = int(prod_cache_time)",
"self._production = None\nself._lastprod = 0\nself._phase = 0",
"now = int(time.time())\nif self._production... | <|body_start_0|>
super(NOAAWCOSS, self).__init__(False, False, DO_NOT_SET, name, name + '.ncep.noaa.gov')
self._phase = phase
self._production = None
self._lastprod = 0
self._prod_cache_time = int(prod_cache_time)
<|end_body_0|>
<|body_start_1|>
self._production = None
... | !Represents the NOAA WCOSS clusters, Tide, Gyre and the test system Eddy. Automatically determines which WCOSS the program is on based on the first letter of socket.gethostname(). Will report no ACL support, and no group quotas. Hence, the cluster should use group IDs for access control. The production accessor is no l... | NOAAWCOSS | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NOAAWCOSS:
"""!Represents the NOAA WCOSS clusters, Tide, Gyre and the test system Eddy. Automatically determines which WCOSS the program is on based on the first letter of socket.gethostname(). Will report no ACL support, and no group quotas. Hence, the cluster should use group IDs for access con... | stack_v2_sparse_classes_36k_train_023624 | 11,161 | permissive | [
{
"docstring": "!Creates a NOAAWCOSS object, and optionally specifies the time for which the result of self.production should be cached. Default: 30 seconds. @param prod_cache_time how long to cache the prod vs. dev information, in seconds",
"name": "__init__",
"signature": "def __init__(self, prod_cach... | 3 | null | Implement the Python class `NOAAWCOSS` described below.
Class description:
!Represents the NOAA WCOSS clusters, Tide, Gyre and the test system Eddy. Automatically determines which WCOSS the program is on based on the first letter of socket.gethostname(). Will report no ACL support, and no group quotas. Hence, the clus... | Implement the Python class `NOAAWCOSS` described below.
Class description:
!Represents the NOAA WCOSS clusters, Tide, Gyre and the test system Eddy. Automatically determines which WCOSS the program is on based on the first letter of socket.gethostname(). Will report no ACL support, and no group quotas. Hence, the clus... | a666ac3b58d19f04249f76c9340f2e4a4a27939b | <|skeleton|>
class NOAAWCOSS:
"""!Represents the NOAA WCOSS clusters, Tide, Gyre and the test system Eddy. Automatically determines which WCOSS the program is on based on the first letter of socket.gethostname(). Will report no ACL support, and no group quotas. Hence, the cluster should use group IDs for access con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NOAAWCOSS:
"""!Represents the NOAA WCOSS clusters, Tide, Gyre and the test system Eddy. Automatically determines which WCOSS the program is on based on the first letter of socket.gethostname(). Will report no ACL support, and no group quotas. Hence, the cluster should use group IDs for access control. The pro... | the_stack_v2_python_sparse | produtil/cluster.py | dtcenter/METplus | train | 41 |
cdccf9ce61e3ef8700b9ec2d4199ea011ca33e3a | [
"self.columns = columns\nself.drop_columns = drop_columns\nself.sorted_cols = sorted_cols\nfor chunk in iterator_in:\n unique_symbols, start_indices = np.unique(chunk[columns], return_index=True)\n if not self.sorted_cols:\n start_indices.sort()\n if len(start_indices) > 1:\n for split_c in n... | <|body_start_0|>
self.columns = columns
self.drop_columns = drop_columns
self.sorted_cols = sorted_cols
for chunk in iterator_in:
unique_symbols, start_indices = np.unique(chunk[columns], return_index=True)
if not self.sorted_cols:
start_indices.so... | SplitChunks | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplitChunks:
def _process_chunks(self, iterator_in, columns, drop_columns=False, sorted_cols=True):
"""Split a chunk based on a list of columns columns : sequence[str] Sequence of column names for np.unique. Can't be a tuple, can be a list. See numpy docs for more. drop_columns : bool Sp... | stack_v2_sparse_classes_36k_train_023625 | 7,380 | no_license | [
{
"docstring": "Split a chunk based on a list of columns columns : sequence[str] Sequence of column names for np.unique. Can't be a tuple, can be a list. See numpy docs for more. drop_columns : bool Split out columns that are constant, leaving varying data. This is currently used for conversion to HDF5. **Chang... | 2 | null | Implement the Python class `SplitChunks` described below.
Class description:
Implement the SplitChunks class.
Method signatures and docstrings:
- def _process_chunks(self, iterator_in, columns, drop_columns=False, sorted_cols=True): Split a chunk based on a list of columns columns : sequence[str] Sequence of column n... | Implement the Python class `SplitChunks` described below.
Class description:
Implement the SplitChunks class.
Method signatures and docstrings:
- def _process_chunks(self, iterator_in, columns, drop_columns=False, sorted_cols=True): Split a chunk based on a list of columns columns : sequence[str] Sequence of column n... | 85969e681b9c74e24e60cc524a952f9585ea9ce9 | <|skeleton|>
class SplitChunks:
def _process_chunks(self, iterator_in, columns, drop_columns=False, sorted_cols=True):
"""Split a chunk based on a list of columns columns : sequence[str] Sequence of column names for np.unique. Can't be a tuple, can be a list. See numpy docs for more. drop_columns : bool Sp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SplitChunks:
def _process_chunks(self, iterator_in, columns, drop_columns=False, sorted_cols=True):
"""Split a chunk based on a list of columns columns : sequence[str] Sequence of column names for np.unique. Can't be a tuple, can be a list. See numpy docs for more. drop_columns : bool Split out column... | the_stack_v2_python_sparse | Example_of_processing_tick data/marketflow/marketflow/processing.py | alexanu/Python_Trading_Snippets | train | 18 | |
7cb3b0d427c34330ba865ba1b4c21a10e602ee9e | [
"self.width = width\nself.height = height\nself.food = food\nself.food_index = 0\nself.movement = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}\nself.snake = deque([(0, 0)])\nself.snake_set = {(0, 0): 1}",
"newhead = (self.snake[0][0] + self.movement[direction][0], self.snake[0][1] + self.movement[direct... | <|body_start_0|>
self.width = width
self.height = height
self.food = food
self.food_index = 0
self.movement = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}
self.snake = deque([(0, 0)])
self.snake_set = {(0, 0): 1}
<|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_023626 | 2,378 | 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_006760 | 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 -... | 37efffbd41d4b3ea1e5ee1145f438c945a2ebf78 | <|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 | 353Design Snake Game.py | maying0120/leetcode | train | 0 | |
a2cace009e5ae6907d422bb2d22796e400f550c1 | [
"if request.method == 'GET':\n queryset = Image.objects.filter(owner=pk)\n serializer = self.image_serializer(queryset, many=True)\n return Response(serializer.data)\nelif request.method == 'POST':\n try:\n file = request.data['file']\n except KeyError:\n return Response({'detail': 'No ... | <|body_start_0|>
if request.method == 'GET':
queryset = Image.objects.filter(owner=pk)
serializer = self.image_serializer(queryset, many=True)
return Response(serializer.data)
elif request.method == 'POST':
try:
file = request.data['file']
... | Viewset for handling student queries | StudentViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentViewSet:
"""Viewset for handling student queries"""
def images(self, request, pk=None):
"""Checks a specific student's images"""
<|body_0|>
def courses(self, request, pk=None):
"""Checks a specific student's courses"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_023627 | 7,767 | no_license | [
{
"docstring": "Checks a specific student's images",
"name": "images",
"signature": "def images(self, request, pk=None)"
},
{
"docstring": "Checks a specific student's courses",
"name": "courses",
"signature": "def courses(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011777 | Implement the Python class `StudentViewSet` described below.
Class description:
Viewset for handling student queries
Method signatures and docstrings:
- def images(self, request, pk=None): Checks a specific student's images
- def courses(self, request, pk=None): Checks a specific student's courses | Implement the Python class `StudentViewSet` described below.
Class description:
Viewset for handling student queries
Method signatures and docstrings:
- def images(self, request, pk=None): Checks a specific student's images
- def courses(self, request, pk=None): Checks a specific student's courses
<|skeleton|>
class... | 4254efd246b954538a463c03e56c126ed63beec2 | <|skeleton|>
class StudentViewSet:
"""Viewset for handling student queries"""
def images(self, request, pk=None):
"""Checks a specific student's images"""
<|body_0|>
def courses(self, request, pk=None):
"""Checks a specific student's courses"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StudentViewSet:
"""Viewset for handling student queries"""
def images(self, request, pk=None):
"""Checks a specific student's images"""
if request.method == 'GET':
queryset = Image.objects.filter(owner=pk)
serializer = self.image_serializer(queryset, many=True)
... | the_stack_v2_python_sparse | backend/fuskar/views.py | deven96/fuskar-backend | train | 5 |
edddea86721a367327de295a3eaefb20a33720d1 | [
"tag_ptn = '[A-Z][A-Z_]*'\noutput = re.sub('\\\\s', '', output)\nxml = re.sub(f'<({tag_ptn})>', '[\\\\1 ', output)\nxml = re.sub(f'</{tag_ptn}>', '] ', xml)\n\ndef _convert_to_xml(text):\n for _ in range(max(text.count('['), text.count(']'))):\n text = re.sub(f'(?s)[({tag_ptn})([^[]]+?)]', '<\\\\1>\\\\2 <... | <|body_start_0|>
tag_ptn = '[A-Z][A-Z_]*'
output = re.sub('\\s', '', output)
xml = re.sub(f'<({tag_ptn})>', '[\\1 ', output)
xml = re.sub(f'</{tag_ptn}>', '] ', xml)
def _convert_to_xml(text):
for _ in range(max(text.count('['), text.count(']'))):
tex... | Constituency Parsing base class containinig various methods related to Const. Parsing | PororoConstBase | [
"Apache-2.0",
"LicenseRef-scancode-secret-labs-2011",
"HPND",
"ISC",
"MIT",
"Unlicense",
"BSD-2-Clause",
"Python-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PororoConstBase:
"""Constituency Parsing base class containinig various methods related to Const. Parsing"""
def _fix_tree(self, output: str):
"""Fix tree when XML conversion is not conducted Args: output (str): string to fix Returns: text: fixed tree string"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_023628 | 17,917 | permissive | [
{
"docstring": "Fix tree when XML conversion is not conducted Args: output (str): string to fix Returns: text: fixed tree string",
"name": "_fix_tree",
"signature": "def _fix_tree(self, output: str)"
},
{
"docstring": "Prettify model result using XML tree Args: output (str): string to make tree ... | 3 | stack_v2_sparse_classes_30k_train_014113 | Implement the Python class `PororoConstBase` described below.
Class description:
Constituency Parsing base class containinig various methods related to Const. Parsing
Method signatures and docstrings:
- def _fix_tree(self, output: str): Fix tree when XML conversion is not conducted Args: output (str): string to fix R... | Implement the Python class `PororoConstBase` described below.
Class description:
Constituency Parsing base class containinig various methods related to Const. Parsing
Method signatures and docstrings:
- def _fix_tree(self, output: str): Fix tree when XML conversion is not conducted Args: output (str): string to fix R... | 99d04d131479150a53a2e2f58b9f667258e02f9b | <|skeleton|>
class PororoConstBase:
"""Constituency Parsing base class containinig various methods related to Const. Parsing"""
def _fix_tree(self, output: str):
"""Fix tree when XML conversion is not conducted Args: output (str): string to fix Returns: text: fixed tree string"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PororoConstBase:
"""Constituency Parsing base class containinig various methods related to Const. Parsing"""
def _fix_tree(self, output: str):
"""Fix tree when XML conversion is not conducted Args: output (str): string to fix Returns: text: fixed tree string"""
tag_ptn = '[A-Z][A-Z_]*'
... | the_stack_v2_python_sparse | pororo/tasks/constituency_parsing.py | HarshCasper/pororo | train | 0 |
0ebb12dfadb52a9d4c2d5c23447291a205cec406 | [
"if config:\n self.config = Config(config)\n raw_config = deepcopy(self.config)\nelse:\n self.config = LrScheduler.config\n raw_config = self.config.to_dict()\nraw_config.type = self.config.type\nmap_dict = LrSchedulerMappingDict()\nself.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_... | <|body_start_0|>
if config:
self.config = Config(config)
raw_config = deepcopy(self.config)
else:
self.config = LrScheduler.config
raw_config = self.config.to_dict()
raw_config.type = self.config.type
map_dict = LrSchedulerMappingDict()
... | Register and call LrScheduler class. | LrScheduler | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LrScheduler:
"""Register and call LrScheduler class."""
def __init__(self, config=None):
"""Initialize."""
<|body_0|>
def __call__(self, optimizer=None, epochs=None, steps=None):
"""Call lr scheduler class."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_023629 | 2,571 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, config=None)"
},
{
"docstring": "Call lr scheduler class.",
"name": "__call__",
"signature": "def __call__(self, optimizer=None, epochs=None, steps=None)"
}
] | 2 | null | Implement the Python class `LrScheduler` described below.
Class description:
Register and call LrScheduler class.
Method signatures and docstrings:
- def __init__(self, config=None): Initialize.
- def __call__(self, optimizer=None, epochs=None, steps=None): Call lr scheduler class. | Implement the Python class `LrScheduler` described below.
Class description:
Register and call LrScheduler class.
Method signatures and docstrings:
- def __init__(self, config=None): Initialize.
- def __call__(self, optimizer=None, epochs=None, steps=None): Call lr scheduler class.
<|skeleton|>
class LrScheduler:
... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class LrScheduler:
"""Register and call LrScheduler class."""
def __init__(self, config=None):
"""Initialize."""
<|body_0|>
def __call__(self, optimizer=None, epochs=None, steps=None):
"""Call lr scheduler class."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LrScheduler:
"""Register and call LrScheduler class."""
def __init__(self, config=None):
"""Initialize."""
if config:
self.config = Config(config)
raw_config = deepcopy(self.config)
else:
self.config = LrScheduler.config
raw_config =... | the_stack_v2_python_sparse | vega/trainer/modules/lr_schedulers/lr_scheduler.py | huawei-noah/vega | train | 850 |
6a2c036aade131acbaad5b176e42f02df0ee5054 | [
"if not root:\n return ''\narr = [str(root.val)]\ntmp = [root]\nd = deque(tmp)\nwhile d:\n node = d.popleft()\n if node.left:\n arr.append(str(node.left.val))\n d.append(node.left)\n else:\n arr.append('#')\n if node.right:\n arr.append(str(node.right.val))\n d.appe... | <|body_start_0|>
if not root:
return ''
arr = [str(root.val)]
tmp = [root]
d = deque(tmp)
while d:
node = d.popleft()
if node.left:
arr.append(str(node.left.val))
d.append(node.left)
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, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_023630 | 2,128 | 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_018926 | 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:... | b6328e726c8d986d6b85e2d41c7e678e29dc1153 | <|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 ''
arr = [str(root.val)]
tmp = [root]
d = deque(tmp)
while d:
node = d.popleft()
if node.left:
... | the_stack_v2_python_sparse | 297 Serialize and Deserialize Binary Tree.py | dragonlee8/leetcode | train | 0 | |
8df1f5685a66075b63f50c260dcaf7e6c866f776 | [
"self.types = {}\nwith open('resources/types.txt') as file:\n for line in file:\n if not line.startswith('#'):\n tokens = line.split('\\t')\n self.types[tokens[0]] = tokens[1].strip()",
"clausetypes = {'p': 'dcl', 's': 'dcl', 'f': 'dcl', 'r': 'rel', 'd': 'dep'}\nclausetype = clause... | <|body_start_0|>
self.types = {}
with open('resources/types.txt') as file:
for line in file:
if not line.startswith('#'):
tokens = line.split('\t')
self.types[tokens[0]] = tokens[1].strip()
<|end_body_0|>
<|body_start_1|>
claus... | Adds CCG features | CCGTyper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CCGTyper:
"""Adds CCG features"""
def __init__(self):
"""Adds CCG features"""
<|body_0|>
def type_verb(self, surface, pos, tag):
"""Adds CCG features"""
<|body_1|>
def type(self, surface, pos, tag):
"""Retypes it as a verb if it's a verb, cop... | stack_v2_sparse_classes_36k_train_023631 | 24,263 | no_license | [
{
"docstring": "Adds CCG features",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds CCG features",
"name": "type_verb",
"signature": "def type_verb(self, surface, pos, tag)"
},
{
"docstring": "Retypes it as a verb if it's a verb, copula or verbal nou... | 3 | stack_v2_sparse_classes_30k_train_008007 | Implement the Python class `CCGTyper` described below.
Class description:
Adds CCG features
Method signatures and docstrings:
- def __init__(self): Adds CCG features
- def type_verb(self, surface, pos, tag): Adds CCG features
- def type(self, surface, pos, tag): Retypes it as a verb if it's a verb, copula or verbal n... | Implement the Python class `CCGTyper` described below.
Class description:
Adds CCG features
Method signatures and docstrings:
- def __init__(self): Adds CCG features
- def type_verb(self, surface, pos, tag): Adds CCG features
- def type(self, surface, pos, tag): Retypes it as a verb if it's a verb, copula or verbal n... | 0f6e943c2bf639f2bdad278145f6fa25502a02df | <|skeleton|>
class CCGTyper:
"""Adds CCG features"""
def __init__(self):
"""Adds CCG features"""
<|body_0|>
def type_verb(self, surface, pos, tag):
"""Adds CCG features"""
<|body_1|>
def type(self, surface, pos, tag):
"""Retypes it as a verb if it's a verb, cop... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CCGTyper:
"""Adds CCG features"""
def __init__(self):
"""Adds CCG features"""
self.types = {}
with open('resources/types.txt') as file:
for line in file:
if not line.startswith('#'):
tokens = line.split('\t')
self... | the_stack_v2_python_sparse | innealan/acainn.py | colinbatchelor/gdbank | train | 4 |
79fabf9eee9733dcc268edfe5db97e4b15056450 | [
"super(Button, self).__init__()\nself.port = None\nport = ftdi.ftdi_new()\nusb_open = ftdi.ftdi_usb_open_string(port, 's:0x403:0x6001:2eb80091')\nassert usb_open == 0, ftdi.ftdi_get_error_string(port)\nftdi.ftdi_set_bitmode(port, 255, ftdi.BITMODE_BITBANG)\nself.port = port\nself.queue = queue.Queue()\nself.daemon ... | <|body_start_0|>
super(Button, self).__init__()
self.port = None
port = ftdi.ftdi_new()
usb_open = ftdi.ftdi_usb_open_string(port, 's:0x403:0x6001:2eb80091')
assert usb_open == 0, ftdi.ftdi_get_error_string(port)
ftdi.ftdi_set_bitmode(port, 255, ftdi.BITMODE_BITBANG)
... | Docstring | Button | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Button:
"""Docstring"""
def __init__(self):
"""Docstring Parameters ---------- Returns -------"""
<|body_0|>
def run(self):
"""Docstring Parameters ---------- Returns -------"""
<|body_1|>
def _check(self):
"""Docstring Parameters ---------- ... | stack_v2_sparse_classes_36k_train_023632 | 2,002 | permissive | [
{
"docstring": "Docstring Parameters ---------- Returns -------",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Docstring Parameters ---------- Returns -------",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Docstring Parameters -------... | 5 | stack_v2_sparse_classes_30k_train_001012 | Implement the Python class `Button` described below.
Class description:
Docstring
Method signatures and docstrings:
- def __init__(self): Docstring Parameters ---------- Returns -------
- def run(self): Docstring Parameters ---------- Returns -------
- def _check(self): Docstring Parameters ---------- Returns -------... | Implement the Python class `Button` described below.
Class description:
Docstring
Method signatures and docstrings:
- def __init__(self): Docstring Parameters ---------- Returns -------
- def run(self): Docstring Parameters ---------- Returns -------
- def _check(self): Docstring Parameters ---------- Returns -------... | a0e296aa663b49e767c9ebb274defb54b301eb12 | <|skeleton|>
class Button:
"""Docstring"""
def __init__(self):
"""Docstring Parameters ---------- Returns -------"""
<|body_0|>
def run(self):
"""Docstring Parameters ---------- Returns -------"""
<|body_1|>
def _check(self):
"""Docstring Parameters ---------- ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Button:
"""Docstring"""
def __init__(self):
"""Docstring Parameters ---------- Returns -------"""
super(Button, self).__init__()
self.port = None
port = ftdi.ftdi_new()
usb_open = ftdi.ftdi_usb_open_string(port, 's:0x403:0x6001:2eb80091')
assert usb_open ==... | the_stack_v2_python_sparse | riglib/button.py | carmenalab/brain-python-interface | train | 9 |
e9d5f911db466574d83bbbdff41d017b178f8281 | [
"if not isinstance(translation, (list, tuple)) or len(translation) != 2:\n raise ValueError('translation argument must be list/tuple with two values!')\nself.translation = translation\nself.lazy = lazy\nself.reference = reference\nself.tx = tio.ANTsTransform(precision='float', dimension=2, transform_type='Affine... | <|body_start_0|>
if not isinstance(translation, (list, tuple)) or len(translation) != 2:
raise ValueError('translation argument must be list/tuple with two values!')
self.translation = translation
self.lazy = lazy
self.reference = reference
self.tx = tio.ANTsTransform... | Create an ANTs Affine Transform with a specified translation. | Translate2D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Translate2D:
"""Create an ANTs Affine Transform with a specified translation."""
def __init__(self, translation, reference=None, lazy=False):
"""Initialize a Translate2D object Arguments --------- translation : list or tuple translation values for each axis, in degrees. Negative valu... | stack_v2_sparse_classes_36k_train_023633 | 21,674 | permissive | [
{
"docstring": "Initialize a Translate2D object Arguments --------- translation : list or tuple translation values for each axis, in degrees. Negative values can be used for translation in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform.... | 2 | null | Implement the Python class `Translate2D` described below.
Class description:
Create an ANTs Affine Transform with a specified translation.
Method signatures and docstrings:
- def __init__(self, translation, reference=None, lazy=False): Initialize a Translate2D object Arguments --------- translation : list or tuple tr... | Implement the Python class `Translate2D` described below.
Class description:
Create an ANTs Affine Transform with a specified translation.
Method signatures and docstrings:
- def __init__(self, translation, reference=None, lazy=False): Initialize a Translate2D object Arguments --------- translation : list or tuple tr... | 41f2dd3fcf72654f284dac1a9448033e963f0afb | <|skeleton|>
class Translate2D:
"""Create an ANTs Affine Transform with a specified translation."""
def __init__(self, translation, reference=None, lazy=False):
"""Initialize a Translate2D object Arguments --------- translation : list or tuple translation values for each axis, in degrees. Negative valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Translate2D:
"""Create an ANTs Affine Transform with a specified translation."""
def __init__(self, translation, reference=None, lazy=False):
"""Initialize a Translate2D object Arguments --------- translation : list or tuple translation values for each axis, in degrees. Negative values can be use... | the_stack_v2_python_sparse | ants/contrib/sampling/affine2d.py | ANTsX/ANTsPy | train | 483 |
8b20a63bcd129a40335a6c71cd1795fe058266e0 | [
"self._last_dts: dict[av.stream.Stream, int | float] = defaultdict(lambda: NEGATIVE_INF)\nself._missing_dts = 0\nself._max_dts_gap = MAX_TIMESTAMP_GAP * max(inv_video_time_base, inv_audio_time_base)",
"if packet.dts is None:\n if self._missing_dts >= MAX_MISSING_DTS:\n raise StreamWorkerError(f'No dts i... | <|body_start_0|>
self._last_dts: dict[av.stream.Stream, int | float] = defaultdict(lambda: NEGATIVE_INF)
self._missing_dts = 0
self._max_dts_gap = MAX_TIMESTAMP_GAP * max(inv_video_time_base, inv_audio_time_base)
<|end_body_0|>
<|body_start_1|>
if packet.dts is None:
if self... | Validate ordering of timestamps for packets in a stream. | TimestampValidator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimestampValidator:
"""Validate ordering of timestamps for packets in a stream."""
def __init__(self, inv_video_time_base: int, inv_audio_time_base: int) -> None:
"""Initialize the TimestampValidator."""
<|body_0|>
def is_valid(self, packet: av.Packet) -> bool:
"... | stack_v2_sparse_classes_36k_train_023634 | 26,217 | permissive | [
{
"docstring": "Initialize the TimestampValidator.",
"name": "__init__",
"signature": "def __init__(self, inv_video_time_base: int, inv_audio_time_base: int) -> None"
},
{
"docstring": "Validate the packet timestamp based on ordering within the stream.",
"name": "is_valid",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_011704 | Implement the Python class `TimestampValidator` described below.
Class description:
Validate ordering of timestamps for packets in a stream.
Method signatures and docstrings:
- def __init__(self, inv_video_time_base: int, inv_audio_time_base: int) -> None: Initialize the TimestampValidator.
- def is_valid(self, packe... | Implement the Python class `TimestampValidator` described below.
Class description:
Validate ordering of timestamps for packets in a stream.
Method signatures and docstrings:
- def __init__(self, inv_video_time_base: int, inv_audio_time_base: int) -> None: Initialize the TimestampValidator.
- def is_valid(self, packe... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class TimestampValidator:
"""Validate ordering of timestamps for packets in a stream."""
def __init__(self, inv_video_time_base: int, inv_audio_time_base: int) -> None:
"""Initialize the TimestampValidator."""
<|body_0|>
def is_valid(self, packet: av.Packet) -> bool:
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimestampValidator:
"""Validate ordering of timestamps for packets in a stream."""
def __init__(self, inv_video_time_base: int, inv_audio_time_base: int) -> None:
"""Initialize the TimestampValidator."""
self._last_dts: dict[av.stream.Stream, int | float] = defaultdict(lambda: NEGATIVE_IN... | the_stack_v2_python_sparse | homeassistant/components/stream/worker.py | home-assistant/core | train | 35,501 |
c2533d5c468ab00d0283d2a9d16863fa737622e9 | [
"th = 10\ned = EnergyDecision(th)\nself.assertEqual(th, ed.threshold)",
"global signal\nth = 0.8\nwd = WaveformDecision(th)\nself.assertEqual(th, wd.threshold)\narr = [1] * 1024\ndec = wd.decision(np.array(arr))\ndec = (0, 0)\nself.assertEqual((0, 0.0), dec)",
"in_th = 10\nmin_th = 1\nmax_th = 20\nk = 1\ndelta_... | <|body_start_0|>
th = 10
ed = EnergyDecision(th)
self.assertEqual(th, ed.threshold)
<|end_body_0|>
<|body_start_1|>
global signal
th = 0.8
wd = WaveformDecision(th)
self.assertEqual(th, wd.threshold)
arr = [1] * 1024
dec = wd.decision(np.array(arr... | Test algorithm module. | QaDecision | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QaDecision:
"""Test algorithm module."""
def test_ed_001(self):
"""Test EnergyDecision threshold."""
<|body_0|>
def test_ed_002(self):
"""Test Waveform threshold."""
<|body_1|>
def test_bayes_001(self):
"""Test BayesLearningThreshold basic pa... | stack_v2_sparse_classes_36k_train_023635 | 3,293 | permissive | [
{
"docstring": "Test EnergyDecision threshold.",
"name": "test_ed_001",
"signature": "def test_ed_001(self)"
},
{
"docstring": "Test Waveform threshold.",
"name": "test_ed_002",
"signature": "def test_ed_002(self)"
},
{
"docstring": "Test BayesLearningThreshold basic parameters."... | 4 | null | Implement the Python class `QaDecision` described below.
Class description:
Test algorithm module.
Method signatures and docstrings:
- def test_ed_001(self): Test EnergyDecision threshold.
- def test_ed_002(self): Test Waveform threshold.
- def test_bayes_001(self): Test BayesLearningThreshold basic parameters.
- def... | Implement the Python class `QaDecision` described below.
Class description:
Test algorithm module.
Method signatures and docstrings:
- def test_ed_001(self): Test EnergyDecision threshold.
- def test_ed_002(self): Test Waveform threshold.
- def test_bayes_001(self): Test BayesLearningThreshold basic parameters.
- def... | aafc0e93a81da86f414743b6b19ff4739045763a | <|skeleton|>
class QaDecision:
"""Test algorithm module."""
def test_ed_001(self):
"""Test EnergyDecision threshold."""
<|body_0|>
def test_ed_002(self):
"""Test Waveform threshold."""
<|body_1|>
def test_bayes_001(self):
"""Test BayesLearningThreshold basic pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QaDecision:
"""Test algorithm module."""
def test_ed_001(self):
"""Test EnergyDecision threshold."""
th = 10
ed = EnergyDecision(th)
self.assertEqual(th, ed.threshold)
def test_ed_002(self):
"""Test Waveform threshold."""
global signal
th = 0.8... | the_stack_v2_python_sparse | python/sensing/qa_test.py | ComputerNetworks-UFRGS/OpERA | train | 3 |
011c3a8810414fd1a8bb0017dbd26865ee2990c4 | [
"self.name = name\nself.year = year\nif artist is None:\n self.artist = 'Various Artists'\nelse:\n self.artist = artist\nself.tracks = []",
"song_found = find_object(song, self.tracks)\nif song_found is None:\n song_found = Song(self, self.artist)\n if position is None:\n self.tracks.append(son... | <|body_start_0|>
self.name = name
self.year = year
if artist is None:
self.artist = 'Various Artists'
else:
self.artist = artist
self.tracks = []
<|end_body_0|>
<|body_start_1|>
song_found = find_object(song, self.tracks)
if song_found is ... | Class to represent an album using it's tracklist. Attrbutes: name (str): The name of the album. year (int): Release year. artist (str): The name of the artist who made the album. Default to "Various Artists" tracks (List[song]): A list of the songs on the album Methods: add_song: Add song to track list. | Album | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Album:
"""Class to represent an album using it's tracklist. Attrbutes: name (str): The name of the album. year (int): Release year. artist (str): The name of the artist who made the album. Default to "Various Artists" tracks (List[song]): A list of the songs on the album Methods: add_song: Add so... | stack_v2_sparse_classes_36k_train_023636 | 4,693 | no_license | [
{
"docstring": "Initialize attributes.",
"name": "__init__",
"signature": "def __init__(self, name, year, artist=None)"
},
{
"docstring": "Add song to track list. Arguments: song (Song): The title of the song to add. position (int) [optional]: Position to add track to, default will add to end.",... | 2 | null | Implement the Python class `Album` described below.
Class description:
Class to represent an album using it's tracklist. Attrbutes: name (str): The name of the album. year (int): Release year. artist (str): The name of the artist who made the album. Default to "Various Artists" tracks (List[song]): A list of the songs... | Implement the Python class `Album` described below.
Class description:
Class to represent an album using it's tracklist. Attrbutes: name (str): The name of the album. year (int): Release year. artist (str): The name of the artist who made the album. Default to "Various Artists" tracks (List[song]): A list of the songs... | a5eb6ead483da2fc895d169e5ed8ba1e79c2d061 | <|skeleton|>
class Album:
"""Class to represent an album using it's tracklist. Attrbutes: name (str): The name of the album. year (int): Release year. artist (str): The name of the artist who made the album. Default to "Various Artists" tracks (List[song]): A list of the songs on the album Methods: add_song: Add so... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Album:
"""Class to represent an album using it's tracklist. Attrbutes: name (str): The name of the album. year (int): Release year. artist (str): The name of the artist who made the album. Default to "Various Artists" tracks (List[song]): A list of the songs on the album Methods: add_song: Add song to track l... | the_stack_v2_python_sparse | 12: Object Oriented Programming/song.py | ntkawasaki/complete-python-masterclass | train | 0 |
6e3f40715f8a6cd83d41f632df9abf2f9f5acd03 | [
"self.player = player1\nself.hits = player1.hits\nself.misses = player1.misses\nself.print_accuracy()",
"total = self.hits + self.misses\nprint(responses[21])\nprint(responses[18] % (self.hits / total * 100, total))\nif Save_Accuracy:\n with open('score_data.txt', 'a') as file:\n file.write('\\n%s' % st... | <|body_start_0|>
self.player = player1
self.hits = player1.hits
self.misses = player1.misses
self.print_accuracy()
<|end_body_0|>
<|body_start_1|>
total = self.hits + self.misses
print(responses[21])
print(responses[18] % (self.hits / total * 100, total))
... | This Class Exception is used for flow control and to display data when called. | GameWin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameWin:
"""This Class Exception is used for flow control and to display data when called."""
def __init__(self, player1):
"""The __init__ computes a players accuracy and displays it. :param player1:"""
<|body_0|>
def print_accuracy(self):
"""This function is use... | stack_v2_sparse_classes_36k_train_023637 | 29,261 | permissive | [
{
"docstring": "The __init__ computes a players accuracy and displays it. :param player1:",
"name": "__init__",
"signature": "def __init__(self, player1)"
},
{
"docstring": "This function is used to computer and display player accuracy.",
"name": "print_accuracy",
"signature": "def print... | 2 | stack_v2_sparse_classes_30k_train_007217 | Implement the Python class `GameWin` described below.
Class description:
This Class Exception is used for flow control and to display data when called.
Method signatures and docstrings:
- def __init__(self, player1): The __init__ computes a players accuracy and displays it. :param player1:
- def print_accuracy(self):... | Implement the Python class `GameWin` described below.
Class description:
This Class Exception is used for flow control and to display data when called.
Method signatures and docstrings:
- def __init__(self, player1): The __init__ computes a players accuracy and displays it. :param player1:
- def print_accuracy(self):... | 2b6e173bf739bda2926bf3d4a300d9a36cb9b85c | <|skeleton|>
class GameWin:
"""This Class Exception is used for flow control and to display data when called."""
def __init__(self, player1):
"""The __init__ computes a players accuracy and displays it. :param player1:"""
<|body_0|>
def print_accuracy(self):
"""This function is use... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameWin:
"""This Class Exception is used for flow control and to display data when called."""
def __init__(self, player1):
"""The __init__ computes a players accuracy and displays it. :param player1:"""
self.player = player1
self.hits = player1.hits
self.misses = player1.m... | the_stack_v2_python_sparse | Old/Other_Scripts/Battleship_new_ai_0_9_7_wcomments.py | zeziba/Battleship_revisited | train | 0 |
b94b0d8ca71f2b118e6a0fac5e411a128b329a6f | [
"def helper(pre, l, r) -> List[str]:\n \"\"\"Helper function\n :param l: Number of left parenthesis that can be used.\n :param r: Number of right parenthesis that can be used.\n \"\"\"\n if l == 0 and r == 0:\n return [pre]\n output = []\n if l > 0:\n outpu... | <|body_start_0|>
def helper(pre, l, r) -> List[str]:
"""Helper function
:param l: Number of left parenthesis that can be used.
:param r: Number of right parenthesis that can be used.
"""
if l == 0 and r == 0:
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis_v1(self, n: int) -> List[str]:
"""Helper return a list."""
<|body_0|>
def generateParenthesis_v2(self, n: int) -> List[str]:
"""Pass the output list to the helper."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def... | stack_v2_sparse_classes_36k_train_023638 | 1,877 | no_license | [
{
"docstring": "Helper return a list.",
"name": "generateParenthesis_v1",
"signature": "def generateParenthesis_v1(self, n: int) -> List[str]"
},
{
"docstring": "Pass the output list to the helper.",
"name": "generateParenthesis_v2",
"signature": "def generateParenthesis_v2(self, n: int)... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis_v1(self, n: int) -> List[str]: Helper return a list.
- def generateParenthesis_v2(self, n: int) -> List[str]: Pass the output list to the helper. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis_v1(self, n: int) -> List[str]: Helper return a list.
- def generateParenthesis_v2(self, n: int) -> List[str]: Pass the output list to the helper.
<|skele... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def generateParenthesis_v1(self, n: int) -> List[str]:
"""Helper return a list."""
<|body_0|>
def generateParenthesis_v2(self, n: int) -> List[str]:
"""Pass the output list to the helper."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def generateParenthesis_v1(self, n: int) -> List[str]:
"""Helper return a list."""
def helper(pre, l, r) -> List[str]:
"""Helper function
:param l: Number of left parenthesis that can be used.
:param r: Number of right parenthesis t... | the_stack_v2_python_sparse | python3/recursion/generat_parentheses.py | victorchu/algorithms | train | 0 | |
c1a29de6fd66c2073a3ac859d258884fa76ebbd0 | [
"with open(file_name, 'r') as content_file:\n content = content_file.read()\nself.content = json.loads(content)",
"r = random.randint(0, len(self.content) - 1)\nc = self.content[r]\nreturn (c['rgb'][0], c['rgb'][1], c['rgb'][2])",
"for c in self.content:\n if c['name'] == name:\n return (c['rgb'][0... | <|body_start_0|>
with open(file_name, 'r') as content_file:
content = content_file.read()
self.content = json.loads(content)
<|end_body_0|>
<|body_start_1|>
r = random.randint(0, len(self.content) - 1)
c = self.content[r]
return (c['rgb'][0], c['rgb'][1], c['rgb'][2]... | Opens a json file of web colors, and loads it into dictionary, to return an rgb of a random color or given one. Attributes: get_random_color: Returns a random rgb tuple from the color dictionary. get_rgb: Returns a named rgb tuple from the color dictionary. | Colors | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Colors:
"""Opens a json file of web colors, and loads it into dictionary, to return an rgb of a random color or given one. Attributes: get_random_color: Returns a random rgb tuple from the color dictionary. get_rgb: Returns a named rgb tuple from the color dictionary."""
def __init__(self, f... | stack_v2_sparse_classes_36k_train_023639 | 6,905 | no_license | [
{
"docstring": "Opens a json file of web colors, and loads it into dictionary.",
"name": "__init__",
"signature": "def __init__(self, file_name=DIRPATH + '/Json_Files/colors.json')"
},
{
"docstring": "Returns a random rgb tuple from the color dictionary Args: None Returns: color (tuple) : (r,g,b... | 3 | stack_v2_sparse_classes_30k_train_004846 | Implement the Python class `Colors` described below.
Class description:
Opens a json file of web colors, and loads it into dictionary, to return an rgb of a random color or given one. Attributes: get_random_color: Returns a random rgb tuple from the color dictionary. get_rgb: Returns a named rgb tuple from the color d... | Implement the Python class `Colors` described below.
Class description:
Opens a json file of web colors, and loads it into dictionary, to return an rgb of a random color or given one. Attributes: get_random_color: Returns a random rgb tuple from the color dictionary. get_rgb: Returns a named rgb tuple from the color d... | 76bba6ed5d95f1d24f1ba6ab18d625222365a4f3 | <|skeleton|>
class Colors:
"""Opens a json file of web colors, and loads it into dictionary, to return an rgb of a random color or given one. Attributes: get_random_color: Returns a random rgb tuple from the color dictionary. get_rgb: Returns a named rgb tuple from the color dictionary."""
def __init__(self, f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Colors:
"""Opens a json file of web colors, and loads it into dictionary, to return an rgb of a random color or given one. Attributes: get_random_color: Returns a random rgb tuple from the color dictionary. get_rgb: Returns a named rgb tuple from the color dictionary."""
def __init__(self, file_name=DIRP... | the_stack_v2_python_sparse | Assignments/Program_2/main.py | 13OT/Spatial-DS-Alathel | train | 0 |
9f4e2099a8b13414d090f12e6d2869d363cc8ccf | [
"if not isinstance(organization_id, str) or not bool(organization_id.strip()):\n message: str = 'organization_id cannot be Null'\n raise InputError(status=error_codes.input_error_code, description=message)\nif not isinstance(plan_id, str) or not bool(plan_id.strip()):\n message: str = 'plan_id cannot be Nu... | <|body_start_0|>
if not isinstance(organization_id, str) or not bool(organization_id.strip()):
message: str = 'organization_id cannot be Null'
raise InputError(status=error_codes.input_error_code, description=message)
if not isinstance(plan_id, str) or not bool(plan_id.strip()):
... | **Class PlanValidators** validating and authenticating calls to MembershipPlans Database | PlanValidators | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlanValidators:
"""**Class PlanValidators** validating and authenticating calls to MembershipPlans Database"""
def plan_exist(organization_id: str, plan_id: str) -> Optional[bool]:
"""**plan_exist** checks if plan exist using plan_id if this is the case the returns True else False ra... | stack_v2_sparse_classes_36k_train_023640 | 27,330 | permissive | [
{
"docstring": "**plan_exist** checks if plan exist using plan_id if this is the case the returns True else False raises InputError or TypeError in case of an invalid input :param organization_id: unique organization id :param plan_id: unique plan_id :return: True if plan exist or False Otherwise",
"name": ... | 4 | null | Implement the Python class `PlanValidators` described below.
Class description:
**Class PlanValidators** validating and authenticating calls to MembershipPlans Database
Method signatures and docstrings:
- def plan_exist(organization_id: str, plan_id: str) -> Optional[bool]: **plan_exist** checks if plan exist using p... | Implement the Python class `PlanValidators` described below.
Class description:
**Class PlanValidators** validating and authenticating calls to MembershipPlans Database
Method signatures and docstrings:
- def plan_exist(organization_id: str, plan_id: str) -> Optional[bool]: **plan_exist** checks if plan exist using p... | e8cf1df3f061c9745977e207568ffed2abdc70fc | <|skeleton|>
class PlanValidators:
"""**Class PlanValidators** validating and authenticating calls to MembershipPlans Database"""
def plan_exist(organization_id: str, plan_id: str) -> Optional[bool]:
"""**plan_exist** checks if plan exist using plan_id if this is the case the returns True else False ra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlanValidators:
"""**Class PlanValidators** validating and authenticating calls to MembershipPlans Database"""
def plan_exist(organization_id: str, plan_id: str) -> Optional[bool]:
"""**plan_exist** checks if plan exist using plan_id if this is the case the returns True else False raises InputErr... | the_stack_v2_python_sparse | database/memberships.py | saaiiravi/membership_and_affiliate_api | train | 0 |
ba3b1dbe2bade3fa8b036169389243f1e909a952 | [
"import green\ngrb, gr = green.green_renormalization(self.intra, self.inter, error=error, energy=energy, delta=delta)\nreturn gr",
"gr = self.get_green(energy, error=error, delta=delta)\nt = self.coupling\nselfenergy = t.H * gr * t\nreturn selfenergy"
] | <|body_start_0|>
import green
grb, gr = green.green_renormalization(self.intra, self.inter, error=error, energy=energy, delta=delta)
return gr
<|end_body_0|>
<|body_start_1|>
gr = self.get_green(energy, error=error, delta=delta)
t = self.coupling
selfenergy = t.H * gr * ... | Class for a lead | Lead | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lead:
"""Class for a lead"""
def get_green(self, energy, error=1e-05, delta=1e-05):
"""Get surface green function"""
<|body_0|>
def get_selfenergy(self, energy, error=0.0001, delta=0.0001):
"""Get selfenergy"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_023641 | 4,419 | no_license | [
{
"docstring": "Get surface green function",
"name": "get_green",
"signature": "def get_green(self, energy, error=1e-05, delta=1e-05)"
},
{
"docstring": "Get selfenergy",
"name": "get_selfenergy",
"signature": "def get_selfenergy(self, energy, error=0.0001, delta=0.0001)"
}
] | 2 | null | Implement the Python class `Lead` described below.
Class description:
Class for a lead
Method signatures and docstrings:
- def get_green(self, energy, error=1e-05, delta=1e-05): Get surface green function
- def get_selfenergy(self, energy, error=0.0001, delta=0.0001): Get selfenergy | Implement the Python class `Lead` described below.
Class description:
Class for a lead
Method signatures and docstrings:
- def get_green(self, energy, error=1e-05, delta=1e-05): Get surface green function
- def get_selfenergy(self, energy, error=0.0001, delta=0.0001): Get selfenergy
<|skeleton|>
class Lead:
"""C... | 50deb0e59fffe4031f05094572552ca5be59e741 | <|skeleton|>
class Lead:
"""Class for a lead"""
def get_green(self, energy, error=1e-05, delta=1e-05):
"""Get surface green function"""
<|body_0|>
def get_selfenergy(self, energy, error=0.0001, delta=0.0001):
"""Get selfenergy"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lead:
"""Class for a lead"""
def get_green(self, energy, error=1e-05, delta=1e-05):
"""Get surface green function"""
import green
grb, gr = green.green_renormalization(self.intra, self.inter, error=error, energy=energy, delta=delta)
return gr
def get_selfenergy(self, ... | the_stack_v2_python_sparse | development/pysrc/multiterminal.py | Huaguiyuan/quantum-honeycomp | train | 1 |
3e8f8782fbbda973bff4a17a604581968c45578a | [
"if n in cache_dict:\n return cache_dict[n]\nif 0 <= n <= 1:\n return 1\nif n > 1:\n total = self.climbStairs(n - 1) + self.climbStairs(n - 2)\n if n not in cache_dict:\n cache_dict[n] = total\n return total",
"last_one_step = 2\nlast_two_step = 1\nif n == 1:\n return last_two_step\nif n ... | <|body_start_0|>
if n in cache_dict:
return cache_dict[n]
if 0 <= n <= 1:
return 1
if n > 1:
total = self.climbStairs(n - 1) + self.climbStairs(n - 2)
if n not in cache_dict:
cache_dict[n] = total
return total
<|end_body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs1(self, n: int) -> int:
"""递归 :param n: :return:"""
<|body_0|>
def climbStairs(self, n: int) -> int:
"""动态规划 :param n: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n in cache_dict:
return cache_dic... | stack_v2_sparse_classes_36k_train_023642 | 2,371 | no_license | [
{
"docstring": "递归 :param n: :return:",
"name": "climbStairs1",
"signature": "def climbStairs1(self, n: int) -> int"
},
{
"docstring": "动态规划 :param n: :return:",
"name": "climbStairs",
"signature": "def climbStairs(self, n: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_017016 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs1(self, n: int) -> int: 递归 :param n: :return:
- def climbStairs(self, n: int) -> int: 动态规划 :param n: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs1(self, n: int) -> int: 递归 :param n: :return:
- def climbStairs(self, n: int) -> int: 动态规划 :param n: :return:
<|skeleton|>
class Solution:
def climbStairs1(s... | bbcb7c3c9aa51141695d73b90bf8f04c794be131 | <|skeleton|>
class Solution:
def climbStairs1(self, n: int) -> int:
"""递归 :param n: :return:"""
<|body_0|>
def climbStairs(self, n: int) -> int:
"""动态规划 :param n: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def climbStairs1(self, n: int) -> int:
"""递归 :param n: :return:"""
if n in cache_dict:
return cache_dict[n]
if 0 <= n <= 1:
return 1
if n > 1:
total = self.climbStairs(n - 1) + self.climbStairs(n - 2)
if n not in cache_d... | the_stack_v2_python_sparse | 00001_00100/00070_爬楼梯.py | xiphodon/leetcode_studio | train | 1 | |
5c14c0d7e7dcde930f9e07dc59851e44684e558d | [
"url = utils.urljoin(self.base_path, 'users', user.id, 'roles', role.id)\nresp = session.put(url)\nif resp.status_code == 204:\n return True\nreturn False",
"url = utils.urljoin(self.base_path, 'users', user.id, 'roles', role.id)\nresp = session.head(url)\nif resp.status_code == 204:\n return True\nreturn F... | <|body_start_0|>
url = utils.urljoin(self.base_path, 'users', user.id, 'roles', role.id)
resp = session.put(url)
if resp.status_code == 204:
return True
return False
<|end_body_0|>
<|body_start_1|>
url = utils.urljoin(self.base_path, 'users', user.id, 'roles', role.i... | System | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class System:
def assign_role_to_user(self, session, user, role):
"""Assign role to user on system"""
<|body_0|>
def validate_user_has_role(self, session, user, role):
"""Validates that a user has a role on a system"""
<|body_1|>
def unassign_role_from_user(se... | stack_v2_sparse_classes_36k_train_023643 | 2,771 | permissive | [
{
"docstring": "Assign role to user on system",
"name": "assign_role_to_user",
"signature": "def assign_role_to_user(self, session, user, role)"
},
{
"docstring": "Validates that a user has a role on a system",
"name": "validate_user_has_role",
"signature": "def validate_user_has_role(se... | 6 | null | Implement the Python class `System` described below.
Class description:
Implement the System class.
Method signatures and docstrings:
- def assign_role_to_user(self, session, user, role): Assign role to user on system
- def validate_user_has_role(self, session, user, role): Validates that a user has a role on a syste... | Implement the Python class `System` described below.
Class description:
Implement the System class.
Method signatures and docstrings:
- def assign_role_to_user(self, session, user, role): Assign role to user on system
- def validate_user_has_role(self, session, user, role): Validates that a user has a role on a syste... | d474eb84c605c429bb9cccb166cabbdd1654d73c | <|skeleton|>
class System:
def assign_role_to_user(self, session, user, role):
"""Assign role to user on system"""
<|body_0|>
def validate_user_has_role(self, session, user, role):
"""Validates that a user has a role on a system"""
<|body_1|>
def unassign_role_from_user(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class System:
def assign_role_to_user(self, session, user, role):
"""Assign role to user on system"""
url = utils.urljoin(self.base_path, 'users', user.id, 'roles', role.id)
resp = session.put(url)
if resp.status_code == 204:
return True
return False
def vali... | the_stack_v2_python_sparse | openstack/identity/v3/system.py | openstack/openstacksdk | train | 124 | |
3d0c8af1ebfe88c84ea3b13cda8ae5505f594ead | [
"payment_method = self.data.get('req_payment_method')\nif payment_method == 'card':\n card_type = self.data.get('req_card_type')\n card_type_description = CARD_TYPES.get(card_type, '')\n card_number = self.data.get('req_card_number', '')\n return f'{card_type_description} | {card_number}'\nelif payment_... | <|body_start_0|>
payment_method = self.data.get('req_payment_method')
if payment_method == 'card':
card_type = self.data.get('req_card_type')
card_type_description = CARD_TYPES.get(card_type, '')
card_number = self.data.get('req_card_number', '')
return f'... | The contents of the message from CyberSource about an Order fulfillment or cancellation | Receipt | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Receipt:
"""The contents of the message from CyberSource about an Order fulfillment or cancellation"""
def payment_method(self):
"""Try to guess the payment source based on the Cybersource receipt"""
<|body_0|>
def __str__(self):
"""Description of Receipt"""
... | stack_v2_sparse_classes_36k_train_023644 | 6,187 | permissive | [
{
"docstring": "Try to guess the payment source based on the Cybersource receipt",
"name": "payment_method",
"signature": "def payment_method(self)"
},
{
"docstring": "Description of Receipt",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008845 | Implement the Python class `Receipt` described below.
Class description:
The contents of the message from CyberSource about an Order fulfillment or cancellation
Method signatures and docstrings:
- def payment_method(self): Try to guess the payment source based on the Cybersource receipt
- def __str__(self): Descripti... | Implement the Python class `Receipt` described below.
Class description:
The contents of the message from CyberSource about an Order fulfillment or cancellation
Method signatures and docstrings:
- def payment_method(self): Try to guess the payment source based on the Cybersource receipt
- def __str__(self): Descripti... | 339c67b84b661a37ffe32580da72383d95666c5c | <|skeleton|>
class Receipt:
"""The contents of the message from CyberSource about an Order fulfillment or cancellation"""
def payment_method(self):
"""Try to guess the payment source based on the Cybersource receipt"""
<|body_0|>
def __str__(self):
"""Description of Receipt"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Receipt:
"""The contents of the message from CyberSource about an Order fulfillment or cancellation"""
def payment_method(self):
"""Try to guess the payment source based on the Cybersource receipt"""
payment_method = self.data.get('req_payment_method')
if payment_method == 'card':... | the_stack_v2_python_sparse | ecommerce/models.py | mitodl/bootcamp-ecommerce | train | 6 |
0e2229b616d9f49e9080b271842340ed4c456852 | [
"b = x.max(axis=1, keepdims=True)\ny = np.exp(x - b)\nout = y / y.sum(axis=1, keepdims=True)\nself.out = out\nreturn out",
"x = self.out\nbatch, features = x.shape\nidxs = np.arange(features)\nshape = (batch, features, features)\ndiagonal = np.zeros(shape)\ndiagonal[:, idxs, idxs] = x\ndxdtx = diagonal - np.einsu... | <|body_start_0|>
b = x.max(axis=1, keepdims=True)
y = np.exp(x - b)
out = y / y.sum(axis=1, keepdims=True)
self.out = out
return out
<|end_body_0|>
<|body_start_1|>
x = self.out
batch, features = x.shape
idxs = np.arange(features)
shape = (batch, ... | Softmax activation module. | SoftMaxModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftMaxModule:
"""Softmax activation module."""
def forward(self, x):
"""Forward pass. Args: x: input to the module Returns: out: output of the module"""
<|body_0|>
def backward(self, dout):
"""Backward pass. Args: dout: gradients of the previous modul Returns: d... | stack_v2_sparse_classes_36k_train_023645 | 5,181 | no_license | [
{
"docstring": "Forward pass. Args: x: input to the module Returns: out: output of the module",
"name": "forward",
"signature": "def forward(self, x)"
},
{
"docstring": "Backward pass. Args: dout: gradients of the previous modul Returns: dx: gradients with respect to the input of the module",
... | 2 | stack_v2_sparse_classes_30k_train_003694 | Implement the Python class `SoftMaxModule` described below.
Class description:
Softmax activation module.
Method signatures and docstrings:
- def forward(self, x): Forward pass. Args: x: input to the module Returns: out: output of the module
- def backward(self, dout): Backward pass. Args: dout: gradients of the prev... | Implement the Python class `SoftMaxModule` described below.
Class description:
Softmax activation module.
Method signatures and docstrings:
- def forward(self, x): Forward pass. Args: x: input to the module Returns: out: output of the module
- def backward(self, dout): Backward pass. Args: dout: gradients of the prev... | b2cd0d67337b101f3e204e519625e1aaf3cea43b | <|skeleton|>
class SoftMaxModule:
"""Softmax activation module."""
def forward(self, x):
"""Forward pass. Args: x: input to the module Returns: out: output of the module"""
<|body_0|>
def backward(self, dout):
"""Backward pass. Args: dout: gradients of the previous modul Returns: d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SoftMaxModule:
"""Softmax activation module."""
def forward(self, x):
"""Forward pass. Args: x: input to the module Returns: out: output of the module"""
b = x.max(axis=1, keepdims=True)
y = np.exp(x - b)
out = y / y.sum(axis=1, keepdims=True)
self.out = out
... | the_stack_v2_python_sparse | assignment_1/code/modules.py | Ivan-Yovchev/uvadlc_practicals_2019 | train | 0 |
48966475e1d1fa8435d560a77c1235ed4d73ef1c | [
"super().__init__()\nself.experiment_name = experiment_name\nself.default_rec_name = default_rec_name\nself.train_func = train_func\nself._call_in_subproc = call_in_subproc",
"if isinstance(tasks, dict):\n tasks = [tasks]\nif len(tasks) == 0:\n return []\nif train_func is None:\n train_func = self.train_... | <|body_start_0|>
super().__init__()
self.experiment_name = experiment_name
self.default_rec_name = default_rec_name
self.train_func = train_func
self._call_in_subproc = call_in_subproc
<|end_body_0|>
<|body_start_1|>
if isinstance(tasks, dict):
tasks = [tasks... | Trainer based on (R)ecorder. It will train a list of tasks and return a list of model recorders in a linear way. Assumption: models were defined by `task` and the results will be saved to `Recorder`. | TrainerR | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainerR:
"""Trainer based on (R)ecorder. It will train a list of tasks and return a list of model recorders in a linear way. Assumption: models were defined by `task` and the results will be saved to `Recorder`."""
def __init__(self, experiment_name: Optional[str]=None, train_func: Callable... | stack_v2_sparse_classes_36k_train_023646 | 22,767 | permissive | [
{
"docstring": "Init TrainerR. Args: experiment_name (str, optional): the default name of experiment. train_func (Callable, optional): default training method. Defaults to `task_train`. call_in_subproc (bool): call the process in subprocess to force memory release",
"name": "__init__",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_015871 | Implement the Python class `TrainerR` described below.
Class description:
Trainer based on (R)ecorder. It will train a list of tasks and return a list of model recorders in a linear way. Assumption: models were defined by `task` and the results will be saved to `Recorder`.
Method signatures and docstrings:
- def __in... | Implement the Python class `TrainerR` described below.
Class description:
Trainer based on (R)ecorder. It will train a list of tasks and return a list of model recorders in a linear way. Assumption: models were defined by `task` and the results will be saved to `Recorder`.
Method signatures and docstrings:
- def __in... | 4c30e5827b74bcc45f14cf3ae0c1715459ed09ae | <|skeleton|>
class TrainerR:
"""Trainer based on (R)ecorder. It will train a list of tasks and return a list of model recorders in a linear way. Assumption: models were defined by `task` and the results will be saved to `Recorder`."""
def __init__(self, experiment_name: Optional[str]=None, train_func: Callable... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainerR:
"""Trainer based on (R)ecorder. It will train a list of tasks and return a list of model recorders in a linear way. Assumption: models were defined by `task` and the results will be saved to `Recorder`."""
def __init__(self, experiment_name: Optional[str]=None, train_func: Callable=task_train, ... | the_stack_v2_python_sparse | qlib/model/trainer.py | microsoft/qlib | train | 12,822 |
99ffe5a18e304ef5dcec3ce66075ac2a4bcc82c8 | [
"ans = []\n\ndef f(k, res):\n if k < 0:\n return k\n lst = [str(i + 1) for i in range(n) if str(i + 1) not in res]\n if len(lst) == 0:\n k -= 1\n if k == 0:\n ans.append(''.join(res))\n return k - 1\n return k\n for i in lst:\n k = f(k, res + [i])... | <|body_start_0|>
ans = []
def f(k, res):
if k < 0:
return k
lst = [str(i + 1) for i in range(n) if str(i + 1) not in res]
if len(lst) == 0:
k -= 1
if k == 0:
ans.append(''.join(res))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getPermutation(self, n, k):
""":type n: int :type k: int :rtype: str"""
<|body_0|>
def getPermutation2(self, n, k):
""":type n: int :type k: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = []
def f(k, res... | stack_v2_sparse_classes_36k_train_023647 | 1,285 | no_license | [
{
"docstring": ":type n: int :type k: int :rtype: str",
"name": "getPermutation",
"signature": "def getPermutation(self, n, k)"
},
{
"docstring": ":type n: int :type k: int :rtype: str",
"name": "getPermutation2",
"signature": "def getPermutation2(self, n, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getPermutation(self, n, k): :type n: int :type k: int :rtype: str
- def getPermutation2(self, n, k): :type n: int :type k: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getPermutation(self, n, k): :type n: int :type k: int :rtype: str
- def getPermutation2(self, n, k): :type n: int :type k: int :rtype: str
<|skeleton|>
class Solution:
... | 93cbb01487a61e37159e8bdd4bf40f623e131c19 | <|skeleton|>
class Solution:
def getPermutation(self, n, k):
""":type n: int :type k: int :rtype: str"""
<|body_0|>
def getPermutation2(self, n, k):
""":type n: int :type k: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getPermutation(self, n, k):
""":type n: int :type k: int :rtype: str"""
ans = []
def f(k, res):
if k < 0:
return k
lst = [str(i + 1) for i in range(n) if str(i + 1) not in res]
if len(lst) == 0:
k -= 1
... | the_stack_v2_python_sparse | Leetcode_medium/math/60.py | HenryBalthier/Python-Learning | train | 0 | |
5884c9d06bb9947a11e2247472b18c5c2f5c5815 | [
"global op\nop = 0\nnext = pcs.Field('next_header', 8)\nlen = pcs.Field('length', 8)\ntype = pcs.Field('type', 8)\npcs.Packet.__init__(self, [next, len, type], bytes)",
"global op\nop += 1\notype = pcs.Field('otype' + str(op), 8)\nolen = pcs.Field('olength' + str(op), 8, default=len / 8)\nif len != 0:\n odata ... | <|body_start_0|>
global op
op = 0
next = pcs.Field('next_header', 8)
len = pcs.Field('length', 8)
type = pcs.Field('type', 8)
pcs.Packet.__init__(self, [next, len, type], bytes)
<|end_body_0|>
<|body_start_1|>
global op
op += 1
otype = pcs.Field('... | A class that contains the IPv6 hop-by-hop options extension-headers. | hopopts | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class hopopts:
"""A class that contains the IPv6 hop-by-hop options extension-headers."""
def __init__(self, bytes=None):
"""IPv6 hopbyhop options extension header from RFC 2460"""
<|body_0|>
def option(self, len=0):
"""add option header to the hop-by-hop extension hea... | stack_v2_sparse_classes_36k_train_023648 | 7,919 | no_license | [
{
"docstring": "IPv6 hopbyhop options extension header from RFC 2460",
"name": "__init__",
"signature": "def __init__(self, bytes=None)"
},
{
"docstring": "add option header to the hop-by-hop extension header",
"name": "option",
"signature": "def option(self, len=0)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000066 | Implement the Python class `hopopts` described below.
Class description:
A class that contains the IPv6 hop-by-hop options extension-headers.
Method signatures and docstrings:
- def __init__(self, bytes=None): IPv6 hopbyhop options extension header from RFC 2460
- def option(self, len=0): add option header to the hop... | Implement the Python class `hopopts` described below.
Class description:
A class that contains the IPv6 hop-by-hop options extension-headers.
Method signatures and docstrings:
- def __init__(self, bytes=None): IPv6 hopbyhop options extension header from RFC 2460
- def option(self, len=0): add option header to the hop... | a070a39586b582fbeea72abf12bbfd812955ad81 | <|skeleton|>
class hopopts:
"""A class that contains the IPv6 hop-by-hop options extension-headers."""
def __init__(self, bytes=None):
"""IPv6 hopbyhop options extension header from RFC 2460"""
<|body_0|>
def option(self, len=0):
"""add option header to the hop-by-hop extension hea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class hopopts:
"""A class that contains the IPv6 hop-by-hop options extension-headers."""
def __init__(self, bytes=None):
"""IPv6 hopbyhop options extension header from RFC 2460"""
global op
op = 0
next = pcs.Field('next_header', 8)
len = pcs.Field('length', 8)
t... | the_stack_v2_python_sparse | src/pcs/packets/ipv6.py | bilouro/tcptest | train | 0 |
e26a2843d3a6f3a121b0e217070f5cfa6bddf605 | [
"self.vec2d = vec2d\nself.r = 0\nself.c = 0",
"ret = self.vec2d[self.r][self.c]\nself.c += 1\nreturn ret",
"while self.r < len(self.vec2d):\n if self.c < len(self.vec2d[self.r]):\n return True\n self.r += 1\n self.c = 0\nreturn False"
] | <|body_start_0|>
self.vec2d = vec2d
self.r = 0
self.c = 0
<|end_body_0|>
<|body_start_1|>
ret = self.vec2d[self.r][self.c]
self.c += 1
return ret
<|end_body_1|>
<|body_start_2|>
while self.r < len(self.vec2d):
if self.c < len(self.vec2d[self.r]):
... | Vector2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_023649 | 1,140 | no_license | [
{
"docstring": "Initialize your data structure here. :type vec2d: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, vec2d)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",... | 3 | stack_v2_sparse_classes_30k_train_016968 | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool
<|skeleton|>
class V... | 9190d3d178f1733aa226973757ee7e045b7bab00 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
self.vec2d = vec2d
self.r = 0
self.c = 0
def next(self):
""":rtype: int"""
ret = self.vec2d[self.r][self.c]
self.c += 1
return ret
... | the_stack_v2_python_sparse | Flatten2DVector.py | ellinx/LC-python | train | 1 | |
096573f2bca70e8d3ded0fe79343445a56c6bf05 | [
"if not p and (not q):\n return True\nif not p or not q:\n return False\nif p.val != q.val:\n return False\nreturn self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)",
"if not p and (not q):\n return True\nstack = [p, q]\nwhile stack:\n rgt, lft = (stack.pop(), stack.pop())\n ... | <|body_start_0|>
if not p and (not q):
return True
if not p or not q:
return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
<|end_body_0|>
<|body_start_1|>
if not p and (not q... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
"""Recursion"""
<|body_0|>
def isSameTree(self, p, q):
"""Iteration"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not p and (not q):
return True
if not p or not q:
return Fal... | stack_v2_sparse_classes_36k_train_023650 | 927 | no_license | [
{
"docstring": "Recursion",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
},
{
"docstring": "Iteration",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000884 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): Recursion
- def isSameTree(self, p, q): Iteration | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): Recursion
- def isSameTree(self, p, q): Iteration
<|skeleton|>
class Solution:
def isSameTree(self, p, q):
"""Recursion"""
<|bod... | 1269b05a51e834e620d0adf4c3a10fe1a917b458 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
"""Recursion"""
<|body_0|>
def isSameTree(self, p, q):
"""Iteration"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSameTree(self, p, q):
"""Recursion"""
if not p and (not q):
return True
if not p or not q:
return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
... | the_stack_v2_python_sparse | leetcode/python/same_tree.py | rioshen/Problems | train | 1 | |
c5bf2ddf795239e47efce42fd9be9cd3513c06bd | [
"if not name:\n name = self.GetDefaultName()\nsuper(ResourceCache, self).__init__(name=name, create=create, version=VERSION)",
"path = [config.Paths().cache_dir]\naccount = properties.VALUES.core.account.Get(required=False)\nif account:\n path.append(account)\nfiles.MakeDir(os.path.join(*path))\npath.append... | <|body_start_0|>
if not name:
name = self.GetDefaultName()
super(ResourceCache, self).__init__(name=name, create=create, version=VERSION)
<|end_body_0|>
<|body_start_1|>
path = [config.Paths().cache_dir]
account = properties.VALUES.core.account.Get(required=False)
if... | A resource cache object. | ResourceCache | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceCache:
"""A resource cache object."""
def __init__(self, name=None, create=True):
"""ResourceCache constructor. Args: name: The persistent cache object name. If None then a default name conditioned on the account name is used. <GLOBAL_CONFIG_DIR>/cache/<ACCOUNT>/resource.cach... | stack_v2_sparse_classes_36k_train_023651 | 21,185 | permissive | [
{
"docstring": "ResourceCache constructor. Args: name: The persistent cache object name. If None then a default name conditioned on the account name is used. <GLOBAL_CONFIG_DIR>/cache/<ACCOUNT>/resource.cache create: Create the cache if it doesn't exist if True.",
"name": "__init__",
"signature": "def _... | 2 | stack_v2_sparse_classes_30k_test_000376 | Implement the Python class `ResourceCache` described below.
Class description:
A resource cache object.
Method signatures and docstrings:
- def __init__(self, name=None, create=True): ResourceCache constructor. Args: name: The persistent cache object name. If None then a default name conditioned on the account name i... | Implement the Python class `ResourceCache` described below.
Class description:
A resource cache object.
Method signatures and docstrings:
- def __init__(self, name=None, create=True): ResourceCache constructor. Args: name: The persistent cache object name. If None then a default name conditioned on the account name i... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class ResourceCache:
"""A resource cache object."""
def __init__(self, name=None, create=True):
"""ResourceCache constructor. Args: name: The persistent cache object name. If None then a default name conditioned on the account name is used. <GLOBAL_CONFIG_DIR>/cache/<ACCOUNT>/resource.cach... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourceCache:
"""A resource cache object."""
def __init__(self, name=None, create=True):
"""ResourceCache constructor. Args: name: The persistent cache object name. If None then a default name conditioned on the account name is used. <GLOBAL_CONFIG_DIR>/cache/<ACCOUNT>/resource.cache create: Cre... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/core/cache/resource_cache.py | bopopescu/socialliteapp | train | 0 |
42adfa548cad9d2e0ce89e1696786a04422b0d4d | [
"self.open_ticket_office_manage()\nself.input_ticket_office_add_info(self.add_list, self.info_dict)\nself.click_button_for_one(u'确 定')",
"self.ticket_office_add()\ntips = self.get_tips()\nself.assert_result_equal(u'新增成功', tips, u'兑奖处管理新增')\nsleep(2)\nself.put_away_main_menu()\nself.choose_ticket_province_city(sel... | <|body_start_0|>
self.open_ticket_office_manage()
self.input_ticket_office_add_info(self.add_list, self.info_dict)
self.click_button_for_one(u'确 定')
<|end_body_0|>
<|body_start_1|>
self.ticket_office_add()
tips = self.get_tips()
self.assert_result_equal(u'新增成功', tips, u'... | 彩票兑奖管理(兑奖处理) | TicketOfficeManageTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TicketOfficeManageTest:
"""彩票兑奖管理(兑奖处理)"""
def ticket_office_add(self):
"""统一的新增入口"""
<|body_0|>
def test_ticket_office_manage_add(self):
"""兑奖处管理"""
<|body_1|>
def test_ticket_office_manage_edite(self):
"""兑奖处管理编辑"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_023652 | 3,702 | no_license | [
{
"docstring": "统一的新增入口",
"name": "ticket_office_add",
"signature": "def ticket_office_add(self)"
},
{
"docstring": "兑奖处管理",
"name": "test_ticket_office_manage_add",
"signature": "def test_ticket_office_manage_add(self)"
},
{
"docstring": "兑奖处管理编辑",
"name": "test_ticket_offic... | 5 | null | Implement the Python class `TicketOfficeManageTest` described below.
Class description:
彩票兑奖管理(兑奖处理)
Method signatures and docstrings:
- def ticket_office_add(self): 统一的新增入口
- def test_ticket_office_manage_add(self): 兑奖处管理
- def test_ticket_office_manage_edite(self): 兑奖处管理编辑
- def test_ticket_office_status_cancel(sel... | Implement the Python class `TicketOfficeManageTest` described below.
Class description:
彩票兑奖管理(兑奖处理)
Method signatures and docstrings:
- def ticket_office_add(self): 统一的新增入口
- def test_ticket_office_manage_add(self): 兑奖处管理
- def test_ticket_office_manage_edite(self): 兑奖处管理编辑
- def test_ticket_office_status_cancel(sel... | dcae68955b2857bbfe411145432865c57561c9ef | <|skeleton|>
class TicketOfficeManageTest:
"""彩票兑奖管理(兑奖处理)"""
def ticket_office_add(self):
"""统一的新增入口"""
<|body_0|>
def test_ticket_office_manage_add(self):
"""兑奖处管理"""
<|body_1|>
def test_ticket_office_manage_edite(self):
"""兑奖处管理编辑"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TicketOfficeManageTest:
"""彩票兑奖管理(兑奖处理)"""
def ticket_office_add(self):
"""统一的新增入口"""
self.open_ticket_office_manage()
self.input_ticket_office_add_info(self.add_list, self.info_dict)
self.click_button_for_one(u'确 定')
def test_ticket_office_manage_add(self):
"... | the_stack_v2_python_sparse | genlot_vlt2/cases/BusinessOperation/lottery_manage/ticket_office_manage_test.py | bbwdi/auto | train | 1 |
779b848f20ae8870d56f19c96f83f2297c7dfbd9 | [
"super(DropArea, self).__init__()\nself.itemTypes = itemTypes\nself.yRouterDrop = None\nscene = QtGui.QGraphicsScene(self)\nscene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex)\nself.setScene(scene)\nself.setRenderHint(QtGui.QPainter.Antialiasing)\nself.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse... | <|body_start_0|>
super(DropArea, self).__init__()
self.itemTypes = itemTypes
self.yRouterDrop = None
scene = QtGui.QGraphicsScene(self)
scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex)
self.setScene(scene)
self.setRenderHint(QtGui.QPainter.Antialiasing)
... | DropArea | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DropArea:
def __init__(self, itemTypes):
"""Create a page of dropable nodes."""
<|body_0|>
def refactorLocation(self, location):
"""Resize and reposition nodes based on dock location."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(DropArea, s... | stack_v2_sparse_classes_36k_train_023653 | 3,523 | permissive | [
{
"docstring": "Create a page of dropable nodes.",
"name": "__init__",
"signature": "def __init__(self, itemTypes)"
},
{
"docstring": "Resize and reposition nodes based on dock location.",
"name": "refactorLocation",
"signature": "def refactorLocation(self, location)"
}
] | 2 | null | Implement the Python class `DropArea` described below.
Class description:
Implement the DropArea class.
Method signatures and docstrings:
- def __init__(self, itemTypes): Create a page of dropable nodes.
- def refactorLocation(self, location): Resize and reposition nodes based on dock location. | Implement the Python class `DropArea` described below.
Class description:
Implement the DropArea class.
Method signatures and docstrings:
- def __init__(self, itemTypes): Create a page of dropable nodes.
- def refactorLocation(self, location): Resize and reposition nodes based on dock location.
<|skeleton|>
class Dr... | d095076113c1e84c33f52ef46a3df1f8bc8ffa43 | <|skeleton|>
class DropArea:
def __init__(self, itemTypes):
"""Create a page of dropable nodes."""
<|body_0|>
def refactorLocation(self, location):
"""Resize and reposition nodes based on dock location."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DropArea:
def __init__(self, itemTypes):
"""Create a page of dropable nodes."""
super(DropArea, self).__init__()
self.itemTypes = itemTypes
self.yRouterDrop = None
scene = QtGui.QGraphicsScene(self)
scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex)
... | the_stack_v2_python_sparse | frontend/src/gbuilder/UI/DropBar.py | citelab/gini5 | train | 12 | |
9b433925de3a69053df70c4fa8beb9a285498806 | [
"super().__init__(api, coordinator, name, dev_id, sensor)\nself._icon = None\nself._model = model\nif model is None:\n self._model = sensor_type[SENSOR_MAP_MODEL]\nself._unit_of_measurement = sensor_type[SENSOR_MAP_UOM]\nself._dev_class = sensor_type[SENSOR_MAP_DEVICE_CLASS]\nif dev_id == self._api.gateway_id:\n... | <|body_start_0|>
super().__init__(api, coordinator, name, dev_id, sensor)
self._icon = None
self._model = model
if model is None:
self._model = sensor_type[SENSOR_MAP_MODEL]
self._unit_of_measurement = sensor_type[SENSOR_MAP_UOM]
self._dev_class = sensor_type[... | Power sensor entities. | PwPowerSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PwPowerSensor:
"""Power sensor entities."""
def __init__(self, api, coordinator, name, dev_id, sensor, sensor_type, model):
"""Set up the Plugwise API."""
<|body_0|>
def _async_process_data(self):
"""Update the entity."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_023654 | 11,153 | permissive | [
{
"docstring": "Set up the Plugwise API.",
"name": "__init__",
"signature": "def __init__(self, api, coordinator, name, dev_id, sensor, sensor_type, model)"
},
{
"docstring": "Update the entity.",
"name": "_async_process_data",
"signature": "def _async_process_data(self)"
}
] | 2 | null | Implement the Python class `PwPowerSensor` described below.
Class description:
Power sensor entities.
Method signatures and docstrings:
- def __init__(self, api, coordinator, name, dev_id, sensor, sensor_type, model): Set up the Plugwise API.
- def _async_process_data(self): Update the entity. | Implement the Python class `PwPowerSensor` described below.
Class description:
Power sensor entities.
Method signatures and docstrings:
- def __init__(self, api, coordinator, name, dev_id, sensor, sensor_type, model): Set up the Plugwise API.
- def _async_process_data(self): Update the entity.
<|skeleton|>
class PwP... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class PwPowerSensor:
"""Power sensor entities."""
def __init__(self, api, coordinator, name, dev_id, sensor, sensor_type, model):
"""Set up the Plugwise API."""
<|body_0|>
def _async_process_data(self):
"""Update the entity."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PwPowerSensor:
"""Power sensor entities."""
def __init__(self, api, coordinator, name, dev_id, sensor, sensor_type, model):
"""Set up the Plugwise API."""
super().__init__(api, coordinator, name, dev_id, sensor)
self._icon = None
self._model = model
if model is Non... | the_stack_v2_python_sparse | homeassistant/components/plugwise/sensor.py | BenWoodford/home-assistant | train | 11 |
bf352035591a769e7cfa4416d62b8036336da5c9 | [
"Module.__init__(self, **kwargs)\nself._sources = [sources] if isinstance(sources, str) else sources\nself._publisher = self.add_child_object(publisher, Publisher)\nself._max_ellipticity = max_ellipticity\nself._correct_for_airmass = correct_for_airmass",
"await Module.open(self)\nlog.info('Subscribing to new ima... | <|body_start_0|>
Module.__init__(self, **kwargs)
self._sources = [sources] if isinstance(sources, str) else sources
self._publisher = self.add_child_object(publisher, Publisher)
self._max_ellipticity = max_ellipticity
self._correct_for_airmass = correct_for_airmass
<|end_body_0|>... | Measures seeing on reduced images with a catalog. | Seeing | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Seeing:
"""Measures seeing on reduced images with a catalog."""
def __init__(self, sources: Optional[Union[str, List[str]]]=None, publisher: Optional[Union[Publisher, Dict[str, Any]]]=None, max_ellipticity: float=0.2, correct_for_airmass: bool=True, **kwargs: Any):
"""Creates a new s... | stack_v2_sparse_classes_36k_train_023655 | 3,630 | permissive | [
{
"docstring": "Creates a new seeing estimator. Args: sources: List of sources (e.g. cameras) to process images from or None for all. publisher: Publisher to publish results to. max_ellipticity: Maximum ellipticity for sources to consider. correct_for_zenith: Whether to correct seeing for airmass.",
"name":... | 3 | null | Implement the Python class `Seeing` described below.
Class description:
Measures seeing on reduced images with a catalog.
Method signatures and docstrings:
- def __init__(self, sources: Optional[Union[str, List[str]]]=None, publisher: Optional[Union[Publisher, Dict[str, Any]]]=None, max_ellipticity: float=0.2, correc... | Implement the Python class `Seeing` described below.
Class description:
Measures seeing on reduced images with a catalog.
Method signatures and docstrings:
- def __init__(self, sources: Optional[Union[str, List[str]]]=None, publisher: Optional[Union[Publisher, Dict[str, Any]]]=None, max_ellipticity: float=0.2, correc... | 2d7a06e5485b61b6ca7e51d99b08651ea6021086 | <|skeleton|>
class Seeing:
"""Measures seeing on reduced images with a catalog."""
def __init__(self, sources: Optional[Union[str, List[str]]]=None, publisher: Optional[Union[Publisher, Dict[str, Any]]]=None, max_ellipticity: float=0.2, correct_for_airmass: bool=True, **kwargs: Any):
"""Creates a new s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Seeing:
"""Measures seeing on reduced images with a catalog."""
def __init__(self, sources: Optional[Union[str, List[str]]]=None, publisher: Optional[Union[Publisher, Dict[str, Any]]]=None, max_ellipticity: float=0.2, correct_for_airmass: bool=True, **kwargs: Any):
"""Creates a new seeing estimat... | the_stack_v2_python_sparse | pyobs/modules/image/seeing.py | pyobs/pyobs-core | train | 9 |
cfd7138c712b3a62643e83e1f03453e19bab8b26 | [
"l, r = (0, len(nums))\nwhile l < r:\n m = l + (r - l) // 2\n if nums[m] == target:\n return m\n elif nums[m] < target:\n l = m + 1\n else:\n r = m\nreturn -1",
"l, r = (0, len(nums) - 1)\nwhile l <= r:\n m = l + (r - l) // 2\n if nums[m] == target:\n return m\n el... | <|body_start_0|>
l, r = (0, len(nums))
while l < r:
m = l + (r - l) // 2
if nums[m] == target:
return m
elif nums[m] < target:
l = m + 1
else:
r = m
return -1
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums: List[int], target: int) -> int:
"""Two Pointers Running Time: O(log n) where n is the length of nums."""
<|body_0|>
def search_1(self, nums: List[int], target: int) -> int:
"""Two Pointers Running Time: O(log n) where n is the length ... | stack_v2_sparse_classes_36k_train_023656 | 1,522 | permissive | [
{
"docstring": "Two Pointers Running Time: O(log n) where n is the length of nums.",
"name": "search",
"signature": "def search(self, nums: List[int], target: int) -> int"
},
{
"docstring": "Two Pointers Running Time: O(log n) where n is the length of nums.",
"name": "search_1",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_011937 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums: List[int], target: int) -> int: Two Pointers Running Time: O(log n) where n is the length of nums.
- def search_1(self, nums: List[int], target: int) -> in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums: List[int], target: int) -> int: Two Pointers Running Time: O(log n) where n is the length of nums.
- def search_1(self, nums: List[int], target: int) -> in... | 4a508a982b125a3a90ea893ae70863df7c99cc70 | <|skeleton|>
class Solution:
def search(self, nums: List[int], target: int) -> int:
"""Two Pointers Running Time: O(log n) where n is the length of nums."""
<|body_0|>
def search_1(self, nums: List[int], target: int) -> int:
"""Two Pointers Running Time: O(log n) where n is the length ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def search(self, nums: List[int], target: int) -> int:
"""Two Pointers Running Time: O(log n) where n is the length of nums."""
l, r = (0, len(nums))
while l < r:
m = l + (r - l) // 2
if nums[m] == target:
return m
elif nums... | the_stack_v2_python_sparse | solutions/704_binary_search.py | YiqunPeng/leetcode_pro | train | 0 | |
d2873897107956bd9357ca502e2b4c8461e60388 | [
"self.store = store\nself.db = store.db\nself.querystring = querystring\nself.debug = debug\nself.classfactory = classfactory",
"j = 0\nwhile j < maxtries:\n if self.checkone(objectlist, validator, minrows, maxrows):\n return True\n time.sleep(delay)\n j += 1\nprint('Rerunning failed query with de... | <|body_start_0|>
self.store = store
self.db = store.db
self.querystring = querystring
self.debug = debug
self.classfactory = classfactory
<|end_body_0|>
<|body_start_1|>
j = 0
while j < maxtries:
if self.checkone(objectlist, validator, minrows, maxrow... | This class performs queries and validates that the results meet some specific criteria. This class is a component of our system test tools - not part of the operational software. The general idea is that after a test completes, we can see if it updated the database correctly by running some particular query whose resul... | QueryTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueryTest:
"""This class performs queries and validates that the results meet some specific criteria. This class is a component of our system test tools - not part of the operational software. The general idea is that after a test completes, we can see if it updated the database correctly by runn... | stack_v2_sparse_classes_36k_train_023657 | 8,447 | no_license | [
{
"docstring": "Init function for the QueryTest class The querystring we're given will be given to the string <i>format</i> method along with a set of objects passed in to runandcheck() to create the final query.",
"name": "__init__",
"signature": "def __init__(self, store, querystring, classfactory, de... | 3 | null | Implement the Python class `QueryTest` described below.
Class description:
This class performs queries and validates that the results meet some specific criteria. This class is a component of our system test tools - not part of the operational software. The general idea is that after a test completes, we can see if it... | Implement the Python class `QueryTest` described below.
Class description:
This class performs queries and validates that the results meet some specific criteria. This class is a component of our system test tools - not part of the operational software. The general idea is that after a test completes, we can see if it... | 9ac993317c6501cb1e1cf09025f43dbe1d015035 | <|skeleton|>
class QueryTest:
"""This class performs queries and validates that the results meet some specific criteria. This class is a component of our system test tools - not part of the operational software. The general idea is that after a test completes, we can see if it updated the database correctly by runn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QueryTest:
"""This class performs queries and validates that the results meet some specific criteria. This class is a component of our system test tools - not part of the operational software. The general idea is that after a test completes, we can see if it updated the database correctly by running some part... | the_stack_v2_python_sparse | cma/systemtests/querytest.py | assimilation/assimilation-official | train | 52 |
470a8fd7ad30e7bf35fdec4d8def98577850bf3d | [
"super(AioCommIndicator, self).__init__(label)\nself._message_type = message_type\nif isinstance(aio_nodes, dict):\n self._aio_nodes = aio_nodes\nelif isinstance(aio_nodes, list):\n self._aio_nodes = {x: x for x in aio_nodes}\nelse:\n self._aio_nodes = {aio_nodes: aio_nodes}\nself._normal_if_any = normal_i... | <|body_start_0|>
super(AioCommIndicator, self).__init__(label)
self._message_type = message_type
if isinstance(aio_nodes, dict):
self._aio_nodes = aio_nodes
elif isinstance(aio_nodes, list):
self._aio_nodes = {x: x for x in aio_nodes}
else:
sel... | Base class to check AIO communications. Attributes: _message_type: Short name of the message type. _aio_nodes: Short names of AIO nodes from where messages should be received. | AioCommIndicator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AioCommIndicator:
"""Base class to check AIO communications. Attributes: _message_type: Short name of the message type. _aio_nodes: Short names of AIO nodes from where messages should be received."""
def __init__(self, label, message_type, aio_nodes, normal_if_any=False):
"""Initiali... | stack_v2_sparse_classes_36k_train_023658 | 5,951 | permissive | [
{
"docstring": "Initialize an AIO Update Indicator. Show green if the message is sent from all specified AIO nodes. If only a subset of the AIO nodes are sending the message, show either green or yellow, depending on the value of `normal_if_any`. If none of the nodes is sending the message, show red. Args: labe... | 2 | null | Implement the Python class `AioCommIndicator` described below.
Class description:
Base class to check AIO communications. Attributes: _message_type: Short name of the message type. _aio_nodes: Short names of AIO nodes from where messages should be received.
Method signatures and docstrings:
- def __init__(self, label... | Implement the Python class `AioCommIndicator` described below.
Class description:
Base class to check AIO communications. Attributes: _message_type: Short name of the message type. _aio_nodes: Short names of AIO nodes from where messages should be received.
Method signatures and docstrings:
- def __init__(self, label... | 818ae8b7119b200a28af6b3669a3045f30e0dc64 | <|skeleton|>
class AioCommIndicator:
"""Base class to check AIO communications. Attributes: _message_type: Short name of the message type. _aio_nodes: Short names of AIO nodes from where messages should be received."""
def __init__(self, label, message_type, aio_nodes, normal_if_any=False):
"""Initiali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AioCommIndicator:
"""Base class to check AIO communications. Attributes: _message_type: Short name of the message type. _aio_nodes: Short names of AIO nodes from where messages should be received."""
def __init__(self, label, message_type, aio_nodes, normal_if_any=False):
"""Initialize an AIO Upd... | the_stack_v2_python_sparse | gs/monitor2/apps/plugins/indicators/aio_comms.py | ghomsy/makani | train | 0 |
bc551d4180f53a7862f59f31b9a2248619c167e4 | [
"super(ConsoleWidget, self).__init__('Console', parent)\nself.setAllowedAreas(QtCore.Qt.DockWidgetArea.BottomDockWidgetArea)\nself._initUI()",
"frame = QtGui.QFrame()\nself.setWidget(frame)\nlayout = QtGui.QVBoxLayout()\nframe.setLayout(layout)\nself.console = QtGui.QTextEdit(frame)\nself.console.setReadOnly(True... | <|body_start_0|>
super(ConsoleWidget, self).__init__('Console', parent)
self.setAllowedAreas(QtCore.Qt.DockWidgetArea.BottomDockWidgetArea)
self._initUI()
<|end_body_0|>
<|body_start_1|>
frame = QtGui.QFrame()
self.setWidget(frame)
layout = QtGui.QVBoxLayout()
fr... | A dockable widget to display the command console. | ConsoleWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsoleWidget:
"""A dockable widget to display the command console."""
def __init__(self, parent=None):
"""Create and initialize a ConsoleWidget. Args: parent (QWidget): Parent Qt widget."""
<|body_0|>
def _initUI(self):
"""A private method to setup the UI."""
... | stack_v2_sparse_classes_36k_train_023659 | 1,196 | no_license | [
{
"docstring": "Create and initialize a ConsoleWidget. Args: parent (QWidget): Parent Qt widget.",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "A private method to setup the UI.",
"name": "_initUI",
"signature": "def _initUI(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000049 | Implement the Python class `ConsoleWidget` described below.
Class description:
A dockable widget to display the command console.
Method signatures and docstrings:
- def __init__(self, parent=None): Create and initialize a ConsoleWidget. Args: parent (QWidget): Parent Qt widget.
- def _initUI(self): A private method t... | Implement the Python class `ConsoleWidget` described below.
Class description:
A dockable widget to display the command console.
Method signatures and docstrings:
- def __init__(self, parent=None): Create and initialize a ConsoleWidget. Args: parent (QWidget): Parent Qt widget.
- def _initUI(self): A private method t... | b7f6adf76ab7e52eef585497ffd9ef93d6a0a4e0 | <|skeleton|>
class ConsoleWidget:
"""A dockable widget to display the command console."""
def __init__(self, parent=None):
"""Create and initialize a ConsoleWidget. Args: parent (QWidget): Parent Qt widget."""
<|body_0|>
def _initUI(self):
"""A private method to setup the UI."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConsoleWidget:
"""A dockable widget to display the command console."""
def __init__(self, parent=None):
"""Create and initialize a ConsoleWidget. Args: parent (QWidget): Parent Qt widget."""
super(ConsoleWidget, self).__init__('Console', parent)
self.setAllowedAreas(QtCore.Qt.Dock... | the_stack_v2_python_sparse | BaseStation/Views/ConsoleWidget.py | ISU-MAVRIC/MAVRIC_Controller | train | 0 |
a52986be543427835a02850a35e69985f3b2ec27 | [
"try:\n import puremagic\n return True\nexcept ModuleNotFoundError as ex:\n pass\nreturn False",
"filename = file_check.check_file(filename)\nimport puremagic\ntry:\n rv = puremagic.magic_file(filename)\n if not rv:\n return None\n return clazz._find_mime_type(rv)\nexcept Exception as ex:... | <|body_start_0|>
try:
import puremagic
return True
except ModuleNotFoundError as ex:
pass
return False
<|end_body_0|>
<|body_start_1|>
filename = file_check.check_file(filename)
import puremagic
try:
rv = puremagic.magic_fi... | _file_mime_type_detector_puremagic | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _file_mime_type_detector_puremagic:
def is_supported(clazz):
"""Return True if this class is supported on the current platform."""
<|body_0|>
def detect_mime_type(clazz, filename):
"""Detect the mime type for file."""
<|body_1|>
def _find_mime_type(clazz... | stack_v2_sparse_classes_36k_train_023660 | 1,234 | permissive | [
{
"docstring": "Return True if this class is supported on the current platform.",
"name": "is_supported",
"signature": "def is_supported(clazz)"
},
{
"docstring": "Detect the mime type for file.",
"name": "detect_mime_type",
"signature": "def detect_mime_type(clazz, filename)"
},
{
... | 3 | null | Implement the Python class `_file_mime_type_detector_puremagic` described below.
Class description:
Implement the _file_mime_type_detector_puremagic class.
Method signatures and docstrings:
- def is_supported(clazz): Return True if this class is supported on the current platform.
- def detect_mime_type(clazz, filenam... | Implement the Python class `_file_mime_type_detector_puremagic` described below.
Class description:
Implement the _file_mime_type_detector_puremagic class.
Method signatures and docstrings:
- def is_supported(clazz): Return True if this class is supported on the current platform.
- def detect_mime_type(clazz, filenam... | b9dd35b518848cea82e43d5016e425cc7dac32e5 | <|skeleton|>
class _file_mime_type_detector_puremagic:
def is_supported(clazz):
"""Return True if this class is supported on the current platform."""
<|body_0|>
def detect_mime_type(clazz, filename):
"""Detect the mime type for file."""
<|body_1|>
def _find_mime_type(clazz... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _file_mime_type_detector_puremagic:
def is_supported(clazz):
"""Return True if this class is supported on the current platform."""
try:
import puremagic
return True
except ModuleNotFoundError as ex:
pass
return False
def detect_mime_type... | the_stack_v2_python_sparse | lib/bes/fs/_detail/_file_mime_type_detector_puremagic.py | reconstruir/bes | train | 0 | |
b250b7a81b52dacf26e239f6b832f2c516810265 | [
"email = self.cleaned_data['email']\nsession = orm.sessionmaker()\nusers = session.query(User).filter_by(email=email).all()\nif len(users) == 0:\n raise forms.ValidationError(_(u\"That e-mail address doesn't have an associated user account. Are you sure\\nyou've registered?\"))\nself.users_cache = [u for u in us... | <|body_start_0|>
email = self.cleaned_data['email']
session = orm.sessionmaker()
users = session.query(User).filter_by(email=email).all()
if len(users) == 0:
raise forms.ValidationError(_(u"That e-mail address doesn't have an associated user account. Are you sure\nyou've regi... | PasswordResetForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResetForm:
def clean_email(self):
"""Validates that a user exists with the given e-mail address."""
<|body_0|>
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email... | stack_v2_sparse_classes_36k_train_023661 | 4,569 | no_license | [
{
"docstring": "Validates that a user exists with the given e-mail address.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Generates a one-use only link for resetting password and sends to the user.",
"name": "save",
"signature": "def save(self, domain_o... | 2 | stack_v2_sparse_classes_30k_train_017881 | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that a user exists with the given e-mail address.
- def save(self, domain_override=None, subject_template_name='registration/pa... | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that a user exists with the given e-mail address.
- def save(self, domain_override=None, subject_template_name='registration/pa... | a0327728aeb56cedfd7a350590979252c057655b | <|skeleton|>
class PasswordResetForm:
def clean_email(self):
"""Validates that a user exists with the given e-mail address."""
<|body_0|>
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PasswordResetForm:
def clean_email(self):
"""Validates that a user exists with the given e-mail address."""
email = self.cleaned_data['email']
session = orm.sessionmaker()
users = session.query(User).filter_by(email=email).all()
if len(users) == 0:
raise for... | the_stack_v2_python_sparse | baph/auth/forms.py | devhub/baph | train | 8 | |
3b6edaabf5e2f3c9bcf1fd86bb2a9c65f84a2310 | [
"super(wxToolBarContainer, self).__init__(*args, **kwargs)\nself._tool_bars = []\nself.SetSizer(wx.BoxSizer(wx.VERTICAL))\nself.SetDoubleBuffered(True)",
"tool_bars = self._tool_bars\nif tool_bar not in tool_bars:\n tool_bars.append(tool_bar)\n tool_bar.Reparent(self)\n self.GetSizer().Add(tool_bar, 0, w... | <|body_start_0|>
super(wxToolBarContainer, self).__init__(*args, **kwargs)
self._tool_bars = []
self.SetSizer(wx.BoxSizer(wx.VERTICAL))
self.SetDoubleBuffered(True)
<|end_body_0|>
<|body_start_1|>
tool_bars = self._tool_bars
if tool_bar not in tool_bars:
tool... | A simple wx.Panel that arranges the tool bars for a main window. | wxToolBarContainer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wxToolBarContainer:
"""A simple wx.Panel that arranges the tool bars for a main window."""
def __init__(self, *args, **kwargs):
"""Initialize a wxToolBarContainer. Parameters ---------- *args, **kwargs The positional and keyword arguments to initialize a wx.Panel."""
<|body_0... | stack_v2_sparse_classes_36k_train_023662 | 14,672 | permissive | [
{
"docstring": "Initialize a wxToolBarContainer. Parameters ---------- *args, **kwargs The positional and keyword arguments to initialize a wx.Panel.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Add a tool bar to the container. If the tool bar alrea... | 3 | stack_v2_sparse_classes_30k_train_011494 | Implement the Python class `wxToolBarContainer` described below.
Class description:
A simple wx.Panel that arranges the tool bars for a main window.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize a wxToolBarContainer. Parameters ---------- *args, **kwargs The positional and keywor... | Implement the Python class `wxToolBarContainer` described below.
Class description:
A simple wx.Panel that arranges the tool bars for a main window.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize a wxToolBarContainer. Parameters ---------- *args, **kwargs The positional and keywor... | 15c20b035a73187e8e66fa20a43c3a4372d008bd | <|skeleton|>
class wxToolBarContainer:
"""A simple wx.Panel that arranges the tool bars for a main window."""
def __init__(self, *args, **kwargs):
"""Initialize a wxToolBarContainer. Parameters ---------- *args, **kwargs The positional and keyword arguments to initialize a wx.Panel."""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class wxToolBarContainer:
"""A simple wx.Panel that arranges the tool bars for a main window."""
def __init__(self, *args, **kwargs):
"""Initialize a wxToolBarContainer. Parameters ---------- *args, **kwargs The positional and keyword arguments to initialize a wx.Panel."""
super(wxToolBarContai... | the_stack_v2_python_sparse | enaml/wx/wx_main_window.py | ContinuumIO/enaml | train | 2 |
03ec0f020726295e01791edcdb7fe6a72f38cc03 | [
"self.head = head\nc = head\nlength = 0\nwhile c:\n length += 1\n c = c.next\nself.length = length",
"c = self.head\nrand_index = randrange(0, self.length)\nwhile rand_index:\n c = c.next\n rand_index -= 1\nreturn c.val"
] | <|body_start_0|>
self.head = head
c = head
length = 0
while c:
length += 1
c = c.next
self.length = length
<|end_body_0|>
<|body_start_1|>
c = self.head
rand_index = randrange(0, self.length)
while rand_index:
c = c.nex... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
<|body_0|>
def getRandom(self):
"""Returns a random node's value. :rtype: int"""
... | stack_v2_sparse_classes_36k_train_023663 | 1,038 | no_license | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode",
"name": "__init__",
"signature": "def __init__(self, head)"
},
{
"docstring": "Returns a random node's value. :rtype: int",
"name": "g... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode
- def getRan... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode
- def getRan... | 97533d53c8892b6519e99f344489fa4fd4c9ab93 | <|skeleton|>
class Solution:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
<|body_0|>
def getRandom(self):
"""Returns a random node's value. :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
self.head = head
c = head
length = 0
while c:
length += 1
c = c.... | the_stack_v2_python_sparse | 12. ReserviorSampling/382.py | proTao/leetcode | train | 0 | |
a30dc668ed4919bd8a22cc3bec519de812a774a5 | [
"print('Inside __init__()')\nself.arg1 = arg1\nself.arg2 = arg2\nself.arg3 = arg3",
"print('Inside __call__()')\n\ndef wrapped_f(*args):\n print('Inside wrapped_f()')\n print('Decorator arguments:', self.arg1, self.arg2, self.arg3)\n f(*args)\n print('After f(*args)')\nreturn wrapped_f"
] | <|body_start_0|>
print('Inside __init__()')
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
<|end_body_0|>
<|body_start_1|>
print('Inside __call__()')
def wrapped_f(*args):
print('Inside wrapped_f()')
print('Decorator arguments:', self.arg1, s... | DecoratorWithArguments | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoratorWithArguments:
def __init__(self, arg1, arg2, arg3):
"""If there are decorator arguments, the function to be decorated is not passed to the constructor!"""
<|body_0|>
def __call__(self, f):
"""If there are decorator arguments, __call__() is only called once,... | stack_v2_sparse_classes_36k_train_023664 | 2,861 | no_license | [
{
"docstring": "If there are decorator arguments, the function to be decorated is not passed to the constructor!",
"name": "__init__",
"signature": "def __init__(self, arg1, arg2, arg3)"
},
{
"docstring": "If there are decorator arguments, __call__() is only called once, as part of the decoratio... | 2 | stack_v2_sparse_classes_30k_train_014831 | Implement the Python class `DecoratorWithArguments` described below.
Class description:
Implement the DecoratorWithArguments class.
Method signatures and docstrings:
- def __init__(self, arg1, arg2, arg3): If there are decorator arguments, the function to be decorated is not passed to the constructor!
- def __call__(... | Implement the Python class `DecoratorWithArguments` described below.
Class description:
Implement the DecoratorWithArguments class.
Method signatures and docstrings:
- def __init__(self, arg1, arg2, arg3): If there are decorator arguments, the function to be decorated is not passed to the constructor!
- def __call__(... | d0b821a48a05f0ec28db73351b6e7a07b435b4a5 | <|skeleton|>
class DecoratorWithArguments:
def __init__(self, arg1, arg2, arg3):
"""If there are decorator arguments, the function to be decorated is not passed to the constructor!"""
<|body_0|>
def __call__(self, f):
"""If there are decorator arguments, __call__() is only called once,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoratorWithArguments:
def __init__(self, arg1, arg2, arg3):
"""If there are decorator arguments, the function to be decorated is not passed to the constructor!"""
print('Inside __init__()')
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
def __call__(self, f):... | the_stack_v2_python_sparse | src/main/python/lang/decorator_example.py | solma/com.sma | train | 4 | |
b6e462fae276bc2cfbb8d86c9b3165dff01b1cdf | [
"test = 'abacabaca'\nd = Ling(test)\nself.assertEqual(d.s, 'abacabaca')\nself.assertEqual(Ling(test).calculate(), '3\\naca\\nba\\nca')\ntest = 'abaca'\nself.assertEqual(Ling(test).calculate(), '0')\ntest = 'fffffaafgfg'",
"import random\nimport timeit\ntest = str(nmax) + ' ' + str(nmax) + '\\n'\nnumnums = [str(i)... | <|body_start_0|>
test = 'abacabaca'
d = Ling(test)
self.assertEqual(d.s, 'abacabaca')
self.assertEqual(Ling(test).calculate(), '3\naca\nba\nca')
test = 'abaca'
self.assertEqual(Ling(test).calculate(), '0')
test = 'fffffaafgfg'
<|end_body_0|>
<|body_start_1|>
... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Ling class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = 'abacabaca'
d = Ling(test)
self.assertEqual(d.s, ... | stack_v2_sparse_classes_36k_train_023665 | 3,411 | permissive | [
{
"docstring": "Ling class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010999 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Ling class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Ling class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"""L... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Ling class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class unitTests:
def test_single_test(self):
"""Ling class testing"""
test = 'abacabaca'
d = Ling(test)
self.assertEqual(d.s, 'abacabaca')
self.assertEqual(Ling(test).calculate(), '3\naca\nba\nca')
test = 'abaca'
self.assertEqual(Ling(test).calculate(), '0')
... | the_stack_v2_python_sparse | codeforces/667C_ling.py | snsokolov/contests | train | 1 | |
2bf78e04b1dbf4dd052f9358942a9a23d3c0f141 | [
"self.dn = np.zeros((nsteps, nfrac))\nself.nav = float(natoms) / frac ** 2\nreturn",
"for j in range(nfrac):\n hist, xedges, yedges = np.histogram2d(xs, ys, bins=frac[j], range=[[0, 1], [0, 1]])\n std = np.std(hist)\n self.dn[step, j] = std\nif plot == 'True':\n plt.loglog(self.nav, self.dn[step], mar... | <|body_start_0|>
self.dn = np.zeros((nsteps, nfrac))
self.nav = float(natoms) / frac ** 2
return
<|end_body_0|>
<|body_start_1|>
for j in range(nfrac):
hist, xedges, yedges = np.histogram2d(xs, ys, bins=frac[j], range=[[0, 1], [0, 1]])
std = np.std(hist)
... | NumberFluctuation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumberFluctuation:
def __init__(self, nsteps, natoms, line):
"""initialize: allocate arrays to store results"""
<|body_0|>
def compute(self, step, xs, ys, plot='False'):
"""compute number fluctuations"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023666 | 1,343 | no_license | [
{
"docstring": "initialize: allocate arrays to store results",
"name": "__init__",
"signature": "def __init__(self, nsteps, natoms, line)"
},
{
"docstring": "compute number fluctuations",
"name": "compute",
"signature": "def compute(self, step, xs, ys, plot='False')"
}
] | 2 | null | Implement the Python class `NumberFluctuation` described below.
Class description:
Implement the NumberFluctuation class.
Method signatures and docstrings:
- def __init__(self, nsteps, natoms, line): initialize: allocate arrays to store results
- def compute(self, step, xs, ys, plot='False'): compute number fluctuati... | Implement the Python class `NumberFluctuation` described below.
Class description:
Implement the NumberFluctuation class.
Method signatures and docstrings:
- def __init__(self, nsteps, natoms, line): initialize: allocate arrays to store results
- def compute(self, step, xs, ys, plot='False'): compute number fluctuati... | 7d2659bee85c955c680eda019cbff6e2b93ecff2 | <|skeleton|>
class NumberFluctuation:
def __init__(self, nsteps, natoms, line):
"""initialize: allocate arrays to store results"""
<|body_0|>
def compute(self, step, xs, ys, plot='False'):
"""compute number fluctuations"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumberFluctuation:
def __init__(self, nsteps, natoms, line):
"""initialize: allocate arrays to store results"""
self.dn = np.zeros((nsteps, nfrac))
self.nav = float(natoms) / frac ** 2
return
def compute(self, step, xs, ys, plot='False'):
"""compute number fluctuat... | the_stack_v2_python_sparse | analyse_collective/numberfluctuation.py | melampyge/CollectiveFilament | train | 0 | |
929415e28cd27f08856ade898c069d066e6a7851 | [
"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... | Missing associated documentation comment in .proto file. | BfRuntimeServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BfRuntimeServicer:
"""Missing associated documentation comment in .proto file."""
def Write(self, request, context):
"""Update one or more P4 entities on the target."""
<|body_0|>
def Read(self, request, context):
"""Read one or more P4 entities from the target."... | stack_v2_sparse_classes_36k_train_023667 | 9,014 | permissive | [
{
"docstring": "Update one or more P4 entities on the target.",
"name": "Write",
"signature": "def Write(self, request, context)"
},
{
"docstring": "Read one or more P4 entities from the target.",
"name": "Read",
"signature": "def Read(self, request, context)"
},
{
"docstring": "... | 5 | stack_v2_sparse_classes_30k_train_003276 | Implement the Python class `BfRuntimeServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Write(self, request, context): Update one or more P4 entities on the target.
- def Read(self, request, context): Read one or more P4 entit... | Implement the Python class `BfRuntimeServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Write(self, request, context): Update one or more P4 entities on the target.
- def Read(self, request, context): Read one or more P4 entit... | a9fea4d7e48de05e17b9da14e5c31455a9f00f9d | <|skeleton|>
class BfRuntimeServicer:
"""Missing associated documentation comment in .proto file."""
def Write(self, request, context):
"""Update one or more P4 entities on the target."""
<|body_0|>
def Read(self, request, context):
"""Read one or more P4 entities from the target."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BfRuntimeServicer:
"""Missing associated documentation comment in .proto file."""
def Write(self, request, context):
"""Update one or more P4 entities on the target."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise Not... | the_stack_v2_python_sparse | stamper_targets/Wedge100B65/bfrt_grpc/bfruntime_pb2_grpc.py | ralfkundel/P4STA | train | 27 |
fe822199076e2f754b7545029325ed80aebe53fb | [
"try:\n quiz = Quizzes.objects.get(id=quiz_id)\nexcept DoesNotExist as e:\n return not_found()\nfields = {'id', 'name', 'quizQuestions', 'published'}\nembedded = {'course': {'id': 'course'}}\nconverted = convert_embedded_doc(quiz, fields, embedded)\nreturn jsonify(converted)",
"query = Quizzes.objects.get(i... | <|body_start_0|>
try:
quiz = Quizzes.objects.get(id=quiz_id)
except DoesNotExist as e:
return not_found()
fields = {'id', 'name', 'quizQuestions', 'published'}
embedded = {'course': {'id': 'course'}}
converted = convert_embedded_doc(quiz, fields, embedded)... | Flask-resftul resource for returning db.quiz collection. | QuizApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuizApi:
"""Flask-resftul resource for returning db.quiz collection."""
def get(self, quiz_id: str) -> Response:
"""GET response method for single document in Quizzes collection. :return: JSON object"""
<|body_0|>
def put(self, quiz_id: str) -> Response:
"""PUT r... | stack_v2_sparse_classes_36k_train_023668 | 6,369 | no_license | [
{
"docstring": "GET response method for single document in Quizzes collection. :return: JSON object",
"name": "get",
"signature": "def get(self, quiz_id: str) -> Response"
},
{
"docstring": "PUT response method for updating a quiz. JSON Web Token is required.",
"name": "put",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_003077 | Implement the Python class `QuizApi` described below.
Class description:
Flask-resftul resource for returning db.quiz collection.
Method signatures and docstrings:
- def get(self, quiz_id: str) -> Response: GET response method for single document in Quizzes collection. :return: JSON object
- def put(self, quiz_id: st... | Implement the Python class `QuizApi` described below.
Class description:
Flask-resftul resource for returning db.quiz collection.
Method signatures and docstrings:
- def get(self, quiz_id: str) -> Response: GET response method for single document in Quizzes collection. :return: JSON object
- def put(self, quiz_id: st... | 7f44c736c95866aaf820627ea54d3f00b3ada779 | <|skeleton|>
class QuizApi:
"""Flask-resftul resource for returning db.quiz collection."""
def get(self, quiz_id: str) -> Response:
"""GET response method for single document in Quizzes collection. :return: JSON object"""
<|body_0|>
def put(self, quiz_id: str) -> Response:
"""PUT r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuizApi:
"""Flask-resftul resource for returning db.quiz collection."""
def get(self, quiz_id: str) -> Response:
"""GET response method for single document in Quizzes collection. :return: JSON object"""
try:
quiz = Quizzes.objects.get(id=quiz_id)
except DoesNotExist as... | the_stack_v2_python_sparse | backend/uimpactify/controller/quiz.py | ObaidaSaleh/E-learning-app | train | 1 |
6095fbbff0a049cca5c70e958feacd249bc9f003 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SearchRequest()",
"from .aggregation_option import AggregationOption\nfrom .collapse_property import CollapseProperty\nfrom .entity_type import EntityType\nfrom .result_template_option import ResultTemplateOption\nfrom .search_alterati... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SearchRequest()
<|end_body_0|>
<|body_start_1|>
from .aggregation_option import AggregationOption
from .collapse_property import CollapseProperty
from .entity_type import EntityT... | SearchRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SearchRequest:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k_train_023669 | 10,584 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: SearchRequest",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | null | Implement the Python class `SearchRequest` described below.
Class description:
Implement the SearchRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SearchRequest: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `SearchRequest` described below.
Class description:
Implement the SearchRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SearchRequest: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SearchRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SearchRequest:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SearchRequest:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: SearchReques... | the_stack_v2_python_sparse | msgraph/generated/models/search_request.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
870d845c3f4d1670dc5e4050ae2a98d1e7d833c3 | [
"if len(A) < 3:\n return False\nfor i in range(1, len(A) - 1):\n if all((A[m] > A[m - 1] for m in range(1, i + 1))) and all((A[n] > A[n + 1] for n in range(i, len(A) - 1))):\n return True\nreturn False",
"if len(A) < 3:\n return False\nif A[-1] > A[-2] or A[0] > A[1]:\n return False\nflag = 'gr... | <|body_start_0|>
if len(A) < 3:
return False
for i in range(1, len(A) - 1):
if all((A[m] > A[m - 1] for m in range(1, i + 1))) and all((A[n] > A[n + 1] for n in range(i, len(A) - 1))):
return True
return False
<|end_body_0|>
<|body_start_1|>
if le... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
<|body_0|>
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
<|body_1|>
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
... | stack_v2_sparse_classes_36k_train_023670 | 1,335 | no_license | [
{
"docstring": ":type A: List[int] :rtype: bool",
"name": "validMountainArray",
"signature": "def validMountainArray(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: bool",
"name": "validMountainArray",
"signature": "def validMountainArray(self, A)"
},
{
"docstring": ":typ... | 3 | stack_v2_sparse_classes_30k_train_005482 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validMountainArray(self, A): :type A: List[int] :rtype: bool
- def validMountainArray(self, A): :type A: List[int] :rtype: bool
- def validMountainArray(self, A): :type A: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validMountainArray(self, A): :type A: List[int] :rtype: bool
- def validMountainArray(self, A): :type A: List[int] :rtype: bool
- def validMountainArray(self, A): :type A: Li... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
<|body_0|>
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
<|body_1|>
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
if len(A) < 3:
return False
for i in range(1, len(A) - 1):
if all((A[m] > A[m - 1] for m in range(1, i + 1))) and all((A[n] > A[n + 1] for n in range(i, len(A) - 1))):
... | the_stack_v2_python_sparse | 0941_Valid_Mountain_Array.py | bingli8802/leetcode | train | 0 | |
faaf4636d6f7d0159e7e72cd333bc71cc0a1ab5c | [
"self._grid_size = (grid_width, grid_height)\nself.total_region = Region()\nself._map: defaultdict[GridCoordinate, list[ValueType]] = defaultdict(list)\nself._fixed: list[ValueType] = []",
"x1, y1, width, height = region\nx2 = x1 + width - 1\ny2 = y1 + height - 1\ngrid_width, grid_height = self._grid_size\nreturn... | <|body_start_0|>
self._grid_size = (grid_width, grid_height)
self.total_region = Region()
self._map: defaultdict[GridCoordinate, list[ValueType]] = defaultdict(list)
self._fixed: list[ValueType] = []
<|end_body_0|>
<|body_start_1|>
x1, y1, width, height = region
x2 = x1 ... | A spatial map allows for data to be associated with rectangular regions in Euclidean space, and efficiently queried. When the SpatialMap is populated, a reference to each value is placed into one or more buckets associated with a regular grid that covers 2D space. The SpatialMap is able to quickly retrieve the values u... | SpatialMap | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialMap:
"""A spatial map allows for data to be associated with rectangular regions in Euclidean space, and efficiently queried. When the SpatialMap is populated, a reference to each value is placed into one or more buckets associated with a regular grid that covers 2D space. The SpatialMap is... | stack_v2_sparse_classes_36k_train_023671 | 3,707 | permissive | [
{
"docstring": "Create a spatial map with the given grid size. Args: grid_width: Width of a grid square. grid_height: Height of a grid square.",
"name": "__init__",
"signature": "def __init__(self, grid_width: int=100, grid_height: int=20) -> None"
},
{
"docstring": "Get the grid squares under a... | 4 | null | Implement the Python class `SpatialMap` described below.
Class description:
A spatial map allows for data to be associated with rectangular regions in Euclidean space, and efficiently queried. When the SpatialMap is populated, a reference to each value is placed into one or more buckets associated with a regular grid ... | Implement the Python class `SpatialMap` described below.
Class description:
A spatial map allows for data to be associated with rectangular regions in Euclidean space, and efficiently queried. When the SpatialMap is populated, a reference to each value is placed into one or more buckets associated with a regular grid ... | b74ac1e47fdd16133ca567390c99ea19de278c5a | <|skeleton|>
class SpatialMap:
"""A spatial map allows for data to be associated with rectangular regions in Euclidean space, and efficiently queried. When the SpatialMap is populated, a reference to each value is placed into one or more buckets associated with a regular grid that covers 2D space. The SpatialMap is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpatialMap:
"""A spatial map allows for data to be associated with rectangular regions in Euclidean space, and efficiently queried. When the SpatialMap is populated, a reference to each value is placed into one or more buckets associated with a regular grid that covers 2D space. The SpatialMap is able to quic... | the_stack_v2_python_sparse | src/textual/_spatial_map.py | Textualize/textual | train | 14,818 |
80670ba2d33a4cac3488bf10bb67ea994f506fe7 | [
"self.n = 0\nself.container = dict()\nself.helper = dict()",
"if self.container.get(val, False):\n return False\nelse:\n self.n += 1\n self.container[val] = self.n\n self.helper[self.n] = val\n return True",
"if self.container.get(val, False):\n number = self.helper[self.n]\n index = self.c... | <|body_start_0|>
self.n = 0
self.container = dict()
self.helper = dict()
<|end_body_0|>
<|body_start_1|>
if self.container.get(val, False):
return False
else:
self.n += 1
self.container[val] = self.n
self.helper[self.n] = val
... | RandomizedSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_023672 | 1,631 | 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. :type val: int :rtype: bool",
"name": "insert",
"signature": ... | 4 | stack_v2_sparse_classes_30k_train_017212 | 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): Inserts a value to the set. Returns true if the set did not already contain the specif... | 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): Inserts a value to the set. Returns true if the set did not already contain the specif... | 2f46f85e1e297b0a50fdb66956b1d05622a4063d | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
self.n = 0
self.container = dict()
self.helper = dict()
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type ... | the_stack_v2_python_sparse | dan/Problems/Medium/Hashtable/380. Insert Delete GetRandom O(1)/solution.py | xudaaaaan/Leetcode | train | 0 | |
67aa310d438af4c15b0fff235b6f3d109c2c00b3 | [
"self.P = 1000\nself.sizes = np.array([0, 2, 3, 5, 8, 10, 12])\nself.calibration = BSS_Calibration()\nself.experiment = self.process_experiment()\nfoil_experiment = Au_Foil_Data()\nfoil_data = Au_Foil_Theoretical(foil_experiment)\nself.nebp_fudge_factor = foil_data.nebp_fudge_factor\nself.calc_responses()\nreturn",... | <|body_start_0|>
self.P = 1000
self.sizes = np.array([0, 2, 3, 5, 8, 10, 12])
self.calibration = BSS_Calibration()
self.experiment = self.process_experiment()
foil_experiment = Au_Foil_Data()
foil_data = Au_Foil_Theoretical(foil_experiment)
self.nebp_fudge_factor ... | Docstring. | BSS_Data | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSS_Data:
"""Docstring."""
def __init__(self):
"""Docstring."""
<|body_0|>
def process_experiment(self):
"""Implement after experiment."""
<|body_1|>
def calc_responses(self):
"""Docstring."""
<|body_2|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_023673 | 3,669 | permissive | [
{
"docstring": "Docstring.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Implement after experiment.",
"name": "process_experiment",
"signature": "def process_experiment(self)"
},
{
"docstring": "Docstring.",
"name": "calc_responses",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_007480 | Implement the Python class `BSS_Data` described below.
Class description:
Docstring.
Method signatures and docstrings:
- def __init__(self): Docstring.
- def process_experiment(self): Implement after experiment.
- def calc_responses(self): Docstring. | Implement the Python class `BSS_Data` described below.
Class description:
Docstring.
Method signatures and docstrings:
- def __init__(self): Docstring.
- def process_experiment(self): Implement after experiment.
- def calc_responses(self): Docstring.
<|skeleton|>
class BSS_Data:
"""Docstring."""
def __init_... | bfb3335b24d878f30e41ac099b73ed7668347014 | <|skeleton|>
class BSS_Data:
"""Docstring."""
def __init__(self):
"""Docstring."""
<|body_0|>
def process_experiment(self):
"""Implement after experiment."""
<|body_1|>
def calc_responses(self):
"""Docstring."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BSS_Data:
"""Docstring."""
def __init__(self):
"""Docstring."""
self.P = 1000
self.sizes = np.array([0, 2, 3, 5, 8, 10, 12])
self.calibration = BSS_Calibration()
self.experiment = self.process_experiment()
foil_experiment = Au_Foil_Data()
foil_data ... | the_stack_v2_python_sparse | experiment/bss_in_beam.py | ericgiunta/nebp | train | 0 |
9318ffbc8f7bf0945097c6001525212440b0dd75 | [
"self.counts = Counter()\nself.vals = defaultdict(set)\nself.max_v = 0\nself.min_v = 0",
"self.counts[key] += 1\nv = self.counts[key]\nself.vals[v].add(key)\nif v > 1:\n self.vals[v - 1].remove(key)\n if not self.vals[v - 1]:\n del self.vals[v - 1]\nif v > self.max_v:\n self.max_v = v\nif v == 1:\... | <|body_start_0|>
self.counts = Counter()
self.vals = defaultdict(set)
self.max_v = 0
self.min_v = 0
<|end_body_0|>
<|body_start_1|>
self.counts[key] += 1
v = self.counts[key]
self.vals[v].add(key)
if v > 1:
self.vals[v - 1].remove(key)
... | use a Counter to record the counts of key use defaultdict(set) to record the counts[v]: {keys} use a min_v, max_v to record the min_counts and max_counts update min_v, max_v at each inc and dec operation TLE, still not O(n) to get min_v | AllOne | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllOne:
"""use a Counter to record the counts of key use defaultdict(set) to record the counts[v]: {keys} use a min_v, max_v to record the min_counts and max_counts update min_v, max_v at each inc and dec operation TLE, still not O(n) to get min_v"""
def __init__(self):
"""Initialize... | stack_v2_sparse_classes_36k_train_023674 | 13,920 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1.",
"name": "inc",
"signature": "def inc(self, key: str) -> None"
},
{
"docstrin... | 5 | null | Implement the Python class `AllOne` described below.
Class description:
use a Counter to record the counts of key use defaultdict(set) to record the counts[v]: {keys} use a min_v, max_v to record the min_counts and max_counts update min_v, max_v at each inc and dec operation TLE, still not O(n) to get min_v
Method si... | Implement the Python class `AllOne` described below.
Class description:
use a Counter to record the counts of key use defaultdict(set) to record the counts[v]: {keys} use a min_v, max_v to record the min_counts and max_counts update min_v, max_v at each inc and dec operation TLE, still not O(n) to get min_v
Method si... | f96a2273c6831a8035e1adacfa452f73c599ae16 | <|skeleton|>
class AllOne:
"""use a Counter to record the counts of key use defaultdict(set) to record the counts[v]: {keys} use a min_v, max_v to record the min_counts and max_counts update min_v, max_v at each inc and dec operation TLE, still not O(n) to get min_v"""
def __init__(self):
"""Initialize... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllOne:
"""use a Counter to record the counts of key use defaultdict(set) to record the counts[v]: {keys} use a min_v, max_v to record the min_counts and max_counts update min_v, max_v at each inc and dec operation TLE, still not O(n) to get min_v"""
def __init__(self):
"""Initialize your data st... | the_stack_v2_python_sparse | Python/432_AllOonDataStructure.py | here0009/LeetCode | train | 1 |
f1ec4eeda520fa7c3ef2b4d6ed013a879cce534e | [
"super(MultiHeadAttnMlpModel, self).__init__()\nnum_dim = 500\nnum_seq = 100\nself.attn = MultiHeadAttention(num_head, num_dim, num_dim_k, num_dim_v, d_rate_attn)\nself.bn = nn.BatchNorm1d(num_dim)\nself.mlp = nn.Sequential()\nself.mlp.add_module('fc1', nn.Linear(num_seq * num_dim, num_dim))\nself.mlp.add_module('b... | <|body_start_0|>
super(MultiHeadAttnMlpModel, self).__init__()
num_dim = 500
num_seq = 100
self.attn = MultiHeadAttention(num_head, num_dim, num_dim_k, num_dim_v, d_rate_attn)
self.bn = nn.BatchNorm1d(num_dim)
self.mlp = nn.Sequential()
self.mlp.add_module('fc1', ... | MultiHeadAttnMlpModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttnMlpModel:
def __init__(self, num_head=8, num_dim_k=64, num_dim_v=64, d_rate_attn=0.1, act_func1='LeakyReLU', dim2=100, act_func2='LeakyReLU'):
"""num_head: for Attn, the number of head in MultiHeadAttention num_dim_k: for Attn, the number of dimension query and key will mapp... | stack_v2_sparse_classes_36k_train_023675 | 21,586 | no_license | [
{
"docstring": "num_head: for Attn, the number of head in MultiHeadAttention num_dim_k: for Attn, the number of dimension query and key will mapping to num_dim_v: for Attn, the number of dimension value will mapping to d_rate_attn: drop out rate for MultiHeadAttention",
"name": "__init__",
"signature": ... | 2 | stack_v2_sparse_classes_30k_val_000594 | Implement the Python class `MultiHeadAttnMlpModel` described below.
Class description:
Implement the MultiHeadAttnMlpModel class.
Method signatures and docstrings:
- def __init__(self, num_head=8, num_dim_k=64, num_dim_v=64, d_rate_attn=0.1, act_func1='LeakyReLU', dim2=100, act_func2='LeakyReLU'): num_head: for Attn,... | Implement the Python class `MultiHeadAttnMlpModel` described below.
Class description:
Implement the MultiHeadAttnMlpModel class.
Method signatures and docstrings:
- def __init__(self, num_head=8, num_dim_k=64, num_dim_v=64, d_rate_attn=0.1, act_func1='LeakyReLU', dim2=100, act_func2='LeakyReLU'): num_head: for Attn,... | be85ee0c1fa915ae08ffb857643f9429a7749c0e | <|skeleton|>
class MultiHeadAttnMlpModel:
def __init__(self, num_head=8, num_dim_k=64, num_dim_v=64, d_rate_attn=0.1, act_func1='LeakyReLU', dim2=100, act_func2='LeakyReLU'):
"""num_head: for Attn, the number of head in MultiHeadAttention num_dim_k: for Attn, the number of dimension query and key will mapp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadAttnMlpModel:
def __init__(self, num_head=8, num_dim_k=64, num_dim_v=64, d_rate_attn=0.1, act_func1='LeakyReLU', dim2=100, act_func2='LeakyReLU'):
"""num_head: for Attn, the number of head in MultiHeadAttention num_dim_k: for Attn, the number of dimension query and key will mapping to num_dim... | the_stack_v2_python_sparse | models/FullHiddenModel.py | HuangYiran/MasterArbeit | train | 1 | |
09c4ab2c86549fb08d887dd75c27cfa0ca4b18e5 | [
"if not head:\n return False\ntortoise = head\nhare = head.next\nwhile hare and hare.next and (tortoise != hare):\n tortoise = tortoise.next\n hare = hare.next.next\nreturn tortoise == hare",
"if not head:\n return False\nk = lam = 1\ntortoise = head\nhare = head.next\nwhile hare and tortoise != hare:... | <|body_start_0|>
if not head:
return False
tortoise = head
hare = head.next
while hare and hare.next and (tortoise != hare):
tortoise = tortoise.next
hare = hare.next.next
return tortoise == hare
<|end_body_0|>
<|body_start_1|>
if not ... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasCycle1(self, head):
"""Floyd's Tortoise and Hare (44ms)"""
<|body_0|>
def hasCycle2(self, head):
"""Brent's algorithm (40ms)"""
<|body_1|>
def hasCycle3(self, head):
"""Hashtable (36ms)"""
<|body_2|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_023676 | 1,916 | permissive | [
{
"docstring": "Floyd's Tortoise and Hare (44ms)",
"name": "hasCycle1",
"signature": "def hasCycle1(self, head)"
},
{
"docstring": "Brent's algorithm (40ms)",
"name": "hasCycle2",
"signature": "def hasCycle2(self, head)"
},
{
"docstring": "Hashtable (36ms)",
"name": "hasCycle... | 3 | stack_v2_sparse_classes_30k_train_018588 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle1(self, head): Floyd's Tortoise and Hare (44ms)
- def hasCycle2(self, head): Brent's algorithm (40ms)
- def hasCycle3(self, head): Hashtable (36ms) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle1(self, head): Floyd's Tortoise and Hare (44ms)
- def hasCycle2(self, head): Brent's algorithm (40ms)
- def hasCycle3(self, head): Hashtable (36ms)
<|skeleton|>
clas... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def hasCycle1(self, head):
"""Floyd's Tortoise and Hare (44ms)"""
<|body_0|>
def hasCycle2(self, head):
"""Brent's algorithm (40ms)"""
<|body_1|>
def hasCycle3(self, head):
"""Hashtable (36ms)"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hasCycle1(self, head):
"""Floyd's Tortoise and Hare (44ms)"""
if not head:
return False
tortoise = head
hare = head.next
while hare and hare.next and (tortoise != hare):
tortoise = tortoise.next
hare = hare.next.next
... | the_stack_v2_python_sparse | leetcode/0141_linked_list_cycle.py | chaosWsF/Python-Practice | train | 1 | |
8fc2a8fe7b793033ec83c2571d4e9e642be0924e | [
"self.environment = environment\nself.num_objects_protected = num_objects_protected\nself.num_objects_unprotected = num_objects_unprotected\nself.protected_size_bytes = protected_size_bytes\nself.unprotected_size_bytes = unprotected_size_bytes",
"if dictionary is None:\n return None\nenvironment = dictionary.g... | <|body_start_0|>
self.environment = environment
self.num_objects_protected = num_objects_protected
self.num_objects_unprotected = num_objects_unprotected
self.protected_size_bytes = protected_size_bytes
self.unprotected_size_bytes = unprotected_size_bytes
<|end_body_0|>
<|body_s... | Implementation of the 'ProtectedObjectsSummaryByEnv' model. Specifies the protection summary of given environment type. Attributes: environment (EnvironmentProtectedObjectsSummaryByEnvEnum): Specifies the environment. num_objects_protected (long|int): Specifies the total number of protected objects. num_objects_unprote... | ProtectedObjectsSummaryByEnv | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectedObjectsSummaryByEnv:
"""Implementation of the 'ProtectedObjectsSummaryByEnv' model. Specifies the protection summary of given environment type. Attributes: environment (EnvironmentProtectedObjectsSummaryByEnvEnum): Specifies the environment. num_objects_protected (long|int): Specifies th... | stack_v2_sparse_classes_36k_train_023677 | 2,944 | permissive | [
{
"docstring": "Constructor for the ProtectedObjectsSummaryByEnv class",
"name": "__init__",
"signature": "def __init__(self, environment=None, num_objects_protected=None, num_objects_unprotected=None, protected_size_bytes=None, unprotected_size_bytes=None)"
},
{
"docstring": "Creates an instanc... | 2 | null | Implement the Python class `ProtectedObjectsSummaryByEnv` described below.
Class description:
Implementation of the 'ProtectedObjectsSummaryByEnv' model. Specifies the protection summary of given environment type. Attributes: environment (EnvironmentProtectedObjectsSummaryByEnvEnum): Specifies the environment. num_obj... | Implement the Python class `ProtectedObjectsSummaryByEnv` described below.
Class description:
Implementation of the 'ProtectedObjectsSummaryByEnv' model. Specifies the protection summary of given environment type. Attributes: environment (EnvironmentProtectedObjectsSummaryByEnvEnum): Specifies the environment. num_obj... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectedObjectsSummaryByEnv:
"""Implementation of the 'ProtectedObjectsSummaryByEnv' model. Specifies the protection summary of given environment type. Attributes: environment (EnvironmentProtectedObjectsSummaryByEnvEnum): Specifies the environment. num_objects_protected (long|int): Specifies th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProtectedObjectsSummaryByEnv:
"""Implementation of the 'ProtectedObjectsSummaryByEnv' model. Specifies the protection summary of given environment type. Attributes: environment (EnvironmentProtectedObjectsSummaryByEnvEnum): Specifies the environment. num_objects_protected (long|int): Specifies the total numbe... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protected_objects_summary_by_env.py | cohesity/management-sdk-python | train | 24 |
d3ab54656e8174a453b32d941aec1b1da12139a0 | [
"data, status_code = self._rest_delete('/execution/' + str(execution_id))\nif status_code == 204:\n return\nelse:\n raise ZoeAPIException(data)",
"data, status_code = self._rest_delete('/execution/delete/' + str(execution_id))\nif status_code == 204:\n return\nelse:\n raise ZoeAPIException(data)",
"... | <|body_start_0|>
data, status_code = self._rest_delete('/execution/' + str(execution_id))
if status_code == 204:
return
else:
raise ZoeAPIException(data)
<|end_body_0|>
<|body_start_1|>
data, status_code = self._rest_delete('/execution/delete/' + str(execution_id... | The execution API class. | ZoeExecutionsAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZoeExecutionsAPI:
"""The execution API class."""
def terminate(self, execution_id):
"""Terminates an execution. :param execution_id: the execution to terminate :return: True if the operation was successful, False otherwise :type execution_id: int :rtype: bool"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_023678 | 4,706 | permissive | [
{
"docstring": "Terminates an execution. :param execution_id: the execution to terminate :return: True if the operation was successful, False otherwise :type execution_id: int :rtype: bool",
"name": "terminate",
"signature": "def terminate(self, execution_id)"
},
{
"docstring": "Deletes an execu... | 6 | null | Implement the Python class `ZoeExecutionsAPI` described below.
Class description:
The execution API class.
Method signatures and docstrings:
- def terminate(self, execution_id): Terminates an execution. :param execution_id: the execution to terminate :return: True if the operation was successful, False otherwise :typ... | Implement the Python class `ZoeExecutionsAPI` described below.
Class description:
The execution API class.
Method signatures and docstrings:
- def terminate(self, execution_id): Terminates an execution. :param execution_id: the execution to terminate :return: True if the operation was successful, False otherwise :typ... | c8e0c908af1954a8b41d0f6de23d08589564f0ab | <|skeleton|>
class ZoeExecutionsAPI:
"""The execution API class."""
def terminate(self, execution_id):
"""Terminates an execution. :param execution_id: the execution to terminate :return: True if the operation was successful, False otherwise :type execution_id: int :rtype: bool"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZoeExecutionsAPI:
"""The execution API class."""
def terminate(self, execution_id):
"""Terminates an execution. :param execution_id: the execution to terminate :return: True if the operation was successful, False otherwise :type execution_id: int :rtype: bool"""
data, status_code = self._... | the_stack_v2_python_sparse | zoe_cmd/api_lib/executions.py | DistributedSystemsGroup/zoe | train | 60 |
158a984a3eb238590f8c559a4ddb68550061853e | [
"for sqrt_b in [WhiteCovariance, BrownianCovariance, PinkCovariance]:\n n = 64\n ident = jnp.eye(n)[:, :, None]\n sqrt_b_dense = sqrt_b.forward(ident)[Ellipsis, 0]\n _, slogdet = jnp.linalg.slogdet(sqrt_b_dense)\n logdet = slogdet * 2\n logdet2 = sqrt_b.logdet((ident + jnp.zeros(2)).shape)[0]\n ... | <|body_start_0|>
for sqrt_b in [WhiteCovariance, BrownianCovariance, PinkCovariance]:
n = 64
ident = jnp.eye(n)[:, :, None]
sqrt_b_dense = sqrt_b.forward(ident)[Ellipsis, 0]
_, slogdet = jnp.linalg.slogdet(sqrt_b_dense)
logdet = slogdet * 2
... | CovarianceTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CovarianceTest:
def test_covariance_logdet(self):
"""Test whether logdet method matches numpy logdet with dense matrix."""
<|body_0|>
def test_covariance_inverse(self):
"""Test covariance forward and inverse are in fact inverses of each other."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_023679 | 2,268 | permissive | [
{
"docstring": "Test whether logdet method matches numpy logdet with dense matrix.",
"name": "test_covariance_logdet",
"signature": "def test_covariance_logdet(self)"
},
{
"docstring": "Test covariance forward and inverse are in fact inverses of each other.",
"name": "test_covariance_inverse... | 2 | null | Implement the Python class `CovarianceTest` described below.
Class description:
Implement the CovarianceTest class.
Method signatures and docstrings:
- def test_covariance_logdet(self): Test whether logdet method matches numpy logdet with dense matrix.
- def test_covariance_inverse(self): Test covariance forward and ... | Implement the Python class `CovarianceTest` described below.
Class description:
Implement the CovarianceTest class.
Method signatures and docstrings:
- def test_covariance_logdet(self): Test whether logdet method matches numpy logdet with dense matrix.
- def test_covariance_inverse(self): Test covariance forward and ... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class CovarianceTest:
def test_covariance_logdet(self):
"""Test whether logdet method matches numpy logdet with dense matrix."""
<|body_0|>
def test_covariance_inverse(self):
"""Test covariance forward and inverse are in fact inverses of each other."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CovarianceTest:
def test_covariance_logdet(self):
"""Test whether logdet method matches numpy logdet with dense matrix."""
for sqrt_b in [WhiteCovariance, BrownianCovariance, PinkCovariance]:
n = 64
ident = jnp.eye(n)[:, :, None]
sqrt_b_dense = sqrt_b.forwar... | the_stack_v2_python_sparse | simulation_research/diffusion/covariance_test.py | Jimmy-INL/google-research | train | 1 | |
395e36665d523d4ccbb30d24c912b8e71cba6822 | [
"wiz = self.browse(cr, uid, ids, context=context)[0]\ndata = {}\ndata['parameters'] = {'partner_id': context.get('active_id'), 'date_start': wiz.date_start, 'date_end': wiz.date_end}\nreturn {'type': 'ir.actions.report.xml', 'report_name': 'statement_general', 'datas': data}",
"wiz = self.browse(cr, uid, ids, con... | <|body_start_0|>
wiz = self.browse(cr, uid, ids, context=context)[0]
data = {}
data['parameters'] = {'partner_id': context.get('active_id'), 'date_start': wiz.date_start, 'date_end': wiz.date_end}
return {'type': 'ir.actions.report.xml', 'report_name': 'statement_general', 'datas': data}... | statement_general_report | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class statement_general_report:
def launch(self, cr, uid, ids, context=None):
"""Launch the report, and pass each value in the form as parameters"""
<|body_0|>
def launch_detail(self, cr, uid, ids, context=None):
"""Launch the report, and pass each value in the form as par... | stack_v2_sparse_classes_36k_train_023680 | 2,762 | no_license | [
{
"docstring": "Launch the report, and pass each value in the form as parameters",
"name": "launch",
"signature": "def launch(self, cr, uid, ids, context=None)"
},
{
"docstring": "Launch the report, and pass each value in the form as parameters",
"name": "launch_detail",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_015485 | Implement the Python class `statement_general_report` described below.
Class description:
Implement the statement_general_report class.
Method signatures and docstrings:
- def launch(self, cr, uid, ids, context=None): Launch the report, and pass each value in the form as parameters
- def launch_detail(self, cr, uid, ... | Implement the Python class `statement_general_report` described below.
Class description:
Implement the statement_general_report class.
Method signatures and docstrings:
- def launch(self, cr, uid, ids, context=None): Launch the report, and pass each value in the form as parameters
- def launch_detail(self, cr, uid, ... | a5e9f95c59be058aead30e1c6de867ed36354e6a | <|skeleton|>
class statement_general_report:
def launch(self, cr, uid, ids, context=None):
"""Launch the report, and pass each value in the form as parameters"""
<|body_0|>
def launch_detail(self, cr, uid, ids, context=None):
"""Launch the report, and pass each value in the form as par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class statement_general_report:
def launch(self, cr, uid, ids, context=None):
"""Launch the report, and pass each value in the form as parameters"""
wiz = self.browse(cr, uid, ids, context=context)[0]
data = {}
data['parameters'] = {'partner_id': context.get('active_id'), 'date_start... | the_stack_v2_python_sparse | prooaddons/customer_statement/report/report.py | wissemsh/prooaddons | train | 0 | |
1a97a4ae27a13c71b986d79a19d50e00ba31ff7c | [
"super().__init__(*args, **kwargs)\nfor field in self._meta.fields:\n method_name = f'get_{field.name}_help_text'\n partial_method = partial(self._get_help_text, field_name=field.name)\n setattr(self, method_name, partial_method)",
"for field in self._meta.fields:\n if field.name == field_name:\n ... | <|body_start_0|>
super().__init__(*args, **kwargs)
for field in self._meta.fields:
method_name = f'get_{field.name}_help_text'
partial_method = partial(self._get_help_text, field_name=field.name)
setattr(self, method_name, partial_method)
<|end_body_0|>
<|body_start_... | Base Model Class to dynamically add get_foo_help_text() methods for all model fields. | HelpTextModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HelpTextModel:
"""Base Model Class to dynamically add get_foo_help_text() methods for all model fields."""
def __init__(self, *args, **kwargs):
"""Loop over fields and add a new help_text getter method for each."""
<|body_0|>
def _get_help_text(self, field_name):
... | stack_v2_sparse_classes_36k_train_023681 | 5,994 | permissive | [
{
"docstring": "Loop over fields and add a new help_text getter method for each.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Loop over all fields and return the help_text for the requested field.",
"name": "_get_help_text",
"signature": "de... | 2 | null | Implement the Python class `HelpTextModel` described below.
Class description:
Base Model Class to dynamically add get_foo_help_text() methods for all model fields.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Loop over fields and add a new help_text getter method for each.
- def _get_help... | Implement the Python class `HelpTextModel` described below.
Class description:
Base Model Class to dynamically add get_foo_help_text() methods for all model fields.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Loop over fields and add a new help_text getter method for each.
- def _get_help... | 767deb7f58429e9162e0c2ef79be9f0f38f37ce1 | <|skeleton|>
class HelpTextModel:
"""Base Model Class to dynamically add get_foo_help_text() methods for all model fields."""
def __init__(self, *args, **kwargs):
"""Loop over fields and add a new help_text getter method for each."""
<|body_0|>
def _get_help_text(self, field_name):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HelpTextModel:
"""Base Model Class to dynamically add get_foo_help_text() methods for all model fields."""
def __init__(self, *args, **kwargs):
"""Loop over fields and add a new help_text getter method for each."""
super().__init__(*args, **kwargs)
for field in self._meta.fields:
... | the_stack_v2_python_sparse | src/utils/models.py | bornhack/bornhack-website | train | 9 |
aa23c08a92b938eed93e0900debebda960f76beb | [
"txt.replace('&', '&')\nfor entity, code in XML.entities.items():\n txt.replace(entity, code)\nreturn txt",
"for entity, code in XML.entities.items():\n txt.replace(code, entity)\ntxt.replace('&', '&')\nreturn txt"
] | <|body_start_0|>
txt.replace('&', '&')
for entity, code in XML.entities.items():
txt.replace(entity, code)
return txt
<|end_body_0|>
<|body_start_1|>
for entity, code in XML.entities.items():
txt.replace(code, entity)
txt.replace('&', '&')
... | a class containing usefull method for XML | XML | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XML:
"""a class containing usefull method for XML"""
def encode(txt):
"""a method to replace XML entities by XML representation"""
<|body_0|>
def decode(txt):
"""a method to replace XML representation of entities by the original entities"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_023682 | 1,137 | permissive | [
{
"docstring": "a method to replace XML entities by XML representation",
"name": "encode",
"signature": "def encode(txt)"
},
{
"docstring": "a method to replace XML representation of entities by the original entities",
"name": "decode",
"signature": "def decode(txt)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016000 | Implement the Python class `XML` described below.
Class description:
a class containing usefull method for XML
Method signatures and docstrings:
- def encode(txt): a method to replace XML entities by XML representation
- def decode(txt): a method to replace XML representation of entities by the original entities | Implement the Python class `XML` described below.
Class description:
a class containing usefull method for XML
Method signatures and docstrings:
- def encode(txt): a method to replace XML entities by XML representation
- def decode(txt): a method to replace XML representation of entities by the original entities
<|s... | 39082e7833383bbe7dd414381f1b295e3b778439 | <|skeleton|>
class XML:
"""a class containing usefull method for XML"""
def encode(txt):
"""a method to replace XML entities by XML representation"""
<|body_0|>
def decode(txt):
"""a method to replace XML representation of entities by the original entities"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XML:
"""a class containing usefull method for XML"""
def encode(txt):
"""a method to replace XML entities by XML representation"""
txt.replace('&', '&')
for entity, code in XML.entities.items():
txt.replace(entity, code)
return txt
def decode(txt):
... | the_stack_v2_python_sparse | usefullFunctions.py | chankeh/Blender-Render-Manager | train | 0 |
c2a4def907bfa3172043466f151509bb36b94795 | [
"if isinstance(value, bool):\n return int(value)\ntry:\n result = value\n if value and isinstance(value, str):\n float_value = float(value)\n result = int(float_value)\n if result != float_value:\n raise ValueError()\n if not is_integer(result):\n raise ValueError(... | <|body_start_0|>
if isinstance(value, bool):
return int(value)
try:
result = value
if value and isinstance(value, str):
float_value = float(value)
result = int(float_value)
if result != float_value:
r... | Built-in scalar which handle int values. | ScalarInt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalarInt:
"""Built-in scalar which handle int values."""
def coerce_output(self, value: Any) -> int:
"""Coerce the resolved value for output. :param value: value to coerce :type value: Any :return: the coerced value :rtype: int"""
<|body_0|>
def coerce_input(self, value... | stack_v2_sparse_classes_36k_train_023683 | 3,477 | permissive | [
{
"docstring": "Coerce the resolved value for output. :param value: value to coerce :type value: Any :return: the coerced value :rtype: int",
"name": "coerce_output",
"signature": "def coerce_output(self, value: Any) -> int"
},
{
"docstring": "Coerce the user input from variable value. :param va... | 3 | null | Implement the Python class `ScalarInt` described below.
Class description:
Built-in scalar which handle int values.
Method signatures and docstrings:
- def coerce_output(self, value: Any) -> int: Coerce the resolved value for output. :param value: value to coerce :type value: Any :return: the coerced value :rtype: in... | Implement the Python class `ScalarInt` described below.
Class description:
Built-in scalar which handle int values.
Method signatures and docstrings:
- def coerce_output(self, value: Any) -> int: Coerce the resolved value for output. :param value: value to coerce :type value: Any :return: the coerced value :rtype: in... | 421c1e937f553d6a5bf2f30154022c0d77053cfb | <|skeleton|>
class ScalarInt:
"""Built-in scalar which handle int values."""
def coerce_output(self, value: Any) -> int:
"""Coerce the resolved value for output. :param value: value to coerce :type value: Any :return: the coerced value :rtype: int"""
<|body_0|>
def coerce_input(self, value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScalarInt:
"""Built-in scalar which handle int values."""
def coerce_output(self, value: Any) -> int:
"""Coerce the resolved value for output. :param value: value to coerce :type value: Any :return: the coerced value :rtype: int"""
if isinstance(value, bool):
return int(value)... | the_stack_v2_python_sparse | tartiflette/scalar/builtins/int.py | tartiflette/tartiflette | train | 586 |
66fd1ec3cb10324cbcae3f1f4f991a56c6bcf56e | [
"super(Slack, self).__init__()\nself._web_hook_url = web_hook_url\nself._channel = channel\nself._username = username\nself._icon = icon",
"payload = self._get_payload(message)\ndata = json.dumps(payload).encode('utf-8')\nrequest = Request(self._web_hook_url, data=data)\nresponse = urlopen(request)\nreturn respon... | <|body_start_0|>
super(Slack, self).__init__()
self._web_hook_url = web_hook_url
self._channel = channel
self._username = username
self._icon = icon
<|end_body_0|>
<|body_start_1|>
payload = self._get_payload(message)
data = json.dumps(payload).encode('utf-8')
... | Slack | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Slack:
def __init__(self, web_hook_url, channel=None, username=None, icon=None):
"""Initiate the object :param web_hook_url: The webhook url :param channel: A custom channel :param username: A custom username :param icon: A custom icon"""
<|body_0|>
def send(self, message):
... | stack_v2_sparse_classes_36k_train_023684 | 2,574 | permissive | [
{
"docstring": "Initiate the object :param web_hook_url: The webhook url :param channel: A custom channel :param username: A custom username :param icon: A custom icon",
"name": "__init__",
"signature": "def __init__(self, web_hook_url, channel=None, username=None, icon=None)"
},
{
"docstring": ... | 4 | stack_v2_sparse_classes_30k_train_019108 | Implement the Python class `Slack` described below.
Class description:
Implement the Slack class.
Method signatures and docstrings:
- def __init__(self, web_hook_url, channel=None, username=None, icon=None): Initiate the object :param web_hook_url: The webhook url :param channel: A custom channel :param username: A c... | Implement the Python class `Slack` described below.
Class description:
Implement the Slack class.
Method signatures and docstrings:
- def __init__(self, web_hook_url, channel=None, username=None, icon=None): Initiate the object :param web_hook_url: The webhook url :param channel: A custom channel :param username: A c... | 0c9d94b353d4d149db9492eb4ae0aa87cc1e082c | <|skeleton|>
class Slack:
def __init__(self, web_hook_url, channel=None, username=None, icon=None):
"""Initiate the object :param web_hook_url: The webhook url :param channel: A custom channel :param username: A custom username :param icon: A custom icon"""
<|body_0|>
def send(self, message):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Slack:
def __init__(self, web_hook_url, channel=None, username=None, icon=None):
"""Initiate the object :param web_hook_url: The webhook url :param channel: A custom channel :param username: A custom username :param icon: A custom icon"""
super(Slack, self).__init__()
self._web_hook_ur... | the_stack_v2_python_sparse | scriptcore/integrations/slack/slack.py | LowieHuyghe/script-core | train | 0 | |
e955820313eabe3d29d4c56fc56d7e425b7eeb83 | [
"super().__init__()\nif isinstance(output_size, int):\n output_size = (output_size, output_size)\nassert len(output_size) == 2\nassert isinstance(output_size[0], int) and isinstance(output_size[1], int)\nself.output_size = output_size\nif pooler_type == 'ROIAlign':\n self.level_poolers = nn.ModuleList((ROIAli... | <|body_start_0|>
super().__init__()
if isinstance(output_size, int):
output_size = (output_size, output_size)
assert len(output_size) == 2
assert isinstance(output_size[0], int) and isinstance(output_size[1], int)
self.output_size = output_size
if pooler_type ... | Region of interest feature map pooler that supports pooling from one or more feature maps. | ROIPooler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ROIPooler:
"""Region of interest feature map pooler that supports pooling from one or more feature maps."""
def __init__(self, output_size, scales, sampling_ratio, pooler_type, canonical_box_size=224, canonical_level=4):
"""Args: output_size (int, tuple[int] or list[int]): output siz... | stack_v2_sparse_classes_36k_train_023685 | 11,509 | permissive | [
{
"docstring": "Args: output_size (int, tuple[int] or list[int]): output size of the pooled region, e.g., 14 x 14. If tuple or list is given, the length must be 2. scales (list[float]): The scale for each low-level pooling op relative to the input image. For a feature map with stride s relative to the input ima... | 2 | stack_v2_sparse_classes_30k_train_015526 | Implement the Python class `ROIPooler` described below.
Class description:
Region of interest feature map pooler that supports pooling from one or more feature maps.
Method signatures and docstrings:
- def __init__(self, output_size, scales, sampling_ratio, pooler_type, canonical_box_size=224, canonical_level=4): Arg... | Implement the Python class `ROIPooler` described below.
Class description:
Region of interest feature map pooler that supports pooling from one or more feature maps.
Method signatures and docstrings:
- def __init__(self, output_size, scales, sampling_ratio, pooler_type, canonical_box_size=224, canonical_level=4): Arg... | 80307d2d5e06f06a8a677cc2653f23a4c56402ac | <|skeleton|>
class ROIPooler:
"""Region of interest feature map pooler that supports pooling from one or more feature maps."""
def __init__(self, output_size, scales, sampling_ratio, pooler_type, canonical_box_size=224, canonical_level=4):
"""Args: output_size (int, tuple[int] or list[int]): output siz... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ROIPooler:
"""Region of interest feature map pooler that supports pooling from one or more feature maps."""
def __init__(self, output_size, scales, sampling_ratio, pooler_type, canonical_box_size=224, canonical_level=4):
"""Args: output_size (int, tuple[int] or list[int]): output size of the pool... | the_stack_v2_python_sparse | detectron2/modeling/poolers.py | facebookresearch/detectron2 | train | 27,469 |
351690db470e0b05b8d162671f34ad6551fceb48 | [
"config = copy.deepcopy(DYN_PRIOR_GMM)\nconfig.update(hyperparams)\nself._hyperparams = config\nself.X = None\nself.U = None\nself.gmm = GMM()\nself._min_samp = self._hyperparams['min_samples_per_cluster']\nself._max_samples = self._hyperparams['max_samples']\nself._max_clusters = self._hyperparams['max_clusters']\... | <|body_start_0|>
config = copy.deepcopy(DYN_PRIOR_GMM)
config.update(hyperparams)
self._hyperparams = config
self.X = None
self.U = None
self.gmm = GMM()
self._min_samp = self._hyperparams['min_samples_per_cluster']
self._max_samples = self._hyperparams['m... | A dynamics prior encoded as a GMM over [x_t, u_t, x_t+1] points. See: S. Levine*, C. Finn*, T. Darrell, P. Abbeel, "End-to-end training of Deep Visuomotor Policies", arXiv:1504.00702, Appendix A.3. | DynamicsPriorGMM | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicsPriorGMM:
"""A dynamics prior encoded as a GMM over [x_t, u_t, x_t+1] points. See: S. Levine*, C. Finn*, T. Darrell, P. Abbeel, "End-to-end training of Deep Visuomotor Policies", arXiv:1504.00702, Appendix A.3."""
def __init__(self, hyperparams):
"""Hyperparameters: min_sampl... | stack_v2_sparse_classes_36k_train_023686 | 3,709 | permissive | [
{
"docstring": "Hyperparameters: min_samples_per_cluster: Minimum samples per cluster. max_clusters: Maximum number of clusters to fit. max_samples: Maximum number of trajectories to use for fitting the GMM at any given time. strength: Adjusts the strength of the prior.",
"name": "__init__",
"signature"... | 4 | stack_v2_sparse_classes_30k_train_011539 | Implement the Python class `DynamicsPriorGMM` described below.
Class description:
A dynamics prior encoded as a GMM over [x_t, u_t, x_t+1] points. See: S. Levine*, C. Finn*, T. Darrell, P. Abbeel, "End-to-end training of Deep Visuomotor Policies", arXiv:1504.00702, Appendix A.3.
Method signatures and docstrings:
- de... | Implement the Python class `DynamicsPriorGMM` described below.
Class description:
A dynamics prior encoded as a GMM over [x_t, u_t, x_t+1] points. See: S. Levine*, C. Finn*, T. Darrell, P. Abbeel, "End-to-end training of Deep Visuomotor Policies", arXiv:1504.00702, Appendix A.3.
Method signatures and docstrings:
- de... | 04ef980cf22272d2c09f4213625dd4428f3632ca | <|skeleton|>
class DynamicsPriorGMM:
"""A dynamics prior encoded as a GMM over [x_t, u_t, x_t+1] points. See: S. Levine*, C. Finn*, T. Darrell, P. Abbeel, "End-to-end training of Deep Visuomotor Policies", arXiv:1504.00702, Appendix A.3."""
def __init__(self, hyperparams):
"""Hyperparameters: min_sampl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DynamicsPriorGMM:
"""A dynamics prior encoded as a GMM over [x_t, u_t, x_t+1] points. See: S. Levine*, C. Finn*, T. Darrell, P. Abbeel, "End-to-end training of Deep Visuomotor Policies", arXiv:1504.00702, Appendix A.3."""
def __init__(self, hyperparams):
"""Hyperparameters: min_samples_per_cluste... | the_stack_v2_python_sparse | python/gps/algorithm/dynamics/dynamics_prior_gmm.py | SymbioRobotics/gps | train | 9 |
1e86525deb4a6157c9aa9c8d61fdcda33ccc8e8b | [
"d = defaultdict(list)\nfor s in strs:\n key = ''.join(sorted(s))\n d[key].append(s)\nreturn list(d.values())",
"d = defaultdict(list)\nfor s in strs:\n key = reduce(lambda x, y: x + y, sorted(s))\n d[key].append(s)\nreturn [v for v in d.values()]"
] | <|body_start_0|>
d = defaultdict(list)
for s in strs:
key = ''.join(sorted(s))
d[key].append(s)
return list(d.values())
<|end_body_0|>
<|body_start_1|>
d = defaultdict(list)
for s in strs:
key = reduce(lambda x, y: x + y, sorted(s))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams_v1(self, strs: List[str]) -> List[List[str]]:
"""Use join + sorted to sort the string."""
<|body_0|>
def groupAnagrams_v2(self, strs: List[str]) -> List[List[str]]:
"""Use reduce + sorted to sort the string."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_023687 | 1,736 | no_license | [
{
"docstring": "Use join + sorted to sort the string.",
"name": "groupAnagrams_v1",
"signature": "def groupAnagrams_v1(self, strs: List[str]) -> List[List[str]]"
},
{
"docstring": "Use reduce + sorted to sort the string.",
"name": "groupAnagrams_v2",
"signature": "def groupAnagrams_v2(se... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams_v1(self, strs: List[str]) -> List[List[str]]: Use join + sorted to sort the string.
- def groupAnagrams_v2(self, strs: List[str]) -> List[List[str]]: Use reduce... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams_v1(self, strs: List[str]) -> List[List[str]]: Use join + sorted to sort the string.
- def groupAnagrams_v2(self, strs: List[str]) -> List[List[str]]: Use reduce... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def groupAnagrams_v1(self, strs: List[str]) -> List[List[str]]:
"""Use join + sorted to sort the string."""
<|body_0|>
def groupAnagrams_v2(self, strs: List[str]) -> List[List[str]]:
"""Use reduce + sorted to sort the string."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams_v1(self, strs: List[str]) -> List[List[str]]:
"""Use join + sorted to sort the string."""
d = defaultdict(list)
for s in strs:
key = ''.join(sorted(s))
d[key].append(s)
return list(d.values())
def groupAnagrams_v2(self, s... | the_stack_v2_python_sparse | python3/string_array/group_anagrams.py | victorchu/algorithms | train | 0 | |
84afd4eb2a6ea027dde53cc27aedbde599f8c9b8 | [
"aicpu_file_path = os.path.join(self._profiling_dir, self._file_name_aicpu_time.format(self._device_id))\naicpu_file_path = validate_and_normalize_path(aicpu_file_path, raise_key='Invalid aicpu file path.')\nif not os.path.isfile(aicpu_file_path):\n logger.warning('The file <%s> does not exist.', aicpu_file_path... | <|body_start_0|>
aicpu_file_path = os.path.join(self._profiling_dir, self._file_name_aicpu_time.format(self._device_id))
aicpu_file_path = validate_and_normalize_path(aicpu_file_path, raise_key='Invalid aicpu file path.')
if not os.path.isfile(aicpu_file_path):
logger.warning('The fi... | The analyser for analyzing all the AICPU operators. Args: profiling_dir (str): The directory where the parsed profiling files are located. device_id (str): The device ID. Raises: ProfilerPathErrorException: If the profiling dir is invalid. | AicpuDetailAnalyser | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AicpuDetailAnalyser:
"""The analyser for analyzing all the AICPU operators. Args: profiling_dir (str): The directory where the parsed profiling files are located. device_id (str): The device ID. Raises: ProfilerPathErrorException: If the profiling dir is invalid."""
def _load(self):
... | stack_v2_sparse_classes_36k_train_023688 | 25,551 | permissive | [
{
"docstring": "Load data according to the parsed AICPU operator file.",
"name": "_load",
"signature": "def _load(self)"
},
{
"docstring": "Filter the profiling data according to the filter condition. Args: filter_condition (dict): The filter condition.",
"name": "_filter",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_000318 | Implement the Python class `AicpuDetailAnalyser` described below.
Class description:
The analyser for analyzing all the AICPU operators. Args: profiling_dir (str): The directory where the parsed profiling files are located. device_id (str): The device ID. Raises: ProfilerPathErrorException: If the profiling dir is inv... | Implement the Python class `AicpuDetailAnalyser` described below.
Class description:
The analyser for analyzing all the AICPU operators. Args: profiling_dir (str): The directory where the parsed profiling files are located. device_id (str): The device ID. Raises: ProfilerPathErrorException: If the profiling dir is inv... | a774d893fb2f21dbc3edb5cd89f9e6eec274ebf1 | <|skeleton|>
class AicpuDetailAnalyser:
"""The analyser for analyzing all the AICPU operators. Args: profiling_dir (str): The directory where the parsed profiling files are located. device_id (str): The device ID. Raises: ProfilerPathErrorException: If the profiling dir is invalid."""
def _load(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AicpuDetailAnalyser:
"""The analyser for analyzing all the AICPU operators. Args: profiling_dir (str): The directory where the parsed profiling files are located. device_id (str): The device ID. Raises: ProfilerPathErrorException: If the profiling dir is invalid."""
def _load(self):
"""Load data ... | the_stack_v2_python_sparse | mindinsight/profiler/analyser/analyser.py | mindspore-ai/mindinsight | train | 224 |
aa7b06d4c33494cafd7a746fa40b3329c1105c38 | [
"b_values = self._encoding(max_log_scale, embedding_size, num_inputs)\na_values = torch.ones(b_values.shape[1])\nFourierFeatureMLP.__init__(self, num_inputs, num_outputs, a_values, b_values, [num_channels] * num_layers)",
"embedding_size = embedding_size // num_inputs\nfrequencies_matrix = 2.0 ** torch.linspace(0... | <|body_start_0|>
b_values = self._encoding(max_log_scale, embedding_size, num_inputs)
a_values = torch.ones(b_values.shape[1])
FourierFeatureMLP.__init__(self, num_inputs, num_outputs, a_values, b_values, [num_channels] * num_layers)
<|end_body_0|>
<|body_start_1|>
embedding_size = embe... | Version of FFN with positional encoding. | PositionalFourierMLP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalFourierMLP:
"""Version of FFN with positional encoding."""
def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256):
"""Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs ... | stack_v2_sparse_classes_36k_train_023689 | 17,353 | no_license | [
{
"docstring": "Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int): Number of dimensions in the output max_log_scale (float): Maximum log scale for embedding num_layers (int, optional): Number of layers in the MLP. Defaults to 4. num_channels (int, optional): Number of chan... | 2 | null | Implement the Python class `PositionalFourierMLP` described below.
Class description:
Version of FFN with positional encoding.
Method signatures and docstrings:
- def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256): Constructor. Args: num_inp... | Implement the Python class `PositionalFourierMLP` described below.
Class description:
Version of FFN with positional encoding.
Method signatures and docstrings:
- def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256): Constructor. Args: num_inp... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class PositionalFourierMLP:
"""Version of FFN with positional encoding."""
def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256):
"""Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PositionalFourierMLP:
"""Version of FFN with positional encoding."""
def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256):
"""Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int): Number... | the_stack_v2_python_sparse | generated/test_matajoh_fourier_feature_nets.py | jansel/pytorch-jit-paritybench | train | 35 |
47c1372c924a27b39091b5582b11ed75eb85d0cb | [
"key_string = 'sqlite_version'\nerror_strings = ['fts3tokenize', 'unknown tokenizer', 'file error', 'unable to delete/modify user-function due to active statements', 'DISTINCT is not supported for window functions', 'ORDER BY clause', 'abbreviated query algorithm search']\nkey_error_strings = [error_strings[0], err... | <|body_start_0|>
key_string = 'sqlite_version'
error_strings = ['fts3tokenize', 'unknown tokenizer', 'file error', 'unable to delete/modify user-function due to active statements', 'DISTINCT is not supported for window functions', 'ORDER BY clause', 'abbreviated query algorithm search']
key_erro... | Seeker (Identifier) for the zlib open source library. | SqliteSeeker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SqliteSeeker:
"""Seeker (Identifier) for the zlib open source library."""
def searchLib(self, logger):
"""Check if the open source library is located somewhere in the binary. Args: logger (logger): elementals logger instance Return Value: number of library instances that were found i... | stack_v2_sparse_classes_36k_train_023690 | 3,269 | permissive | [
{
"docstring": "Check if the open source library is located somewhere in the binary. Args: logger (logger): elementals logger instance Return Value: number of library instances that were found in the binary",
"name": "searchLib",
"signature": "def searchLib(self, logger)"
},
{
"docstring": "Iden... | 2 | null | Implement the Python class `SqliteSeeker` described below.
Class description:
Seeker (Identifier) for the zlib open source library.
Method signatures and docstrings:
- def searchLib(self, logger): Check if the open source library is located somewhere in the binary. Args: logger (logger): elementals logger instance Re... | Implement the Python class `SqliteSeeker` described below.
Class description:
Seeker (Identifier) for the zlib open source library.
Method signatures and docstrings:
- def searchLib(self, logger): Check if the open source library is located somewhere in the binary. Args: logger (logger): elementals logger instance Re... | 03adda0775bfa338bfc61bfac14fe457b283a85c | <|skeleton|>
class SqliteSeeker:
"""Seeker (Identifier) for the zlib open source library."""
def searchLib(self, logger):
"""Check if the open source library is located somewhere in the binary. Args: logger (logger): elementals logger instance Return Value: number of library instances that were found i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SqliteSeeker:
"""Seeker (Identifier) for the zlib open source library."""
def searchLib(self, logger):
"""Check if the open source library is located somewhere in the binary. Args: logger (logger): elementals logger instance Return Value: number of library instances that were found in the binary"... | the_stack_v2_python_sparse | src/libs/sqlite.py | MITRE-Reversing-Internship/Karta-Modified | train | 1 |
c304412776bb401013b68891d817ab2218926480 | [
"if not nums:\n return\nblucket = [[], [], []]\nfor v in nums:\n blucket[v % 10].append(v)\nnums[:] = [b for a in blucket for b in a]\nreturn nums",
"i = j = 0\nfor k in range(len(nums)):\n v = nums[k]\n nums[k] = 2\n if v < 2:\n nums[j] = 1\n j += 1\n if v == 0:\n nums[i] =... | <|body_start_0|>
if not nums:
return
blucket = [[], [], []]
for v in nums:
blucket[v % 10].append(v)
nums[:] = [b for a in blucket for b in a]
return nums
<|end_body_0|>
<|body_start_1|>
i = j = 0
for k in range(len(nums)):
v =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_36k_train_023691 | 1,210 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "so... | 2 | stack_v2_sparse_classes_30k_train_002522 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def sortColors2(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 sortColors(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def sortColors2(self, nums): :type nums: List[int] :rtype: ... | 472f780c3214aab5c713612812d834ccbe589434 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
if not nums:
return
blucket = [[], [], []]
for v in nums:
blucket[v % 10].append(v)
nums[:] = [b for a in blucket... | the_stack_v2_python_sparse | 2/75-Sort_Colors.py | ChangXiaodong/Leetcode-solutions | train | 4 | |
f1598614291b289d44c72e4f851bc0e56a366b3e | [
"super().__init__()\nself._raw_image = pygame.image.load('top_penguin.png')\nself._raw_image = self._raw_image.convert_alpha()\nself.image = self._raw_image\nself.rect = self.image.get_rect()\nself.rect.topleft = (0, screen.get_height() / 2 - self.rect.height / 2)\nself._speed = 5\nself._angle = 0",
"if direction... | <|body_start_0|>
super().__init__()
self._raw_image = pygame.image.load('top_penguin.png')
self._raw_image = self._raw_image.convert_alpha()
self.image = self._raw_image
self.rect = self.image.get_rect()
self.rect.topleft = (0, screen.get_height() / 2 - self.rect.height /... | A player-controlled character. | Penguin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Penguin:
"""A player-controlled character."""
def __init__(self, screen: pygame.Surface) -> None:
"""Initialize from parameters."""
<|body_0|>
def move(self, screen: pygame.Surface, direction: int) -> None:
"""Move in direction."""
<|body_1|>
def bac... | stack_v2_sparse_classes_36k_train_023692 | 7,402 | no_license | [
{
"docstring": "Initialize from parameters.",
"name": "__init__",
"signature": "def __init__(self, screen: pygame.Surface) -> None"
},
{
"docstring": "Move in direction.",
"name": "move",
"signature": "def move(self, screen: pygame.Surface, direction: int) -> None"
},
{
"docstrin... | 3 | null | Implement the Python class `Penguin` described below.
Class description:
A player-controlled character.
Method signatures and docstrings:
- def __init__(self, screen: pygame.Surface) -> None: Initialize from parameters.
- def move(self, screen: pygame.Surface, direction: int) -> None: Move in direction.
- def backup(... | Implement the Python class `Penguin` described below.
Class description:
A player-controlled character.
Method signatures and docstrings:
- def __init__(self, screen: pygame.Surface) -> None: Initialize from parameters.
- def move(self, screen: pygame.Surface, direction: int) -> None: Move in direction.
- def backup(... | 0fe17edf6ffcb35265032c6449d866b9434fda00 | <|skeleton|>
class Penguin:
"""A player-controlled character."""
def __init__(self, screen: pygame.Surface) -> None:
"""Initialize from parameters."""
<|body_0|>
def move(self, screen: pygame.Surface, direction: int) -> None:
"""Move in direction."""
<|body_1|>
def bac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Penguin:
"""A player-controlled character."""
def __init__(self, screen: pygame.Surface) -> None:
"""Initialize from parameters."""
super().__init__()
self._raw_image = pygame.image.load('top_penguin.png')
self._raw_image = self._raw_image.convert_alpha()
self.imag... | the_stack_v2_python_sparse | Chapter10TextbookCode/Listing 10-9.py | ProfessorBurke/PythonObjectsGames | train | 3 |
a86ec7ebfff3c462cfd5e5f1c06f52a1b9d1ad8b | [
"self.people = people if people else []\nself.missing = []\nif fname:\n with open(fname, newline='') as fp:\n reader = csv.reader(fp, delimiter=',', quotechar='|')\n for row in reader:\n r = requests.get('http://directory.arizona.edu/phonebook?lastname=' + row[0] + '&firstname=' + row[1]... | <|body_start_0|>
self.people = people if people else []
self.missing = []
if fname:
with open(fname, newline='') as fp:
reader = csv.reader(fp, delimiter=',', quotechar='|')
for row in reader:
r = requests.get('http://directory.ariz... | People | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class People:
def __init__(self, people=None, fname=None):
"""initializes the people and missing instance variables from a file people: a list of Person objects fname: a string representation of a file name"""
<|body_0|>
def select_people(self, peep_lst, search_name):
"""a... | stack_v2_sparse_classes_36k_train_023693 | 8,144 | no_license | [
{
"docstring": "initializes the people and missing instance variables from a file people: a list of Person objects fname: a string representation of a file name",
"name": "__init__",
"signature": "def __init__(self, people=None, fname=None)"
},
{
"docstring": "asks user to choose people out of p... | 4 | stack_v2_sparse_classes_30k_train_005816 | Implement the Python class `People` described below.
Class description:
Implement the People class.
Method signatures and docstrings:
- def __init__(self, people=None, fname=None): initializes the people and missing instance variables from a file people: a list of Person objects fname: a string representation of a fi... | Implement the Python class `People` described below.
Class description:
Implement the People class.
Method signatures and docstrings:
- def __init__(self, people=None, fname=None): initializes the people and missing instance variables from a file people: a list of Person objects fname: a string representation of a fi... | 1ae1928d39861007f9e7ed1463d4c62730c5e7ed | <|skeleton|>
class People:
def __init__(self, people=None, fname=None):
"""initializes the people and missing instance variables from a file people: a list of Person objects fname: a string representation of a file name"""
<|body_0|>
def select_people(self, peep_lst, search_name):
"""a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class People:
def __init__(self, people=None, fname=None):
"""initializes the people and missing instance variables from a file people: a list of Person objects fname: a string representation of a file name"""
self.people = people if people else []
self.missing = []
if fname:
... | the_stack_v2_python_sparse | Python/UAPhonebookSearch/UAPhonebookSearch.py | bhudnell/Past-Work | train | 0 | |
b7430d53b55a61c1e7153ec971d49b72b8a0b563 | [
"self.n_classes = number_class\nself.is_training = is_training\nself.is_simplified = is_simplified\nself.dropout = dropout",
"if not self.is_simplified:\n net, _ = unet.unet(input_batch, self.n_classes, is_training=is_training, dropout=dropout, weight_decay=0.0005)\nelse:\n net, _ = simplified_unet.unet(inp... | <|body_start_0|>
self.n_classes = number_class
self.is_training = is_training
self.is_simplified = is_simplified
self.dropout = dropout
<|end_body_0|>
<|body_start_1|>
if not self.is_simplified:
net, _ = unet.unet(input_batch, self.n_classes, is_training=is_training,... | UnetModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnetModel:
def __init__(self, number_class=3, is_training=True, is_simplified=False, dropout=True):
"""Create the model"""
<|body_0|>
def _create_network(self, input_batch, dropout=False, is_training=True):
"""Args: input_batch: batch of pre-processed images. keep_pr... | stack_v2_sparse_classes_36k_train_023694 | 4,646 | permissive | [
{
"docstring": "Create the model",
"name": "__init__",
"signature": "def __init__(self, number_class=3, is_training=True, is_simplified=False, dropout=True)"
},
{
"docstring": "Args: input_batch: batch of pre-processed images. keep_prob: probability of keeping neurons intact. Returns: A downsamp... | 5 | stack_v2_sparse_classes_30k_train_000682 | Implement the Python class `UnetModel` described below.
Class description:
Implement the UnetModel class.
Method signatures and docstrings:
- def __init__(self, number_class=3, is_training=True, is_simplified=False, dropout=True): Create the model
- def _create_network(self, input_batch, dropout=False, is_training=Tr... | Implement the Python class `UnetModel` described below.
Class description:
Implement the UnetModel class.
Method signatures and docstrings:
- def __init__(self, number_class=3, is_training=True, is_simplified=False, dropout=True): Create the model
- def _create_network(self, input_batch, dropout=False, is_training=Tr... | 57904544c6d6b43dcd5937afeb474c0a47456d98 | <|skeleton|>
class UnetModel:
def __init__(self, number_class=3, is_training=True, is_simplified=False, dropout=True):
"""Create the model"""
<|body_0|>
def _create_network(self, input_batch, dropout=False, is_training=True):
"""Args: input_batch: batch of pre-processed images. keep_pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnetModel:
def __init__(self, number_class=3, is_training=True, is_simplified=False, dropout=True):
"""Create the model"""
self.n_classes = number_class
self.is_training = is_training
self.is_simplified = is_simplified
self.dropout = dropout
def _create_network(sel... | the_stack_v2_python_sparse | models/model_unet.py | cliang1453/IHC-based-labels-generation-and-semantic-segmentation-for-lung-cancer | train | 0 | |
83c0b70fcf56401f49bfb8cc4801d338245a861e | [
"collaboration = db.Collaboration.get(id)\nif not collaboration:\n return ({'msg': 'collaboration having collaboration_id={} can not be found'.format(id)}, HTTPStatus.NOT_FOUND)\nreturn (self.node_schema.dump(collaboration.nodes, many=True).data, HTTPStatus.OK)",
"collaboration = db.Collaboration.get(id)\nif n... | <|body_start_0|>
collaboration = db.Collaboration.get(id)
if not collaboration:
return ({'msg': 'collaboration having collaboration_id={} can not be found'.format(id)}, HTTPStatus.NOT_FOUND)
return (self.node_schema.dump(collaboration.nodes, many=True).data, HTTPStatus.OK)
<|end_body... | Resource for /api/collaboration/<int:id>/node. | CollaborationNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollaborationNode:
"""Resource for /api/collaboration/<int:id>/node."""
def get(self, id):
""""Return a list of nodes that belong to the collaboration."""
<|body_0|>
def post(self, id):
"""Add an node to a specific collaboration."""
<|body_1|>
def de... | stack_v2_sparse_classes_36k_train_023695 | 14,133 | permissive | [
{
"docstring": "\"Return a list of nodes that belong to the collaboration.",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Add an node to a specific collaboration.",
"name": "post",
"signature": "def post(self, id)"
},
{
"docstring": "Remove node from collabo... | 3 | stack_v2_sparse_classes_30k_train_010946 | Implement the Python class `CollaborationNode` described below.
Class description:
Resource for /api/collaboration/<int:id>/node.
Method signatures and docstrings:
- def get(self, id): "Return a list of nodes that belong to the collaboration.
- def post(self, id): Add an node to a specific collaboration.
- def delete... | Implement the Python class `CollaborationNode` described below.
Class description:
Resource for /api/collaboration/<int:id>/node.
Method signatures and docstrings:
- def get(self, id): "Return a list of nodes that belong to the collaboration.
- def post(self, id): Add an node to a specific collaboration.
- def delete... | a64827981db26b34dd1dcea1cb2282d03dd4545d | <|skeleton|>
class CollaborationNode:
"""Resource for /api/collaboration/<int:id>/node."""
def get(self, id):
""""Return a list of nodes that belong to the collaboration."""
<|body_0|>
def post(self, id):
"""Add an node to a specific collaboration."""
<|body_1|>
def de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollaborationNode:
"""Resource for /api/collaboration/<int:id>/node."""
def get(self, id):
""""Return a list of nodes that belong to the collaboration."""
collaboration = db.Collaboration.get(id)
if not collaboration:
return ({'msg': 'collaboration having collaboration... | the_stack_v2_python_sparse | vantage6/server/resource/collaboration.py | mindrenee/vantage6-server | train | 0 |
fcb0bded96199e93c2eb5196f72d8da001de0924 | [
"if not overwrite_destination and os.path.exists(installation_dir):\n raise ValueError(f'Plugin {repr(cls)} cannot be installed into existing path {installation_dir} because overwrite_destination={overwrite_destination}.')\nsuper().install(installation_dir=installation_dir, overwrite_destination=True)\nprint(f'P... | <|body_start_0|>
if not overwrite_destination and os.path.exists(installation_dir):
raise ValueError(f'Plugin {repr(cls)} cannot be installed into existing path {installation_dir} because overwrite_destination={overwrite_destination}.')
super().install(installation_dir=installation_dir, over... | Plugins are self-contained, python modules that may assume enb is installed. - They can be installed into your projects via the enb CLI (e.g., with `enb plugin install <name> <clone_dir>`), and then imported like any other module. - The list of plugins available off-the-box can be obtained using the enb CLI (e.g., with... | Plugin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plugin:
"""Plugins are self-contained, python modules that may assume enb is installed. - They can be installed into your projects via the enb CLI (e.g., with `enb plugin install <name> <clone_dir>`), and then imported like any other module. - The list of plugins available off-the-box can be obta... | stack_v2_sparse_classes_36k_train_023696 | 5,481 | permissive | [
{
"docstring": "Make a copy of this plugin into installation_dir, ready to be imported. By default, a verbatim copy of the source plugin's dir is made. Any previous contents in installation_dir are overwritten. Then any explicit requirements are met (external software may be downloaded and pip packages installe... | 2 | stack_v2_sparse_classes_30k_train_014022 | Implement the Python class `Plugin` described below.
Class description:
Plugins are self-contained, python modules that may assume enb is installed. - They can be installed into your projects via the enb CLI (e.g., with `enb plugin install <name> <clone_dir>`), and then imported like any other module. - The list of pl... | Implement the Python class `Plugin` described below.
Class description:
Plugins are self-contained, python modules that may assume enb is installed. - They can be installed into your projects via the enb CLI (e.g., with `enb plugin install <name> <clone_dir>`), and then imported like any other module. - The list of pl... | 35f9eecd93a3e8cc90631c3a819a36de1c40401f | <|skeleton|>
class Plugin:
"""Plugins are self-contained, python modules that may assume enb is installed. - They can be installed into your projects via the enb CLI (e.g., with `enb plugin install <name> <clone_dir>`), and then imported like any other module. - The list of plugins available off-the-box can be obta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Plugin:
"""Plugins are self-contained, python modules that may assume enb is installed. - They can be installed into your projects via the enb CLI (e.g., with `enb plugin install <name> <clone_dir>`), and then imported like any other module. - The list of plugins available off-the-box can be obtained using th... | the_stack_v2_python_sparse | enb/plugins/plugin.py | esterjara/experiment-notebook | train | 0 |
f7ca3b54bc99fa691e5de6d9765569aee8b78fa6 | [
"super(ChromeCacheIndexFileParser, self).__init__()\nself.creation_time = None\nself.index_table = []",
"file_header_map = self._GetDataTypeMap('chrome_cache_index_file_header')\ntry:\n file_header, _ = self._ReadStructureFromFileObject(file_object, 0, file_header_map)\nexcept (ValueError, errors.ParseError) a... | <|body_start_0|>
super(ChromeCacheIndexFileParser, self).__init__()
self.creation_time = None
self.index_table = []
<|end_body_0|>
<|body_start_1|>
file_header_map = self._GetDataTypeMap('chrome_cache_index_file_header')
try:
file_header, _ = self._ReadStructureFromF... | Chrome cache index file parser. Attributes: creation_time (int): creation time, in number of microseconds since January 1, 1601, 00:00:00 UTC. index_table (list[CacheAddress]): the cache addresses which are stored in the index file. | ChromeCacheIndexFileParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChromeCacheIndexFileParser:
"""Chrome cache index file parser. Attributes: creation_time (int): creation time, in number of microseconds since January 1, 1601, 00:00:00 UTC. index_table (list[CacheAddress]): the cache addresses which are stored in the index file."""
def __init__(self):
... | stack_v2_sparse_classes_36k_train_023697 | 16,868 | permissive | [
{
"docstring": "Initializes an index file.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Parses the file header. Args: file_object (dfvfs.FileIO): a file-like object to parse. Raises: ParseError: if the file header cannot be read.",
"name": "_ParseFileHeader",
... | 4 | null | Implement the Python class `ChromeCacheIndexFileParser` described below.
Class description:
Chrome cache index file parser. Attributes: creation_time (int): creation time, in number of microseconds since January 1, 1601, 00:00:00 UTC. index_table (list[CacheAddress]): the cache addresses which are stored in the index ... | Implement the Python class `ChromeCacheIndexFileParser` described below.
Class description:
Chrome cache index file parser. Attributes: creation_time (int): creation time, in number of microseconds since January 1, 1601, 00:00:00 UTC. index_table (list[CacheAddress]): the cache addresses which are stored in the index ... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class ChromeCacheIndexFileParser:
"""Chrome cache index file parser. Attributes: creation_time (int): creation time, in number of microseconds since January 1, 1601, 00:00:00 UTC. index_table (list[CacheAddress]): the cache addresses which are stored in the index file."""
def __init__(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChromeCacheIndexFileParser:
"""Chrome cache index file parser. Attributes: creation_time (int): creation time, in number of microseconds since January 1, 1601, 00:00:00 UTC. index_table (list[CacheAddress]): the cache addresses which are stored in the index file."""
def __init__(self):
"""Initial... | the_stack_v2_python_sparse | plaso/parsers/chrome_cache.py | log2timeline/plaso | train | 1,506 |
8df4588e64d3b243be3231bb032ed64ef8f3fa80 | [
"if 'base.group_no_one' in groups.split(',') and self.env.user.has_group('cq_technical_features.group_technical_features'):\n return True\nreturn super(Base, self).user_has_groups(groups)",
"current_user = self.env.user\nallowed_group = 'cq_technical_features.group_import_csv'\nallowed_group_id = self.env.ref(... | <|body_start_0|>
if 'base.group_no_one' in groups.split(',') and self.env.user.has_group('cq_technical_features.group_technical_features'):
return True
return super(Base, self).user_has_groups(groups)
<|end_body_0|>
<|body_start_1|>
current_user = self.env.user
allowed_group... | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
def user_has_groups(self, groups):
"""Return True for users in the technical features group when membership of the original group is checked, even if debug mode is not enabled."""
<|body_0|>
def load(self, fields, data):
"""Overriding this method we only allow ... | stack_v2_sparse_classes_36k_train_023698 | 2,044 | no_license | [
{
"docstring": "Return True for users in the technical features group when membership of the original group is checked, even if debug mode is not enabled.",
"name": "user_has_groups",
"signature": "def user_has_groups(self, groups)"
},
{
"docstring": "Overriding this method we only allow its exe... | 2 | stack_v2_sparse_classes_30k_val_000135 | Implement the Python class `Base` described below.
Class description:
Implement the Base class.
Method signatures and docstrings:
- def user_has_groups(self, groups): Return True for users in the technical features group when membership of the original group is checked, even if debug mode is not enabled.
- def load(s... | Implement the Python class `Base` described below.
Class description:
Implement the Base class.
Method signatures and docstrings:
- def user_has_groups(self, groups): Return True for users in the technical features group when membership of the original group is checked, even if debug mode is not enabled.
- def load(s... | e5c18cf9bc003d48f1359ab1271cc68fc204c17d | <|skeleton|>
class Base:
def user_has_groups(self, groups):
"""Return True for users in the technical features group when membership of the original group is checked, even if debug mode is not enabled."""
<|body_0|>
def load(self, fields, data):
"""Overriding this method we only allow ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base:
def user_has_groups(self, groups):
"""Return True for users in the technical features group when membership of the original group is checked, even if debug mode is not enabled."""
if 'base.group_no_one' in groups.split(',') and self.env.user.has_group('cq_technical_features.group_technic... | the_stack_v2_python_sparse | cq_technical_features/models/base.py | ssiccardi/odoo10_generic_addons | train | 0 | |
7920a2b30a0f7e7eae3d906b1916377f4c7df1d2 | [
"activation = self.config['arch']['activation']\ndropout = self.config['arch']['drop']\nfull_layers = self.config['arch']['full']\nidimensions = self.config['idimensions']\nodimensions = self.config['odimensions']\nrdimensions = self.config['rdimensions']\ninput = Input(shape=idimensions)\nif rdimensions > 0:\n ... | <|body_start_0|>
activation = self.config['arch']['activation']
dropout = self.config['arch']['drop']
full_layers = self.config['arch']['full']
idimensions = self.config['idimensions']
odimensions = self.config['odimensions']
rdimensions = self.config['rdimensions']
... | Mutitlayer perceptron with sequence to sequence architecture for recursive training | MLPS2SRecursiveArchitecture | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLPS2SRecursiveArchitecture:
"""Mutitlayer perceptron with sequence to sequence architecture for recursive training"""
def generate_model(self):
"""Model for MLP recursive multiple regression (s2s) It takes as inputs the data and the predictions of the previous step :return:"""
... | stack_v2_sparse_classes_36k_train_023699 | 2,752 | no_license | [
{
"docstring": "Model for MLP recursive multiple regression (s2s) It takes as inputs the data and the predictions of the previous step :return:",
"name": "generate_model",
"signature": "def generate_model(self)"
},
{
"docstring": "Returns the predictions of the model for some data :param val_x: ... | 2 | null | Implement the Python class `MLPS2SRecursiveArchitecture` described below.
Class description:
Mutitlayer perceptron with sequence to sequence architecture for recursive training
Method signatures and docstrings:
- def generate_model(self): Model for MLP recursive multiple regression (s2s) It takes as inputs the data a... | Implement the Python class `MLPS2SRecursiveArchitecture` described below.
Class description:
Mutitlayer perceptron with sequence to sequence architecture for recursive training
Method signatures and docstrings:
- def generate_model(self): Model for MLP recursive multiple regression (s2s) It takes as inputs the data a... | a339737ec23d6f54090396eda7d8507c313a8c79 | <|skeleton|>
class MLPS2SRecursiveArchitecture:
"""Mutitlayer perceptron with sequence to sequence architecture for recursive training"""
def generate_model(self):
"""Model for MLP recursive multiple regression (s2s) It takes as inputs the data and the predictions of the previous step :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MLPS2SRecursiveArchitecture:
"""Mutitlayer perceptron with sequence to sequence architecture for recursive training"""
def generate_model(self):
"""Model for MLP recursive multiple regression (s2s) It takes as inputs the data and the predictions of the previous step :return:"""
activation... | the_stack_v2_python_sparse | Wind/Architectures/MLPS2SRecursiveArchitecture.py | bejar/Wind | train | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.