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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5d3215aed2f7a7efbe1d2107b7d4bb3f2fc89682 | [
"try:\n qs = Schema({Optional('page', default=1): schema_int, Optional('count', default=20): schema_int, Optional('limit', default=1): schema_bool, Optional('only'): schema_unicode, Optional('order_by', default='name'): schema_unicode}).validate(self.get_query_args())\nexcept SchemaError as e:\n logging.warn(... | <|body_start_0|>
try:
qs = Schema({Optional('page', default=1): schema_int, Optional('count', default=20): schema_int, Optional('limit', default=1): schema_bool, Optional('only'): schema_unicode, Optional('order_by', default='name'): schema_unicode}).validate(self.get_query_args())
except Sc... | Node | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
def get(self):
"""站点列表 :return:"""
<|body_0|>
def post(self):
"""站点添加 :return:"""
<|body_1|>
def delete(self):
"""站点删除 :return:"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
try:
qs = Schema({Optional('page',... | stack_v2_sparse_classes_36k_train_011500 | 24,267 | permissive | [
{
"docstring": "站点列表 :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "站点添加 :return:",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "站点删除 :return:",
"name": "delete",
"signature": "def delete(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_020596 | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def get(self): 站点列表 :return:
- def post(self): 站点添加 :return:
- def delete(self): 站点删除 :return: | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def get(self): 站点列表 :return:
- def post(self): 站点添加 :return:
- def delete(self): 站点删除 :return:
<|skeleton|>
class Node:
def get(self):
"""站点列表 :return:"""
<|body_0|... | a7c9567975b5372b2edabddb0fec8d73bc01c3dc | <|skeleton|>
class Node:
def get(self):
"""站点列表 :return:"""
<|body_0|>
def post(self):
"""站点添加 :return:"""
<|body_1|>
def delete(self):
"""站点删除 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Node:
def get(self):
"""站点列表 :return:"""
try:
qs = Schema({Optional('page', default=1): schema_int, Optional('count', default=20): schema_int, Optional('limit', default=1): schema_bool, Optional('only'): schema_unicode, Optional('order_by', default='name'): schema_unicode}).validat... | the_stack_v2_python_sparse | Dispatcher/api_gateway/express/handlers/yun.py | cash2one/Logistics | train | 0 | |
232e095ac99da773819fe664104c323467512b4d | [
"rights = access.Checker(params)\nnew_params = {}\nnew_params['rights'] = rights\nnew_params['logic'] = priority_group_logic\nnew_params['name'] = 'Cron'\nnew_params['django_patterns_defaults'] = [('^%(url_name)s/(?P<access_type>poke)$', 'soc.views.models.%(module_name)s.poke', 'Poke %(name_short)s')]\nparams = dic... | <|body_start_0|>
rights = access.Checker(params)
new_params = {}
new_params['rights'] = rights
new_params['logic'] = priority_group_logic
new_params['name'] = 'Cron'
new_params['django_patterns_defaults'] = [('^%(url_name)s/(?P<access_type>poke)$', 'soc.views.models.%(mod... | View methods for the Cron model. | View | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
"""View methods for the Cron model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
<|body_0|... | stack_v2_sparse_classes_36k_train_011501 | 3,167 | permissive | [
{
"docstring": "Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View",
"name": "__init__",
"signature": "def __init__(self, params=None)"
},
{
"docstring": "View call... | 2 | stack_v2_sparse_classes_30k_train_000848 | Implement the Python class `View` described below.
Class description:
View methods for the Cron model.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: para... | Implement the Python class `View` described below.
Class description:
View methods for the Cron model.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: para... | 5c5d50eea89372e967994dac3bd8b06d25b4f0fa | <|skeleton|>
class View:
"""View methods for the Cron model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class View:
"""View methods for the Cron model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
rights = access.Checke... | the_stack_v2_python_sparse | src/melange/src/soc/views/models/cron.py | MatthewWilkes/mw4068-packaging | train | 0 |
72dc28be21e84567063e62a7b57fe638d79ba093 | [
"networks = self.sf.query_all(format_soql('SELECT Id FROM Network WHERE Name = {network_name} LIMIT 1', network_name=network_name))\nif not networks['records']:\n raise SalesforceException(f'No Network record found with Name \"{network_name}\"')\nself.logger.info(f'Creating NetworkMemberGroup records for {networ... | <|body_start_0|>
networks = self.sf.query_all(format_soql('SELECT Id FROM Network WHERE Name = {network_name} LIMIT 1', network_name=network_name))
if not networks['records']:
raise SalesforceException(f'No Network record found with Name "{network_name}"')
self.logger.info(f'Creating... | Creates NetworkMemberGroup for a Network (Experience Site) for Profiles and Permission Sets that don't already have a corresponding NetworkMemberGroup. Raises exceptions if records cannot be found: - Network with Name network_name - Profiles with Names in profile_names - Permission Sets with Names in permission_set_nam... | CreateNetworkMemberGroups | [
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateNetworkMemberGroups:
"""Creates NetworkMemberGroup for a Network (Experience Site) for Profiles and Permission Sets that don't already have a corresponding NetworkMemberGroup. Raises exceptions if records cannot be found: - Network with Name network_name - Profiles with Names in profile_nam... | stack_v2_sparse_classes_36k_train_011502 | 6,853 | permissive | [
{
"docstring": "Returns Id of Network record with Name network_name. Raises a SalesforceException if no Network is found.",
"name": "_get_network_id",
"signature": "def _get_network_id(self, network_name: str) -> str"
},
{
"docstring": "Collect existing NetworkMemberGroup Parent IDs (associated ... | 6 | stack_v2_sparse_classes_30k_train_014247 | Implement the Python class `CreateNetworkMemberGroups` described below.
Class description:
Creates NetworkMemberGroup for a Network (Experience Site) for Profiles and Permission Sets that don't already have a corresponding NetworkMemberGroup. Raises exceptions if records cannot be found: - Network with Name network_na... | Implement the Python class `CreateNetworkMemberGroups` described below.
Class description:
Creates NetworkMemberGroup for a Network (Experience Site) for Profiles and Permission Sets that don't already have a corresponding NetworkMemberGroup. Raises exceptions if records cannot be found: - Network with Name network_na... | 9ccf3c9566f78c6e9102ac214db30470cef660c1 | <|skeleton|>
class CreateNetworkMemberGroups:
"""Creates NetworkMemberGroup for a Network (Experience Site) for Profiles and Permission Sets that don't already have a corresponding NetworkMemberGroup. Raises exceptions if records cannot be found: - Network with Name network_name - Profiles with Names in profile_nam... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateNetworkMemberGroups:
"""Creates NetworkMemberGroup for a Network (Experience Site) for Profiles and Permission Sets that don't already have a corresponding NetworkMemberGroup. Raises exceptions if records cannot be found: - Network with Name network_name - Profiles with Names in profile_names - Permissi... | the_stack_v2_python_sparse | cumulusci/tasks/salesforce/network_member_group.py | SFDO-Tooling/CumulusCI | train | 226 |
5fcc73fcf727364396166beb408a2428452ac776 | [
"if not isinstance(model, BayesianNetwork):\n raise NotImplementedError('Bayesian Parameter Estimation is only implemented for BayesianNetwork')\nelif len(model.latents) != 0:\n raise ValueError(f'Bayesian Parameter Estimation works only on models with all observed variables. Found latent variables: {model.la... | <|body_start_0|>
if not isinstance(model, BayesianNetwork):
raise NotImplementedError('Bayesian Parameter Estimation is only implemented for BayesianNetwork')
elif len(model.latents) != 0:
raise ValueError(f'Bayesian Parameter Estimation works only on models with all observed var... | BayesianEstimator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianEstimator:
def __init__(self, model, data, **kwargs):
"""Class used to compute parameters for a model using Bayesian Parameter Estimation. See `MaximumLikelihoodEstimator` for constructor parameters."""
<|body_0|>
def get_parameters(self, prior_type='BDeu', equivalen... | stack_v2_sparse_classes_36k_train_011503 | 10,409 | permissive | [
{
"docstring": "Class used to compute parameters for a model using Bayesian Parameter Estimation. See `MaximumLikelihoodEstimator` for constructor parameters.",
"name": "__init__",
"signature": "def __init__(self, model, data, **kwargs)"
},
{
"docstring": "Method to estimate the model parameters... | 3 | null | Implement the Python class `BayesianEstimator` described below.
Class description:
Implement the BayesianEstimator class.
Method signatures and docstrings:
- def __init__(self, model, data, **kwargs): Class used to compute parameters for a model using Bayesian Parameter Estimation. See `MaximumLikelihoodEstimator` fo... | Implement the Python class `BayesianEstimator` described below.
Class description:
Implement the BayesianEstimator class.
Method signatures and docstrings:
- def __init__(self, model, data, **kwargs): Class used to compute parameters for a model using Bayesian Parameter Estimation. See `MaximumLikelihoodEstimator` fo... | 6d66bde4c7f140ba14892174c59370b2b7964e90 | <|skeleton|>
class BayesianEstimator:
def __init__(self, model, data, **kwargs):
"""Class used to compute parameters for a model using Bayesian Parameter Estimation. See `MaximumLikelihoodEstimator` for constructor parameters."""
<|body_0|>
def get_parameters(self, prior_type='BDeu', equivalen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BayesianEstimator:
def __init__(self, model, data, **kwargs):
"""Class used to compute parameters for a model using Bayesian Parameter Estimation. See `MaximumLikelihoodEstimator` for constructor parameters."""
if not isinstance(model, BayesianNetwork):
raise NotImplementedError('B... | the_stack_v2_python_sparse | pgmpy/estimators/BayesianEstimator.py | pgmpy/pgmpy | train | 2,617 | |
dd34e1a082e8d51d63d92359b9a114789d9006fb | [
"old_namespace = NamespacesModel.query.filter(NamespacesModel.namespace == namespace.namespace).first()\nif old_namespace:\n return (False, from_dict(Namespace, old_namespace.as_dict()))\nwith DBConnectionHander() as conn:\n try:\n new_namespace = NamespacesModel(**namespace.__dict__)\n conn.ses... | <|body_start_0|>
old_namespace = NamespacesModel.query.filter(NamespacesModel.namespace == namespace.namespace).first()
if old_namespace:
return (False, from_dict(Namespace, old_namespace.as_dict()))
with DBConnectionHander() as conn:
try:
new_namespace = ... | A manager of Namespaces model. | NamespaceRepositoryManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NamespaceRepositoryManager:
"""A manager of Namespaces model."""
def get_or_create(cls, namespace: Namespace) -> Tuple[bool, Namespace]:
"""Insert a single record into database Args: namespace (Namespace): An namespace object. Returns: Tuple[bool, Namespace]: A boolean indicating if ... | stack_v2_sparse_classes_36k_train_011504 | 3,770 | no_license | [
{
"docstring": "Insert a single record into database Args: namespace (Namespace): An namespace object. Returns: Tuple[bool, Namespace]: A boolean indicating if the namespace was created (True) or recovered from database (False), and a instance of the created namespace.",
"name": "get_or_create",
"signat... | 3 | stack_v2_sparse_classes_30k_train_011857 | Implement the Python class `NamespaceRepositoryManager` described below.
Class description:
A manager of Namespaces model.
Method signatures and docstrings:
- def get_or_create(cls, namespace: Namespace) -> Tuple[bool, Namespace]: Insert a single record into database Args: namespace (Namespace): An namespace object. ... | Implement the Python class `NamespaceRepositoryManager` described below.
Class description:
A manager of Namespaces model.
Method signatures and docstrings:
- def get_or_create(cls, namespace: Namespace) -> Tuple[bool, Namespace]: Insert a single record into database Args: namespace (Namespace): An namespace object. ... | 5d240fea783a453137c9a3697b67dae67b08a73d | <|skeleton|>
class NamespaceRepositoryManager:
"""A manager of Namespaces model."""
def get_or_create(cls, namespace: Namespace) -> Tuple[bool, Namespace]:
"""Insert a single record into database Args: namespace (Namespace): An namespace object. Returns: Tuple[bool, Namespace]: A boolean indicating if ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NamespaceRepositoryManager:
"""A manager of Namespaces model."""
def get_or_create(cls, namespace: Namespace) -> Tuple[bool, Namespace]:
"""Insert a single record into database Args: namespace (Namespace): An namespace object. Returns: Tuple[bool, Namespace]: A boolean indicating if the namespace... | the_stack_v2_python_sparse | src/adapters/repositories/namespace.py | sgelias/blu | train | 0 |
e094adcc06d95287efec38b54ea8121981a9f329 | [
"try:\n state_folder_obj = StateFolder.objects.get(id=int(uid))\nexcept:\n return None\nreturn state_folder_obj",
"jobs_list = []\nstate_folder_obj = self._get_folder_object(uid)\nif state_folder_obj:\n if state_folder_obj.is_root_node() and state_folder_obj.name == 'Private':\n jobs = state_folde... | <|body_start_0|>
try:
state_folder_obj = StateFolder.objects.get(id=int(uid))
except:
return None
return state_folder_obj
<|end_body_0|>
<|body_start_1|>
jobs_list = []
state_folder_obj = self._get_folder_object(uid)
if state_folder_obj:
... | List down all the jobs in the database without public private segregation. | JobLeafView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobLeafView:
"""List down all the jobs in the database without public private segregation."""
def _get_folder_object(self, uid):
"""Get the folder object on the basis of UID"""
<|body_0|>
def _get_leaf_jobs(self, uid):
"""To get a list of all leaf nodes"""
... | stack_v2_sparse_classes_36k_train_011505 | 47,872 | no_license | [
{
"docstring": "Get the folder object on the basis of UID",
"name": "_get_folder_object",
"signature": "def _get_folder_object(self, uid)"
},
{
"docstring": "To get a list of all leaf nodes",
"name": "_get_leaf_jobs",
"signature": "def _get_leaf_jobs(self, uid)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_test_000887 | Implement the Python class `JobLeafView` described below.
Class description:
List down all the jobs in the database without public private segregation.
Method signatures and docstrings:
- def _get_folder_object(self, uid): Get the folder object on the basis of UID
- def _get_leaf_jobs(self, uid): To get a list of all... | Implement the Python class `JobLeafView` described below.
Class description:
List down all the jobs in the database without public private segregation.
Method signatures and docstrings:
- def _get_folder_object(self, uid): Get the folder object on the basis of UID
- def _get_leaf_jobs(self, uid): To get a list of all... | 122a172caea82ef660e81a9dfc6377afd731f9cb | <|skeleton|>
class JobLeafView:
"""List down all the jobs in the database without public private segregation."""
def _get_folder_object(self, uid):
"""Get the folder object on the basis of UID"""
<|body_0|>
def _get_leaf_jobs(self, uid):
"""To get a list of all leaf nodes"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JobLeafView:
"""List down all the jobs in the database without public private segregation."""
def _get_folder_object(self, uid):
"""Get the folder object on the basis of UID"""
try:
state_folder_obj = StateFolder.objects.get(id=int(uid))
except:
return None... | the_stack_v2_python_sparse | sso/files/gui/sse/job/views.py | nofxrok/headless | train | 1 |
624da4dcc8c6a8ae5c6a0d01e5663e0216d964ca | [
"super(STFT, self).__init__()\nassert pad_mode in ['constant', 'reflect']\nself.n_fft = n_fft\nself.center = center\nself.pad_mode = pad_mode\nif win_length is None:\n win_length = n_fft\nif hop_length is None:\n hop_length = int(win_length // 4)\nfft_window = librosa.filters.get_window(window, win_length, ff... | <|body_start_0|>
super(STFT, self).__init__()
assert pad_mode in ['constant', 'reflect']
self.n_fft = n_fft
self.center = center
self.pad_mode = pad_mode
if win_length is None:
win_length = n_fft
if hop_length is None:
hop_length = int(win_... | STFT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class STFT:
def __init__(self, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='reflect', freeze_parameters=True):
"""Implementation of STFT with Conv1d. The function has the same output of librosa.core.stft"""
<|body_0|>
def forward(self, input)... | stack_v2_sparse_classes_36k_train_011506 | 25,139 | no_license | [
{
"docstring": "Implementation of STFT with Conv1d. The function has the same output of librosa.core.stft",
"name": "__init__",
"signature": "def __init__(self, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='reflect', freeze_parameters=True)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_016158 | Implement the Python class `STFT` described below.
Class description:
Implement the STFT class.
Method signatures and docstrings:
- def __init__(self, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='reflect', freeze_parameters=True): Implementation of STFT with Conv1d. The function... | Implement the Python class `STFT` described below.
Class description:
Implement the STFT class.
Method signatures and docstrings:
- def __init__(self, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='reflect', freeze_parameters=True): Implementation of STFT with Conv1d. The function... | 7ab627aefa56525735684b6671918d7c7db1cc07 | <|skeleton|>
class STFT:
def __init__(self, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='reflect', freeze_parameters=True):
"""Implementation of STFT with Conv1d. The function has the same output of librosa.core.stft"""
<|body_0|>
def forward(self, input)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class STFT:
def __init__(self, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, pad_mode='reflect', freeze_parameters=True):
"""Implementation of STFT with Conv1d. The function has the same output of librosa.core.stft"""
super(STFT, self).__init__()
assert pad_mode i... | the_stack_v2_python_sparse | easy_gold/pann_utils.py | wdy06/kaggle-birdsong-recognition | train | 1 | |
d48cfdcf7c832d7ab459c0a1e9f7d98a1398e882 | [
"super(RelacionAntecesorSucesorForm, self).__init__(*args, **kwargs)\nself.fields['antecesor'] = forms.ModelChoiceField(queryset=item.get_fase().fase_anterior.get_item_estado(EstadoDeItem.EN_LINEA_BASE))\nself.item = item",
"antecesor = self.cleaned_data['antecesor']\nif self.item in antecesor.get_sucesores():\n ... | <|body_start_0|>
super(RelacionAntecesorSucesorForm, self).__init__(*args, **kwargs)
self.fields['antecesor'] = forms.ModelChoiceField(queryset=item.get_fase().fase_anterior.get_item_estado(EstadoDeItem.EN_LINEA_BASE))
self.item = item
<|end_body_0|>
<|body_start_1|>
antecesor = self.cl... | Form que permite la creación de un nueva relacion antecesor-sucesor entre item. Es necesario especificar un antecesor para el item si es que no se encuentra en la primera fase del proyecto. Campos: - Antecesor: Item, antecesor de este item (no requerido en la primera fase) | RelacionAntecesorSucesorForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelacionAntecesorSucesorForm:
"""Form que permite la creación de un nueva relacion antecesor-sucesor entre item. Es necesario especificar un antecesor para el item si es que no se encuentra en la primera fase del proyecto. Campos: - Antecesor: Item, antecesor de este item (no requerido en la prim... | stack_v2_sparse_classes_36k_train_011507 | 12,403 | no_license | [
{
"docstring": "Constructor de la clase RelacionAntecesorSucesorForm. Los items candidatos para el campo Antecesor son seleccionados de la fase anterior aquellos que estan en una linea base. Argumentos: - item: Item, items de la fase anterior que cumplan que esten en una linea base",
"name": "__init__",
... | 2 | null | Implement the Python class `RelacionAntecesorSucesorForm` described below.
Class description:
Form que permite la creación de un nueva relacion antecesor-sucesor entre item. Es necesario especificar un antecesor para el item si es que no se encuentra en la primera fase del proyecto. Campos: - Antecesor: Item, anteceso... | Implement the Python class `RelacionAntecesorSucesorForm` described below.
Class description:
Form que permite la creación de un nueva relacion antecesor-sucesor entre item. Es necesario especificar un antecesor para el item si es que no se encuentra en la primera fase del proyecto. Campos: - Antecesor: Item, anteceso... | 423e79d437b8666f9508b4b0eeb2be67533b8b2d | <|skeleton|>
class RelacionAntecesorSucesorForm:
"""Form que permite la creación de un nueva relacion antecesor-sucesor entre item. Es necesario especificar un antecesor para el item si es que no se encuentra en la primera fase del proyecto. Campos: - Antecesor: Item, antecesor de este item (no requerido en la prim... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelacionAntecesorSucesorForm:
"""Form que permite la creación de un nueva relacion antecesor-sucesor entre item. Es necesario especificar un antecesor para el item si es que no se encuentra en la primera fase del proyecto. Campos: - Antecesor: Item, antecesor de este item (no requerido en la primera fase)"""
... | the_stack_v2_python_sparse | gestion_de_item/forms.py | jbust97/proyecto_is2 | train | 0 |
c799c473c22cc454275a942954661ae0d90bccc2 | [
"mdata = dict()\nmdata['riff'] = header[:4]\nmdata['size'] = to_int(header[4:8]) + 8\nmdata['wave'] = header[8:12]\nmdata['fmt'] = header[12:16]\nmdata['16'] = to_int(header[16:20])\nmdata['type'] = to_int(header[20:22])\nmdata['nch'] = to_int(header[22:24])\nmdata['fs'] = to_int(header[24:28])\nmdata['bps'] = to_i... | <|body_start_0|>
mdata = dict()
mdata['riff'] = header[:4]
mdata['size'] = to_int(header[4:8]) + 8
mdata['wave'] = header[8:12]
mdata['fmt'] = header[12:16]
mdata['16'] = to_int(header[16:20])
mdata['type'] = to_int(header[20:22])
mdata['nch'] = to_int(hea... | Clase con métodos estáticos útiles para trabajar con metadata de un .wav | WAVMdata | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WAVMdata:
"""Clase con métodos estáticos útiles para trabajar con metadata de un .wav"""
def get_metadata(header):
"""Recibe el header de un archivo .wav (primeros 44 bytes) Y retorna un diccionario con su metadata"""
<|body_0|>
def write_mdata(mdata, file):
"""R... | stack_v2_sparse_classes_36k_train_011508 | 7,055 | no_license | [
{
"docstring": "Recibe el header de un archivo .wav (primeros 44 bytes) Y retorna un diccionario con su metadata",
"name": "get_metadata",
"signature": "def get_metadata(header)"
},
{
"docstring": "Recibe una metadata (diccionario) y un archivo de output, y escribe en el archivo un header de .wa... | 2 | stack_v2_sparse_classes_30k_train_018557 | Implement the Python class `WAVMdata` described below.
Class description:
Clase con métodos estáticos útiles para trabajar con metadata de un .wav
Method signatures and docstrings:
- def get_metadata(header): Recibe el header de un archivo .wav (primeros 44 bytes) Y retorna un diccionario con su metadata
- def write_... | Implement the Python class `WAVMdata` described below.
Class description:
Clase con métodos estáticos útiles para trabajar con metadata de un .wav
Method signatures and docstrings:
- def get_metadata(header): Recibe el header de un archivo .wav (primeros 44 bytes) Y retorna un diccionario con su metadata
- def write_... | 1458756a37d927d8dd365ba21cef4490360f1985 | <|skeleton|>
class WAVMdata:
"""Clase con métodos estáticos útiles para trabajar con metadata de un .wav"""
def get_metadata(header):
"""Recibe el header de un archivo .wav (primeros 44 bytes) Y retorna un diccionario con su metadata"""
<|body_0|>
def write_mdata(mdata, file):
"""R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WAVMdata:
"""Clase con métodos estáticos útiles para trabajar con metadata de un .wav"""
def get_metadata(header):
"""Recibe el header de un archivo .wav (primeros 44 bytes) Y retorna un diccionario con su metadata"""
mdata = dict()
mdata['riff'] = header[:4]
mdata['size']... | the_stack_v2_python_sparse | Ayudantias/10 - IO Archivos/WAV example/ejemplo_wav.py | frhuerta/Syllabus | train | 0 |
df7617286d23776d92a0be04957f9c9ea699b97d | [
"self.service = service\nself.action = action\nif cmdstring is not None:\n self.cmdstring = cmdstring\nelse:\n self.cmdstring = service\nif pidfile is not None:\n self.pidfiles = [pidfile]\nelse:\n self.pidfiles = ['/var/snap/{service}/current/run/{service}.pid'.format(service=service)]",
"detected_pi... | <|body_start_0|>
self.service = service
self.action = action
if cmdstring is not None:
self.cmdstring = cmdstring
else:
self.cmdstring = service
if pidfile is not None:
self.pidfiles = [pidfile]
else:
self.pidfiles = ['/var/... | ProcessMonitor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessMonitor:
def __init__(self, service, cmdstring=None, pidfile=None, action='restart'):
"""service: service name (used to restart it). cmdstring: string to look for in running command name (e.g. "docker") pidfile: None or path to look for pid file(s). Bash-style globbing is supporte... | stack_v2_sparse_classes_36k_train_011509 | 4,231 | permissive | [
{
"docstring": "service: service name (used to restart it). cmdstring: string to look for in running command name (e.g. \"docker\") pidfile: None or path to look for pid file(s). Bash-style globbing is supported, e.g. \"/var/snap/docker/*/run/docker.pid\". action: \"restart\" the service or \"reboot\" the machi... | 4 | stack_v2_sparse_classes_30k_train_003138 | Implement the Python class `ProcessMonitor` described below.
Class description:
Implement the ProcessMonitor class.
Method signatures and docstrings:
- def __init__(self, service, cmdstring=None, pidfile=None, action='restart'): service: service name (used to restart it). cmdstring: string to look for in running comm... | Implement the Python class `ProcessMonitor` described below.
Class description:
Implement the ProcessMonitor class.
Method signatures and docstrings:
- def __init__(self, service, cmdstring=None, pidfile=None, action='restart'): service: service name (used to restart it). cmdstring: string to look for in running comm... | c910fd5ac1d1b5e234f40f9f5592cc981e9bb5db | <|skeleton|>
class ProcessMonitor:
def __init__(self, service, cmdstring=None, pidfile=None, action='restart'):
"""service: service name (used to restart it). cmdstring: string to look for in running command name (e.g. "docker") pidfile: None or path to look for pid file(s). Bash-style globbing is supporte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProcessMonitor:
def __init__(self, service, cmdstring=None, pidfile=None, action='restart'):
"""service: service name (used to restart it). cmdstring: string to look for in running command name (e.g. "docker") pidfile: None or path to look for pid file(s). Bash-style globbing is supported, e.g. "/var/... | the_stack_v2_python_sparse | paradrop/daemon/paradrop/lib/misc/procmon.py | ParadropLabs/Paradrop | train | 88 | |
a40fed583f7dec77f5f0075ce85977998b8bc6f6 | [
"if not isinstance(check_cases, bool):\n raise TypeError(\"'check_cases' parameter supports type bool\")\nparameters = {'pattern': regular_expression}\nif not check_cases:\n parameters['flags'] = re.IGNORECASE\nself.regexps[regexp_name] = re.compile(**parameters)",
"if regexp_name in self.regexps:\n desi... | <|body_start_0|>
if not isinstance(check_cases, bool):
raise TypeError("'check_cases' parameter supports type bool")
parameters = {'pattern': regular_expression}
if not check_cases:
parameters['flags'] = re.IGNORECASE
self.regexps[regexp_name] = re.compile(**param... | StringHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringHelper:
def add_regexp(self, regexp_name, regular_expression, check_cases=False):
"""Add Regular Expression To Be Precompiled And Stored. Parameters ---------- regexp_name: str Desired name for the regular expression to be stored with. regular_expression: str The regular expression... | stack_v2_sparse_classes_36k_train_011510 | 5,561 | no_license | [
{
"docstring": "Add Regular Expression To Be Precompiled And Stored. Parameters ---------- regexp_name: str Desired name for the regular expression to be stored with. regular_expression: str The regular expression to be compiled check_cases: bool (default: False) If you want the compiled regular expression to b... | 6 | stack_v2_sparse_classes_30k_train_009262 | Implement the Python class `StringHelper` described below.
Class description:
Implement the StringHelper class.
Method signatures and docstrings:
- def add_regexp(self, regexp_name, regular_expression, check_cases=False): Add Regular Expression To Be Precompiled And Stored. Parameters ---------- regexp_name: str Desi... | Implement the Python class `StringHelper` described below.
Class description:
Implement the StringHelper class.
Method signatures and docstrings:
- def add_regexp(self, regexp_name, regular_expression, check_cases=False): Add Regular Expression To Be Precompiled And Stored. Parameters ---------- regexp_name: str Desi... | f0628443e4862ecbbcaf4a4b90f19b63c95b0289 | <|skeleton|>
class StringHelper:
def add_regexp(self, regexp_name, regular_expression, check_cases=False):
"""Add Regular Expression To Be Precompiled And Stored. Parameters ---------- regexp_name: str Desired name for the regular expression to be stored with. regular_expression: str The regular expression... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringHelper:
def add_regexp(self, regexp_name, regular_expression, check_cases=False):
"""Add Regular Expression To Be Precompiled And Stored. Parameters ---------- regexp_name: str Desired name for the regular expression to be stored with. regular_expression: str The regular expression to be compile... | the_stack_v2_python_sparse | apps/esports/stringhelper.py | FidelElie/smite-central | train | 1 | |
e9cb660a1c7045c03c1273d84d15e511fa36cda2 | [
"new_stack_index = self.stack_index - mask\nif np.any(new_stack_index < 0):\n raise ValueError('Popping the last value off a stack.')\nbatch_size = self.stack_index.shape[0]\nindices = new_stack_index * batch_size + np.arange(batch_size)\nreturn (Stack(self.stack, new_stack_index), np.take(self.stack, indices, a... | <|body_start_0|>
new_stack_index = self.stack_index - mask
if np.any(new_stack_index < 0):
raise ValueError('Popping the last value off a stack.')
batch_size = self.stack_index.shape[0]
indices = new_stack_index * batch_size + np.arange(batch_size)
return (Stack(self.... | Internal container for a batched stack. The implementation is a preallocated array and a (batched) stack pointer. The namedtuple structure exposes the full state of the stack, and is useful for testing, passing through flatten/unflatten operations, and general symmetry with the TensorFlow backend. | Stack | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stack:
"""Internal container for a batched stack. The implementation is a preallocated array and a (batched) stack pointer. The namedtuple structure exposes the full state of the stack, and is useful for testing, passing through flatten/unflatten operations, and general symmetry with the TensorFl... | stack_v2_sparse_classes_36k_train_011511 | 16,869 | permissive | [
{
"docstring": "Pops each indicated batch member, returning a previous write. Args: mask: Boolean array of shape `[batch_size]`. The threads at `True` indices of `mask` will have their frame pointers regressed by 1. Returns: stack: Updated variable. Does not mutate `self`. read: The new top of the stack, after ... | 2 | null | Implement the Python class `Stack` described below.
Class description:
Internal container for a batched stack. The implementation is a preallocated array and a (batched) stack pointer. The namedtuple structure exposes the full state of the stack, and is useful for testing, passing through flatten/unflatten operations,... | Implement the Python class `Stack` described below.
Class description:
Internal container for a batched stack. The implementation is a preallocated array and a (batched) stack pointer. The namedtuple structure exposes the full state of the stack, and is useful for testing, passing through flatten/unflatten operations,... | 42a64ba0d9e0973b1707fcd9b8bd8d14b2d4e3e5 | <|skeleton|>
class Stack:
"""Internal container for a batched stack. The implementation is a preallocated array and a (batched) stack pointer. The namedtuple structure exposes the full state of the stack, and is useful for testing, passing through flatten/unflatten operations, and general symmetry with the TensorFl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stack:
"""Internal container for a batched stack. The implementation is a preallocated array and a (batched) stack pointer. The namedtuple structure exposes the full state of the stack, and is useful for testing, passing through flatten/unflatten operations, and general symmetry with the TensorFlow backend.""... | the_stack_v2_python_sparse | tensorflow_probability/python/experimental/auto_batching/numpy_backend.py | tensorflow/probability | train | 4,055 |
2b11effbfb09edf6c98c5c18827a315b70733118 | [
"length = len(word)\nwhile i < length and j < length:\n if word[i] == word[j]:\n i += 1\n j += 1\n elif word[i] < word[j]:\n return -1\n else:\n return 1\nreturn 0",
"indices = range(len(word))\nsuffix_array = sorted(indices, key=functools.cmp_to_key(lambda i, j: SuffixArrayUt... | <|body_start_0|>
length = len(word)
while i < length and j < length:
if word[i] == word[j]:
i += 1
j += 1
elif word[i] < word[j]:
return -1
else:
return 1
return 0
<|end_body_0|>
<|body_start_1|>... | SuffixArrayUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuffixArrayUtil:
def _suffix_compare(word, i, j):
"""Compares suffixes without generating entire suffixes. Idea: To compare the suffixes word[i:] and word[j:], compare the letters at the ith and jth indices. Return -1 if the ith letter comes before the jth letter, 1 if jth letter comes b... | stack_v2_sparse_classes_36k_train_011512 | 7,989 | no_license | [
{
"docstring": "Compares suffixes without generating entire suffixes. Idea: To compare the suffixes word[i:] and word[j:], compare the letters at the ith and jth indices. Return -1 if the ith letter comes before the jth letter, 1 if jth letter comes before the ith letter. If the letters match, repeat the proces... | 2 | stack_v2_sparse_classes_30k_train_018302 | Implement the Python class `SuffixArrayUtil` described below.
Class description:
Implement the SuffixArrayUtil class.
Method signatures and docstrings:
- def _suffix_compare(word, i, j): Compares suffixes without generating entire suffixes. Idea: To compare the suffixes word[i:] and word[j:], compare the letters at t... | Implement the Python class `SuffixArrayUtil` described below.
Class description:
Implement the SuffixArrayUtil class.
Method signatures and docstrings:
- def _suffix_compare(word, i, j): Compares suffixes without generating entire suffixes. Idea: To compare the suffixes word[i:] and word[j:], compare the letters at t... | 01dd6f0dadf62a520bcafafddf7bf2b79e8e2603 | <|skeleton|>
class SuffixArrayUtil:
def _suffix_compare(word, i, j):
"""Compares suffixes without generating entire suffixes. Idea: To compare the suffixes word[i:] and word[j:], compare the letters at the ith and jth indices. Return -1 if the ith letter comes before the jth letter, 1 if jth letter comes b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuffixArrayUtil:
def _suffix_compare(word, i, j):
"""Compares suffixes without generating entire suffixes. Idea: To compare the suffixes word[i:] and word[j:], compare the letters at the ith and jth indices. Return -1 if the ith letter comes before the jth letter, 1 if jth letter comes before the ith ... | the_stack_v2_python_sparse | course4-strings/assignments/assignment_003_suffix_array_matching/suffix_array_matching_burrows_wheeler2.py | dmitri-mamrukov/coursera-data-structures-and-algorithms | train | 1 | |
bf8d2f008f626698d41ab65acfc7c83450f1a3f7 | [
"N = len(nums)\nresult = 0\na = 0\nb = 0\nfor x in nums:\n if x == 1:\n a += 1\n b += 1\n result = max(a, result)\n else:\n a = b\n b = 0\nif result == N:\n result -= 1\nreturn result",
"N = len(nums)\nresult = 0\nzero_num = 0\nleft = 0\nright = 0\nwhile right < N:\n ... | <|body_start_0|>
N = len(nums)
result = 0
a = 0
b = 0
for x in nums:
if x == 1:
a += 1
b += 1
result = max(a, result)
else:
a = b
b = 0
if result == N:
resu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestSubarray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestSubarray2(self, nums):
"""滑动窗口法,统计窗口内0的个数,雄安与等于1则扩大窗口,否则滑动窗口"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
N = len(nums)
result = 0
... | stack_v2_sparse_classes_36k_train_011513 | 1,746 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestSubarray",
"signature": "def longestSubarray(self, nums)"
},
{
"docstring": "滑动窗口法,统计窗口内0的个数,雄安与等于1则扩大窗口,否则滑动窗口",
"name": "longestSubarray2",
"signature": "def longestSubarray2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011995 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubarray(self, nums): :type nums: List[int] :rtype: int
- def longestSubarray2(self, nums): 滑动窗口法,统计窗口内0的个数,雄安与等于1则扩大窗口,否则滑动窗口 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubarray(self, nums): :type nums: List[int] :rtype: int
- def longestSubarray2(self, nums): 滑动窗口法,统计窗口内0的个数,雄安与等于1则扩大窗口,否则滑动窗口
<|skeleton|>
class Solution:
def l... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class Solution:
def longestSubarray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestSubarray2(self, nums):
"""滑动窗口法,统计窗口内0的个数,雄安与等于1则扩大窗口,否则滑动窗口"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestSubarray(self, nums):
""":type nums: List[int] :rtype: int"""
N = len(nums)
result = 0
a = 0
b = 0
for x in nums:
if x == 1:
a += 1
b += 1
result = max(a, result)
else:
... | the_stack_v2_python_sparse | 竞赛/29场/删掉一个元素以后全为 1 的最长子数组_M.py | 2226171237/Algorithmpractice | train | 0 | |
d8edef84a12d610f1752cfb28d7e7095e32b6a8f | [
"self.ar_coeffs = ar_coeffs\nself.ma_coeffs = ma_coeffs\nself.arma_process = sm.tsa.ArmaProcess.from_coeffs(self.ar_coeffs, self.ma_coeffs)",
"if seed is None:\n seed = 0\nnp.random.seed(seed)\nindex = pd.date_range(**date_range_kwargs)\nnsample = index.size\ndata = self.arma_process.generate_sample(nsample=ns... | <|body_start_0|>
self.ar_coeffs = ar_coeffs
self.ma_coeffs = ma_coeffs
self.arma_process = sm.tsa.ArmaProcess.from_coeffs(self.ar_coeffs, self.ma_coeffs)
<|end_body_0|>
<|body_start_1|>
if seed is None:
seed = 0
np.random.seed(seed)
index = pd.date_range(**da... | A thin wrapper around statsmodels `ArmaProcess`, with Pandas support. | ArmaProcess | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArmaProcess:
"""A thin wrapper around statsmodels `ArmaProcess`, with Pandas support."""
def __init__(self, ar_coeffs: List[float], ma_coeffs: List[float]) -> None:
"""Initialize `arma_process` using given coefficients. Useful properties include - arroots - isinvertible - isstationar... | stack_v2_sparse_classes_36k_train_011514 | 14,310 | permissive | [
{
"docstring": "Initialize `arma_process` using given coefficients. Useful properties include - arroots - isinvertible - isstationary - maroots Further details are available at - https://www.statsmodels.org/stable/generated/statsmodels.tsa.arima_process.ArmaProcess.html # pylint: disable=line-too-long",
"na... | 2 | stack_v2_sparse_classes_30k_train_012423 | Implement the Python class `ArmaProcess` described below.
Class description:
A thin wrapper around statsmodels `ArmaProcess`, with Pandas support.
Method signatures and docstrings:
- def __init__(self, ar_coeffs: List[float], ma_coeffs: List[float]) -> None: Initialize `arma_process` using given coefficients. Useful ... | Implement the Python class `ArmaProcess` described below.
Class description:
A thin wrapper around statsmodels `ArmaProcess`, with Pandas support.
Method signatures and docstrings:
- def __init__(self, ar_coeffs: List[float], ma_coeffs: List[float]) -> None: Initialize `arma_process` using given coefficients. Useful ... | 363c59fa29df2ba2719cbad2f8a19ae12cc54a92 | <|skeleton|>
class ArmaProcess:
"""A thin wrapper around statsmodels `ArmaProcess`, with Pandas support."""
def __init__(self, ar_coeffs: List[float], ma_coeffs: List[float]) -> None:
"""Initialize `arma_process` using given coefficients. Useful properties include - arroots - isinvertible - isstationar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArmaProcess:
"""A thin wrapper around statsmodels `ArmaProcess`, with Pandas support."""
def __init__(self, ar_coeffs: List[float], ma_coeffs: List[float]) -> None:
"""Initialize `arma_process` using given coefficients. Useful properties include - arroots - isinvertible - isstationary - maroots F... | the_stack_v2_python_sparse | core/artificial_signal_generators.py | srlindemann/amp | train | 0 |
2e6ab69451099779cedf3260b950dd3b5e12c5d7 | [
"a = list()\nb = list()\nfor c in s:\n if c in '0123456789':\n a.append(c)\n else:\n b.append(c)\nif abs(len(a) - len(b)) > 1:\n return ''\nm = a if len(a) >= len(b) else b\nn = a if len(a) < len(b) else b\nret = list()\nfor i in range(len(n)):\n ret.append(m[i])\n ret.append(n[i])\nif ... | <|body_start_0|>
a = list()
b = list()
for c in s:
if c in '0123456789':
a.append(c)
else:
b.append(c)
if abs(len(a) - len(b)) > 1:
return ''
m = a if len(a) >= len(b) else b
n = a if len(a) < len(b) else... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reformat2(self, s):
""":type s: str :rtype: str thought: put numbers and chars into 2 lists, they abs length diff should be <= 1, if so, assemble them 04/06/2022 12:39 Accepted 52 ms 13.6 MB python easy 5-10min. long code"""
<|body_0|>
def reformat(self, s):
... | stack_v2_sparse_classes_36k_train_011515 | 2,627 | no_license | [
{
"docstring": ":type s: str :rtype: str thought: put numbers and chars into 2 lists, they abs length diff should be <= 1, if so, assemble them 04/06/2022 12:39 Accepted 52 ms 13.6 MB python easy 5-10min. long code",
"name": "reformat2",
"signature": "def reformat2(self, s)"
},
{
"docstring": ":... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reformat2(self, s): :type s: str :rtype: str thought: put numbers and chars into 2 lists, they abs length diff should be <= 1, if so, assemble them 04/06/2022 12:39 Accepted ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reformat2(self, s): :type s: str :rtype: str thought: put numbers and chars into 2 lists, they abs length diff should be <= 1, if so, assemble them 04/06/2022 12:39 Accepted ... | 02726da394971ef02616a038dadc126c6ff260de | <|skeleton|>
class Solution:
def reformat2(self, s):
""":type s: str :rtype: str thought: put numbers and chars into 2 lists, they abs length diff should be <= 1, if so, assemble them 04/06/2022 12:39 Accepted 52 ms 13.6 MB python easy 5-10min. long code"""
<|body_0|>
def reformat(self, s):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reformat2(self, s):
""":type s: str :rtype: str thought: put numbers and chars into 2 lists, they abs length diff should be <= 1, if so, assemble them 04/06/2022 12:39 Accepted 52 ms 13.6 MB python easy 5-10min. long code"""
a = list()
b = list()
for c in s:
... | the_stack_v2_python_sparse | N1417_ReformatTheString.py | zerghua/leetcode-python | train | 2 | |
f46f115a99e08f66785c17588e879842178b3f2b | [
"parser = reqparse.RequestParser()\nparser.add_argument('nombre', type=str, required=True, help='Falta el nombre')\nparser.add_argument('fecha', type=str, required=True, help='Falta la fecha')\nparser.add_argument('tipo', type=str, required=True, help='Falta el tipo')\nparser.add_argument('raza', type=str, required... | <|body_start_0|>
parser = reqparse.RequestParser()
parser.add_argument('nombre', type=str, required=True, help='Falta el nombre')
parser.add_argument('fecha', type=str, required=True, help='Falta la fecha')
parser.add_argument('tipo', type=str, required=True, help='Falta el tipo')
... | MascotaController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MascotaController:
def post(self):
"""Metodo que permite la creacion de una mascota"""
<|body_0|>
def get(self, id_usuario):
"""Metodo que permite traer todas las mascotas de un mismo dueño"""
<|body_1|>
def put(self, id_mascota):
"""Metodo que p... | stack_v2_sparse_classes_36k_train_011516 | 3,925 | no_license | [
{
"docstring": "Metodo que permite la creacion de una mascota",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Metodo que permite traer todas las mascotas de un mismo dueño",
"name": "get",
"signature": "def get(self, id_usuario)"
},
{
"docstring": "Metodo que p... | 3 | stack_v2_sparse_classes_30k_train_021510 | Implement the Python class `MascotaController` described below.
Class description:
Implement the MascotaController class.
Method signatures and docstrings:
- def post(self): Metodo que permite la creacion de una mascota
- def get(self, id_usuario): Metodo que permite traer todas las mascotas de un mismo dueño
- def p... | Implement the Python class `MascotaController` described below.
Class description:
Implement the MascotaController class.
Method signatures and docstrings:
- def post(self): Metodo que permite la creacion de una mascota
- def get(self, id_usuario): Metodo que permite traer todas las mascotas de un mismo dueño
- def p... | 3b85c36a3ed8d2d5ee1d0fb6e8ca18599621fe47 | <|skeleton|>
class MascotaController:
def post(self):
"""Metodo que permite la creacion de una mascota"""
<|body_0|>
def get(self, id_usuario):
"""Metodo que permite traer todas las mascotas de un mismo dueño"""
<|body_1|>
def put(self, id_mascota):
"""Metodo que p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MascotaController:
def post(self):
"""Metodo que permite la creacion de una mascota"""
parser = reqparse.RequestParser()
parser.add_argument('nombre', type=str, required=True, help='Falta el nombre')
parser.add_argument('fecha', type=str, required=True, help='Falta la fecha')
... | the_stack_v2_python_sparse | BackEnd/Semana13/Veterinaria/controllers/mascota.py | jorgegarba/CodiGo9 | train | 6 | |
3d09766fdf1e1215cea9c91ecd7b899192dfb13f | [
"self.server = server\nself.context = context\nif username is None:\n self.authdata = snmp.CommunityData(secret, mpModel=1)\nelse:\n self.authdata = snmp.UsmUserData(username, authKey=secret, privKey=secret, authProtocol=snmp.usmHMACSHAAuthProtocol)\nself.eng = snmp.SnmpEngine()",
"tp = _get_transport(self.... | <|body_start_0|>
self.server = server
self.context = context
if username is None:
self.authdata = snmp.CommunityData(secret, mpModel=1)
else:
self.authdata = snmp.UsmUserData(username, authKey=secret, privKey=secret, authProtocol=snmp.usmHMACSHAAuthProtocol)
... | Session | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Session:
def __init__(self, server, secret, username=None, context=None):
"""Create a new session to interrogate a switch If username is not given, it is assumed that the secret is community string, and v2c is used. If a username given, it'll assume SHA auth and DES privacy with the secr... | stack_v2_sparse_classes_36k_train_011517 | 5,041 | permissive | [
{
"docstring": "Create a new session to interrogate a switch If username is not given, it is assumed that the secret is community string, and v2c is used. If a username given, it'll assume SHA auth and DES privacy with the secret being the same for both. :param server: The network name/address to target :param ... | 2 | stack_v2_sparse_classes_30k_train_000283 | Implement the Python class `Session` described below.
Class description:
Implement the Session class.
Method signatures and docstrings:
- def __init__(self, server, secret, username=None, context=None): Create a new session to interrogate a switch If username is not given, it is assumed that the secret is community s... | Implement the Python class `Session` described below.
Class description:
Implement the Session class.
Method signatures and docstrings:
- def __init__(self, server, secret, username=None, context=None): Create a new session to interrogate a switch If username is not given, it is assumed that the secret is community s... | f3e7d4ab672c73c65888b934e5c2d8c10ea10720 | <|skeleton|>
class Session:
def __init__(self, server, secret, username=None, context=None):
"""Create a new session to interrogate a switch If username is not given, it is assumed that the secret is community string, and v2c is used. If a username given, it'll assume SHA auth and DES privacy with the secr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Session:
def __init__(self, server, secret, username=None, context=None):
"""Create a new session to interrogate a switch If username is not given, it is assumed that the secret is community string, and v2c is used. If a username given, it'll assume SHA auth and DES privacy with the secret being the s... | the_stack_v2_python_sparse | confluent_server/confluent/snmputil.py | xcat2/confluent | train | 36 | |
4f28ee82d2b97e7def405006bb6ae8b7e175277b | [
"self.__testX = testX\nself.__testY = testY\nself.__model = model\nself.__test()",
"prints_types.printProcess('\\n# Evaluate on test data')\nresults = self.__model.evaluate(self.__testX, self.__testY, batch_size=32)\nprint('test loss ' + str(results[0]) + ' , test acc ' + str(results[1]))"
] | <|body_start_0|>
self.__testX = testX
self.__testY = testY
self.__model = model
self.__test()
<|end_body_0|>
<|body_start_1|>
prints_types.printProcess('\n# Evaluate on test data')
results = self.__model.evaluate(self.__testX, self.__testY, batch_size=32)
print('... | TestModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestModel:
def __init__(self, testX, testY, model):
"""Create the TestModel class object. :param testX: array :param testY: array :param plot_dir: string :param model: file :return: None"""
<|body_0|>
def __test(self):
"""This function responsible for testing the mod... | stack_v2_sparse_classes_36k_train_011518 | 1,219 | no_license | [
{
"docstring": "Create the TestModel class object. :param testX: array :param testY: array :param plot_dir: string :param model: file :return: None",
"name": "__init__",
"signature": "def __init__(self, testX, testY, model)"
},
{
"docstring": "This function responsible for testing the model. it ... | 2 | stack_v2_sparse_classes_30k_val_000180 | Implement the Python class `TestModel` described below.
Class description:
Implement the TestModel class.
Method signatures and docstrings:
- def __init__(self, testX, testY, model): Create the TestModel class object. :param testX: array :param testY: array :param plot_dir: string :param model: file :return: None
- d... | Implement the Python class `TestModel` described below.
Class description:
Implement the TestModel class.
Method signatures and docstrings:
- def __init__(self, testX, testY, model): Create the TestModel class object. :param testX: array :param testY: array :param plot_dir: string :param model: file :return: None
- d... | 9b7f035dca04e9ac4d20d4d9fa9e687ce583603b | <|skeleton|>
class TestModel:
def __init__(self, testX, testY, model):
"""Create the TestModel class object. :param testX: array :param testY: array :param plot_dir: string :param model: file :return: None"""
<|body_0|>
def __test(self):
"""This function responsible for testing the mod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestModel:
def __init__(self, testX, testY, model):
"""Create the TestModel class object. :param testX: array :param testY: array :param plot_dir: string :param model: file :return: None"""
self.__testX = testX
self.__testY = testY
self.__model = model
self.__test()
... | the_stack_v2_python_sparse | python files/test_model.py | maayan121/project_python_letters-DL | train | 0 | |
b4a6310af564ce2702de94669565df8fd0cc988c | [
"super(RateOfChangeTransformer, self).__init__(**kwargs)\nself.cache = {}\nself.scale = self.scale or '1'",
"LOG.debug(_('handling sample %s'), (s,))\nkey = s.name + s.resource_id\nprev = self.cache.get(key)\ntimestamp = timeutils.parse_isotime(s.timestamp)\nself.cache[key] = (s.volume, timestamp)\nif prev:\n ... | <|body_start_0|>
super(RateOfChangeTransformer, self).__init__(**kwargs)
self.cache = {}
self.scale = self.scale or '1'
<|end_body_0|>
<|body_start_1|>
LOG.debug(_('handling sample %s'), (s,))
key = s.name + s.resource_id
prev = self.cache.get(key)
timestamp = ti... | Transformer based on the rate of change of a sample volume. For example taking the current and previous volumes of a cumulative sample and producing a gauge value based on the proportion of some maximum used. | RateOfChangeTransformer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RateOfChangeTransformer:
"""Transformer based on the rate of change of a sample volume. For example taking the current and previous volumes of a cumulative sample and producing a gauge value based on the proportion of some maximum used."""
def __init__(self, **kwargs):
"""Initialize ... | stack_v2_sparse_classes_36k_train_011519 | 9,873 | permissive | [
{
"docstring": "Initialize transformer with configured parameters.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Handle a sample, converting if necessary.",
"name": "handle_sample",
"signature": "def handle_sample(self, context, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020547 | Implement the Python class `RateOfChangeTransformer` described below.
Class description:
Transformer based on the rate of change of a sample volume. For example taking the current and previous volumes of a cumulative sample and producing a gauge value based on the proportion of some maximum used.
Method signatures an... | Implement the Python class `RateOfChangeTransformer` described below.
Class description:
Transformer based on the rate of change of a sample volume. For example taking the current and previous volumes of a cumulative sample and producing a gauge value based on the proportion of some maximum used.
Method signatures an... | 56e20c1777e0c938ac42bd8056f84af9e0b76e46 | <|skeleton|>
class RateOfChangeTransformer:
"""Transformer based on the rate of change of a sample volume. For example taking the current and previous volumes of a cumulative sample and producing a gauge value based on the proportion of some maximum used."""
def __init__(self, **kwargs):
"""Initialize ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RateOfChangeTransformer:
"""Transformer based on the rate of change of a sample volume. For example taking the current and previous volumes of a cumulative sample and producing a gauge value based on the proportion of some maximum used."""
def __init__(self, **kwargs):
"""Initialize transformer w... | the_stack_v2_python_sparse | CodeAnalysis/SourceMeter_Interface/SourceMeter-8.2.0-x64-linux/Python/Demo/ceilometer/ceilometer/transformer/conversions.py | obahy/Susereum | train | 3 |
b0c01766dcb6f4cdafdfd38dff7229501b862d85 | [
"src = self.unpack('%ds' % size, size)\nassert type(src) == bytes\npos = src.find(b'\\x00')\nif pos == -1:\n return src\nelse:\n return src[:pos]",
"frame = vmd.BoneFrame(self.read_text(15))\nframe.frame, frame.pos.x, frame.pos.y, frame.pos.z, frame.q.x, frame.q.y, frame.q.z, frame.q.w = struct.unpack('I7f'... | <|body_start_0|>
src = self.unpack('%ds' % size, size)
assert type(src) == bytes
pos = src.find(b'\x00')
if pos == -1:
return src
else:
return src[:pos]
<|end_body_0|>
<|body_start_1|>
frame = vmd.BoneFrame(self.read_text(15))
frame.frame,... | Reader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reader:
def read_text(self, size):
"""read cp932 text"""
<|body_0|>
def read_bone_frame(self):
"""フレームひとつ分を読み込む(111 bytes)"""
<|body_1|>
def read_morph_frame(self):
"""モーフデータひとつ分を読み込む(23 bytes)"""
<|body_2|>
def read_camera_frame(sel... | stack_v2_sparse_classes_36k_train_011520 | 2,940 | no_license | [
{
"docstring": "read cp932 text",
"name": "read_text",
"signature": "def read_text(self, size)"
},
{
"docstring": "フレームひとつ分を読み込む(111 bytes)",
"name": "read_bone_frame",
"signature": "def read_bone_frame(self)"
},
{
"docstring": "モーフデータひとつ分を読み込む(23 bytes)",
"name": "read_morph... | 4 | null | Implement the Python class `Reader` described below.
Class description:
Implement the Reader class.
Method signatures and docstrings:
- def read_text(self, size): read cp932 text
- def read_bone_frame(self): フレームひとつ分を読み込む(111 bytes)
- def read_morph_frame(self): モーフデータひとつ分を読み込む(23 bytes)
- def read_camera_frame(self)... | Implement the Python class `Reader` described below.
Class description:
Implement the Reader class.
Method signatures and docstrings:
- def read_text(self, size): read cp932 text
- def read_bone_frame(self): フレームひとつ分を読み込む(111 bytes)
- def read_morph_frame(self): モーフデータひとつ分を読み込む(23 bytes)
- def read_camera_frame(self)... | f69bc448ed44875d30fcfda1acb33962015386c9 | <|skeleton|>
class Reader:
def read_text(self, size):
"""read cp932 text"""
<|body_0|>
def read_bone_frame(self):
"""フレームひとつ分を読み込む(111 bytes)"""
<|body_1|>
def read_morph_frame(self):
"""モーフデータひとつ分を読み込む(23 bytes)"""
<|body_2|>
def read_camera_frame(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reader:
def read_text(self, size):
"""read cp932 text"""
src = self.unpack('%ds' % size, size)
assert type(src) == bytes
pos = src.find(b'\x00')
if pos == -1:
return src
else:
return src[:pos]
def read_bone_frame(self):
"""フレ... | the_stack_v2_python_sparse | scripts/addons_extern/blender26-meshio/pymeshio/vmd/reader.py | motorsep/blenderpython | train | 1 | |
2602f297aff6f6af88435da0541e409ae7c33db9 | [
"visited = set()\n\ndef dfs(node):\n if not node:\n return False\n if k - node.val in visited:\n return True\n visited.add(node.val)\n return dfs(node.left) or dfs(node.right)\nreturn dfs(root)",
"s = set()\n\ndef traverse(node):\n if not node:\n return False\n if k - node.v... | <|body_start_0|>
visited = set()
def dfs(node):
if not node:
return False
if k - node.val in visited:
return True
visited.add(node.val)
return dfs(node.left) or dfs(node.right)
return dfs(root)
<|end_body_0|>
<|bod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
"""09/03/2021 23:20"""
<|body_0|>
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
"""10/29/2022 14:12"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
visited =... | stack_v2_sparse_classes_36k_train_011521 | 2,121 | no_license | [
{
"docstring": "09/03/2021 23:20",
"name": "findTarget",
"signature": "def findTarget(self, root: Optional[TreeNode], k: int) -> bool"
},
{
"docstring": "10/29/2022 14:12",
"name": "findTarget",
"signature": "def findTarget(self, root: Optional[TreeNode], k: int) -> bool"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTarget(self, root: Optional[TreeNode], k: int) -> bool: 09/03/2021 23:20
- def findTarget(self, root: Optional[TreeNode], k: int) -> bool: 10/29/2022 14:12 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTarget(self, root: Optional[TreeNode], k: int) -> bool: 09/03/2021 23:20
- def findTarget(self, root: Optional[TreeNode], k: int) -> bool: 10/29/2022 14:12
<|skeleton|>
... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
"""09/03/2021 23:20"""
<|body_0|>
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
"""10/29/2022 14:12"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
"""09/03/2021 23:20"""
visited = set()
def dfs(node):
if not node:
return False
if k - node.val in visited:
return True
visited.add(node.val)
... | the_stack_v2_python_sparse | leetcode/solved/653_Two_Sum_IV_-_Input_is_a_BST/solution.py | sungminoh/algorithms | train | 0 | |
ba805584c4da990698932610b1f9b705b0c1ab8b | [
"super(DepthWiseConv1DBLock, self).__init__()\nself.causal = causal\nself.padding = (kernel - 1) * dilation if causal else padding\nself.conv1d = nn.Conv1d(in_chan, hidden_chan, 1)\nself.dconv1d = nn.Conv1d(hidden_chan, hidden_chan, kernel, dilation=dilation, groups=hidden_chan, padding=self.padding)\nself.res = nn... | <|body_start_0|>
super(DepthWiseConv1DBLock, self).__init__()
self.causal = causal
self.padding = (kernel - 1) * dilation if causal else padding
self.conv1d = nn.Conv1d(in_chan, hidden_chan, 1)
self.dconv1d = nn.Conv1d(hidden_chan, hidden_chan, kernel, dilation=dilation, groups=h... | Depth-Wise 1 Dimensionnal Convolution Block Attributes: causal {bool} -- choose cLN instead of gLN (default: {False}) padding {int} -- padding size conv1d {nn.Module} -- 1 dimensionnal convolution layer dconv1d {nn.Module} -- 1 dimensionnal depth-wise convolution layer res {nn.Module} -- 1 dimensionnal resiudal convolu... | DepthWiseConv1DBLock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DepthWiseConv1DBLock:
"""Depth-Wise 1 Dimensionnal Convolution Block Attributes: causal {bool} -- choose cLN instead of gLN (default: {False}) padding {int} -- padding size conv1d {nn.Module} -- 1 dimensionnal convolution layer dconv1d {nn.Module} -- 1 dimensionnal depth-wise convolution layer re... | stack_v2_sparse_classes_36k_train_011522 | 9,814 | permissive | [
{
"docstring": "Initialization Arguments: in_chan {int} -- input channel size hidden_chan {int} -- hidden channel size kernel {int} -- kernel size padding {int} -- padding size Keyword Arguments: dilation {int} -- dilation factor for altrous conv (default: {1}) causal {bool} -- choose cLN instead of gLN (defaul... | 2 | stack_v2_sparse_classes_30k_train_016035 | Implement the Python class `DepthWiseConv1DBLock` described below.
Class description:
Depth-Wise 1 Dimensionnal Convolution Block Attributes: causal {bool} -- choose cLN instead of gLN (default: {False}) padding {int} -- padding size conv1d {nn.Module} -- 1 dimensionnal convolution layer dconv1d {nn.Module} -- 1 dimen... | Implement the Python class `DepthWiseConv1DBLock` described below.
Class description:
Depth-Wise 1 Dimensionnal Convolution Block Attributes: causal {bool} -- choose cLN instead of gLN (default: {False}) padding {int} -- padding size conv1d {nn.Module} -- 1 dimensionnal convolution layer dconv1d {nn.Module} -- 1 dimen... | 2415502fa8a38d4624b1c71e926f1723bdc8535c | <|skeleton|>
class DepthWiseConv1DBLock:
"""Depth-Wise 1 Dimensionnal Convolution Block Attributes: causal {bool} -- choose cLN instead of gLN (default: {False}) padding {int} -- padding size conv1d {nn.Module} -- 1 dimensionnal convolution layer dconv1d {nn.Module} -- 1 dimensionnal depth-wise convolution layer re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DepthWiseConv1DBLock:
"""Depth-Wise 1 Dimensionnal Convolution Block Attributes: causal {bool} -- choose cLN instead of gLN (default: {False}) padding {int} -- padding size conv1d {nn.Module} -- 1 dimensionnal convolution layer dconv1d {nn.Module} -- 1 dimensionnal depth-wise convolution layer res {nn.Module}... | the_stack_v2_python_sparse | SPK_SP_Master/wass/convtasnet/modules.py | adamwhitakerwilson/speaker_separation | train | 0 |
2e8cfb29049079d49079532558b611c01b910c11 | [
"try:\n return config_parser.get(section_name, value_name)\nexcept configparser.NoOptionError:\n return None",
"config_parser = configparser.ConfigParser(interpolation=None)\nconfig_parser.read_file(file_object)\nfor section_name in config_parser.sections():\n preset_definition = PresetDefinition(section... | <|body_start_0|>
try:
return config_parser.get(section_name, value_name)
except configparser.NoOptionError:
return None
<|end_body_0|>
<|body_start_1|>
config_parser = configparser.ConfigParser(interpolation=None)
config_parser.read_file(file_object)
for ... | Preset definition reader. | PresetDefinitionReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PresetDefinitionReader:
"""Preset definition reader."""
def _GetConfigValue(self, config_parser, section_name, value_name):
"""Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that contains the... | stack_v2_sparse_classes_36k_train_011523 | 2,420 | permissive | [
{
"docstring": "Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that contains the value. value_name (str): name of the value. Returns: object: value or None if the value does not exists.",
"name": "_GetConfigValue",
... | 2 | stack_v2_sparse_classes_30k_train_020405 | Implement the Python class `PresetDefinitionReader` described below.
Class description:
Preset definition reader.
Method signatures and docstrings:
- def _GetConfigValue(self, config_parser, section_name, value_name): Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. ... | Implement the Python class `PresetDefinitionReader` described below.
Class description:
Preset definition reader.
Method signatures and docstrings:
- def _GetConfigValue(self, config_parser, section_name, value_name): Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. ... | 34709706cc3bee84db45883043b9dfc1811ba65b | <|skeleton|>
class PresetDefinitionReader:
"""Preset definition reader."""
def _GetConfigValue(self, config_parser, section_name, value_name):
"""Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that contains the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PresetDefinitionReader:
"""Preset definition reader."""
def _GetConfigValue(self, config_parser, section_name, value_name):
"""Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that contains the value. value... | the_stack_v2_python_sparse | l2tdevtools/presets.py | log2timeline/l2tdevtools | train | 7 |
c0f07234bf121bb26bbe7e1a043d32e1e5edcae7 | [
"super().__init__(compute_on_call=compute_on_call, prefix=prefix, suffix=suffix, num_classes=num_classes, mode=mode)\nself.zero_division = zero_division\nself.reset()",
"kv_metrics = {}\nfor aggregation_name, aggregated_metrics in zip(('_micro', '_macro', '_weighted'), (micro, macro, weighted)):\n metrics = {f... | <|body_start_0|>
super().__init__(compute_on_call=compute_on_call, prefix=prefix, suffix=suffix, num_classes=num_classes, mode=mode)
self.zero_division = zero_division
self.reset()
<|end_body_0|>
<|body_start_1|>
kv_metrics = {}
for aggregation_name, aggregated_metrics in zip(('... | Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: mode: one of "binary", "multiclass" and "multilabel" num_classes: number of classes in loader's dataset zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be one o... | PrecisionRecallF1SupportMetric | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrecisionRecallF1SupportMetric:
"""Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: mode: one of "binary", "multiclass" and "multilabel" num_classes: number of classes in loader's dataset zero_division: value to set in case of zero division durin... | stack_v2_sparse_classes_36k_train_011524 | 30,124 | permissive | [
{
"docstring": "Init PrecisionRecallF1SupportMetric instance",
"name": "__init__",
"signature": "def __init__(self, mode: str, num_classes: int=None, zero_division: int=0, compute_on_call: bool=True, prefix: str=None, suffix: str=None) -> None"
},
{
"docstring": "Convert metrics aggregation to k... | 6 | stack_v2_sparse_classes_30k_train_014163 | Implement the Python class `PrecisionRecallF1SupportMetric` described below.
Class description:
Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: mode: one of "binary", "multiclass" and "multilabel" num_classes: number of classes in loader's dataset zero_division: valu... | Implement the Python class `PrecisionRecallF1SupportMetric` described below.
Class description:
Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: mode: one of "binary", "multiclass" and "multilabel" num_classes: number of classes in loader's dataset zero_division: valu... | ac8567dc389fb7a265e3104e8a743497aa903165 | <|skeleton|>
class PrecisionRecallF1SupportMetric:
"""Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: mode: one of "binary", "multiclass" and "multilabel" num_classes: number of classes in loader's dataset zero_division: value to set in case of zero division durin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrecisionRecallF1SupportMetric:
"""Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: mode: one of "binary", "multiclass" and "multilabel" num_classes: number of classes in loader's dataset zero_division: value to set in case of zero division during metrics (pr... | the_stack_v2_python_sparse | catalyst/metrics/_classification.py | Podidiving/catalyst | train | 2 |
51e8309a510f98c5bd0635ee220ab05d022941b4 | [
"def power2(self, n):\n \"\"\" 超时。 判断一个数是否是2的幂,2^0 = 1 \"\"\"\n if n > 0:\n return n & n - 1 == 0\n return False\nlength = len(deliciousness)\nres_dict = {}\nnum = 0\nfor i in range(length):\n for j in range(i + 1, length):\n if power2(deliciousness[i] + deliciousness[j]):\n num... | <|body_start_0|>
def power2(self, n):
""" 超时。 判断一个数是否是2的幂,2^0 = 1 """
if n > 0:
return n & n - 1 == 0
return False
length = len(deliciousness)
res_dict = {}
num = 0
for i in range(length):
for j in range(i + 1, lengt... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def feasting(self, deliciousness: list) -> int:
"""递归会超时"""
<|body_0|>
def countPairs(self, deliciousness: list) -> int:
"""字典方法,时间复杂度O(N)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def power2(self, n):
""" 超时。 判断一个数是否是2的幂... | stack_v2_sparse_classes_36k_train_011525 | 3,725 | no_license | [
{
"docstring": "递归会超时",
"name": "feasting",
"signature": "def feasting(self, deliciousness: list) -> int"
},
{
"docstring": "字典方法,时间复杂度O(N)",
"name": "countPairs",
"signature": "def countPairs(self, deliciousness: list) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_011121 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def feasting(self, deliciousness: list) -> int: 递归会超时
- def countPairs(self, deliciousness: list) -> int: 字典方法,时间复杂度O(N) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def feasting(self, deliciousness: list) -> int: 递归会超时
- def countPairs(self, deliciousness: list) -> int: 字典方法,时间复杂度O(N)
<|skeleton|>
class Solution:
def feasting(self, del... | 91d0a4145b066c885272cf1896b5564439f855fa | <|skeleton|>
class Solution:
def feasting(self, deliciousness: list) -> int:
"""递归会超时"""
<|body_0|>
def countPairs(self, deliciousness: list) -> int:
"""字典方法,时间复杂度O(N)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def feasting(self, deliciousness: list) -> int:
"""递归会超时"""
def power2(self, n):
""" 超时。 判断一个数是否是2的幂,2^0 = 1 """
if n > 0:
return n & n - 1 == 0
return False
length = len(deliciousness)
res_dict = {}
num = 0
... | the_stack_v2_python_sparse | 数组系列/leetcode1711 大餐计数.py | Deaseyy/algorithm | train | 0 | |
8848485f64fe45a228b309280e6f28c046356aec | [
"self.table = DBFetcher(dot_t_system_dir, 'db', 'admin').fetch()\nself.ssid_hash = None\nself.password_hash = None\nself.private_key = None\nself.get_keys()",
"ssid_hash = hashlib.sha256(ssid.encode()).hexdigest()\npassword_hash = hashlib.sha256(password.encode()).hexdigest()\npublic_key = hashlib.sha256((ssid + ... | <|body_start_0|>
self.table = DBFetcher(dot_t_system_dir, 'db', 'admin').fetch()
self.ssid_hash = None
self.password_hash = None
self.private_key = None
self.get_keys()
<|end_body_0|>
<|body_start_1|>
ssid_hash = hashlib.sha256(ssid.encode()).hexdigest()
password... | Class to define an administrator for managing admin authentication keys of tracking system. This class provides necessary initiations and functions named :func:`t_system.administration.Administrator.change_keys` for changing admin entry keys. | Administrator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Administrator:
"""Class to define an administrator for managing admin authentication keys of tracking system. This class provides necessary initiations and functions named :func:`t_system.administration.Administrator.change_keys` for changing admin entry keys."""
def __init__(self):
... | stack_v2_sparse_classes_36k_train_011526 | 4,830 | permissive | [
{
"docstring": "Initialization method of :class:`t_system.administration.Administrator` class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "The high-level method to change keys of secret entry point for root authorized. 2 key(ssid and password) authentication uses s... | 5 | stack_v2_sparse_classes_30k_train_006395 | Implement the Python class `Administrator` described below.
Class description:
Class to define an administrator for managing admin authentication keys of tracking system. This class provides necessary initiations and functions named :func:`t_system.administration.Administrator.change_keys` for changing admin entry key... | Implement the Python class `Administrator` described below.
Class description:
Class to define an administrator for managing admin authentication keys of tracking system. This class provides necessary initiations and functions named :func:`t_system.administration.Administrator.change_keys` for changing admin entry key... | a9d63fbbdc208c578d6a6153bf2ba13142b3c7a5 | <|skeleton|>
class Administrator:
"""Class to define an administrator for managing admin authentication keys of tracking system. This class provides necessary initiations and functions named :func:`t_system.administration.Administrator.change_keys` for changing admin entry keys."""
def __init__(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Administrator:
"""Class to define an administrator for managing admin authentication keys of tracking system. This class provides necessary initiations and functions named :func:`t_system.administration.Administrator.change_keys` for changing admin entry keys."""
def __init__(self):
"""Initializa... | the_stack_v2_python_sparse | t_system/administration.py | ahmetishakoglu/T_System | train | 0 |
5c336c4021ba4d34d56a4bdd14fbf635dd7c5eea | [
"super().__init__()\nassert _type in ['ID3', 'C4.5', 'CART']\nassert predict_type in ['classification', 'regression']\nself.tree_count = tree_count\nself.attr_ratio = attr_ratio\nself.type = _type\nself.predict_type = predict_type\nself.split_count = split_count\nself.thread_count = min(thread_count, tree_count)\ni... | <|body_start_0|>
super().__init__()
assert _type in ['ID3', 'C4.5', 'CART']
assert predict_type in ['classification', 'regression']
self.tree_count = tree_count
self.attr_ratio = attr_ratio
self.type = _type
self.predict_type = predict_type
self.split_coun... | RandomForest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomForest:
def __init__(self, tree_count=50, attr_ratio=0.5, _type='CART', predict_type='classification', split_count=10, thread_count=5) -> None:
"""tree_count 决策树数量 attr_ratio 每一次决策树分裂时随机所选属性数目占总属性数目的比例 _type 决策树类型 predict_type 预测类型 classification 分类 regression 回归 split_count 对于连续属性... | stack_v2_sparse_classes_36k_train_011527 | 6,222 | no_license | [
{
"docstring": "tree_count 决策树数量 attr_ratio 每一次决策树分裂时随机所选属性数目占总属性数目的比例 _type 决策树类型 predict_type 预测类型 classification 分类 regression 回归 split_count 对于连续属性切分的次数 process_count 建立随机森林的进程数",
"name": "__init__",
"signature": "def __init__(self, tree_count=50, attr_ratio=0.5, _type='CART', predict_type='classifi... | 5 | stack_v2_sparse_classes_30k_train_005651 | Implement the Python class `RandomForest` described below.
Class description:
Implement the RandomForest class.
Method signatures and docstrings:
- def __init__(self, tree_count=50, attr_ratio=0.5, _type='CART', predict_type='classification', split_count=10, thread_count=5) -> None: tree_count 决策树数量 attr_ratio 每一次决策树... | Implement the Python class `RandomForest` described below.
Class description:
Implement the RandomForest class.
Method signatures and docstrings:
- def __init__(self, tree_count=50, attr_ratio=0.5, _type='CART', predict_type='classification', split_count=10, thread_count=5) -> None: tree_count 决策树数量 attr_ratio 每一次决策树... | cc9520554682172ba690cbcf517ac8fc5ec180b0 | <|skeleton|>
class RandomForest:
def __init__(self, tree_count=50, attr_ratio=0.5, _type='CART', predict_type='classification', split_count=10, thread_count=5) -> None:
"""tree_count 决策树数量 attr_ratio 每一次决策树分裂时随机所选属性数目占总属性数目的比例 _type 决策树类型 predict_type 预测类型 classification 分类 regression 回归 split_count 对于连续属性... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomForest:
def __init__(self, tree_count=50, attr_ratio=0.5, _type='CART', predict_type='classification', split_count=10, thread_count=5) -> None:
"""tree_count 决策树数量 attr_ratio 每一次决策树分裂时随机所选属性数目占总属性数目的比例 _type 决策树类型 predict_type 预测类型 classification 分类 regression 回归 split_count 对于连续属性切分的次数 process_... | the_stack_v2_python_sparse | Code/random_forest.py | zgood9527/Basic4AI | train | 2 | |
85f0336c7172858a0663ef959058988dd8cd52dd | [
"n = len(nums)\nfor i in range(n - 1):\n if nums[i + 1] - nums[i] - 1 >= k:\n return nums[i] + k\n else:\n k -= nums[i + 1] - nums[i] - 1\nreturn nums[-1] + k",
"set1 = set(nums)\nset2 = set(list(range(nums[0], nums[-1] + k + 1)))\nset3 = set2 - set1\nl = sorted(list(set3))\nreturn l[k - 1]"
] | <|body_start_0|>
n = len(nums)
for i in range(n - 1):
if nums[i + 1] - nums[i] - 1 >= k:
return nums[i] + k
else:
k -= nums[i + 1] - nums[i] - 1
return nums[-1] + k
<|end_body_0|>
<|body_start_1|>
set1 = set(nums)
set2 = se... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def missingElement(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def missingElement2(self, nums, k):
"""超时 [247645,695157,1735965,4220736,4322043,9465544,9543270,9900210] 10 :type nums: List[int] :type k: int :rtype: int"""... | stack_v2_sparse_classes_36k_train_011528 | 1,502 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "missingElement",
"signature": "def missingElement(self, nums, k)"
},
{
"docstring": "超时 [247645,695157,1735965,4220736,4322043,9465544,9543270,9900210] 10 :type nums: List[int] :type k: int :rtype: int",
"name": "missi... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingElement(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def missingElement2(self, nums, k): 超时 [247645,695157,1735965,4220736,4322043,9465544,9543270,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingElement(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def missingElement2(self, nums, k): 超时 [247645,695157,1735965,4220736,4322043,9465544,9543270,... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def missingElement(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def missingElement2(self, nums, k):
"""超时 [247645,695157,1735965,4220736,4322043,9465544,9543270,9900210] 10 :type nums: List[int] :type k: int :rtype: int"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def missingElement(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
n = len(nums)
for i in range(n - 1):
if nums[i + 1] - nums[i] - 1 >= k:
return nums[i] + k
else:
k -= nums[i + 1] - nums[i] - 1
... | the_stack_v2_python_sparse | contest/全国高校春季编程大赛/决赛/1. 有序数组中的缺失元素.py | lovehhf/LeetCode | train | 0 | |
5e84e325ac2ef030edca249fdc576bd17d94478c | [
"mean = self.get_mean(window_features, **kwargs)\nstd = self.get_std(window_features, mean, **kwargs)\nreturn (mean, std)",
"mean, std = aggregated_feature\nif self.bool(std == 0, **kwargs):\n return original_feature * 0\nz_score = abs((original_feature - mean) / self.escape_null(std))\nif self.bool(z_score > ... | <|body_start_0|>
mean = self.get_mean(window_features, **kwargs)
std = self.get_std(window_features, mean, **kwargs)
return (mean, std)
<|end_body_0|>
<|body_start_1|>
mean, std = aggregated_feature
if self.bool(std == 0, **kwargs):
return original_feature * 0
... | ... | ZScoreZeroSWFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZScoreZeroSWFilter:
"""..."""
def aggregate_window_item(self, window_features, **kwargs):
""":param window_features: :param kwargs: :return:"""
<|body_0|>
def combine_feature_item(self, original_feature, aggregated_feature, sigma_num=0, **kwargs):
""":param origi... | stack_v2_sparse_classes_36k_train_011529 | 1,456 | permissive | [
{
"docstring": ":param window_features: :param kwargs: :return:",
"name": "aggregate_window_item",
"signature": "def aggregate_window_item(self, window_features, **kwargs)"
},
{
"docstring": ":param original_feature: :param aggregated_feature: :param sigma_num: :param kwargs: :return:",
"nam... | 2 | stack_v2_sparse_classes_30k_train_017070 | Implement the Python class `ZScoreZeroSWFilter` described below.
Class description:
...
Method signatures and docstrings:
- def aggregate_window_item(self, window_features, **kwargs): :param window_features: :param kwargs: :return:
- def combine_feature_item(self, original_feature, aggregated_feature, sigma_num=0, **... | Implement the Python class `ZScoreZeroSWFilter` described below.
Class description:
...
Method signatures and docstrings:
- def aggregate_window_item(self, window_features, **kwargs): :param window_features: :param kwargs: :return:
- def combine_feature_item(self, original_feature, aggregated_feature, sigma_num=0, **... | 617ff45c9c3c96bbd9a975aef15f1b2697282b9c | <|skeleton|>
class ZScoreZeroSWFilter:
"""..."""
def aggregate_window_item(self, window_features, **kwargs):
""":param window_features: :param kwargs: :return:"""
<|body_0|>
def combine_feature_item(self, original_feature, aggregated_feature, sigma_num=0, **kwargs):
""":param origi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZScoreZeroSWFilter:
"""..."""
def aggregate_window_item(self, window_features, **kwargs):
""":param window_features: :param kwargs: :return:"""
mean = self.get_mean(window_features, **kwargs)
std = self.get_std(window_features, mean, **kwargs)
return (mean, std)
def c... | the_stack_v2_python_sparse | shot_detector/filters/sliding_window/zscore_zero_swfilter.py | w495/python-video-shot-detector | train | 20 |
5b5f7d155e0187329a63a2074340f7e4b6fa484f | [
"super().__init__()\nself.colors = colors\nself.nb_points = len(colors)\nself.size = size\nsmallest_height = size.height() / (2 * self.nb_points + 4)\nself.size_text = QSize(self.size.width(), smallest_height)\nself.size_edit_text = QSize(self.size.width() / 4, smallest_height)\nself.size_edit = QSize(self.size.wid... | <|body_start_0|>
super().__init__()
self.colors = colors
self.nb_points = len(colors)
self.size = size
smallest_height = size.height() / (2 * self.nb_points + 4)
self.size_text = QSize(self.size.width(), smallest_height)
self.size_edit_text = QSize(self.size.width... | QGridLayout class that displays QTextEdit objects. | CalibrationPoints | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalibrationPoints:
"""QGridLayout class that displays QTextEdit objects."""
def __init__(self, size, colors, points):
"""Construct the objects to manage the QTextEdit objects. Args: size (QSize): the size of the QGridLayout. colors (list of Qt.Color): the colors of the points. points... | stack_v2_sparse_classes_36k_train_011530 | 2,916 | no_license | [
{
"docstring": "Construct the objects to manage the QTextEdit objects. Args: size (QSize): the size of the QGridLayout. colors (list of Qt.Color): the colors of the points. points (array, shape = (len(colors), 2)): the points on which the information will be registered.",
"name": "__init__",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_019049 | Implement the Python class `CalibrationPoints` described below.
Class description:
QGridLayout class that displays QTextEdit objects.
Method signatures and docstrings:
- def __init__(self, size, colors, points): Construct the objects to manage the QTextEdit objects. Args: size (QSize): the size of the QGridLayout. co... | Implement the Python class `CalibrationPoints` described below.
Class description:
QGridLayout class that displays QTextEdit objects.
Method signatures and docstrings:
- def __init__(self, size, colors, points): Construct the objects to manage the QTextEdit objects. Args: size (QSize): the size of the QGridLayout. co... | 237ca81580db43525d8945017c0565b9722046ad | <|skeleton|>
class CalibrationPoints:
"""QGridLayout class that displays QTextEdit objects."""
def __init__(self, size, colors, points):
"""Construct the objects to manage the QTextEdit objects. Args: size (QSize): the size of the QGridLayout. colors (list of Qt.Color): the colors of the points. points... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CalibrationPoints:
"""QGridLayout class that displays QTextEdit objects."""
def __init__(self, size, colors, points):
"""Construct the objects to manage the QTextEdit objects. Args: size (QSize): the size of the QGridLayout. colors (list of Qt.Color): the colors of the points. points (array, shap... | the_stack_v2_python_sparse | src/d0_utils/point_selection/information_points/calibration_points.py | remingtonCarmi/TrackingSwimmingENPC | train | 0 |
0da50b1cc82c6ee04bb83c2d2a3a14999b679593 | [
"self.n_estimator = n_estimator\nself.trees = []\nself.max_sample = max_sample\nself.criterion = criterion\nself.max_depth = max_depth\nself.min_leaf_size = min_leaf_size",
"m, n_feature = X_train.shape\nsample = self.max_sample if isinstance(self.max_sample, int) else int(self.max_sample * m)\nfor _ in range(sel... | <|body_start_0|>
self.n_estimator = n_estimator
self.trees = []
self.max_sample = max_sample
self.criterion = criterion
self.max_depth = max_depth
self.min_leaf_size = min_leaf_size
<|end_body_0|>
<|body_start_1|>
m, n_feature = X_train.shape
sample = sel... | RandomForest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomForest:
def __init__(self, n_estimator=100, criterion='gini', max_depth=3, min_leaf_size=4, max_sample=0.5):
"""Random forest is a supervised learning algorithm. Some week estimator works together to build a strong estimator. :param n_estimator: Total number of tree that will be cr... | stack_v2_sparse_classes_36k_train_011531 | 5,246 | no_license | [
{
"docstring": "Random forest is a supervised learning algorithm. Some week estimator works together to build a strong estimator. :param n_estimator: Total number of tree that will be created :param criterion: The loss function that will be used. gini/entropy :param max_depth: Maximum depth of each tree. :param... | 3 | stack_v2_sparse_classes_30k_train_014025 | Implement the Python class `RandomForest` described below.
Class description:
Implement the RandomForest class.
Method signatures and docstrings:
- def __init__(self, n_estimator=100, criterion='gini', max_depth=3, min_leaf_size=4, max_sample=0.5): Random forest is a supervised learning algorithm. Some week estimator... | Implement the Python class `RandomForest` described below.
Class description:
Implement the RandomForest class.
Method signatures and docstrings:
- def __init__(self, n_estimator=100, criterion='gini', max_depth=3, min_leaf_size=4, max_sample=0.5): Random forest is a supervised learning algorithm. Some week estimator... | d8ed73d9c319135bd2fd8440d8610846c31f6c5d | <|skeleton|>
class RandomForest:
def __init__(self, n_estimator=100, criterion='gini', max_depth=3, min_leaf_size=4, max_sample=0.5):
"""Random forest is a supervised learning algorithm. Some week estimator works together to build a strong estimator. :param n_estimator: Total number of tree that will be cr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomForest:
def __init__(self, n_estimator=100, criterion='gini', max_depth=3, min_leaf_size=4, max_sample=0.5):
"""Random forest is a supervised learning algorithm. Some week estimator works together to build a strong estimator. :param n_estimator: Total number of tree that will be created :param c... | the_stack_v2_python_sparse | machine_learning/ensemble/bagging/random_forest/random_forest.py | Jayem-11/machine-learning-scratch | train | 0 | |
01e4e587e2d95052389b6fe6f8256049f209ab56 | [
"ExpTimeEstimator.__init__(self, **kwargs)\nself._source_detection = source_detection\nself._edge = edge\nself._bias = bias\nself._saturated = saturated\nself.coordinates = (None, None)",
"source_detection = get_object(self._source_detection, SourceDetection)\ncatalog = (await source_detection(image)).catalog\nif... | <|body_start_0|>
ExpTimeEstimator.__init__(self, **kwargs)
self._source_detection = source_detection
self._edge = edge
self._bias = bias
self._saturated = saturated
self.coordinates = (None, None)
<|end_body_0|>
<|body_start_1|>
source_detection = get_object(self... | Estimate exposure time from a star. | StarExpTimeEstimator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StarExpTimeEstimator:
"""Estimate exposure time from a star."""
def __init__(self, source_detection: Union[Dict[str, Any], SourceDetection], edge: float=0.1, bias: float=0.0, saturated: float=0.7, **kwargs: Any):
"""Create new exp time estimator from single star. Args: source_detecti... | stack_v2_sparse_classes_36k_train_011532 | 2,779 | permissive | [
{
"docstring": "Create new exp time estimator from single star. Args: source_detection: Source detection to use. edge: Fraction of image to ignore at each border. bias: Bias level of image. saturated: Fraction of saturation that is used as brightness limit.",
"name": "__init__",
"signature": "def __init... | 2 | null | Implement the Python class `StarExpTimeEstimator` described below.
Class description:
Estimate exposure time from a star.
Method signatures and docstrings:
- def __init__(self, source_detection: Union[Dict[str, Any], SourceDetection], edge: float=0.1, bias: float=0.0, saturated: float=0.7, **kwargs: Any): Create new ... | Implement the Python class `StarExpTimeEstimator` described below.
Class description:
Estimate exposure time from a star.
Method signatures and docstrings:
- def __init__(self, source_detection: Union[Dict[str, Any], SourceDetection], edge: float=0.1, bias: float=0.0, saturated: float=0.7, **kwargs: Any): Create new ... | 2d7a06e5485b61b6ca7e51d99b08651ea6021086 | <|skeleton|>
class StarExpTimeEstimator:
"""Estimate exposure time from a star."""
def __init__(self, source_detection: Union[Dict[str, Any], SourceDetection], edge: float=0.1, bias: float=0.0, saturated: float=0.7, **kwargs: Any):
"""Create new exp time estimator from single star. Args: source_detecti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StarExpTimeEstimator:
"""Estimate exposure time from a star."""
def __init__(self, source_detection: Union[Dict[str, Any], SourceDetection], edge: float=0.1, bias: float=0.0, saturated: float=0.7, **kwargs: Any):
"""Create new exp time estimator from single star. Args: source_detection: Source de... | the_stack_v2_python_sparse | pyobs/images/processors/exptime/star.py | pyobs/pyobs-core | train | 9 |
82588d123227f13c92810d0e1840fcb1234044b1 | [
"self.user = user or current_user()\nself.spec = sorted_dict(spec)\nself.created = datetime.now().astimezone()",
"new_spec = ContainerSpec(spec, user)\nexisting = session.query(ContainerSpec)\nexisting = existing.filter(ContainerSpec.user == new_spec.user, ContainerSpec.spec.cast(String) == json.dumps(new_spec.sp... | <|body_start_0|>
self.user = user or current_user()
self.spec = sorted_dict(spec)
self.created = datetime.now().astimezone()
<|end_body_0|>
<|body_start_1|>
new_spec = ContainerSpec(spec, user)
existing = session.query(ContainerSpec)
existing = existing.filter(ContainerS... | caliban container spec This class contains the information specifying how to generate a docker container for use in caliban. Please do not instantiate this class directly via its constructor. Instead, use the ContainerSpec.get_or_create() method, or query the database using a session.query() call. The get_or_create() m... | ContainerSpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContainerSpec:
"""caliban container spec This class contains the information specifying how to generate a docker container for use in caliban. Please do not instantiate this class directly via its constructor. Instead, use the ContainerSpec.get_or_create() method, or query the database using a se... | stack_v2_sparse_classes_36k_train_011533 | 18,576 | permissive | [
{
"docstring": "ContainerSpec Args: spec: dictionary containing docker container creation parameters user: username, if None then user is automatically detected",
"name": "__init__",
"signature": "def __init__(self, spec: Dict[str, Any], user: Optional[str]=None)"
},
{
"docstring": "gets an exis... | 2 | stack_v2_sparse_classes_30k_train_016525 | Implement the Python class `ContainerSpec` described below.
Class description:
caliban container spec This class contains the information specifying how to generate a docker container for use in caliban. Please do not instantiate this class directly via its constructor. Instead, use the ContainerSpec.get_or_create() m... | Implement the Python class `ContainerSpec` described below.
Class description:
caliban container spec This class contains the information specifying how to generate a docker container for use in caliban. Please do not instantiate this class directly via its constructor. Instead, use the ContainerSpec.get_or_create() m... | d0e792a8e72fe5cbc186c47a2541e94d5b94c319 | <|skeleton|>
class ContainerSpec:
"""caliban container spec This class contains the information specifying how to generate a docker container for use in caliban. Please do not instantiate this class directly via its constructor. Instead, use the ContainerSpec.get_or_create() method, or query the database using a se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContainerSpec:
"""caliban container spec This class contains the information specifying how to generate a docker container for use in caliban. Please do not instantiate this class directly via its constructor. Instead, use the ContainerSpec.get_or_create() method, or query the database using a session.query()... | the_stack_v2_python_sparse | caliban/history/types.py | google/caliban | train | 499 |
90e08401cf50ef80d42fcfa6c388650e5fc09d54 | [
"user_id = get_jwt_identity()\nbefore = request.args.get('before')\nafter = request.args.get('after')\nlast_checked = UserLastCheckedMessage.get_last_checked_time(user_id, vertex.id)\nif not before and (last_checked or after):\n since = last_checked.time if not after else after\n messages = Message.list_messa... | <|body_start_0|>
user_id = get_jwt_identity()
before = request.args.get('before')
after = request.args.get('after')
last_checked = UserLastCheckedMessage.get_last_checked_time(user_id, vertex.id)
if not before and (last_checked or after):
since = last_checked.time if ... | Container for list and create endpoints for node-messages | ListCreateNodeMessagesView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListCreateNodeMessagesView:
"""Container for list and create endpoints for node-messages"""
def get(self, vertex=None, vertex_type=None, vertex_id=None):
"""Returns all users with their roles currently assigned to the given core vertex"""
<|body_0|>
def post(self, vertex... | stack_v2_sparse_classes_36k_train_011534 | 44,865 | no_license | [
{
"docstring": "Returns all users with their roles currently assigned to the given core vertex",
"name": "get",
"signature": "def get(self, vertex=None, vertex_type=None, vertex_id=None)"
},
{
"docstring": "Creation endpoint used for adding new messages against a node",
"name": "post",
"... | 2 | stack_v2_sparse_classes_30k_train_006071 | Implement the Python class `ListCreateNodeMessagesView` described below.
Class description:
Container for list and create endpoints for node-messages
Method signatures and docstrings:
- def get(self, vertex=None, vertex_type=None, vertex_id=None): Returns all users with their roles currently assigned to the given cor... | Implement the Python class `ListCreateNodeMessagesView` described below.
Class description:
Container for list and create endpoints for node-messages
Method signatures and docstrings:
- def get(self, vertex=None, vertex_type=None, vertex_id=None): Returns all users with their roles currently assigned to the given cor... | 00434985013b65fe45b0a8c8a7f0b50bb727087a | <|skeleton|>
class ListCreateNodeMessagesView:
"""Container for list and create endpoints for node-messages"""
def get(self, vertex=None, vertex_type=None, vertex_id=None):
"""Returns all users with their roles currently assigned to the given core vertex"""
<|body_0|>
def post(self, vertex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListCreateNodeMessagesView:
"""Container for list and create endpoints for node-messages"""
def get(self, vertex=None, vertex_type=None, vertex_id=None):
"""Returns all users with their roles currently assigned to the given core vertex"""
user_id = get_jwt_identity()
before = requ... | the_stack_v2_python_sparse | core/views.py | gingerComms/gingerCommsAPIs | train | 0 |
0419d8e106afa6a4dbaad23097815b8a293c2c17 | [
"self.base_path = base_path\nself.mapreduce_spec = mapreduce_spec\nself.shard_id = shard_id\nself.slice_id = slice_id\nself.input_reader = input_reader\nself.initial_input_reader = initial_input_reader\nself.output_writer = output_writer\nself.retries = retries\nself.handler = handler\nself._input_reader_json = sel... | <|body_start_0|>
self.base_path = base_path
self.mapreduce_spec = mapreduce_spec
self.shard_id = shard_id
self.slice_id = slice_id
self.input_reader = input_reader
self.initial_input_reader = initial_input_reader
self.output_writer = output_writer
self.ret... | A shard's states that are kept in task payload. TransientShardState holds two types of states: 1. Some states just don't need to be saved to datastore. e.g. serialized input reader and output writer instances. 2. Some states are duplicated from datastore, e.g. slice_id, shard_id. These are used to validate the task. | TransientShardState | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransientShardState:
"""A shard's states that are kept in task payload. TransientShardState holds two types of states: 1. Some states just don't need to be saved to datastore. e.g. serialized input reader and output writer instances. 2. Some states are duplicated from datastore, e.g. slice_id, sh... | stack_v2_sparse_classes_36k_train_011535 | 41,282 | permissive | [
{
"docstring": "Init. Args: base_path: base path of this mapreduce job. Deprecated. mapreduce_spec: an instance of MapReduceSpec. shard_id: shard id. slice_id: slice id. When enqueuing task for the next slice, this number is incremented by 1. input_reader: input reader instance for this shard. initial_input_rea... | 5 | stack_v2_sparse_classes_30k_train_007324 | Implement the Python class `TransientShardState` described below.
Class description:
A shard's states that are kept in task payload. TransientShardState holds two types of states: 1. Some states just don't need to be saved to datastore. e.g. serialized input reader and output writer instances. 2. Some states are dupli... | Implement the Python class `TransientShardState` described below.
Class description:
A shard's states that are kept in task payload. TransientShardState holds two types of states: 1. Some states just don't need to be saved to datastore. e.g. serialized input reader and output writer instances. 2. Some states are dupli... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class TransientShardState:
"""A shard's states that are kept in task payload. TransientShardState holds two types of states: 1. Some states just don't need to be saved to datastore. e.g. serialized input reader and output writer instances. 2. Some states are duplicated from datastore, e.g. slice_id, sh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransientShardState:
"""A shard's states that are kept in task payload. TransientShardState holds two types of states: 1. Some states just don't need to be saved to datastore. e.g. serialized input reader and output writer instances. 2. Some states are duplicated from datastore, e.g. slice_id, shard_id. These... | the_stack_v2_python_sparse | third_party/mapreduce/mapreduce/model.py | catapult-project/catapult | train | 2,032 |
f4462d8e663cd757301e73636ae8738517959e84 | [
"s = []\nif root == None:\n return 'None'\nstack = [root]\nwhile stack:\n temp = stack.pop()\n if temp == None:\n s.append('None')\n else:\n s.append(str(temp.val))\n stack.append(temp.right)\n stack.append(temp.left)\nreturn ','.join(s)",
"def helper(l):\n if l[0] == 'N... | <|body_start_0|>
s = []
if root == None:
return 'None'
stack = [root]
while stack:
temp = stack.pop()
if temp == None:
s.append('None')
else:
s.append(str(temp.val))
stack.append(temp.right)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_011536 | 1,329 | 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_002447 | 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:... | e75899634f45b0d60f8b3cb854ab9e503d676a57 | <|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"""
s = []
if root == None:
return 'None'
stack = [root]
while stack:
temp = stack.pop()
if temp == None:
s.append... | the_stack_v2_python_sparse | Python/Tree/Serialize and Deserialize BST.py | GreatTwang/lccc_solution | train | 1 | |
85a61020483aa486895748fb43bedf366c9e517b | [
"subject = loader.render_to_string(subject_template_name, context)\nsubject = ''.join(subject.splitlines())\nbody = loader.render_to_string(email_template_name, context)\nemail_message = EmailMultiAlternatives(subject, body, from_email, [to_email])\nif html_email_template_name is not None:\n html_email = loader.... | <|body_start_0|>
subject = loader.render_to_string(subject_template_name, context)
subject = ''.join(subject.splitlines())
body = loader.render_to_string(email_template_name, context)
email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
if html_email_temp... | PasswordResetForm | [
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"GPL-1.0-or-later",
"Python-2.0.1",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-other-permissive",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResetForm:
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None):
"""Send a django.core.mail.EmailMultiAlternatives to `to_email`."""
<|body_0|>
def get_users(self, email):
"""Given an em... | stack_v2_sparse_classes_36k_train_011537 | 17,187 | permissive | [
{
"docstring": "Send a django.core.mail.EmailMultiAlternatives to `to_email`.",
"name": "send_mail",
"signature": "def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None)"
},
{
"docstring": "Given an email, return matching use... | 3 | null | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): Send a django.core.mail.EmailMult... | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): Send a django.core.mail.EmailMult... | c74a6fad5475495756a5bdb18b2cab2b68d429bc | <|skeleton|>
class PasswordResetForm:
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None):
"""Send a django.core.mail.EmailMultiAlternatives to `to_email`."""
<|body_0|>
def get_users(self, email):
"""Given an em... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PasswordResetForm:
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None):
"""Send a django.core.mail.EmailMultiAlternatives to `to_email`."""
subject = loader.render_to_string(subject_template_name, context)
subjec... | the_stack_v2_python_sparse | django/contrib/auth/forms.py | django/django | train | 73,530 | |
79772a99c2fa4ad12f16ec854d845c14d552a378 | [
"self.assertDirectoryContents(('produce.ini',))\nself.produce('b.txt')\nself.assertDirectoryContents(('produce.ini', 'a.txt', 'b.txt', 'c.txt'))",
"self.assertDirectoryContents(('produce.ini',))\nwith self.assertRaisesRegex(ProduceError, 'cyclic dependency'):\n self.produce('c.txt')\nself.assertDirectoryConten... | <|body_start_0|>
self.assertDirectoryContents(('produce.ini',))
self.produce('b.txt')
self.assertDirectoryContents(('produce.ini', 'a.txt', 'b.txt', 'c.txt'))
<|end_body_0|>
<|body_start_1|>
self.assertDirectoryContents(('produce.ini',))
with self.assertRaisesRegex(ProduceError,... | SoftCycleTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftCycleTest:
def test_soft_cycle_allowed(self):
"""c.txt depends on a.txt, presumably to indicate that you have to build a.txt in order to get c.txt (c.txt is a side output of the instantiated rule for a.txt). That's fine because the instantiated rule for b.txt doesn't have its own rec... | stack_v2_sparse_classes_36k_train_011538 | 1,103 | permissive | [
{
"docstring": "c.txt depends on a.txt, presumably to indicate that you have to build a.txt in order to get c.txt (c.txt is a side output of the instantiated rule for a.txt). That's fine because the instantiated rule for b.txt doesn't have its own recipe, so there's no clash.",
"name": "test_soft_cycle_allo... | 2 | stack_v2_sparse_classes_30k_train_003875 | Implement the Python class `SoftCycleTest` described below.
Class description:
Implement the SoftCycleTest class.
Method signatures and docstrings:
- def test_soft_cycle_allowed(self): c.txt depends on a.txt, presumably to indicate that you have to build a.txt in order to get c.txt (c.txt is a side output of the inst... | Implement the Python class `SoftCycleTest` described below.
Class description:
Implement the SoftCycleTest class.
Method signatures and docstrings:
- def test_soft_cycle_allowed(self): c.txt depends on a.txt, presumably to indicate that you have to build a.txt in order to get c.txt (c.txt is a side output of the inst... | fe4116d063b8820877b9f589e40cae29721511bf | <|skeleton|>
class SoftCycleTest:
def test_soft_cycle_allowed(self):
"""c.txt depends on a.txt, presumably to indicate that you have to build a.txt in order to get c.txt (c.txt is a side output of the instantiated rule for a.txt). That's fine because the instantiated rule for b.txt doesn't have its own rec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SoftCycleTest:
def test_soft_cycle_allowed(self):
"""c.txt depends on a.txt, presumably to indicate that you have to build a.txt in order to get c.txt (c.txt is a side output of the instantiated rule for a.txt). That's fine because the instantiated rule for b.txt doesn't have its own recipe, so there'... | the_stack_v2_python_sparse | t/test_soft_cycle.py | texttheater/produce | train | 14 | |
30040e46f6612422c1fc0ef6f18b770859b94e18 | [
"super().__init__(flatten_flag=flatten_flag, n_pca_components=n_pca_components)\nself.extract_hog_flag = extract_hog_flag\nself.type_cnn = type_cnn",
"if len(x.shape) != 3:\n raise DimensionalityError('DimensionalityError: Invalid shape for the \"x\" image data matrix! A shape {0} was provided, but admissible ... | <|body_start_0|>
super().__init__(flatten_flag=flatten_flag, n_pca_components=n_pca_components)
self.extract_hog_flag = extract_hog_flag
self.type_cnn = type_cnn
<|end_body_0|>
<|body_start_1|>
if len(x.shape) != 3:
raise DimensionalityError('DimensionalityError: Invalid sha... | Children Class of PreProcessor. Used to transform image data before training. | ImagePreProcessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImagePreProcessor:
"""Children Class of PreProcessor. Used to transform image data before training."""
def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn=''):
"""Constructor of the class. :param flatten_flag: (bool) whether to express the nump... | stack_v2_sparse_classes_36k_train_011539 | 17,079 | no_license | [
{
"docstring": "Constructor of the class. :param flatten_flag: (bool) whether to express the numpy array of data with shape [n_samples, n_features] :param n_pca_components: (int) number of principal components that will be computed from the data \"x\". Must be an integer between 2 and 3. :param type_cnn: (str) ... | 4 | stack_v2_sparse_classes_30k_train_006815 | Implement the Python class `ImagePreProcessor` described below.
Class description:
Children Class of PreProcessor. Used to transform image data before training.
Method signatures and docstrings:
- def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn=''): Constructor of the class... | Implement the Python class `ImagePreProcessor` described below.
Class description:
Children Class of PreProcessor. Used to transform image data before training.
Method signatures and docstrings:
- def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn=''): Constructor of the class... | c46f4b2ba7762420186cb710d2932adf00829d6f | <|skeleton|>
class ImagePreProcessor:
"""Children Class of PreProcessor. Used to transform image data before training."""
def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn=''):
"""Constructor of the class. :param flatten_flag: (bool) whether to express the nump... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImagePreProcessor:
"""Children Class of PreProcessor. Used to transform image data before training."""
def __init__(self, flatten_flag=False, n_pca_components=0, extract_hog_flag=False, type_cnn=''):
"""Constructor of the class. :param flatten_flag: (bool) whether to express the numpy array of da... | the_stack_v2_python_sparse | pre_processors.py | jonathand94/ML-Classifiers-Library | train | 0 |
30ba9c21f32cea9d098dc8596f28ec061def3b8a | [
"step1()\nr = xptest_case_register_Delete\nif '恭喜您,账号已成功注册' in r.text:\n print('注册成功')\nassert '恭喜您,账号已成功注册' in r.text",
"step1_1()\nr = xptest_case_register\nif '该用户名已被注册,请更换用户名' in r.text:\n print('账户已注册,请输入新的账号')\nassert '该用户名已被注册,请更换用户名' in r.text",
"step2_1()\nstep2_2()\nr = xptest_case_register\nif ... | <|body_start_0|>
step1()
r = xptest_case_register_Delete
if '恭喜您,账号已成功注册' in r.text:
print('注册成功')
assert '恭喜您,账号已成功注册' in r.text
<|end_body_0|>
<|body_start_1|>
step1_1()
r = xptest_case_register
if '该用户名已被注册,请更换用户名' in r.text:
print('账户已... | Test_regist | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_regist:
def test_register1(self, xptest_case_register_Delete):
"""用例详情的描述: 接口地址:http://web.juhe.cn:8080/constellation/getAll 请求方式:post 请求类型:Content-Type: application/json 头信息: X-Requested-With: XMLHttpRequest Content-Type: application/json 参数:{"account":"test1","email":"1@qq.com","p... | stack_v2_sparse_classes_36k_train_011540 | 8,089 | no_license | [
{
"docstring": "用例详情的描述: 接口地址:http://web.juhe.cn:8080/constellation/getAll 请求方式:post 请求类型:Content-Type: application/json 头信息: X-Requested-With: XMLHttpRequest Content-Type: application/json 参数:{\"account\":\"test1\",\"email\":\"1@qq.com\",\"password\":\"123456\",\"repassword\":\"123456\"} 大概步骤: 1.删除账号test1 2.注册... | 3 | stack_v2_sparse_classes_30k_train_005695 | Implement the Python class `Test_regist` described below.
Class description:
Implement the Test_regist class.
Method signatures and docstrings:
- def test_register1(self, xptest_case_register_Delete): 用例详情的描述: 接口地址:http://web.juhe.cn:8080/constellation/getAll 请求方式:post 请求类型:Content-Type: application/json 头信息: X-Reque... | Implement the Python class `Test_regist` described below.
Class description:
Implement the Test_regist class.
Method signatures and docstrings:
- def test_register1(self, xptest_case_register_Delete): 用例详情的描述: 接口地址:http://web.juhe.cn:8080/constellation/getAll 请求方式:post 请求类型:Content-Type: application/json 头信息: X-Reque... | c3ca50f34dedb3d400fd303957198c4ca006a821 | <|skeleton|>
class Test_regist:
def test_register1(self, xptest_case_register_Delete):
"""用例详情的描述: 接口地址:http://web.juhe.cn:8080/constellation/getAll 请求方式:post 请求类型:Content-Type: application/json 头信息: X-Requested-With: XMLHttpRequest Content-Type: application/json 参数:{"account":"test1","email":"1@qq.com","p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_regist:
def test_register1(self, xptest_case_register_Delete):
"""用例详情的描述: 接口地址:http://web.juhe.cn:8080/constellation/getAll 请求方式:post 请求类型:Content-Type: application/json 头信息: X-Requested-With: XMLHttpRequest Content-Type: application/json 参数:{"account":"test1","email":"1@qq.com","password":"1234... | the_stack_v2_python_sparse | project_hrun/test_login_registers/test_regist_login.py | haloyazhou/halo_1 | train | 0 | |
9ef10f62840fe87c63f72740b07a4416c0e72283 | [
"address = self.transport.getAddress()\nlog.msg('Client %d login in.[%s,%d]' % (self.transport.sessionno, address[0], address[1]))\nself.factory.connmanager.addConnection(self)\nself.factory.doConnectionMade(self)",
"log.msg('Client %d login out.' % self.transport.sessionno)\nself.factory.doConnectionLost(self)\n... | <|body_start_0|>
address = self.transport.getAddress()
log.msg('Client %d login in.[%s,%d]' % (self.transport.sessionno, address[0], address[1]))
self.factory.connmanager.addConnection(self)
self.factory.doConnectionMade(self)
<|end_body_0|>
<|body_start_1|>
log.msg('Client %d l... | 协议 | LiberateProtocol | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LiberateProtocol:
"""协议"""
def connectionMade(self):
"""连接建立处理"""
<|body_0|>
def connectionLost(self, reason):
"""连接断开处理"""
<|body_1|>
def safeToWriteData(self, data, command):
"""线程安全的向客户端发送数据 @param data: str 要向客户端写的数据"""
<|body_2|>... | stack_v2_sparse_classes_36k_train_011541 | 4,082 | no_license | [
{
"docstring": "连接建立处理",
"name": "connectionMade",
"signature": "def connectionMade(self)"
},
{
"docstring": "连接断开处理",
"name": "connectionLost",
"signature": "def connectionLost(self, reason)"
},
{
"docstring": "线程安全的向客户端发送数据 @param data: str 要向客户端写的数据",
"name": "safeToWriteD... | 4 | null | Implement the Python class `LiberateProtocol` described below.
Class description:
协议
Method signatures and docstrings:
- def connectionMade(self): 连接建立处理
- def connectionLost(self, reason): 连接断开处理
- def safeToWriteData(self, data, command): 线程安全的向客户端发送数据 @param data: str 要向客户端写的数据
- def dataReceived(self, data): 数据到达... | Implement the Python class `LiberateProtocol` described below.
Class description:
协议
Method signatures and docstrings:
- def connectionMade(self): 连接建立处理
- def connectionLost(self, reason): 连接断开处理
- def safeToWriteData(self, data, command): 线程安全的向客户端发送数据 @param data: str 要向客户端写的数据
- def dataReceived(self, data): 数据到达... | d7a83a21287ed66aea690ecb6b73588569478be6 | <|skeleton|>
class LiberateProtocol:
"""协议"""
def connectionMade(self):
"""连接建立处理"""
<|body_0|>
def connectionLost(self, reason):
"""连接断开处理"""
<|body_1|>
def safeToWriteData(self, data, command):
"""线程安全的向客户端发送数据 @param data: str 要向客户端写的数据"""
<|body_2|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LiberateProtocol:
"""协议"""
def connectionMade(self):
"""连接建立处理"""
address = self.transport.getAddress()
log.msg('Client %d login in.[%s,%d]' % (self.transport.sessionno, address[0], address[1]))
self.factory.connmanager.addConnection(self)
self.factory.doConnection... | the_stack_v2_python_sparse | gfirefly/netconnect/protoc.py | East196/diabloworld | train | 3 |
89831c845e35c3c951001fd9abce676e6398f5cb | [
"self._server_id = 'd06f-1e8d6b745' if server_id is None else server_id\nself._licenses = 'e656b991-5706-4cb1-af8f-f69323f8f7e4' if licenses is None else licenses\nself._request_zone = 'A' if request_zone is None else request_zone\n_host = '127.0.0.1' if host is None else host\n_port = 9500 if port is 0 else port\n... | <|body_start_0|>
self._server_id = 'd06f-1e8d6b745' if server_id is None else server_id
self._licenses = 'e656b991-5706-4cb1-af8f-f69323f8f7e4' if licenses is None else licenses
self._request_zone = 'A' if request_zone is None else request_zone
_host = '127.0.0.1' if host is None else ho... | Service | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Service:
def __init__(self, server_id=None, host=None, port=0, licenses=None, request_zone=None, time_out=None):
"""初始化 :param server_id: :param host: :param port: :param licenses: :param request_zone: :param time_out:"""
<|body_0|>
def send(self, request_id, message_type, c... | stack_v2_sparse_classes_36k_train_011542 | 3,750 | no_license | [
{
"docstring": "初始化 :param server_id: :param host: :param port: :param licenses: :param request_zone: :param time_out:",
"name": "__init__",
"signature": "def __init__(self, server_id=None, host=None, port=0, licenses=None, request_zone=None, time_out=None)"
},
{
"docstring": "进行TCP请求 :param req... | 5 | stack_v2_sparse_classes_30k_train_001736 | Implement the Python class `Service` described below.
Class description:
Implement the Service class.
Method signatures and docstrings:
- def __init__(self, server_id=None, host=None, port=0, licenses=None, request_zone=None, time_out=None): 初始化 :param server_id: :param host: :param port: :param licenses: :param requ... | Implement the Python class `Service` described below.
Class description:
Implement the Service class.
Method signatures and docstrings:
- def __init__(self, server_id=None, host=None, port=0, licenses=None, request_zone=None, time_out=None): 初始化 :param server_id: :param host: :param port: :param licenses: :param requ... | 8120cc60437ef92e5a462634360e107917d8d9d2 | <|skeleton|>
class Service:
def __init__(self, server_id=None, host=None, port=0, licenses=None, request_zone=None, time_out=None):
"""初始化 :param server_id: :param host: :param port: :param licenses: :param request_zone: :param time_out:"""
<|body_0|>
def send(self, request_id, message_type, c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Service:
def __init__(self, server_id=None, host=None, port=0, licenses=None, request_zone=None, time_out=None):
"""初始化 :param server_id: :param host: :param port: :param licenses: :param request_zone: :param time_out:"""
self._server_id = 'd06f-1e8d6b745' if server_id is None else server_id
... | the_stack_v2_python_sparse | classes/LocalCpp.py | Samuel875154270/src | train | 0 | |
0eb09798c0258e0ed3a5b4bbaaa575446bdc483d | [
"self.frame_type_link = frame_type_link\nself.a_frame_inst = a_frame_inst\nself.b_frame_inst = b_frame_inst\nself.frame_inst_arg_links = []\na_frame_inst.link = self\nb_frame_inst.link = self\nself._link_args()",
"a_frame_inst_args = self.a_frame_inst.args\nb_frame_inst_args = self.b_frame_inst.args\nfor a_frame_... | <|body_start_0|>
self.frame_type_link = frame_type_link
self.a_frame_inst = a_frame_inst
self.b_frame_inst = b_frame_inst
self.frame_inst_arg_links = []
a_frame_inst.link = self
b_frame_inst.link = self
self._link_args()
<|end_body_0|>
<|body_start_1|>
a_... | Frame_inst_link | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Frame_inst_link:
def __init__(self, frame_type_link, a_frame_inst, b_frame_inst):
"""called from Frame_type_link.link_frame_insts"""
<|body_0|>
def _link_args(self):
"""called from __init__"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.frame_... | stack_v2_sparse_classes_36k_train_011543 | 6,044 | no_license | [
{
"docstring": "called from Frame_type_link.link_frame_insts",
"name": "__init__",
"signature": "def __init__(self, frame_type_link, a_frame_inst, b_frame_inst)"
},
{
"docstring": "called from __init__",
"name": "_link_args",
"signature": "def _link_args(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004291 | Implement the Python class `Frame_inst_link` described below.
Class description:
Implement the Frame_inst_link class.
Method signatures and docstrings:
- def __init__(self, frame_type_link, a_frame_inst, b_frame_inst): called from Frame_type_link.link_frame_insts
- def _link_args(self): called from __init__ | Implement the Python class `Frame_inst_link` described below.
Class description:
Implement the Frame_inst_link class.
Method signatures and docstrings:
- def __init__(self, frame_type_link, a_frame_inst, b_frame_inst): called from Frame_type_link.link_frame_insts
- def _link_args(self): called from __init__
<|skelet... | 194446ec1adeec5ef85db3f96b6d8d2876cc8811 | <|skeleton|>
class Frame_inst_link:
def __init__(self, frame_type_link, a_frame_inst, b_frame_inst):
"""called from Frame_type_link.link_frame_insts"""
<|body_0|>
def _link_args(self):
"""called from __init__"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Frame_inst_link:
def __init__(self, frame_type_link, a_frame_inst, b_frame_inst):
"""called from Frame_type_link.link_frame_insts"""
self.frame_type_link = frame_type_link
self.a_frame_inst = a_frame_inst
self.b_frame_inst = b_frame_inst
self.frame_inst_arg_links = []
... | the_stack_v2_python_sparse | udapi-python/udapi/block/valency/link_structures.py | Jankus1994/ud-valency | train | 0 | |
7d11ffbca1b56700327d9bf296d078a445458f85 | [
"filter_parser = reqparse.RequestParser(bundle_errors=True)\nfilter_parser.add_argument('last_pk', type=int, default=0, location='args')\nfilter_parser.add_argument('limit_num', type=int, default=20, location='args')\nfilter_parser_args = filter_parser.parse_args()\ndata = get_fetch_result_limit_rows_by_last_id(**f... | <|body_start_0|>
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.add_argument('last_pk', type=int, default=0, location='args')
filter_parser.add_argument('limit_num', type=int, default=20, location='args')
filter_parser_args = filter_parser.parse_args()
d... | FetchResultListResource | FetchResultListResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetchResultListResource:
"""FetchResultListResource"""
def get(self):
"""Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:"""
<|body_0|>
def post(self):
"""Example: curl http://0.0.0... | stack_v2_sparse_classes_36k_train_011544 | 11,580 | permissive | [
{
"docstring": "Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Example: curl http://0.0.0.0:5000/news/fetch_results -H \"Content-Type: application/... | 2 | stack_v2_sparse_classes_30k_train_007761 | Implement the Python class `FetchResultListResource` described below.
Class description:
FetchResultListResource
Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:
- def post(self): Examp... | Implement the Python class `FetchResultListResource` described below.
Class description:
FetchResultListResource
Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:
- def post(self): Examp... | 6ef54f3f7efbbaff6169e963dcf45ab25e11e593 | <|skeleton|>
class FetchResultListResource:
"""FetchResultListResource"""
def get(self):
"""Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:"""
<|body_0|>
def post(self):
"""Example: curl http://0.0.0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FetchResultListResource:
"""FetchResultListResource"""
def get(self):
"""Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:"""
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.a... | the_stack_v2_python_sparse | web_api/news/resources/fetch_result.py | zhanghe06/flask_restful | train | 2 |
dbd33664f481b75af7745dfc7af14b93996246a2 | [
"self.ruckus = ruckus\nupdate_interval = timedelta(seconds=SCAN_INTERVAL)\nsuper().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)",
"clients = await self.ruckus.api.get_active_clients()\n_LOGGER.debug('fetched %d active clients', len(clients))\nreturn {client[API_CLIENT_MAC]: client for cli... | <|body_start_0|>
self.ruckus = ruckus
update_interval = timedelta(seconds=SCAN_INTERVAL)
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)
<|end_body_0|>
<|body_start_1|>
clients = await self.ruckus.api.get_active_clients()
_LOGGER.debug('fetched %d a... | Coordinator to manage data from Ruckus Unleashed client. | RuckusUnleashedDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RuckusUnleashedDataUpdateCoordinator:
"""Coordinator to manage data from Ruckus Unleashed client."""
def __init__(self, hass: HomeAssistant, *, ruckus: AjaxSession) -> None:
"""Initialize global Ruckus Unleashed data updater."""
<|body_0|>
async def _fetch_clients(self) ... | stack_v2_sparse_classes_36k_train_011545 | 1,639 | permissive | [
{
"docstring": "Initialize global Ruckus Unleashed data updater.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, *, ruckus: AjaxSession) -> None"
},
{
"docstring": "Fetch clients from the API and format them.",
"name": "_fetch_clients",
"signature": "async def... | 3 | stack_v2_sparse_classes_30k_train_009748 | Implement the Python class `RuckusUnleashedDataUpdateCoordinator` described below.
Class description:
Coordinator to manage data from Ruckus Unleashed client.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, ruckus: AjaxSession) -> None: Initialize global Ruckus Unleashed data updater.
-... | Implement the Python class `RuckusUnleashedDataUpdateCoordinator` described below.
Class description:
Coordinator to manage data from Ruckus Unleashed client.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, ruckus: AjaxSession) -> None: Initialize global Ruckus Unleashed data updater.
-... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class RuckusUnleashedDataUpdateCoordinator:
"""Coordinator to manage data from Ruckus Unleashed client."""
def __init__(self, hass: HomeAssistant, *, ruckus: AjaxSession) -> None:
"""Initialize global Ruckus Unleashed data updater."""
<|body_0|>
async def _fetch_clients(self) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RuckusUnleashedDataUpdateCoordinator:
"""Coordinator to manage data from Ruckus Unleashed client."""
def __init__(self, hass: HomeAssistant, *, ruckus: AjaxSession) -> None:
"""Initialize global Ruckus Unleashed data updater."""
self.ruckus = ruckus
update_interval = timedelta(sec... | the_stack_v2_python_sparse | homeassistant/components/ruckus_unleashed/coordinator.py | home-assistant/core | train | 35,501 |
3189a3fa7976f23398a00c625680acf8489454c9 | [
"if isinstance(key, int):\n return ErrorCode(key)\nif key not in ErrorCode._member_map_:\n return extend_enum(ErrorCode, key, default)\nreturn ErrorCode[key]",
"if not (isinstance(value, int) and 0 <= value <= 4294967295):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 14 <= value... | <|body_start_0|>
if isinstance(key, int):
return ErrorCode(key)
if key not in ErrorCode._member_map_:
return extend_enum(ErrorCode, key, default)
return ErrorCode[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 4294967295):
... | [ErrorCode] HTTP/2 Error Code | ErrorCode | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ErrorCode:
"""[ErrorCode] HTTP/2 Error Code"""
def get(key: 'int | str', default: 'int'=-1) -> 'ErrorCode':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value... | stack_v2_sparse_classes_36k_train_011546 | 3,123 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'ErrorCode'"
},
{
"docstring": "Lookup function used when value is not found. A... | 2 | stack_v2_sparse_classes_30k_train_010139 | Implement the Python class `ErrorCode` described below.
Class description:
[ErrorCode] HTTP/2 Error Code
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'ErrorCode': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta pri... | Implement the Python class `ErrorCode` described below.
Class description:
[ErrorCode] HTTP/2 Error Code
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'ErrorCode': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta pri... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class ErrorCode:
"""[ErrorCode] HTTP/2 Error Code"""
def get(key: 'int | str', default: 'int'=-1) -> 'ErrorCode':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ErrorCode:
"""[ErrorCode] HTTP/2 Error Code"""
def get(key: 'int | str', default: 'int'=-1) -> 'ErrorCode':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, int):
return ErrorCode... | the_stack_v2_python_sparse | pcapkit/const/http/error_code.py | JarryShaw/PyPCAPKit | train | 204 |
87834e0d8431b6468925fef848fff951770e1b9a | [
"combined_list = []\nfor m in matrix:\n combined_list.extend(m)\ncombined_list.sort()\nreturn combined_list[k - 1]",
"min_heap = []\nfor i in range(len(matrix)):\n heappush(min_heap, (matrix[i][0], 0, matrix[i]))\nnumber_count = number = 0\nwhile min_heap:\n number, i, num_list = heappop(min_heap)\n n... | <|body_start_0|>
combined_list = []
for m in matrix:
combined_list.extend(m)
combined_list.sort()
return combined_list[k - 1]
<|end_body_0|>
<|body_start_1|>
min_heap = []
for i in range(len(matrix)):
heappush(min_heap, (matrix[i][0], 0, matrix[i]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""Time complexity: nlgn space complexity: n*m"""
<|body_0|>
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""Time complexity: klgM, M is matrix space complexity: O(k)"""
... | stack_v2_sparse_classes_36k_train_011547 | 971 | no_license | [
{
"docstring": "Time complexity: nlgn space complexity: n*m",
"name": "kthSmallest",
"signature": "def kthSmallest(self, matrix: List[List[int]], k: int) -> int"
},
{
"docstring": "Time complexity: klgM, M is matrix space complexity: O(k)",
"name": "kthSmallest",
"signature": "def kthSma... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, matrix: List[List[int]], k: int) -> int: Time complexity: nlgn space complexity: n*m
- def kthSmallest(self, matrix: List[List[int]], k: int) -> int: Time c... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, matrix: List[List[int]], k: int) -> int: Time complexity: nlgn space complexity: n*m
- def kthSmallest(self, matrix: List[List[int]], k: int) -> int: Time c... | e50dc0642f087f37ab3234390be3d8a0ed48fe62 | <|skeleton|>
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""Time complexity: nlgn space complexity: n*m"""
<|body_0|>
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""Time complexity: klgM, M is matrix space complexity: O(k)"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""Time complexity: nlgn space complexity: n*m"""
combined_list = []
for m in matrix:
combined_list.extend(m)
combined_list.sort()
return combined_list[k - 1]
def kthSmallest(self,... | the_stack_v2_python_sparse | Leetcode/378. Kth Smallest Element in a Sorted Matrix.py | brlala/Educative-Grokking-Coding-Exercise | train | 3 | |
4461b2eba907b9afb6292ad0ef79f692485cc5db | [
"super(PretrainTaskModel, self).__init__()\nmodel_type = model_config.get('model_type', 'transformer')\nhidden_size = model_config.get('hidden_size', 512)\nin_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size\nself.conv_decoder = nn.Sequential(nn.Conv1D(in_channels=in_channels, out_channels=128, k... | <|body_start_0|>
super(PretrainTaskModel, self).__init__()
model_type = model_config.get('model_type', 'transformer')
hidden_size = model_config.get('hidden_size', 512)
in_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size
self.conv_decoder = nn.Sequential(nn.Con... | PretrainTaskModel | PretrainTaskModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PretrainTaskModel:
"""PretrainTaskModel"""
def __init__(self, class_num, model_config, encoder_model):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(PretrainTaskModel, s... | stack_v2_sparse_classes_36k_train_011548 | 17,522 | permissive | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self, class_num, model_config, encoder_model)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, input, pos)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000308 | Implement the Python class `PretrainTaskModel` described below.
Class description:
PretrainTaskModel
Method signatures and docstrings:
- def __init__(self, class_num, model_config, encoder_model): __init__
- def forward(self, input, pos): forward | Implement the Python class `PretrainTaskModel` described below.
Class description:
PretrainTaskModel
Method signatures and docstrings:
- def __init__(self, class_num, model_config, encoder_model): __init__
- def forward(self, input, pos): forward
<|skeleton|>
class PretrainTaskModel:
"""PretrainTaskModel"""
... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class PretrainTaskModel:
"""PretrainTaskModel"""
def __init__(self, class_num, model_config, encoder_model):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PretrainTaskModel:
"""PretrainTaskModel"""
def __init__(self, class_num, model_config, encoder_model):
"""__init__"""
super(PretrainTaskModel, self).__init__()
model_type = model_config.get('model_type', 'transformer')
hidden_size = model_config.get('hidden_size', 512)
... | the_stack_v2_python_sparse | pahelix/model_zoo/protein_sequence_model.py | PaddlePaddle/PaddleHelix | train | 771 |
d0e49691d01165326447f346c7624fdbf6e7f72d | [
"self.domain = domain or config.Master.master_domain\nself.permitted_domains = permitted_domains or config.Master.permitted_domains\nif self.permitted_domains:\n assert isinstance(self.permitted_domains, tuple), 'permitted_domains must be a tuple, now it is a %s (value: %s)' % (type(self.permitted_domains), self... | <|body_start_0|>
self.domain = domain or config.Master.master_domain
self.permitted_domains = permitted_domains or config.Master.permitted_domains
if self.permitted_domains:
assert isinstance(self.permitted_domains, tuple), 'permitted_domains must be a tuple, now it is a %s (value: %... | Similar to buildbot.mail.Domain but permits filtering out people we don't want to spam. Also loads default values from chromium_config. | FilterDomain | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterDomain:
"""Similar to buildbot.mail.Domain but permits filtering out people we don't want to spam. Also loads default values from chromium_config."""
def __init__(self, domain=None, permitted_domains=None):
"""domain is the default domain to append when only the naked username ... | stack_v2_sparse_classes_36k_train_011549 | 27,927 | permissive | [
{
"docstring": "domain is the default domain to append when only the naked username is available. permitted_domains is a whitelist of domains that emails will be sent to.",
"name": "__init__",
"signature": "def __init__(self, domain=None, permitted_domains=None)"
},
{
"docstring": "If name is al... | 2 | null | Implement the Python class `FilterDomain` described below.
Class description:
Similar to buildbot.mail.Domain but permits filtering out people we don't want to spam. Also loads default values from chromium_config.
Method signatures and docstrings:
- def __init__(self, domain=None, permitted_domains=None): domain is t... | Implement the Python class `FilterDomain` described below.
Class description:
Similar to buildbot.mail.Domain but permits filtering out people we don't want to spam. Also loads default values from chromium_config.
Method signatures and docstrings:
- def __init__(self, domain=None, permitted_domains=None): domain is t... | f8e42c70146c1b668421ee6358dc550a955770a3 | <|skeleton|>
class FilterDomain:
"""Similar to buildbot.mail.Domain but permits filtering out people we don't want to spam. Also loads default values from chromium_config."""
def __init__(self, domain=None, permitted_domains=None):
"""domain is the default domain to append when only the naked username ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterDomain:
"""Similar to buildbot.mail.Domain but permits filtering out people we don't want to spam. Also loads default values from chromium_config."""
def __init__(self, domain=None, permitted_domains=None):
"""domain is the default domain to append when only the naked username is available.... | the_stack_v2_python_sparse | scripts/master/master_utils.py | mcgreevy/chromium-build | train | 0 |
7565b21ed4aa9a3a6cdf47659691f9f758d04c7c | [
"try:\n p_obj.Name = PutGetXML.get_text_from_xml(p_xml, 'Name', 'Missing Name')\n p_obj.Key = PutGetXML.get_int_from_xml(p_xml, 'Key', 0)\n p_obj.Active = PutGetXML.get_bool_from_xml(p_xml, 'Active', False)\n p_obj.UUID = PutGetXML.get_uuid_from_xml(p_xml, 'UUID')\n p_obj.Comment = PutGetXML.get_text... | <|body_start_0|>
try:
p_obj.Name = PutGetXML.get_text_from_xml(p_xml, 'Name', 'Missing Name')
p_obj.Key = PutGetXML.get_int_from_xml(p_xml, 'Key', 0)
p_obj.Active = PutGetXML.get_bool_from_xml(p_xml, 'Active', False)
p_obj.UUID = PutGetXML.get_uuid_from_xml(p_xml,... | XML | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XML:
def read_base_device_object_xml(p_pyhouse_obj, p_obj, p_xml):
"""Get the BaseObject entries from the XML element. @param p_obj: is the object we wish to populate with data @param p_xml: is the element we will extract data from (including children)."""
<|body_0|>
def wri... | stack_v2_sparse_classes_36k_train_011550 | 3,954 | permissive | [
{
"docstring": "Get the BaseObject entries from the XML element. @param p_obj: is the object we wish to populate with data @param p_xml: is the element we will extract data from (including children).",
"name": "read_base_device_object_xml",
"signature": "def read_base_device_object_xml(p_pyhouse_obj, p_... | 2 | stack_v2_sparse_classes_30k_train_010924 | Implement the Python class `XML` described below.
Class description:
Implement the XML class.
Method signatures and docstrings:
- def read_base_device_object_xml(p_pyhouse_obj, p_obj, p_xml): Get the BaseObject entries from the XML element. @param p_obj: is the object we wish to populate with data @param p_xml: is th... | Implement the Python class `XML` described below.
Class description:
Implement the XML class.
Method signatures and docstrings:
- def read_base_device_object_xml(p_pyhouse_obj, p_obj, p_xml): Get the BaseObject entries from the XML element. @param p_obj: is the object we wish to populate with data @param p_xml: is th... | 6444ed0b4c38ab59b9e419e4d54d65d598e6a54e | <|skeleton|>
class XML:
def read_base_device_object_xml(p_pyhouse_obj, p_obj, p_xml):
"""Get the BaseObject entries from the XML element. @param p_obj: is the object we wish to populate with data @param p_xml: is the element we will extract data from (including children)."""
<|body_0|>
def wri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XML:
def read_base_device_object_xml(p_pyhouse_obj, p_obj, p_xml):
"""Get the BaseObject entries from the XML element. @param p_obj: is the object we wish to populate with data @param p_xml: is the element we will extract data from (including children)."""
try:
p_obj.Name = PutGetX... | the_stack_v2_python_sparse | src/Modules/Utilities/device_tools.py | bopopescu/PyHouse_1 | train | 0 | |
07d7ed11ec81e569a68a1df969087a08a0eab14d | [
"self.bnet = bnet\nself.verbose = verbose\nself.is_quantum = is_quantum\nsorted_nd_names = sorted([nd.name for nd in self.bnet.nodes])\nself.bnet_ord_nodes = [self.bnet.get_node_named(name) for name in sorted_nd_names]",
"pairs = sorted([(node.name, str(annotated_story[node])) for node in annotated_story.keys()])... | <|body_start_0|>
self.bnet = bnet
self.verbose = verbose
self.is_quantum = is_quantum
sorted_nd_names = sorted([nd.name for nd in self.bnet.nodes])
self.bnet_ord_nodes = [self.bnet.get_node_named(name) for name in sorted_nd_names]
<|end_body_0|>
<|body_start_1|>
pairs = ... | This is the parent class of all inference engines. Attributes ---------- bnet : BayesNet bnet_ord_nodes : list[BayesNode] list of nodes of bnet ordered alphabetically by node name is_quantum : bool verbose : bool | InferenceEngine | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InferenceEngine:
"""This is the parent class of all inference engines. Attributes ---------- bnet : BayesNet bnet_ord_nodes : list[BayesNode] list of nodes of bnet ordered alphabetically by node name is_quantum : bool verbose : bool"""
def __init__(self, bnet, verbose=False, is_quantum=False... | stack_v2_sparse_classes_36k_train_011551 | 1,732 | permissive | [
{
"docstring": "Constructor Parameters ---------- bnet : BayesNet verbose : bool is_quantum : bool Returns -------",
"name": "__init__",
"signature": "def __init__(self, bnet, verbose=False, is_quantum=False)"
},
{
"docstring": "An annotated story is a dictionary that maps each node to its curre... | 2 | stack_v2_sparse_classes_30k_train_004999 | Implement the Python class `InferenceEngine` described below.
Class description:
This is the parent class of all inference engines. Attributes ---------- bnet : BayesNet bnet_ord_nodes : list[BayesNode] list of nodes of bnet ordered alphabetically by node name is_quantum : bool verbose : bool
Method signatures and do... | Implement the Python class `InferenceEngine` described below.
Class description:
This is the parent class of all inference engines. Attributes ---------- bnet : BayesNet bnet_ord_nodes : list[BayesNode] list of nodes of bnet ordered alphabetically by node name is_quantum : bool verbose : bool
Method signatures and do... | 5b4a3055ea14c2ee9c80c339f759fe2b9c8c51e2 | <|skeleton|>
class InferenceEngine:
"""This is the parent class of all inference engines. Attributes ---------- bnet : BayesNet bnet_ord_nodes : list[BayesNode] list of nodes of bnet ordered alphabetically by node name is_quantum : bool verbose : bool"""
def __init__(self, bnet, verbose=False, is_quantum=False... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InferenceEngine:
"""This is the parent class of all inference engines. Attributes ---------- bnet : BayesNet bnet_ord_nodes : list[BayesNode] list of nodes of bnet ordered alphabetically by node name is_quantum : bool verbose : bool"""
def __init__(self, bnet, verbose=False, is_quantum=False):
""... | the_stack_v2_python_sparse | inference/InferenceEngine.py | artiste-qb-net/quantum-fog | train | 95 |
2fe6b9907dbcb47b467b1c2566b8a85b3b7f4c09 | [
"import collections, bisect\nA = sorted(A)\na = set(A)\ndicts = collections.defaultdict(int)\nfor i in range(len(A)):\n dicts[A[i]] = 1\n k = bisect.bisect_right(A, A[i] ** 0.5)\n for j in range(k):\n if A[i] % A[j] == 0 and A[i] // A[j] in a:\n if A[i] == A[j] ** 2:\n dict... | <|body_start_0|>
import collections, bisect
A = sorted(A)
a = set(A)
dicts = collections.defaultdict(int)
for i in range(len(A)):
dicts[A[i]] = 1
k = bisect.bisect_right(A, A[i] ** 0.5)
for j in range(k):
if A[i] % A[j] == 0 and... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numFactoredBinaryTrees(self, A):
""":type A: List[int] :rtype: int 152ms"""
<|body_0|>
def numBinarydps_1(self, A):
"""562ms :param A: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import collections, bisect
A = sort... | stack_v2_sparse_classes_36k_train_011552 | 2,265 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int 152ms",
"name": "numFactoredBinaryTrees",
"signature": "def numFactoredBinaryTrees(self, A)"
},
{
"docstring": "562ms :param A: :return:",
"name": "numBinarydps_1",
"signature": "def numBinarydps_1(self, A)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numFactoredBinaryTrees(self, A): :type A: List[int] :rtype: int 152ms
- def numBinarydps_1(self, A): 562ms :param A: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numFactoredBinaryTrees(self, A): :type A: List[int] :rtype: int 152ms
- def numBinarydps_1(self, A): 562ms :param A: :return:
<|skeleton|>
class Solution:
def numFactor... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def numFactoredBinaryTrees(self, A):
""":type A: List[int] :rtype: int 152ms"""
<|body_0|>
def numBinarydps_1(self, A):
"""562ms :param A: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numFactoredBinaryTrees(self, A):
""":type A: List[int] :rtype: int 152ms"""
import collections, bisect
A = sorted(A)
a = set(A)
dicts = collections.defaultdict(int)
for i in range(len(A)):
dicts[A[i]] = 1
k = bisect.bisect_r... | the_stack_v2_python_sparse | BinaryTreesWithFactors_MID_823.py | 953250587/leetcode-python | train | 2 | |
570063b5fe19abc96070a1826721ae87c626059c | [
"super().__init__()\nself.stride = stride\nn = int(nOut / k)\nn1 = nOut - (k - 1) * n\nassert down_method in ['avg', 'esp'], 'One of these is suppported (avg or esp)'\nassert n == n1, 'n(={}) and n1(={}) should be equal for Depth-wise Convolution '.format(n, n1)\nself.proj_1x1 = CBR(nIn, n, 1, stride=1, groups=k)\n... | <|body_start_0|>
super().__init__()
self.stride = stride
n = int(nOut / k)
n1 = nOut - (k - 1) * n
assert down_method in ['avg', 'esp'], 'One of these is suppported (avg or esp)'
assert n == n1, 'n(={}) and n1(={}) should be equal for Depth-wise Convolution '.format(n, n1... | This class defines the EESP block, which is based on the following principle REDUCE ---> SPLIT ---> TRANSFORM --> MERGE | EESP | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EESP:
"""This class defines the EESP block, which is based on the following principle REDUCE ---> SPLIT ---> TRANSFORM --> MERGE"""
def __init__(self, nIn, nOut, stride=1, k=4, r_lim=7, down_method='esp'):
""":param nIn: number of input channels :param nOut: number of output channels... | stack_v2_sparse_classes_36k_train_011553 | 12,060 | permissive | [
{
"docstring": ":param nIn: number of input channels :param nOut: number of output channels :param stride: factor by which we should skip (useful for down-sampling). If 2, then down-samples the feature map by 2 :param k: # of parallel branches :param r_lim: A maximum value of receptive field allowed for EESP bl... | 2 | null | Implement the Python class `EESP` described below.
Class description:
This class defines the EESP block, which is based on the following principle REDUCE ---> SPLIT ---> TRANSFORM --> MERGE
Method signatures and docstrings:
- def __init__(self, nIn, nOut, stride=1, k=4, r_lim=7, down_method='esp'): :param nIn: number... | Implement the Python class `EESP` described below.
Class description:
This class defines the EESP block, which is based on the following principle REDUCE ---> SPLIT ---> TRANSFORM --> MERGE
Method signatures and docstrings:
- def __init__(self, nIn, nOut, stride=1, k=4, r_lim=7, down_method='esp'): :param nIn: number... | 0721cbbb278af027409ed4c115ccc743b6daed1b | <|skeleton|>
class EESP:
"""This class defines the EESP block, which is based on the following principle REDUCE ---> SPLIT ---> TRANSFORM --> MERGE"""
def __init__(self, nIn, nOut, stride=1, k=4, r_lim=7, down_method='esp'):
""":param nIn: number of input channels :param nOut: number of output channels... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EESP:
"""This class defines the EESP block, which is based on the following principle REDUCE ---> SPLIT ---> TRANSFORM --> MERGE"""
def __init__(self, nIn, nOut, stride=1, k=4, r_lim=7, down_method='esp'):
""":param nIn: number of input channels :param nOut: number of output channels :param strid... | the_stack_v2_python_sparse | deepclustering/arch/segmentation/epsnetv2/Model.py | jizongFox/deep-clustering-toolbox | train | 37 |
d0d2172188c4d467e22d112b780a90f289ded3a5 | [
"if obj is not None:\n attr = self.fget.__name__\n cached_attr = f'cached_{attr}'\n if hasattr(obj, cached_attr):\n return getattr(obj, cached_attr)\n else:\n value = super().__get__(obj, type)\n setattr(obj, cached_attr, value)\n return value",
"attr = self.fget.__name__\n... | <|body_start_0|>
if obj is not None:
attr = self.fget.__name__
cached_attr = f'cached_{attr}'
if hasattr(obj, cached_attr):
return getattr(obj, cached_attr)
else:
value = super().__get__(obj, type)
setattr(obj, cache... | Cached property, to act like a property with inner cache. Use it like a standard property: class MyClass: @CachedProperty def x(self): return 5 @x.setter def x(self, new_x): print(f"Setting x = {new_x}") Internally, however, the property content is cached when it's modified. This is useful to define widget properties, ... | CachedProperty | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CachedProperty:
"""Cached property, to act like a property with inner cache. Use it like a standard property: class MyClass: @CachedProperty def x(self): return 5 @x.setter def x(self, new_x): print(f"Setting x = {new_x}") Internally, however, the property content is cached when it's modified. Th... | stack_v2_sparse_classes_36k_train_011554 | 4,854 | permissive | [
{
"docstring": "Get the cached value.",
"name": "__get__",
"signature": "def __get__(self, obj, type=None)"
},
{
"docstring": "Set the cache and call the fset function.",
"name": "__set__",
"signature": "def __set__(self, obj, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000674 | Implement the Python class `CachedProperty` described below.
Class description:
Cached property, to act like a property with inner cache. Use it like a standard property: class MyClass: @CachedProperty def x(self): return 5 @x.setter def x(self, new_x): print(f"Setting x = {new_x}") Internally, however, the property c... | Implement the Python class `CachedProperty` described below.
Class description:
Cached property, to act like a property with inner cache. Use it like a standard property: class MyClass: @CachedProperty def x(self): return 5 @x.setter def x(self, new_x): print(f"Setting x = {new_x}") Internally, however, the property c... | 2ff2a0f38119f22ac292aa533dbee3fb4fa04a41 | <|skeleton|>
class CachedProperty:
"""Cached property, to act like a property with inner cache. Use it like a standard property: class MyClass: @CachedProperty def x(self): return 5 @x.setter def x(self, new_x): print(f"Setting x = {new_x}") Internally, however, the property content is cached when it's modified. Th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CachedProperty:
"""Cached property, to act like a property with inner cache. Use it like a standard property: class MyClass: @CachedProperty def x(self): return 5 @x.setter def x(self, new_x): print(f"Setting x = {new_x}") Internally, however, the property content is cached when it's modified. This is useful ... | the_stack_v2_python_sparse | bui/widget/base.py | vincent-lg/bui | train | 4 |
653172093b41a5424b4a2072c94755f2950719e6 | [
"self._pv_values = pv_values\nself._replacements = {}\nif start_time is not None:\n self._replacements['start_time'] = start_time.strftime('%Y-%m-%dT%H_%M_%S')\nif time is not None:\n time_as_string = time.strftime('%Y-%m-%dT%H:%M:%S')\n milliseconds = time.microsecond // 1000\n self._replacements['time... | <|body_start_0|>
self._pv_values = pv_values
self._replacements = {}
if start_time is not None:
self._replacements['start_time'] = start_time.strftime('%Y-%m-%dT%H_%M_%S')
if time is not None:
time_as_string = time.strftime('%Y-%m-%dT%H:%M:%S')
millise... | Code to replace templated values | TemplateReplacer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateReplacer:
"""Code to replace templated values"""
def __init__(self, pv_values, start_time=None, time=None):
"""Args: start_time (datetime.datetime): time used to replace templated "start_time" time (datetime.datetime): time used to templated "time", e.g. start of logging ime ... | stack_v2_sparse_classes_36k_train_011555 | 10,346 | permissive | [
{
"docstring": "Args: start_time (datetime.datetime): time used to replace templated \"start_time\" time (datetime.datetime): time used to templated \"time\", e.g. start of logging ime for log filename pv_values: values of the pvs in order of keyword",
"name": "__init__",
"signature": "def __init__(self... | 2 | null | Implement the Python class `TemplateReplacer` described below.
Class description:
Code to replace templated values
Method signatures and docstrings:
- def __init__(self, pv_values, start_time=None, time=None): Args: start_time (datetime.datetime): time used to replace templated "start_time" time (datetime.datetime): ... | Implement the Python class `TemplateReplacer` described below.
Class description:
Code to replace templated values
Method signatures and docstrings:
- def __init__(self, pv_values, start_time=None, time=None): Args: start_time (datetime.datetime): time used to replace templated "start_time" time (datetime.datetime): ... | 2e605cbff1cfe071571a64bed61708d8c92dc204 | <|skeleton|>
class TemplateReplacer:
"""Code to replace templated values"""
def __init__(self, pv_values, start_time=None, time=None):
"""Args: start_time (datetime.datetime): time used to replace templated "start_time" time (datetime.datetime): time used to templated "time", e.g. start of logging ime ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemplateReplacer:
"""Code to replace templated values"""
def __init__(self, pv_values, start_time=None, time=None):
"""Args: start_time (datetime.datetime): time used to replace templated "start_time" time (datetime.datetime): time used to templated "time", e.g. start of logging ime for log filen... | the_stack_v2_python_sparse | ArchiverAccess/archive_data_file_creator.py | ISISComputingGroup/EPICS-inst_servers | train | 1 |
eb602c7070523634c39075e7466624651c794250 | [
"phi_um, r_um = cart2pol(x_um, y_um)\nsign = np.sign(r_um)\nr_mm = 0.001 * np.abs(r_um)\nr_deg = 3.556 * r_mm + 0.05993 * r_mm ** 2 - 0.007358 * r_mm ** 3\nr_deg += 0.0003027 * r_mm ** 4\nr_deg *= sign\nif coords.lower() == 'cart':\n return pol2cart(phi_um, r_deg)\nelif coords.lower() == 'polar':\n return (ph... | <|body_start_0|>
phi_um, r_um = cart2pol(x_um, y_um)
sign = np.sign(r_um)
r_mm = 0.001 * np.abs(r_um)
r_deg = 3.556 * r_mm + 0.05993 * r_mm ** 2 - 0.007358 * r_mm ** 3
r_deg += 0.0003027 * r_mm ** 4
r_deg *= sign
if coords.lower() == 'cart':
return pol... | Converts between visual angle and retinal eccentricity [Watson2014]_ | Watson2014Map | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Watson2014Map:
"""Converts between visual angle and retinal eccentricity [Watson2014]_"""
def ret2dva(x_um, y_um, coords='cart'):
"""Converts retinal distances (um) to visual angles (deg) This function converts an eccentricity measurement on the retinal surface(in micrometers), measu... | stack_v2_sparse_classes_36k_train_011556 | 18,290 | permissive | [
{
"docstring": "Converts retinal distances (um) to visual angles (deg) This function converts an eccentricity measurement on the retinal surface(in micrometers), measured from the optic axis, into degrees of visual angle using Eq. A6 in [Watson2014]_. Parameters ---------- x_um, y_um : double or array-like Orig... | 3 | stack_v2_sparse_classes_30k_train_003112 | Implement the Python class `Watson2014Map` described below.
Class description:
Converts between visual angle and retinal eccentricity [Watson2014]_
Method signatures and docstrings:
- def ret2dva(x_um, y_um, coords='cart'): Converts retinal distances (um) to visual angles (deg) This function converts an eccentricity ... | Implement the Python class `Watson2014Map` described below.
Class description:
Converts between visual angle and retinal eccentricity [Watson2014]_
Method signatures and docstrings:
- def ret2dva(x_um, y_um, coords='cart'): Converts retinal distances (um) to visual angles (deg) This function converts an eccentricity ... | cb5989d134c6a4fed4723d24e0f2872033d2f5d2 | <|skeleton|>
class Watson2014Map:
"""Converts between visual angle and retinal eccentricity [Watson2014]_"""
def ret2dva(x_um, y_um, coords='cart'):
"""Converts retinal distances (um) to visual angles (deg) This function converts an eccentricity measurement on the retinal surface(in micrometers), measu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Watson2014Map:
"""Converts between visual angle and retinal eccentricity [Watson2014]_"""
def ret2dva(x_um, y_um, coords='cart'):
"""Converts retinal distances (um) to visual angles (deg) This function converts an eccentricity measurement on the retinal surface(in micrometers), measured from the ... | the_stack_v2_python_sparse | pulse2percept/utils/geometry.py | pulse2percept/pulse2percept | train | 54 |
8e92e6e26c411d922a62be85a2ff0009243f0c38 | [
"self.base_field = base_field\nself.size = size\nsuper().__init__(**kwargs)",
"name, path, args, kwargs = super().deconstruct()\nkwargs.update({'base_field': self.base_field.clone(), 'size': self.size})\nreturn (name, path, args, kwargs)"
] | <|body_start_0|>
self.base_field = base_field
self.size = size
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
name, path, args, kwargs = super().deconstruct()
kwargs.update({'base_field': self.base_field.clone(), 'size': self.size})
return (name, path, args, ... | ArrayField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArrayField:
def __init__(self, base_field, size=None, **kwargs):
"""Care for DjangoArrayField's kwargs."""
<|body_0|>
def deconstruct(self):
"""Need to create migrations properly."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.base_field = bas... | stack_v2_sparse_classes_36k_train_011557 | 1,805 | permissive | [
{
"docstring": "Care for DjangoArrayField's kwargs.",
"name": "__init__",
"signature": "def __init__(self, base_field, size=None, **kwargs)"
},
{
"docstring": "Need to create migrations properly.",
"name": "deconstruct",
"signature": "def deconstruct(self)"
}
] | 2 | null | Implement the Python class `ArrayField` described below.
Class description:
Implement the ArrayField class.
Method signatures and docstrings:
- def __init__(self, base_field, size=None, **kwargs): Care for DjangoArrayField's kwargs.
- def deconstruct(self): Need to create migrations properly. | Implement the Python class `ArrayField` described below.
Class description:
Implement the ArrayField class.
Method signatures and docstrings:
- def __init__(self, base_field, size=None, **kwargs): Care for DjangoArrayField's kwargs.
- def deconstruct(self): Need to create migrations properly.
<|skeleton|>
class Arra... | c86ae2614ea9ba80b140a2eb21ad64fdbb47ad7e | <|skeleton|>
class ArrayField:
def __init__(self, base_field, size=None, **kwargs):
"""Care for DjangoArrayField's kwargs."""
<|body_0|>
def deconstruct(self):
"""Need to create migrations properly."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArrayField:
def __init__(self, base_field, size=None, **kwargs):
"""Care for DjangoArrayField's kwargs."""
self.base_field = base_field
self.size = size
super().__init__(**kwargs)
def deconstruct(self):
"""Need to create migrations properly."""
name, path, ... | the_stack_v2_python_sparse | care/utils/models/jsonfield.py | Basharckr/care | train | 1 | |
3a22897ae9fbf3a754be03343fbd247a0f715fc0 | [
"self.cube = set_up_variable_cube(282 * np.ones((3, 3), dtype=np.float32))\nself.expected_data = np.sort(ECC_TEMPERATURE_REALIZATIONS.copy(), axis=0)\npoints_data = [self.expected_data[i].flatten() for i in range(3)]\nself.input_data = np.array(points_data)",
"reshaped_array = restore_non_percentile_dimensions(se... | <|body_start_0|>
self.cube = set_up_variable_cube(282 * np.ones((3, 3), dtype=np.float32))
self.expected_data = np.sort(ECC_TEMPERATURE_REALIZATIONS.copy(), axis=0)
points_data = [self.expected_data[i].flatten() for i in range(3)]
self.input_data = np.array(points_data)
<|end_body_0|>
<... | Test the restore_non_percentile_dimensions. | Test_restore_non_percentile_dimensions | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_restore_non_percentile_dimensions:
"""Test the restore_non_percentile_dimensions."""
def setUp(self):
"""Set up template cube and temperature data."""
<|body_0|>
def test_multiple_percentiles(self):
"""Test the result is an array with the expected shape and ... | stack_v2_sparse_classes_36k_train_011558 | 28,421 | permissive | [
{
"docstring": "Set up template cube and temperature data.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the result is an array with the expected shape and contents.",
"name": "test_multiple_percentiles",
"signature": "def test_multiple_percentiles(self)"
},... | 4 | null | Implement the Python class `Test_restore_non_percentile_dimensions` described below.
Class description:
Test the restore_non_percentile_dimensions.
Method signatures and docstrings:
- def setUp(self): Set up template cube and temperature data.
- def test_multiple_percentiles(self): Test the result is an array with th... | Implement the Python class `Test_restore_non_percentile_dimensions` described below.
Class description:
Test the restore_non_percentile_dimensions.
Method signatures and docstrings:
- def setUp(self): Set up template cube and temperature data.
- def test_multiple_percentiles(self): Test the result is an array with th... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_restore_non_percentile_dimensions:
"""Test the restore_non_percentile_dimensions."""
def setUp(self):
"""Set up template cube and temperature data."""
<|body_0|>
def test_multiple_percentiles(self):
"""Test the result is an array with the expected shape and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_restore_non_percentile_dimensions:
"""Test the restore_non_percentile_dimensions."""
def setUp(self):
"""Set up template cube and temperature data."""
self.cube = set_up_variable_cube(282 * np.ones((3, 3), dtype=np.float32))
self.expected_data = np.sort(ECC_TEMPERATURE_REALIZ... | the_stack_v2_python_sparse | improver_tests/ensemble_copula_coupling/test_utilities.py | metoppv/improver | train | 101 |
d88941b31fa7a36a52c4719a46c7d9e6ea399ec8 | [
"self.queryset = queryset\nself.page = int(page)\nself.pgnum = pgnum\nself.allow_empty_first_page = allow_empty_first_page\nself.extra_context = extra_context if extra_context is not None else {}\nself.paginator = None",
"self.paginator = Paginator(self.queryset, self.pgnum, allow_empty_first_page=self.allow_empt... | <|body_start_0|>
self.queryset = queryset
self.page = int(page)
self.pgnum = pgnum
self.allow_empty_first_page = allow_empty_first_page
self.extra_context = extra_context if extra_context is not None else {}
self.paginator = None
<|end_body_0|>
<|body_start_1|>
s... | Objet custom de pagination. Exemple d'utilisation dans une vue de type view(request, pagenum): :: queryset = Foo.objects.filter(bar=fooz).order_by('baz') paginator = PaginatorRender( queryset, pagenum, 25, allow_empty_first_page=True, extra_context = { 'foo': foo, 'bar', bar, } ) return paginator.render(request, 'path/... | PaginatorRender | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaginatorRender:
"""Objet custom de pagination. Exemple d'utilisation dans une vue de type view(request, pagenum): :: queryset = Foo.objects.filter(bar=fooz).order_by('baz') paginator = PaginatorRender( queryset, pagenum, 25, allow_empty_first_page=True, extra_context = { 'foo': foo, 'bar', bar, ... | stack_v2_sparse_classes_36k_train_011559 | 4,289 | no_license | [
{
"docstring": "Paramètres: + queryset: un QuerySet + page: numéro de la page à afficher + pgnum: nombre d'items à afficher par page + allow_empty_first_page: si False et qu'il n'y a pas de résultat pour la page donnée, lève un 404 + extra_context: contexte à passer au template",
"name": "__init__",
"si... | 3 | stack_v2_sparse_classes_30k_train_019005 | Implement the Python class `PaginatorRender` described below.
Class description:
Objet custom de pagination. Exemple d'utilisation dans une vue de type view(request, pagenum): :: queryset = Foo.objects.filter(bar=fooz).order_by('baz') paginator = PaginatorRender( queryset, pagenum, 25, allow_empty_first_page=True, ext... | Implement the Python class `PaginatorRender` described below.
Class description:
Objet custom de pagination. Exemple d'utilisation dans une vue de type view(request, pagenum): :: queryset = Foo.objects.filter(bar=fooz).order_by('baz') paginator = PaginatorRender( queryset, pagenum, 25, allow_empty_first_page=True, ext... | 5cc5ccf2759d0856ebfc8f9678bb814ef1c5a1ac | <|skeleton|>
class PaginatorRender:
"""Objet custom de pagination. Exemple d'utilisation dans une vue de type view(request, pagenum): :: queryset = Foo.objects.filter(bar=fooz).order_by('baz') paginator = PaginatorRender( queryset, pagenum, 25, allow_empty_first_page=True, extra_context = { 'foo': foo, 'bar', bar, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaginatorRender:
"""Objet custom de pagination. Exemple d'utilisation dans une vue de type view(request, pagenum): :: queryset = Foo.objects.filter(bar=fooz).order_by('baz') paginator = PaginatorRender( queryset, pagenum, 25, allow_empty_first_page=True, extra_context = { 'foo': foo, 'bar', bar, } ) return pa... | the_stack_v2_python_sparse | src/bv/client/utils/paginator.py | bisonvert/bv.client | train | 0 |
9dffa748bf4130da477d2e19d7e1e1a4fb6a5bfb | [
"assert len(sep) == 1\nself._sep = sep\nsuper().__init__(*args, **kwargs)",
"if value is None:\n return None\nelif not isinstance(value, list) or set(map(type, value)) != {str}:\n raise ValueError('ListField stores lists of strings.')\nif any((self._sep in item for item in value)):\n raise ValueError(f'L... | <|body_start_0|>
assert len(sep) == 1
self._sep = sep
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
if value is None:
return None
elif not isinstance(value, list) or set(map(type, value)) != {str}:
raise ValueError('ListField stores li... | A field to facilitate storing lists of strings as a textfield. | ListField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListField:
"""A field to facilitate storing lists of strings as a textfield."""
def __init__(self, sep: str=',', *args: T.Any, **kwargs: T.Any) -> None:
"""init. Args: sep: What separator to use to separate fields. *args: Passed to pw.CharField. *kwargs: Passed to pw.CharField."""
... | stack_v2_sparse_classes_36k_train_011560 | 9,976 | no_license | [
{
"docstring": "init. Args: sep: What separator to use to separate fields. *args: Passed to pw.CharField. *kwargs: Passed to pw.CharField.",
"name": "__init__",
"signature": "def __init__(self, sep: str=',', *args: T.Any, **kwargs: T.Any) -> None"
},
{
"docstring": "Validate and convert to strin... | 3 | stack_v2_sparse_classes_30k_train_015355 | Implement the Python class `ListField` described below.
Class description:
A field to facilitate storing lists of strings as a textfield.
Method signatures and docstrings:
- def __init__(self, sep: str=',', *args: T.Any, **kwargs: T.Any) -> None: init. Args: sep: What separator to use to separate fields. *args: Passe... | Implement the Python class `ListField` described below.
Class description:
A field to facilitate storing lists of strings as a textfield.
Method signatures and docstrings:
- def __init__(self, sep: str=',', *args: T.Any, **kwargs: T.Any) -> None: init. Args: sep: What separator to use to separate fields. *args: Passe... | 46a5fee829c6e722afced0a3bc93cc41ded8c68e | <|skeleton|>
class ListField:
"""A field to facilitate storing lists of strings as a textfield."""
def __init__(self, sep: str=',', *args: T.Any, **kwargs: T.Any) -> None:
"""init. Args: sep: What separator to use to separate fields. *args: Passed to pw.CharField. *kwargs: Passed to pw.CharField."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListField:
"""A field to facilitate storing lists of strings as a textfield."""
def __init__(self, sep: str=',', *args: T.Any, **kwargs: T.Any) -> None:
"""init. Args: sep: What separator to use to separate fields. *args: Passed to pw.CharField. *kwargs: Passed to pw.CharField."""
assert ... | the_stack_v2_python_sparse | services/web/backend/flask_app/database/models.py | arenabox/openFraming | train | 0 |
a968df34f71aabf553e511073d426d30dda445c9 | [
"original_ents = [{'ID': 'test-ID', 'Type': 'test-Type', 'Metadata': {'tags': 'test-tags', 'category': 'test-category', 'created': 'test-created', 'modified': 'test-modified'}}]\noutput_ents = {'Entry': [{'ID': 'test-ID', 'Type': 'test-Type', 'Tags': 'test-tags', 'Category': 'test-category', 'Created': 'test-create... | <|body_start_0|>
original_ents = [{'ID': 'test-ID', 'Type': 'test-Type', 'Metadata': {'tags': 'test-tags', 'category': 'test-category', 'created': 'test-created', 'modified': 'test-modified'}}]
output_ents = {'Entry': [{'ID': 'test-ID', 'Type': 'test-Type', 'Tags': 'test-tags', 'Category': 'test-categor... | TestGetEntries | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGetEntries:
def test_main(self, mocker):
"""Given: - A entry returns from getEntries. When: - No argument parameters are provided. Then: - The fields are being parsed properly in to context."""
<|body_0|>
def test_main_no_ents(self, mocker):
"""Given: - No entrie... | stack_v2_sparse_classes_36k_train_011561 | 3,454 | permissive | [
{
"docstring": "Given: - A entry returns from getEntries. When: - No argument parameters are provided. Then: - The fields are being parsed properly in to context.",
"name": "test_main",
"signature": "def test_main(self, mocker)"
},
{
"docstring": "Given: - No entries returns from getEntries. Whe... | 3 | stack_v2_sparse_classes_30k_train_019525 | Implement the Python class `TestGetEntries` described below.
Class description:
Implement the TestGetEntries class.
Method signatures and docstrings:
- def test_main(self, mocker): Given: - A entry returns from getEntries. When: - No argument parameters are provided. Then: - The fields are being parsed properly in to... | Implement the Python class `TestGetEntries` described below.
Class description:
Implement the TestGetEntries class.
Method signatures and docstrings:
- def test_main(self, mocker): Given: - A entry returns from getEntries. When: - No argument parameters are provided. Then: - The fields are being parsed properly in to... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestGetEntries:
def test_main(self, mocker):
"""Given: - A entry returns from getEntries. When: - No argument parameters are provided. Then: - The fields are being parsed properly in to context."""
<|body_0|>
def test_main_no_ents(self, mocker):
"""Given: - No entrie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestGetEntries:
def test_main(self, mocker):
"""Given: - A entry returns from getEntries. When: - No argument parameters are provided. Then: - The fields are being parsed properly in to context."""
original_ents = [{'ID': 'test-ID', 'Type': 'test-Type', 'Metadata': {'tags': 'test-tags', 'categ... | the_stack_v2_python_sparse | Packs/CommonScripts/Scripts/GetEntries/GetEntries_test.py | demisto/content | train | 1,023 | |
36c7effd88e2e49eed1d2f9183a6383d27f71737 | [
"settings.addListsToRepository('skeinforge_tools.analyze.html', '', self)\nself.fileNameInput = settings.FileNameInput().getFromFileName([('Gcode text files', '*.gcode')], 'Open File for Analyze', self, '')\nimportantFileNames = ['skeinview', 'behold', 'statistic']\nsettings.getRadioPluginsAddPluginFrame(getPlugins... | <|body_start_0|>
settings.addListsToRepository('skeinforge_tools.analyze.html', '', self)
self.fileNameInput = settings.FileNameInput().getFromFileName([('Gcode text files', '*.gcode')], 'Open File for Analyze', self, '')
importantFileNames = ['skeinview', 'behold', 'statistic']
settings... | A class to handle the analyze settings. | AnalyzeRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalyzeRepository:
"""A class to handle the analyze settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Analyze button has been clicked."""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_011562 | 3,017 | no_license | [
{
"docstring": "Set the default settings, execute title & settings fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Analyze button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | null | Implement the Python class `AnalyzeRepository` described below.
Class description:
A class to handle the analyze settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Analyze button has been clicked. | Implement the Python class `AnalyzeRepository` described below.
Class description:
A class to handle the analyze settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Analyze button has been clicked.
<|skeleton|>
class Anal... | fd69d8e856780c826386dc973ceabcc03623f3e8 | <|skeleton|>
class AnalyzeRepository:
"""A class to handle the analyze settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Analyze button has been clicked."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnalyzeRepository:
"""A class to handle the analyze settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
settings.addListsToRepository('skeinforge_tools.analyze.html', '', self)
self.fileNameInput = settings.FileNameInput().getFromFil... | the_stack_v2_python_sparse | skeinforge_tools/analyze.py | bmander/skeinforge | train | 34 |
a90b60c8503c475709da46c87a849d7fe1a1f941 | [
"last = None\nindex = 1\nresult = []\nfor i, s in enumerate(S):\n if s == last:\n index += 1\n else:\n if index >= 3:\n result.append([i - index, i - 1])\n index = 1\n last = s\nif s == last:\n index += 1\nif index > 3:\n result.append([i - index + 2, i])\nreturn resul... | <|body_start_0|>
last = None
index = 1
result = []
for i, s in enumerate(S):
if s == last:
index += 1
else:
if index >= 3:
result.append([i - index, i - 1])
index = 1
last = s
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _largeGroupPositions(self, S):
""":type S: str :rtype: List[List[int]]"""
<|body_0|>
def largeGroupPositions(self, S):
""":type S: str :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
last = None
index = ... | stack_v2_sparse_classes_36k_train_011563 | 2,526 | permissive | [
{
"docstring": ":type S: str :rtype: List[List[int]]",
"name": "_largeGroupPositions",
"signature": "def _largeGroupPositions(self, S)"
},
{
"docstring": ":type S: str :rtype: List[List[int]]",
"name": "largeGroupPositions",
"signature": "def largeGroupPositions(self, S)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _largeGroupPositions(self, S): :type S: str :rtype: List[List[int]]
- def largeGroupPositions(self, S): :type S: str :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _largeGroupPositions(self, S): :type S: str :rtype: List[List[int]]
- def largeGroupPositions(self, S): :type S: str :rtype: List[List[int]]
<|skeleton|>
class Solution:
... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _largeGroupPositions(self, S):
""":type S: str :rtype: List[List[int]]"""
<|body_0|>
def largeGroupPositions(self, S):
""":type S: str :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _largeGroupPositions(self, S):
""":type S: str :rtype: List[List[int]]"""
last = None
index = 1
result = []
for i, s in enumerate(S):
if s == last:
index += 1
else:
if index >= 3:
... | the_stack_v2_python_sparse | 830.positions-of-large-groups.py | windard/leeeeee | train | 0 | |
0ec9cdf1b298f5e9f5fb1e95d35e7630cc30a3c1 | [
"super().__init__(input_size=input_size, hidden_size=hidden_size, bias=bias)\nassert 0 <= dropout <= 1, 'Dropout rate must be in the range [0, 1]'\nassert 0 <= recurrent_dropout <= 1, 'Dropout rate must be in the range [0, 1]'\nself._dropout = dropout\nself._recurrent_dropout = recurrent_dropout",
"if hx is None:... | <|body_start_0|>
super().__init__(input_size=input_size, hidden_size=hidden_size, bias=bias)
assert 0 <= dropout <= 1, 'Dropout rate must be in the range [0, 1]'
assert 0 <= recurrent_dropout <= 1, 'Dropout rate must be in the range [0, 1]'
self._dropout = dropout
self._recurrent... | A wrapper around torch.nn.GRUCell that adds dropout to inputs and hidden. This wrapper makes the implementation more in-line with that of tf.keras.layers.GRUCell It doesn't accomplish it entirely, because: 1) the base GRU cell is different (the ordering of when the reset gate is applied is different between torch and t... | DropoutGRUCell | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DropoutGRUCell:
"""A wrapper around torch.nn.GRUCell that adds dropout to inputs and hidden. This wrapper makes the implementation more in-line with that of tf.keras.layers.GRUCell It doesn't accomplish it entirely, because: 1) the base GRU cell is different (the ordering of when the reset gate i... | stack_v2_sparse_classes_36k_train_011564 | 20,187 | permissive | [
{
"docstring": "Args: input_size: Dimensionality of the input to the GRUCell hidden_size: Dimensionality of the hidden dimension of the GRUCell bias (optional): If False, then the layer does not use bias weights b_ih and b_hh. Defaults to True. dropout (optional): Fraction of the units to drop for the linear tr... | 2 | stack_v2_sparse_classes_30k_train_008521 | Implement the Python class `DropoutGRUCell` described below.
Class description:
A wrapper around torch.nn.GRUCell that adds dropout to inputs and hidden. This wrapper makes the implementation more in-line with that of tf.keras.layers.GRUCell It doesn't accomplish it entirely, because: 1) the base GRU cell is different... | Implement the Python class `DropoutGRUCell` described below.
Class description:
A wrapper around torch.nn.GRUCell that adds dropout to inputs and hidden. This wrapper makes the implementation more in-line with that of tf.keras.layers.GRUCell It doesn't accomplish it entirely, because: 1) the base GRU cell is different... | 8fa75e67c0db8f632b135379740051cd10ff31f2 | <|skeleton|>
class DropoutGRUCell:
"""A wrapper around torch.nn.GRUCell that adds dropout to inputs and hidden. This wrapper makes the implementation more in-line with that of tf.keras.layers.GRUCell It doesn't accomplish it entirely, because: 1) the base GRU cell is different (the ordering of when the reset gate i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DropoutGRUCell:
"""A wrapper around torch.nn.GRUCell that adds dropout to inputs and hidden. This wrapper makes the implementation more in-line with that of tf.keras.layers.GRUCell It doesn't accomplish it entirely, because: 1) the base GRU cell is different (the ordering of when the reset gate is applied is ... | the_stack_v2_python_sparse | rlo/src/rlo/model/layers.py | tomjaguarpaw/knossos-ksc | train | 0 |
4d95e724f4187cb1e7a24f4779a61dd39245b9fc | [
"self._grammar = grammar\nself._items = dict()\nfor term in grammar.terminals:\n created_nonterm = type('ChomskyTerm[' + str(term) + ']', (ChomskyTermNonterminal,), ChomskyTermNonterminal.__dict__.copy())\n created_nonterm.for_term = term\n created_rule = type('ChomskyTerm[' + str(term) + ']', (ChomskyTerm... | <|body_start_0|>
self._grammar = grammar
self._items = dict()
for term in grammar.terminals:
created_nonterm = type('ChomskyTerm[' + str(term) + ']', (ChomskyTermNonterminal,), ChomskyTermNonterminal.__dict__.copy())
created_nonterm.for_term = term
created_rul... | Store all terminals and their appropriate ChomskyTermNonterminal and ChomskyTermRule. Automatically add rule and nonterminal into grammar if the rule is used. | TerminalsFilling | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TerminalsFilling:
"""Store all terminals and their appropriate ChomskyTermNonterminal and ChomskyTermRule. Automatically add rule and nonterminal into grammar if the rule is used."""
def __init__(self, grammar):
""":param grammar: Grammar to work with. Can be modified."""
<|b... | stack_v2_sparse_classes_36k_train_011565 | 8,375 | permissive | [
{
"docstring": ":param grammar: Grammar to work with. Can be modified.",
"name": "__init__",
"signature": "def __init__(self, grammar)"
},
{
"docstring": "Get nonterminal rewritable to term. If the rules is not in the grammar, nonterminal and rule rewritable to terminal are add into grammar. :pa... | 2 | stack_v2_sparse_classes_30k_train_005874 | Implement the Python class `TerminalsFilling` described below.
Class description:
Store all terminals and their appropriate ChomskyTermNonterminal and ChomskyTermRule. Automatically add rule and nonterminal into grammar if the rule is used.
Method signatures and docstrings:
- def __init__(self, grammar): :param gramm... | Implement the Python class `TerminalsFilling` described below.
Class description:
Store all terminals and their appropriate ChomskyTermNonterminal and ChomskyTermRule. Automatically add rule and nonterminal into grammar if the rule is used.
Method signatures and docstrings:
- def __init__(self, grammar): :param gramm... | 8308a1fd349bf9ea0d267360cc9a4ab20d1629e8 | <|skeleton|>
class TerminalsFilling:
"""Store all terminals and their appropriate ChomskyTermNonterminal and ChomskyTermRule. Automatically add rule and nonterminal into grammar if the rule is used."""
def __init__(self, grammar):
""":param grammar: Grammar to work with. Can be modified."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TerminalsFilling:
"""Store all terminals and their appropriate ChomskyTermNonterminal and ChomskyTermRule. Automatically add rule and nonterminal into grammar if the rule is used."""
def __init__(self, grammar):
""":param grammar: Grammar to work with. Can be modified."""
self._grammar = ... | the_stack_v2_python_sparse | grammpy/transforms/ChomskyForm/transform_to_chomsky_normal_form.py | PatrikValkovic/grammpy | train | 2 |
8ebb020c43dfdd23c350639369c67e66cba91f43 | [
"self.body_dict = body_dict\nself.file_s3_uri = file_s3_uri\nself.kms_key = kms_key\nself.session = sagemaker_session",
"if new_save_location_s3_uri is not None:\n self.file_s3_uri = new_save_location_s3_uri\nreturn s3.S3Uploader.upload_string_as_file_body(body=json.dumps(self.body_dict), desired_s3_uri=self.f... | <|body_start_0|>
self.body_dict = body_dict
self.file_s3_uri = file_s3_uri
self.kms_key = kms_key
self.session = sagemaker_session
<|end_body_0|>
<|body_start_1|>
if new_save_location_s3_uri is not None:
self.file_s3_uri = new_save_location_s3_uri
return s3.S... | Represents a file with a body and an S3 uri. | ModelMonitoringFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelMonitoringFile:
"""Represents a file with a body and an S3 uri."""
def __init__(self, body_dict, file_s3_uri, kms_key, sagemaker_session):
"""Initializes a file with a body and an S3 uri. Args: body_dict (str): The body of the JSON file. file_s3_uri (str): The uri of the JSON fi... | stack_v2_sparse_classes_36k_train_011566 | 20,253 | permissive | [
{
"docstring": "Initializes a file with a body and an S3 uri. Args: body_dict (str): The body of the JSON file. file_s3_uri (str): The uri of the JSON file. kms_key (str): The kms key to be used to decrypt the file in S3. sagemaker_session (sagemaker.session.Session): A SageMaker Session object, used for SageMa... | 2 | stack_v2_sparse_classes_30k_train_018161 | Implement the Python class `ModelMonitoringFile` described below.
Class description:
Represents a file with a body and an S3 uri.
Method signatures and docstrings:
- def __init__(self, body_dict, file_s3_uri, kms_key, sagemaker_session): Initializes a file with a body and an S3 uri. Args: body_dict (str): The body of... | Implement the Python class `ModelMonitoringFile` described below.
Class description:
Represents a file with a body and an S3 uri.
Method signatures and docstrings:
- def __init__(self, body_dict, file_s3_uri, kms_key, sagemaker_session): Initializes a file with a body and an S3 uri. Args: body_dict (str): The body of... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class ModelMonitoringFile:
"""Represents a file with a body and an S3 uri."""
def __init__(self, body_dict, file_s3_uri, kms_key, sagemaker_session):
"""Initializes a file with a body and an S3 uri. Args: body_dict (str): The body of the JSON file. file_s3_uri (str): The uri of the JSON fi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelMonitoringFile:
"""Represents a file with a body and an S3 uri."""
def __init__(self, body_dict, file_s3_uri, kms_key, sagemaker_session):
"""Initializes a file with a body and an S3 uri. Args: body_dict (str): The body of the JSON file. file_s3_uri (str): The uri of the JSON file. kms_key (... | the_stack_v2_python_sparse | src/sagemaker/model_monitor/monitoring_files.py | aws/sagemaker-python-sdk | train | 2,050 |
1809ac811b3aa166def31e207ce6c8ab0fcc0046 | [
"if self.request.method == 'GET':\n return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsStaffOfCommunity())\nelif self.request.method == 'POST':\n return (permissions.IsAuthenticated(),)\nelif self.request.method == 'DELETE':\n return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsDep... | <|body_start_0|>
if self.request.method == 'GET':
return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsStaffOfCommunity())
elif self.request.method == 'POST':
return (permissions.IsAuthenticated(),)
elif self.request.method == 'DELETE':
return (perm... | QR code view set | QRCodeViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QRCodeViewSet:
"""QR code view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
"""List QR codes"""
<|bo... | stack_v2_sparse_classes_36k_train_011567 | 7,281 | permissive | [
{
"docstring": "Get permissions",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Get serializer class",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "List QR codes",
"name": "list",
... | 3 | stack_v2_sparse_classes_30k_train_015419 | Implement the Python class `QRCodeViewSet` described below.
Class description:
QR code view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List QR codes | Implement the Python class `QRCodeViewSet` described below.
Class description:
QR code view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List QR codes
<|skeleton|>
class QRCodeView... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class QRCodeViewSet:
"""QR code view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
"""List QR codes"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QRCodeViewSet:
"""QR code view set"""
def get_permissions(self):
"""Get permissions"""
if self.request.method == 'GET':
return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsStaffOfCommunity())
elif self.request.method == 'POST':
return (permissio... | the_stack_v2_python_sparse | generator/views.py | 810Teams/clubs-and-events-backend | train | 3 |
884b24c5e40050a245614050332544662d37e0ea | [
"self.rnd_state = np.random.RandomState(seed)\nself.nb_dims = len(mins)\nself.dims_dicts = []\nself.last_raw_task = None\nself.last_interpolated_task = None\nfor i in range(len(mins)):\n current_min = mins[i]\n current_max = maxs[i]\n region_size = abs(current_max - current_min) / cuttings\n current_dim... | <|body_start_0|>
self.rnd_state = np.random.RandomState(seed)
self.nb_dims = len(mins)
self.dims_dicts = []
self.last_raw_task = None
self.last_interpolated_task = None
for i in range(len(mins)):
current_min = mins[i]
current_max = maxs[i]
... | DimensionsShuffler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DimensionsShuffler:
def __init__(self, mins, maxs, cuttings=4, seed=21):
"""Object evenly cutting a task space into hypercubes and shuffling them. Args: mins: Lower bounds of task space max: Upper bounds of task space cuttings: How many cuttings should be done on each dimension seed: See... | stack_v2_sparse_classes_36k_train_011568 | 2,996 | permissive | [
{
"docstring": "Object evenly cutting a task space into hypercubes and shuffling them. Args: mins: Lower bounds of task space max: Upper bounds of task space cuttings: How many cuttings should be done on each dimension seed: Seed of the random shuffler",
"name": "__init__",
"signature": "def __init__(se... | 3 | stack_v2_sparse_classes_30k_train_004432 | Implement the Python class `DimensionsShuffler` described below.
Class description:
Implement the DimensionsShuffler class.
Method signatures and docstrings:
- def __init__(self, mins, maxs, cuttings=4, seed=21): Object evenly cutting a task space into hypercubes and shuffling them. Args: mins: Lower bounds of task s... | Implement the Python class `DimensionsShuffler` described below.
Class description:
Implement the DimensionsShuffler class.
Method signatures and docstrings:
- def __init__(self, mins, maxs, cuttings=4, seed=21): Object evenly cutting a task space into hypercubes and shuffling them. Args: mins: Lower bounds of task s... | 6c157511a609e84596c4f8aad99e7576a015ee15 | <|skeleton|>
class DimensionsShuffler:
def __init__(self, mins, maxs, cuttings=4, seed=21):
"""Object evenly cutting a task space into hypercubes and shuffling them. Args: mins: Lower bounds of task space max: Upper bounds of task space cuttings: How many cuttings should be done on each dimension seed: See... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DimensionsShuffler:
def __init__(self, mins, maxs, cuttings=4, seed=21):
"""Object evenly cutting a task space into hypercubes and shuffling them. Args: mins: Lower bounds of task space max: Upper bounds of task space cuttings: How many cuttings should be done on each dimension seed: Seed of the rando... | the_stack_v2_python_sparse | TeachMyAgent/teachers/utils/dimensions_shuffler.py | flowersteam/TeachMyAgent | train | 70 | |
c5531fb392267ddeeff02183b2cc622e0ffd8e01 | [
"super(SysFSFanControl, self).__init__(dut)\nself._fans = []\nif fans_info is not None:\n for fan_info in fans_info:\n complete_info = fan_info.copy()\n assert 'fan_id' in complete_info, \"'fan_id' is missing in fans_info\"\n assert 'path' in complete_info, \"'path' is missing in fans_info\"... | <|body_start_0|>
super(SysFSFanControl, self).__init__(dut)
self._fans = []
if fans_info is not None:
for fan_info in fans_info:
complete_info = fan_info.copy()
assert 'fan_id' in complete_info, "'fan_id' is missing in fans_info"
assert... | System module for fan control using sysfs. Implementation for systems which able to control thermal with sysfs API. | SysFSFanControl | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SysFSFanControl:
"""System module for fan control using sysfs. Implementation for systems which able to control thermal with sysfs API."""
def __init__(self, dut, fans_info=None):
"""Constructor. Args: fans_info: A sequence of dicts. Each dict contains information of a fan: - "fan_id... | stack_v2_sparse_classes_36k_train_011569 | 5,738 | permissive | [
{
"docstring": "Constructor. Args: fans_info: A sequence of dicts. Each dict contains information of a fan: - \"fan_id\": The id used in SetFanRPM/GetFanRPM. - \"path\": The path containing files for fan operations. - \"control_mode_filename\": The file to switch auto/manual fan control mode. default is \"pwm1_... | 3 | stack_v2_sparse_classes_30k_train_013747 | Implement the Python class `SysFSFanControl` described below.
Class description:
System module for fan control using sysfs. Implementation for systems which able to control thermal with sysfs API.
Method signatures and docstrings:
- def __init__(self, dut, fans_info=None): Constructor. Args: fans_info: A sequence of ... | Implement the Python class `SysFSFanControl` described below.
Class description:
System module for fan control using sysfs. Implementation for systems which able to control thermal with sysfs API.
Method signatures and docstrings:
- def __init__(self, dut, fans_info=None): Constructor. Args: fans_info: A sequence of ... | a1b0fccd68987d8cd9c89710adc3c04b868347ec | <|skeleton|>
class SysFSFanControl:
"""System module for fan control using sysfs. Implementation for systems which able to control thermal with sysfs API."""
def __init__(self, dut, fans_info=None):
"""Constructor. Args: fans_info: A sequence of dicts. Each dict contains information of a fan: - "fan_id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SysFSFanControl:
"""System module for fan control using sysfs. Implementation for systems which able to control thermal with sysfs API."""
def __init__(self, dut, fans_info=None):
"""Constructor. Args: fans_info: A sequence of dicts. Each dict contains information of a fan: - "fan_id": The id use... | the_stack_v2_python_sparse | py/device/fan.py | bridder/factory | train | 0 |
6e496121999f5a37a17d3e184866cc98b9a7d96e | [
"if not matrix:\n return\nn = matrix.__len__()\nrotate = [[0 for _ in range(n)] for _ in range(n)]\nfor i in range(n):\n for j in range(n):\n rotate[j][n - 1 - i] = matrix[i][j]\nmatrix[:] = rotate[:]",
"if not matrix:\n return\nn = matrix.__len__()\nmatrix.reverse()\nfor i in range(n):\n for j... | <|body_start_0|>
if not matrix:
return
n = matrix.__len__()
rotate = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
rotate[j][n - 1 - i] = matrix[i][j]
matrix[:] = rotate[:]
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p... | stack_v2_sparse_classes_36k_train_011570 | 1,454 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "rotate",
"signature": "def rotate(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
... | 2 | stack_v2_sparse_classes_30k_train_008918 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate1(self, matrix): :type matrix: List[List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate1(self, matrix): :type matrix: List[List[... | 472f780c3214aab5c713612812d834ccbe589434 | <|skeleton|>
class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
if not matrix:
return
n = matrix.__len__()
rotate = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
... | the_stack_v2_python_sparse | 2/48-Rotate_Image.py | ChangXiaodong/Leetcode-solutions | train | 4 | |
1145fe4fc1c4883a54c78b7faf9108e16a4e1071 | [
"self.game = Game(numberOfPlayers, names)\nscreen = GameScreen(self.game)\nConsoleController.__init__(self, screen, commands={ENDL: self.nextMessage})",
"if self.game.over:\n self.stopRunning()\nelse:\n self.runController(RoundController(self.game.getNewRound()))\n if self.game.over:\n self.screen... | <|body_start_0|>
self.game = Game(numberOfPlayers, names)
screen = GameScreen(self.game)
ConsoleController.__init__(self, screen, commands={ENDL: self.nextMessage})
<|end_body_0|>
<|body_start_1|>
if self.game.over:
self.stopRunning()
else:
self.runContro... | Controller for a Game | GameController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameController:
"""Controller for a Game"""
def __init__(self, numberOfPlayers, names):
"""Initialize the Game Controller"""
<|body_0|>
def nextMessage(self, event):
"""Tell the screen to print the next message"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_011571 | 1,075 | no_license | [
{
"docstring": "Initialize the Game Controller",
"name": "__init__",
"signature": "def __init__(self, numberOfPlayers, names)"
},
{
"docstring": "Tell the screen to print the next message",
"name": "nextMessage",
"signature": "def nextMessage(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016955 | Implement the Python class `GameController` described below.
Class description:
Controller for a Game
Method signatures and docstrings:
- def __init__(self, numberOfPlayers, names): Initialize the Game Controller
- def nextMessage(self, event): Tell the screen to print the next message | Implement the Python class `GameController` described below.
Class description:
Controller for a Game
Method signatures and docstrings:
- def __init__(self, numberOfPlayers, names): Initialize the Game Controller
- def nextMessage(self, event): Tell the screen to print the next message
<|skeleton|>
class GameControl... | c46f2e7809b4ffc6443b279ee86edb4a0ac99a09 | <|skeleton|>
class GameController:
"""Controller for a Game"""
def __init__(self, numberOfPlayers, names):
"""Initialize the Game Controller"""
<|body_0|>
def nextMessage(self, event):
"""Tell the screen to print the next message"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameController:
"""Controller for a Game"""
def __init__(self, numberOfPlayers, names):
"""Initialize the Game Controller"""
self.game = Game(numberOfPlayers, names)
screen = GameScreen(self.game)
ConsoleController.__init__(self, screen, commands={ENDL: self.nextMessage})
... | the_stack_v2_python_sparse | src/View/Console/Game/game_controller.py | cloew/KaoPhaseTen | train | 0 |
435f48322403ca8e571f3bccfe8cc3a0a1677b7e | [
"super().__init__()\ncheck_boundaries(boundaries)\nself.boundaries = boundaries\nself.frequencies = frequencies",
"self.randomize(None)\nself.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1])\nself.freqs = self.R.uniform(low=self.frequencies[0], high=self.frequencies[1])\nlength = signal... | <|body_start_0|>
super().__init__()
check_boundaries(boundaries)
self.boundaries = boundaries
self.frequencies = frequencies
<|end_body_0|>
<|body_start_1|>
self.randomize(None)
self.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1])
self... | Add a random square pulse signal to the input signal | SignalRandAddSquarePulse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalRandAddSquarePulse:
"""Add a random square pulse signal to the input signal"""
def __init__(self, boundaries: Sequence[float]=(0.01, 0.2), frequencies: Sequence[float]=(0.001, 0.02)) -> None:
"""Args: boundaries: list defining lower and upper boundaries for the square pulse mag... | stack_v2_sparse_classes_36k_train_011572 | 16,322 | permissive | [
{
"docstring": "Args: boundaries: list defining lower and upper boundaries for the square pulse magnitude, lower and upper values need to be positive , default : ``[0.01, 0.2]`` frequencies: list defining lower and upper frequencies for the square pulse signal generation , default : ``[0.001, 0.02]``",
"nam... | 2 | stack_v2_sparse_classes_30k_train_012528 | Implement the Python class `SignalRandAddSquarePulse` described below.
Class description:
Add a random square pulse signal to the input signal
Method signatures and docstrings:
- def __init__(self, boundaries: Sequence[float]=(0.01, 0.2), frequencies: Sequence[float]=(0.001, 0.02)) -> None: Args: boundaries: list def... | Implement the Python class `SignalRandAddSquarePulse` described below.
Class description:
Add a random square pulse signal to the input signal
Method signatures and docstrings:
- def __init__(self, boundaries: Sequence[float]=(0.01, 0.2), frequencies: Sequence[float]=(0.001, 0.02)) -> None: Args: boundaries: list def... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class SignalRandAddSquarePulse:
"""Add a random square pulse signal to the input signal"""
def __init__(self, boundaries: Sequence[float]=(0.01, 0.2), frequencies: Sequence[float]=(0.001, 0.02)) -> None:
"""Args: boundaries: list defining lower and upper boundaries for the square pulse mag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignalRandAddSquarePulse:
"""Add a random square pulse signal to the input signal"""
def __init__(self, boundaries: Sequence[float]=(0.01, 0.2), frequencies: Sequence[float]=(0.001, 0.02)) -> None:
"""Args: boundaries: list defining lower and upper boundaries for the square pulse magnitude, lower... | the_stack_v2_python_sparse | monai/transforms/signal/array.py | Project-MONAI/MONAI | train | 4,805 |
e7db5176c9018305a437b3164ffb0507d9e9aedd | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email))\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password)\nuser.is_superuser = True\nuser.save(using=self._db)\nreturn user... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.create_user(... | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, email, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, password):
"""Creates and saves a superuser with the given email, date of birth a... | stack_v2_sparse_classes_36k_train_011573 | 2,933 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "create_... | 2 | null | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, email, password): C... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, email, password): C... | e3b905689a5dacfb751077a15bace4d080844b91 | <|skeleton|>
class MyUserManager:
def create_user(self, email, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, password):
"""Creates and saves a superuser with the given email, date of birth a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyUserManager:
def create_user(self, email, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email))
user.... | the_stack_v2_python_sparse | django/accounts/models.py | moskrc/demo | train | 0 | |
7d1fac98740f1012214e7d7e9f6a51fc05d8a1c5 | [
"super(SimpleEncoderDecoder, self).__init__(params)\nself.max_length = params['max_length']\nself.input_voc_size = params['input_voc_size']\nself.hidden_size = params['hidden_size']\nself.encoder_bidirectional = params['encoder_bidirectional']\nself.encoder = EncoderRNN(input_voc_size=self.input_voc_size, hidden_si... | <|body_start_0|>
super(SimpleEncoderDecoder, self).__init__(params)
self.max_length = params['max_length']
self.input_voc_size = params['input_voc_size']
self.hidden_size = params['hidden_size']
self.encoder_bidirectional = params['encoder_bidirectional']
self.encoder = E... | Sequence to Sequence model based on EncoderRNN & DecoderRNN. | SimpleEncoderDecoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleEncoderDecoder:
"""Sequence to Sequence model based on EncoderRNN & DecoderRNN."""
def __init__(self, params):
"""Initializes the Encoder-Decoder network. :param params: dict containing the main parameters set: - max_length: maximal length of the input / output sequence of word... | stack_v2_sparse_classes_36k_train_011574 | 12,975 | permissive | [
{
"docstring": "Initializes the Encoder-Decoder network. :param params: dict containing the main parameters set: - max_length: maximal length of the input / output sequence of words: i.e, max length of the sentences to translate -> upper limit of seq_length - input_voc_size: should correspond to the length of t... | 3 | null | Implement the Python class `SimpleEncoderDecoder` described below.
Class description:
Sequence to Sequence model based on EncoderRNN & DecoderRNN.
Method signatures and docstrings:
- def __init__(self, params): Initializes the Encoder-Decoder network. :param params: dict containing the main parameters set: - max_leng... | Implement the Python class `SimpleEncoderDecoder` described below.
Class description:
Sequence to Sequence model based on EncoderRNN & DecoderRNN.
Method signatures and docstrings:
- def __init__(self, params): Initializes the Encoder-Decoder network. :param params: dict containing the main parameters set: - max_leng... | c655c88cc6aec4d0724c19ea95209f1c2dd6770d | <|skeleton|>
class SimpleEncoderDecoder:
"""Sequence to Sequence model based on EncoderRNN & DecoderRNN."""
def __init__(self, params):
"""Initializes the Encoder-Decoder network. :param params: dict containing the main parameters set: - max_length: maximal length of the input / output sequence of word... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleEncoderDecoder:
"""Sequence to Sequence model based on EncoderRNN & DecoderRNN."""
def __init__(self, params):
"""Initializes the Encoder-Decoder network. :param params: dict containing the main parameters set: - max_length: maximal length of the input / output sequence of words: i.e, max l... | the_stack_v2_python_sparse | models/text2text/simple_encoder_decoder.py | aasseman/mi-prometheus | train | 0 |
f4f5b161af6b1f333d58687b1265ba6b5c90fa49 | [
"for doc_index, document in enumerate(self.document_store):\n target_length = self.target_length()\n tokenized_sentences = (self.tokenizer.tokenize(sentence) for sentence in document)\n segment_pairs = language_model_functions.split_document(tokenized_sentences, target_length)\n random_segments = self.g... | <|body_start_0|>
for doc_index, document in enumerate(self.document_store):
target_length = self.target_length()
tokenized_sentences = (self.tokenizer.tokenize(sentence) for sentence in document)
segment_pairs = language_model_functions.split_document(tokenized_sentences, tar... | The Language Model Dataset generates training batches from the document store. Please note that the process of generating samples from documents is stochastic (in consequences, most of the logic is detached to the `language_model_functions` module). Shuffle data after each epoch is not available. Along with three well-... | LanguageModelDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageModelDataset:
"""The Language Model Dataset generates training batches from the document store. Please note that the process of generating samples from documents is stochastic (in consequences, most of the logic is detached to the `language_model_functions` module). Shuffle data after eac... | stack_v2_sparse_classes_36k_train_011575 | 9,406 | permissive | [
{
"docstring": "The generator produces language model examples. It is equivalent to the single function from Google BERT's or HuggingFace repo. It can be easily adjust to the parallel processing (e.g. using queues).",
"name": "examples_generator",
"signature": "def examples_generator(self) -> Iterable[L... | 4 | stack_v2_sparse_classes_30k_train_012208 | Implement the Python class `LanguageModelDataset` described below.
Class description:
The Language Model Dataset generates training batches from the document store. Please note that the process of generating samples from documents is stochastic (in consequences, most of the logic is detached to the `language_model_fun... | Implement the Python class `LanguageModelDataset` described below.
Class description:
The Language Model Dataset generates training batches from the document store. Please note that the process of generating samples from documents is stochastic (in consequences, most of the logic is detached to the `language_model_fun... | 1e2d57277b33778309131e69b69ead7afbd0dd59 | <|skeleton|>
class LanguageModelDataset:
"""The Language Model Dataset generates training batches from the document store. Please note that the process of generating samples from documents is stochastic (in consequences, most of the logic is detached to the `language_model_functions` module). Shuffle data after eac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LanguageModelDataset:
"""The Language Model Dataset generates training batches from the document store. Please note that the process of generating samples from documents is stochastic (in consequences, most of the logic is detached to the `language_model_functions` module). Shuffle data after each epoch is no... | the_stack_v2_python_sparse | aspect_based_sentiment_analysis/training/datasets/language_model.py | lavanaythakral/Aspect-Based-Sentiment-Analysis | train | 1 |
8c9371ba0f0e14d340e5b7bb9bb67213ca1dd798 | [
"super(Encoder, self).__init__()\nself.features = features\nself.features_dim = features_dim\nself.aggregator = aggregator\nself.emded_dim = emded_dim\nself.cat = concate\nif self.cat:\n self.weight = nn.Parameter(torch.FloatTensor(2 * self.features_dim, self.emded_dim))\nelse:\n self.weight = nn.Parameter(to... | <|body_start_0|>
super(Encoder, self).__init__()
self.features = features
self.features_dim = features_dim
self.aggregator = aggregator
self.emded_dim = emded_dim
self.cat = concate
if self.cat:
self.weight = nn.Parameter(torch.FloatTensor(2 * self.fea... | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def __init__(self, features, features_dim, emded_dim, adj_lists, aggregator, concate=True):
""":param features: mapping functions to ccorresponding features :param features_dim: features dimension :param emded_dim: the transformed feature matrix dimension :param adj_lists: neigh... | stack_v2_sparse_classes_36k_train_011576 | 1,627 | no_license | [
{
"docstring": ":param features: mapping functions to ccorresponding features :param features_dim: features dimension :param emded_dim: the transformed feature matrix dimension :param adj_lists: neighbors of nodes() :param aggregator:",
"name": "__init__",
"signature": "def __init__(self, features, feat... | 2 | stack_v2_sparse_classes_30k_train_019285 | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, features, features_dim, emded_dim, adj_lists, aggregator, concate=True): :param features: mapping functions to ccorresponding features :param features_dim: featu... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, features, features_dim, emded_dim, adj_lists, aggregator, concate=True): :param features: mapping functions to ccorresponding features :param features_dim: featu... | dbc2bdd43442f4af219916dea7975ec31683472b | <|skeleton|>
class Encoder:
def __init__(self, features, features_dim, emded_dim, adj_lists, aggregator, concate=True):
""":param features: mapping functions to ccorresponding features :param features_dim: features dimension :param emded_dim: the transformed feature matrix dimension :param adj_lists: neigh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
def __init__(self, features, features_dim, emded_dim, adj_lists, aggregator, concate=True):
""":param features: mapping functions to ccorresponding features :param features_dim: features dimension :param emded_dim: the transformed feature matrix dimension :param adj_lists: neighbors of nodes(... | the_stack_v2_python_sparse | GraphAttentionNetwork/encode.py | IEGraph/GNN_Sizheli | train | 0 | |
c29108028207fc849f8ccd6e4e3c6d44c3e07681 | [
"def find_measurement_by_name(measurement_name, measurement_list):\n \"\"\"\n 根据测试指标名称获取测量指标\n :param measurement_name:\n :param measurement_list:\n :return:\n \"\"\"\n if not measurement_list:\n return None\n for measurement_cfg in measurement_... | <|body_start_0|>
def find_measurement_by_name(measurement_name, measurement_list):
"""
根据测试指标名称获取测量指标
:param measurement_name:
:param measurement_list:
:return:
"""
if not measurement_list... | MeasurementHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeasurementHelper:
def get_measurements(self, task_cfg):
"""获取测量任务下的所有测量指标 :param task_cfg: :return:"""
<|body_0|>
def get_measurements_by_fingerprint(self, task_cfg):
"""根据指纹对测量任务下的测量指标进行分类 :param task_cfg: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_011577 | 7,612 | permissive | [
{
"docstring": "获取测量任务下的所有测量指标 :param task_cfg: :return:",
"name": "get_measurements",
"signature": "def get_measurements(self, task_cfg)"
},
{
"docstring": "根据指纹对测量任务下的测量指标进行分类 :param task_cfg: :return:",
"name": "get_measurements_by_fingerprint",
"signature": "def get_measurements_by_f... | 2 | null | Implement the Python class `MeasurementHelper` described below.
Class description:
Implement the MeasurementHelper class.
Method signatures and docstrings:
- def get_measurements(self, task_cfg): 获取测量任务下的所有测量指标 :param task_cfg: :return:
- def get_measurements_by_fingerprint(self, task_cfg): 根据指纹对测量任务下的测量指标进行分类 :param... | Implement the Python class `MeasurementHelper` described below.
Class description:
Implement the MeasurementHelper class.
Method signatures and docstrings:
- def get_measurements(self, task_cfg): 获取测量任务下的所有测量指标 :param task_cfg: :return:
- def get_measurements_by_fingerprint(self, task_cfg): 根据指纹对测量任务下的测量指标进行分类 :param... | a72b4e4d78b4375f69887e75abcc1e6a6782c551 | <|skeleton|>
class MeasurementHelper:
def get_measurements(self, task_cfg):
"""获取测量任务下的所有测量指标 :param task_cfg: :return:"""
<|body_0|>
def get_measurements_by_fingerprint(self, task_cfg):
"""根据指纹对测量任务下的测量指标进行分类 :param task_cfg: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeasurementHelper:
def get_measurements(self, task_cfg):
"""获取测量任务下的所有测量指标 :param task_cfg: :return:"""
def find_measurement_by_name(measurement_name, measurement_list):
"""
根据测试指标名称获取测量指标
:param measurement_name:
:param m... | the_stack_v2_python_sparse | measure/measurements.py | RitterHou/search_platform | train | 0 | |
01ff6c31ba85c254b525dd78001b442180481f95 | [
"device_type = request.query_params.get('type')\ndevices = Device.objects.filter(type=device_type) if device_type else Device.objects.all()\nserializer = DeviceDetailSerializer(devices, many=True)\nreturn Response(serializer.data)",
"serializer = DeviceDetailSerializer(data=request.data)\nif serializer.is_valid()... | <|body_start_0|>
device_type = request.query_params.get('type')
devices = Device.objects.filter(type=device_type) if device_type else Device.objects.all()
serializer = DeviceDetailSerializer(devices, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
ser... | DeviceList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceList:
def get(self, request):
"""Get all devices if parameter type it'll filter by type :param request: :return: Response"""
<|body_0|>
def post(self, request):
"""Add new device :param request: :return: Response"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_011578 | 9,166 | no_license | [
{
"docstring": "Get all devices if parameter type it'll filter by type :param request: :return: Response",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Add new device :param request: :return: Response",
"name": "post",
"signature": "def post(self, request)"
}... | 2 | stack_v2_sparse_classes_30k_train_016418 | Implement the Python class `DeviceList` described below.
Class description:
Implement the DeviceList class.
Method signatures and docstrings:
- def get(self, request): Get all devices if parameter type it'll filter by type :param request: :return: Response
- def post(self, request): Add new device :param request: :re... | Implement the Python class `DeviceList` described below.
Class description:
Implement the DeviceList class.
Method signatures and docstrings:
- def get(self, request): Get all devices if parameter type it'll filter by type :param request: :return: Response
- def post(self, request): Add new device :param request: :re... | cdfe2893a0ddb9288039012bafbc1bf5e39a0c75 | <|skeleton|>
class DeviceList:
def get(self, request):
"""Get all devices if parameter type it'll filter by type :param request: :return: Response"""
<|body_0|>
def post(self, request):
"""Add new device :param request: :return: Response"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeviceList:
def get(self, request):
"""Get all devices if parameter type it'll filter by type :param request: :return: Response"""
device_type = request.query_params.get('type')
devices = Device.objects.filter(type=device_type) if device_type else Device.objects.all()
serialize... | the_stack_v2_python_sparse | devices/views.py | player64/home-automation-backend | train | 0 | |
20cc3b56e07bbaf04f98f1258f3b0c7e4eb37e44 | [
"if cls._driver is None:\n if browser_name == 'Chrome':\n cls._driver = webdriver.Chrome(driverPath['Chrome'])\n elif browser_name == 'Firefox':\n cls._driver = webdriver.Firefox(driverPath['Firefox'])\n cls._driver.maximize_window()\n cls._driver.get(URL)\n cls.__login()\n cls._driv... | <|body_start_0|>
if cls._driver is None:
if browser_name == 'Chrome':
cls._driver = webdriver.Chrome(driverPath['Chrome'])
elif browser_name == 'Firefox':
cls._driver = webdriver.Firefox(driverPath['Firefox'])
cls._driver.maximize_window()
... | 浏览器驱动工具类 | Driver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Driver:
"""浏览器驱动工具类"""
def get_driver(cls, browser_name='Chrome'):
"""获取浏览器驱动对象 :param browser_name: :return:"""
<|body_0|>
def __login(cls):
"""私有方法, 只能在类里边使用 类外部无法使用, 子类不能继承 解决登录问题 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if cl... | stack_v2_sparse_classes_36k_train_011579 | 2,453 | no_license | [
{
"docstring": "获取浏览器驱动对象 :param browser_name: :return:",
"name": "get_driver",
"signature": "def get_driver(cls, browser_name='Chrome')"
},
{
"docstring": "私有方法, 只能在类里边使用 类外部无法使用, 子类不能继承 解决登录问题 :return:",
"name": "__login",
"signature": "def __login(cls)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020829 | Implement the Python class `Driver` described below.
Class description:
浏览器驱动工具类
Method signatures and docstrings:
- def get_driver(cls, browser_name='Chrome'): 获取浏览器驱动对象 :param browser_name: :return:
- def __login(cls): 私有方法, 只能在类里边使用 类外部无法使用, 子类不能继承 解决登录问题 :return: | Implement the Python class `Driver` described below.
Class description:
浏览器驱动工具类
Method signatures and docstrings:
- def get_driver(cls, browser_name='Chrome'): 获取浏览器驱动对象 :param browser_name: :return:
- def __login(cls): 私有方法, 只能在类里边使用 类外部无法使用, 子类不能继承 解决登录问题 :return:
<|skeleton|>
class Driver:
"""浏览器驱动工具类"""
... | c777f2f8f532d58577e9f023db38a0d404c3a150 | <|skeleton|>
class Driver:
"""浏览器驱动工具类"""
def get_driver(cls, browser_name='Chrome'):
"""获取浏览器驱动对象 :param browser_name: :return:"""
<|body_0|>
def __login(cls):
"""私有方法, 只能在类里边使用 类外部无法使用, 子类不能继承 解决登录问题 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Driver:
"""浏览器驱动工具类"""
def get_driver(cls, browser_name='Chrome'):
"""获取浏览器驱动对象 :param browser_name: :return:"""
if cls._driver is None:
if browser_name == 'Chrome':
cls._driver = webdriver.Chrome(driverPath['Chrome'])
elif browser_name == 'Firefox'... | the_stack_v2_python_sparse | day6/day6作业.py | gongzuo666/pycharm.web | train | 0 |
764da55932a024173f71a6da9a09b6ab3a639f6d | [
"self.return_urls = return_urls\nself.identity_provider = identity_provider\nself.i_frame = i_frame\nself.language = language\nself.get_social_security_number = get_social_security_number\nself.pre_filled_social_security_number = pre_filled_social_security_number\nself.page_title = page_title\nself.external_referen... | <|body_start_0|>
self.return_urls = return_urls
self.identity_provider = identity_provider
self.i_frame = i_frame
self.language = language
self.get_social_security_number = get_social_security_number
self.pre_filled_social_security_number = pre_filled_social_security_numb... | Implementation of the 'CreateIdentificationRequest' model. Creates a Identity request Attributes: return_urls (ReturnUrls): The return urls to be redirected to after the identification process is done identity_provider (IdentityProvider): The identityprovider to use for the identification, if not set the user will get ... | CreateIdentificationRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateIdentificationRequest:
"""Implementation of the 'CreateIdentificationRequest' model. Creates a Identity request Attributes: return_urls (ReturnUrls): The return urls to be redirected to after the identification process is done identity_provider (IdentityProvider): The identityprovider to us... | stack_v2_sparse_classes_36k_train_011580 | 5,767 | permissive | [
{
"docstring": "Constructor for the CreateIdentificationRequest class",
"name": "__init__",
"signature": "def __init__(self, return_urls=None, identity_provider=None, i_frame=None, language=None, get_social_security_number=None, pre_filled_social_security_number=None, page_title=None, external_reference... | 2 | stack_v2_sparse_classes_30k_test_000156 | Implement the Python class `CreateIdentificationRequest` described below.
Class description:
Implementation of the 'CreateIdentificationRequest' model. Creates a Identity request Attributes: return_urls (ReturnUrls): The return urls to be redirected to after the identification process is done identity_provider (Identi... | Implement the Python class `CreateIdentificationRequest` described below.
Class description:
Implementation of the 'CreateIdentificationRequest' model. Creates a Identity request Attributes: return_urls (ReturnUrls): The return urls to be redirected to after the identification process is done identity_provider (Identi... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class CreateIdentificationRequest:
"""Implementation of the 'CreateIdentificationRequest' model. Creates a Identity request Attributes: return_urls (ReturnUrls): The return urls to be redirected to after the identification process is done identity_provider (IdentityProvider): The identityprovider to us... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateIdentificationRequest:
"""Implementation of the 'CreateIdentificationRequest' model. Creates a Identity request Attributes: return_urls (ReturnUrls): The return urls to be redirected to after the identification process is done identity_provider (IdentityProvider): The identityprovider to use for the ide... | the_stack_v2_python_sparse | idfy_rest_client/models/create_identification_request.py | dealflowteam/Idfy | train | 0 |
dcabea67fbb716277c8c157eb8f0cd15b6494927 | [
"reader = sitk.ImageSeriesReader()\ndicom_names = reader.GetGDCMSeriesFileNames(self.image_path)\nreader.SetFileNames(dicom_names)\nimage = reader.Execute()\ntest_image = np.swapaxes(sitk.GetArrayFromImage(image), 0, 2).astype('float32')\nreturn test_image",
"reader = sitk.ImageSeriesReader()\ndicom_names = reade... | <|body_start_0|>
reader = sitk.ImageSeriesReader()
dicom_names = reader.GetGDCMSeriesFileNames(self.image_path)
reader.SetFileNames(dicom_names)
image = reader.Execute()
test_image = np.swapaxes(sitk.GetArrayFromImage(image), 0, 2).astype('float32')
return test_image
<|en... | Class to read DICOM MRI images | DICOMReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DICOMReader:
"""Class to read DICOM MRI images"""
def get_np_array(self):
"""Return the DICOM image as a Numpy array"""
<|body_0|>
def get_resolution(self):
"""Return the spacing between the slices"""
<|body_1|>
def set_itk_image(self):
"""Se... | stack_v2_sparse_classes_36k_train_011581 | 2,416 | no_license | [
{
"docstring": "Return the DICOM image as a Numpy array",
"name": "get_np_array",
"signature": "def get_np_array(self)"
},
{
"docstring": "Return the spacing between the slices",
"name": "get_resolution",
"signature": "def get_resolution(self)"
},
{
"docstring": "Set ITK image ob... | 3 | stack_v2_sparse_classes_30k_val_000254 | Implement the Python class `DICOMReader` described below.
Class description:
Class to read DICOM MRI images
Method signatures and docstrings:
- def get_np_array(self): Return the DICOM image as a Numpy array
- def get_resolution(self): Return the spacing between the slices
- def set_itk_image(self): Set ITK image obj... | Implement the Python class `DICOMReader` described below.
Class description:
Class to read DICOM MRI images
Method signatures and docstrings:
- def get_np_array(self): Return the DICOM image as a Numpy array
- def get_resolution(self): Return the spacing between the slices
- def set_itk_image(self): Set ITK image obj... | 4cf3ea43aaf4ab435fb46587e0fa51a5f9c2657e | <|skeleton|>
class DICOMReader:
"""Class to read DICOM MRI images"""
def get_np_array(self):
"""Return the DICOM image as a Numpy array"""
<|body_0|>
def get_resolution(self):
"""Return the spacing between the slices"""
<|body_1|>
def set_itk_image(self):
"""Se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DICOMReader:
"""Class to read DICOM MRI images"""
def get_np_array(self):
"""Return the DICOM image as a Numpy array"""
reader = sitk.ImageSeriesReader()
dicom_names = reader.GetGDCMSeriesFileNames(self.image_path)
reader.SetFileNames(dicom_names)
image = reader.Ex... | the_stack_v2_python_sparse | home_backup/mask_SegSRGAN/utils/ImageReader.py | sai36/SRGAN | train | 0 |
83d6e2c4b6caa67128e23742ba3e9a47ff5664d6 | [
"if dtype:\n pyKeOps_Warning('keyword argument dtype in KernelSolve is deprecated ; argument is ignored.')\nreduction_op = 'Sum'\nif opt_arg:\n self.formula = reduction_op + '_Reduction(' + formula + ',' + str(opt_arg) + ',' + str(axis2cat(axis)) + ')'\nelse:\n self.formula = reduction_op + '_Reduction(' +... | <|body_start_0|>
if dtype:
pyKeOps_Warning('keyword argument dtype in KernelSolve is deprecated ; argument is ignored.')
reduction_op = 'Sum'
if opt_arg:
self.formula = reduction_op + '_Reduction(' + formula + ',' + str(opt_arg) + ',' + str(axis2cat(axis)) + ')'
e... | Creates a new conjugate gradient solver. Supporting the same :ref:`generic syntax <part.generic_formulas>` as :class:`numpy.Genred <pykeops.numpy.Genred>`, this module allows you to solve generic optimization problems of the form: .. math:: & & a^{\\star} & =\\operatorname*{argmin}_a \\tfrac 1 2 \\langle a,( \\alpha \\... | KernelSolve | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KernelSolve:
"""Creates a new conjugate gradient solver. Supporting the same :ref:`generic syntax <part.generic_formulas>` as :class:`numpy.Genred <pykeops.numpy.Genred>`, this module allows you to solve generic optimization problems of the form: .. math:: & & a^{\\star} & =\\operatorname*{argmin... | stack_v2_sparse_classes_36k_train_011582 | 12,274 | permissive | [
{
"docstring": "Instantiate a new KernelSolve operation. Note: :class:`KernelSolve` relies on C++ or CUDA kernels that are compiled on-the-fly and stored in a :ref:`cache directory <part.cache>` as shared libraries (\".so\" files) for later use. Args: formula (string): The scalar- or vector-valued expression th... | 2 | stack_v2_sparse_classes_30k_train_019098 | Implement the Python class `KernelSolve` described below.
Class description:
Creates a new conjugate gradient solver. Supporting the same :ref:`generic syntax <part.generic_formulas>` as :class:`numpy.Genred <pykeops.numpy.Genred>`, this module allows you to solve generic optimization problems of the form: .. math:: &... | Implement the Python class `KernelSolve` described below.
Class description:
Creates a new conjugate gradient solver. Supporting the same :ref:`generic syntax <part.generic_formulas>` as :class:`numpy.Genred <pykeops.numpy.Genred>`, this module allows you to solve generic optimization problems of the form: .. math:: &... | 52ed22a7fbbcf4bd02dbdf5dc2b00bf79cceddf5 | <|skeleton|>
class KernelSolve:
"""Creates a new conjugate gradient solver. Supporting the same :ref:`generic syntax <part.generic_formulas>` as :class:`numpy.Genred <pykeops.numpy.Genred>`, this module allows you to solve generic optimization problems of the form: .. math:: & & a^{\\star} & =\\operatorname*{argmin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KernelSolve:
"""Creates a new conjugate gradient solver. Supporting the same :ref:`generic syntax <part.generic_formulas>` as :class:`numpy.Genred <pykeops.numpy.Genred>`, this module allows you to solve generic optimization problems of the form: .. math:: & & a^{\\star} & =\\operatorname*{argmin}_a \\tfrac 1... | the_stack_v2_python_sparse | pykeops/pykeops/numpy/operations.py | getkeops/keops | train | 910 |
afbc1ccabfb95936f9168a77bde4b0c32a1b2ce1 | [
"n = self.L = 0 if not matrix else len(matrix[0])\nm = len(matrix)\ntrees = self.trees = []\nfor i in xrange(m):\n tree = [0] * n + matrix[i]\n for i in xrange(n - 1, 0, -1):\n tree[i] = tree[i << 1] + tree[i << 1 | 1]\n trees += (tree,)",
"col += self.L\ntree = self.trees[row]\ntree[col] = val\nw... | <|body_start_0|>
n = self.L = 0 if not matrix else len(matrix[0])
m = len(matrix)
trees = self.trees = []
for i in xrange(m):
tree = [0] * n + matrix[i]
for i in xrange(n - 1, 0, -1):
tree[i] = tree[i << 1] + tree[i << 1 | 1]
trees += (... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]] n dimensional segment tree"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: None"""
<|body_1|>
def sumRegion(self, row1, col1, r... | stack_v2_sparse_classes_36k_train_011583 | 1,548 | no_license | [
{
"docstring": ":type matrix: List[List[int]] n dimensional segment tree",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row: int :type col: int :type val: int :rtype: None",
"name": "update",
"signature": "def update(self, row, col, val)"
},
... | 3 | stack_v2_sparse_classes_30k_val_000441 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]] n dimensional segment tree
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: Non... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]] n dimensional segment tree
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: Non... | edff905f63ab95cdd40447b27a9c449c9cefec37 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]] n dimensional segment tree"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: None"""
<|body_1|>
def sumRegion(self, row1, col1, r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]] n dimensional segment tree"""
n = self.L = 0 if not matrix else len(matrix[0])
m = len(matrix)
trees = self.trees = []
for i in xrange(m):
tree = [0] * n + matrix[i]
for i in... | the_stack_v2_python_sparse | _0308_Range_Sum_Query_2D_Mutable.py | mingweihe/leetcode | train | 3 | |
3517b4163199387526767f7f9c9fc5ee07ae98cd | [
"initial = super(EditNewAssessment, self).get_initial()\ninitial['title'] = self.assessVers.assessment.title\ninitial['domainPerformance'] = self.assessVers.assessment.domainPerformance\ninitial['domainProduct'] = self.assessVers.assessment.domainProduct\ninitial['domainExamination'] = self.assessVers.assessment.do... | <|body_start_0|>
initial = super(EditNewAssessment, self).get_initial()
initial['title'] = self.assessVers.assessment.title
initial['domainPerformance'] = self.assessVers.assessment.domainPerformance
initial['domainProduct'] = self.assessVers.assessment.domainProduct
initial['dom... | View to edit new assessments (can change fields in :class:`~makeReports.models.assessment_models.Assessment`) Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion` to edit | EditNewAssessment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditNewAssessment:
"""View to edit new assessments (can change fields in :class:`~makeReports.models.assessment_models.Assessment`) Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion` to edit"""
def get_initial(self):
"""Get i... | stack_v2_sparse_classes_36k_train_011584 | 27,436 | no_license | [
{
"docstring": "Get initial values of form based upon current values of the assessment Returns: dict : initial values of form",
"name": "get_initial",
"signature": "def get_initial(self)"
},
{
"docstring": "Edit assessment according to form Args: form (EditNewAssessmentForm) : form to be process... | 2 | stack_v2_sparse_classes_30k_train_001937 | Implement the Python class `EditNewAssessment` described below.
Class description:
View to edit new assessments (can change fields in :class:`~makeReports.models.assessment_models.Assessment`) Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion` to edit
Method ... | Implement the Python class `EditNewAssessment` described below.
Class description:
View to edit new assessments (can change fields in :class:`~makeReports.models.assessment_models.Assessment`) Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion` to edit
Method ... | 472a6fd487811002a60a7812ae2eef941e7182cc | <|skeleton|>
class EditNewAssessment:
"""View to edit new assessments (can change fields in :class:`~makeReports.models.assessment_models.Assessment`) Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion` to edit"""
def get_initial(self):
"""Get i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditNewAssessment:
"""View to edit new assessments (can change fields in :class:`~makeReports.models.assessment_models.Assessment`) Keyword Args: assessIR (str): primary key of :class:`~makeReports.models.assessment_models.AssessmentVersion` to edit"""
def get_initial(self):
"""Get initial values... | the_stack_v2_python_sparse | AACForm/makeReports/views/assessment_views.py | jdboyd-github/AAC-Capstone | train | 0 |
546293c0e1c5c4cad1fdb179d54019c5dfc89714 | [
"self.filename = filename\nself.subclass = subclass\nself.allow_mmap = allow_mmap",
"filename = os.path.join(unpickler._dirname, self.filename)\nnp_ver = [int(x) for x in unpickler.np.__version__.split('.', 2)[:2]]\nallow_mmap = getattr(self, 'allow_mmap', True)\nmemmap_kwargs = {} if not allow_mmap else {'mmap_m... | <|body_start_0|>
self.filename = filename
self.subclass = subclass
self.allow_mmap = allow_mmap
<|end_body_0|>
<|body_start_1|>
filename = os.path.join(unpickler._dirname, self.filename)
np_ver = [int(x) for x in unpickler.np.__version__.split('.', 2)[:2]]
allow_mmap = g... | An object to be persisted instead of numpy arrays. The only thing this object does, is to carry the filename in which the array has been persisted, and the array subclass. | NDArrayWrapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NDArrayWrapper:
"""An object to be persisted instead of numpy arrays. The only thing this object does, is to carry the filename in which the array has been persisted, and the array subclass."""
def __init__(self, filename, subclass, allow_mmap=True):
"""Store the useful information f... | stack_v2_sparse_classes_36k_train_011585 | 17,419 | permissive | [
{
"docstring": "Store the useful information for later",
"name": "__init__",
"signature": "def __init__(self, filename, subclass, allow_mmap=True)"
},
{
"docstring": "Reconstruct the array",
"name": "read",
"signature": "def read(self, unpickler)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015616 | Implement the Python class `NDArrayWrapper` described below.
Class description:
An object to be persisted instead of numpy arrays. The only thing this object does, is to carry the filename in which the array has been persisted, and the array subclass.
Method signatures and docstrings:
- def __init__(self, filename, s... | Implement the Python class `NDArrayWrapper` described below.
Class description:
An object to be persisted instead of numpy arrays. The only thing this object does, is to carry the filename in which the array has been persisted, and the array subclass.
Method signatures and docstrings:
- def __init__(self, filename, s... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class NDArrayWrapper:
"""An object to be persisted instead of numpy arrays. The only thing this object does, is to carry the filename in which the array has been persisted, and the array subclass."""
def __init__(self, filename, subclass, allow_mmap=True):
"""Store the useful information f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NDArrayWrapper:
"""An object to be persisted instead of numpy arrays. The only thing this object does, is to carry the filename in which the array has been persisted, and the array subclass."""
def __init__(self, filename, subclass, allow_mmap=True):
"""Store the useful information for later"""
... | the_stack_v2_python_sparse | Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py | ryfeus/lambda-packs | train | 1,283 |
220e9ee6e2edc49656c370d132a8d86ab49fd99d | [
"mails = Mail.objects.all()\nserializer = MailSerializer(mails, many=True)\nreturn Response(serializer.data)",
"serializer = MailSerializer(data=request.data)\nif serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\nreturn Response(serializer.errors,... | <|body_start_0|>
mails = Mail.objects.all()
serializer = MailSerializer(mails, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
serializer = MailSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Re... | MailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MailView:
def get(self, request, format=None):
"""Get emails ---"""
<|body_0|>
def post(self, request, format=None):
"""Set new email --- Si le mail existe déja alors le rajout ne sera pas permis"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
mails... | stack_v2_sparse_classes_36k_train_011586 | 1,478 | no_license | [
{
"docstring": "Get emails ---",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Set new email --- Si le mail existe déja alors le rajout ne sera pas permis",
"name": "post",
"signature": "def post(self, request, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011950 | Implement the Python class `MailView` described below.
Class description:
Implement the MailView class.
Method signatures and docstrings:
- def get(self, request, format=None): Get emails ---
- def post(self, request, format=None): Set new email --- Si le mail existe déja alors le rajout ne sera pas permis | Implement the Python class `MailView` described below.
Class description:
Implement the MailView class.
Method signatures and docstrings:
- def get(self, request, format=None): Get emails ---
- def post(self, request, format=None): Set new email --- Si le mail existe déja alors le rajout ne sera pas permis
<|skeleto... | 29ac60629afcf946ebb4de09f0aa9b2c003f3c98 | <|skeleton|>
class MailView:
def get(self, request, format=None):
"""Get emails ---"""
<|body_0|>
def post(self, request, format=None):
"""Set new email --- Si le mail existe déja alors le rajout ne sera pas permis"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MailView:
def get(self, request, format=None):
"""Get emails ---"""
mails = Mail.objects.all()
serializer = MailSerializer(mails, many=True)
return Response(serializer.data)
def post(self, request, format=None):
"""Set new email --- Si le mail existe déja alors le ... | the_stack_v2_python_sparse | backend/houssem/mails/views.py | AdouniH/spareTime | train | 0 | |
35eb14f18f7d14b130427e4c9492aa8f7a77a4b4 | [
"pows = np.array(pows)\nnx = len(pows)\nmaxpow = np.max(pows)\nif np.any(pows < 0):\n raise ValueError('All elements of pows must be non-negative integers.')\nsuper().__init__(self._monomial, nf=1, nx=nx, maxderiv=None, zlevel=maxpow)\nself.pows = pows\nreturn",
"nd, nvar = dfun.ndnvar(deriv, var, self.nx)\nif... | <|body_start_0|>
pows = np.array(pows)
nx = len(pows)
maxpow = np.max(pows)
if np.any(pows < 0):
raise ValueError('All elements of pows must be non-negative integers.')
super().__init__(self._monomial, nf=1, nx=nx, maxderiv=None, zlevel=maxpow)
self.pows = pow... | The monominal in multiple variables | Monomial | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Monomial:
"""The monominal in multiple variables"""
def __init__(self, pows):
"""Parameters ---------- pows : array_like A list of non-negative integer exponents."""
<|body_0|>
def _monomial(self, X, deriv=0, out=None, var=None):
"""evaluation function"""
... | stack_v2_sparse_classes_36k_train_011587 | 39,055 | permissive | [
{
"docstring": "Parameters ---------- pows : array_like A list of non-negative integer exponents.",
"name": "__init__",
"signature": "def __init__(self, pows)"
},
{
"docstring": "evaluation function",
"name": "_monomial",
"signature": "def _monomial(self, X, deriv=0, out=None, var=None)"... | 2 | stack_v2_sparse_classes_30k_train_019339 | Implement the Python class `Monomial` described below.
Class description:
The monominal in multiple variables
Method signatures and docstrings:
- def __init__(self, pows): Parameters ---------- pows : array_like A list of non-negative integer exponents.
- def _monomial(self, X, deriv=0, out=None, var=None): evaluatio... | Implement the Python class `Monomial` described below.
Class description:
The monominal in multiple variables
Method signatures and docstrings:
- def __init__(self, pows): Parameters ---------- pows : array_like A list of non-negative integer exponents.
- def _monomial(self, X, deriv=0, out=None, var=None): evaluatio... | c6341a58331deef3728cc43c627c556139deb673 | <|skeleton|>
class Monomial:
"""The monominal in multiple variables"""
def __init__(self, pows):
"""Parameters ---------- pows : array_like A list of non-negative integer exponents."""
<|body_0|>
def _monomial(self, X, deriv=0, out=None, var=None):
"""evaluation function"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Monomial:
"""The monominal in multiple variables"""
def __init__(self, pows):
"""Parameters ---------- pows : array_like A list of non-negative integer exponents."""
pows = np.array(pows)
nx = len(pows)
maxpow = np.max(pows)
if np.any(pows < 0):
raise V... | the_stack_v2_python_sparse | nitrogen/special.py | bchangala/nitrogen | train | 11 |
009f894c80f4e38fa9a68179511d9c76c36abee2 | [
"if self.nb_rects == 0 or self.nb_steps >= self.max_iter or self.stuck:\n return False\nreturn True",
"row = random.randint(0, self.nb_rows - 1)\ncolumn = random.randint(0, self.nb_columns - 1)\nfor colour in self.grid[row]:\n if self.grid[row][colour] & 2 ** column:\n current_colour = colour\n ... | <|body_start_0|>
if self.nb_rects == 0 or self.nb_steps >= self.max_iter or self.stuck:
return False
return True
<|end_body_0|>
<|body_start_1|>
row = random.randint(0, self.nb_rows - 1)
column = random.randint(0, self.nb_columns - 1)
for colour in self.grid[row]:
... | Solves a given grid by picking a point at random and attempting to change its colour; if it reduces the number of problematic point, we keep the solution. | RandomDotGreedySolver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomDotGreedySolver:
"""Solves a given grid by picking a point at random and attempting to change its colour; if it reduces the number of problematic point, we keep the solution."""
def not_done(self):
"""simple method to determine if the solver must terminate"""
<|body_0|>... | stack_v2_sparse_classes_36k_train_011588 | 12,324 | no_license | [
{
"docstring": "simple method to determine if the solver must terminate",
"name": "not_done",
"signature": "def not_done(self)"
},
{
"docstring": "pick a point (row, column) at random and change its colour",
"name": "pick_new_configuration",
"signature": "def pick_new_configuration(self)... | 4 | null | Implement the Python class `RandomDotGreedySolver` described below.
Class description:
Solves a given grid by picking a point at random and attempting to change its colour; if it reduces the number of problematic point, we keep the solution.
Method signatures and docstrings:
- def not_done(self): simple method to det... | Implement the Python class `RandomDotGreedySolver` described below.
Class description:
Solves a given grid by picking a point at random and attempting to change its colour; if it reduces the number of problematic point, we keep the solution.
Method signatures and docstrings:
- def not_done(self): simple method to det... | dd721e096f8445aee48e69c3a3ebf6501aecc95b | <|skeleton|>
class RandomDotGreedySolver:
"""Solves a given grid by picking a point at random and attempting to change its colour; if it reduces the number of problematic point, we keep the solution."""
def not_done(self):
"""simple method to determine if the solver must terminate"""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomDotGreedySolver:
"""Solves a given grid by picking a point at random and attempting to change its colour; if it reduces the number of problematic point, we keep the solution."""
def not_done(self):
"""simple method to determine if the solver must terminate"""
if self.nb_rects == 0 o... | the_stack_v2_python_sparse | grid_challenge/solver.py | aroberge/py-fun | train | 0 |
2ed94ed0ddc4b9de01a24133294e87d322b6ecb3 | [
"self.key = key\nself.value = value\nself.required = required\nself.allowed_types = allowed_types\nself.allowed_values = allowed_values\nself.doc = doc",
"if self.required and self.value is None:\n raise RuntimeError('Option %s is required' % self.key)\nreturn self.value",
"if value is None and (not self.req... | <|body_start_0|>
self.key = key
self.value = value
self.required = required
self.allowed_types = allowed_types
self.allowed_values = allowed_values
self.doc = doc
<|end_body_0|>
<|body_start_1|>
if self.required and self.value is None:
raise RuntimeEr... | Class Option represents a key, value Option, with possible restrictions on type and value, and with documentation. | Option | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Option:
"""Class Option represents a key, value Option, with possible restrictions on type and value, and with documentation."""
def __init__(self, key=None, value=None, required=False, allowed_types=None, allowed_values=None, doc=''):
"""Option constructor: Params/Members: key - the... | stack_v2_sparse_classes_36k_train_011589 | 8,987 | permissive | [
{
"docstring": "Option constructor: Params/Members: key - the string value of the key of the option. value - the value of the option. required - True if the user is required to specify the option, False if the default value is acceptable. If required is True, an error will be raised when get_value is called if ... | 4 | stack_v2_sparse_classes_30k_train_008433 | Implement the Python class `Option` described below.
Class description:
Class Option represents a key, value Option, with possible restrictions on type and value, and with documentation.
Method signatures and docstrings:
- def __init__(self, key=None, value=None, required=False, allowed_types=None, allowed_values=Non... | Implement the Python class `Option` described below.
Class description:
Class Option represents a key, value Option, with possible restrictions on type and value, and with documentation.
Method signatures and docstrings:
- def __init__(self, key=None, value=None, required=False, allowed_types=None, allowed_values=Non... | 3b920bb11953f49673d3a2e87ee474b6315a0b4c | <|skeleton|>
class Option:
"""Class Option represents a key, value Option, with possible restrictions on type and value, and with documentation."""
def __init__(self, key=None, value=None, required=False, allowed_types=None, allowed_values=None, doc=''):
"""Option constructor: Params/Members: key - the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Option:
"""Class Option represents a key, value Option, with possible restrictions on type and value, and with documentation."""
def __init__(self, key=None, value=None, required=False, allowed_types=None, allowed_values=None, doc=''):
"""Option constructor: Params/Members: key - the string value... | the_stack_v2_python_sparse | pyGSM/utilities/options.py | ZimmermanGroup/pyGSM | train | 45 |
24081bea73b4c503c2ea7969c412baef7baf5858 | [
"self.mask = mask\nself.n_inputs = n_inputs\nself.s_hiddens = s_hiddens\nself.s_act = s_act\nself.t_hiddens = t_hiddens\nself.t_act = t_act\nmx = mask * x\nself.s_net = nn.FeedforwardNet(n_inputs, mx)\nfor h in s_hiddens:\n self.s_net.addLayer(h, s_act)\nself.s_net.addLayer(n_inputs, 'linear')\nself.t_net = nn.F... | <|body_start_0|>
self.mask = mask
self.n_inputs = n_inputs
self.s_hiddens = s_hiddens
self.s_act = s_act
self.t_hiddens = t_hiddens
self.t_act = t_act
mx = mask * x
self.s_net = nn.FeedforwardNet(n_inputs, mx)
for h in s_hiddens:
self.s... | Coupling layer for Real NVP. | CouplingLayer | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CouplingLayer:
"""Coupling layer for Real NVP."""
def __init__(self, x, mask, n_inputs, s_hiddens, s_act, t_hiddens, t_act):
"""Constructor of the backward computation graph. :param x: theano array, the input :param mask: theano array, a mask indicating which inputs are unchanged :pa... | stack_v2_sparse_classes_36k_train_011590 | 15,147 | permissive | [
{
"docstring": "Constructor of the backward computation graph. :param x: theano array, the input :param mask: theano array, a mask indicating which inputs are unchanged :param n_inputs: int, number of inputs :param s_hiddens: list of hidden widths for the scale net :param s_act: string, activation function for ... | 2 | stack_v2_sparse_classes_30k_train_015474 | Implement the Python class `CouplingLayer` described below.
Class description:
Coupling layer for Real NVP.
Method signatures and docstrings:
- def __init__(self, x, mask, n_inputs, s_hiddens, s_act, t_hiddens, t_act): Constructor of the backward computation graph. :param x: theano array, the input :param mask: thean... | Implement the Python class `CouplingLayer` described below.
Class description:
Coupling layer for Real NVP.
Method signatures and docstrings:
- def __init__(self, x, mask, n_inputs, s_hiddens, s_act, t_hiddens, t_act): Constructor of the backward computation graph. :param x: theano array, the input :param mask: thean... | d5fa619db637d19f0c3018aeb1431f657dd533bf | <|skeleton|>
class CouplingLayer:
"""Coupling layer for Real NVP."""
def __init__(self, x, mask, n_inputs, s_hiddens, s_act, t_hiddens, t_act):
"""Constructor of the backward computation graph. :param x: theano array, the input :param mask: theano array, a mask indicating which inputs are unchanged :pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CouplingLayer:
"""Coupling layer for Real NVP."""
def __init__(self, x, mask, n_inputs, s_hiddens, s_act, t_hiddens, t_act):
"""Constructor of the backward computation graph. :param x: theano array, the input :param mask: theano array, a mask indicating which inputs are unchanged :param n_inputs:... | the_stack_v2_python_sparse | ml/models/nvps.py | gpapamak/maf | train | 199 |
01aad50b5e7ac76aa13671e1e6209ad65cdcae1f | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn WindowsFirewallNetworkProfile()",
"from .state_management_setting import StateManagementSetting\nfrom .state_management_setting import StateManagementSetting\nfields: Dict[str, Callable[[Any], None]] = {'authorizedApplicationRulesFromG... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return WindowsFirewallNetworkProfile()
<|end_body_0|>
<|body_start_1|>
from .state_management_setting import StateManagementSetting
from .state_management_setting import StateManagementSetting
... | Windows Firewall Profile Policies. | WindowsFirewallNetworkProfile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowsFirewallNetworkProfile:
"""Windows Firewall Profile Policies."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsFirewallNetworkProfile:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The pa... | stack_v2_sparse_classes_36k_train_011591 | 9,152 | 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: WindowsFirewallNetworkProfile",
"name": "create_from_discriminator_value",
"signature": "def create_from_dis... | 3 | stack_v2_sparse_classes_30k_train_010860 | Implement the Python class `WindowsFirewallNetworkProfile` described below.
Class description:
Windows Firewall Profile Policies.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsFirewallNetworkProfile: Creates a new instance of the appropriate cl... | Implement the Python class `WindowsFirewallNetworkProfile` described below.
Class description:
Windows Firewall Profile Policies.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsFirewallNetworkProfile: Creates a new instance of the appropriate cl... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class WindowsFirewallNetworkProfile:
"""Windows Firewall Profile Policies."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsFirewallNetworkProfile:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WindowsFirewallNetworkProfile:
"""Windows Firewall Profile Policies."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsFirewallNetworkProfile:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to u... | the_stack_v2_python_sparse | msgraph/generated/models/windows_firewall_network_profile.py | microsoftgraph/msgraph-sdk-python | train | 135 |
99a87cf4dd8dec1c60589536347e0d301d593081 | [
"super().__init__()\nif not isinstance(data, list):\n msg = 'Invalid DOE case data, expected a list but got a {}.'\n raise RuntimeError(msg.format(data.__class__.__name__))\nself._data = data",
"for case in self._data:\n if not isinstance(case, list):\n msg = 'Invalid DOE case found, expecting a l... | <|body_start_0|>
super().__init__()
if not isinstance(data, list):
msg = 'Invalid DOE case data, expected a list but got a {}.'
raise RuntimeError(msg.format(data.__class__.__name__))
self._data = data
<|end_body_0|>
<|body_start_1|>
for case in self._data:
... | DOE case generator that reads cases from a provided list of DOE cases. This DOE case generator will accept an existing data set in the form of a list of DOE cases, each of which consists of a collection of name/value pairs specifying values for design variables. Attributes ---------- _data : list List of collections of... | ListGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListGenerator:
"""DOE case generator that reads cases from a provided list of DOE cases. This DOE case generator will accept an existing data set in the form of a list of DOE cases, each of which consists of a collection of name/value pairs specifying values for design variables. Attributes -----... | stack_v2_sparse_classes_36k_train_011592 | 21,019 | no_license | [
{
"docstring": "Initialize the ListGenerator. Parameters ---------- data : list list of collections of name, value pairs for the design variables",
"name": "__init__",
"signature": "def __init__(self, data=[])"
},
{
"docstring": "Generate case. Parameters ---------- design_vars : OrderedDict Dic... | 2 | stack_v2_sparse_classes_30k_train_002730 | Implement the Python class `ListGenerator` described below.
Class description:
DOE case generator that reads cases from a provided list of DOE cases. This DOE case generator will accept an existing data set in the form of a list of DOE cases, each of which consists of a collection of name/value pairs specifying values... | Implement the Python class `ListGenerator` described below.
Class description:
DOE case generator that reads cases from a provided list of DOE cases. This DOE case generator will accept an existing data set in the form of a list of DOE cases, each of which consists of a collection of name/value pairs specifying values... | d9e89fe017f1131d554599c248247f73bb9b534d | <|skeleton|>
class ListGenerator:
"""DOE case generator that reads cases from a provided list of DOE cases. This DOE case generator will accept an existing data set in the form of a list of DOE cases, each of which consists of a collection of name/value pairs specifying values for design variables. Attributes -----... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListGenerator:
"""DOE case generator that reads cases from a provided list of DOE cases. This DOE case generator will accept an existing data set in the form of a list of DOE cases, each of which consists of a collection of name/value pairs specifying values for design variables. Attributes ---------- _data :... | the_stack_v2_python_sparse | venv/Lib/site-packages/openmdao/drivers/doe_generators.py | ManojDjs/Heart-rate-estimation | train | 1 |
af84d68340d8b308a239fd36ae47c88c5128bce9 | [
"json_obj = json.loads(json_str)\nif 'KeyPhrases' in json_obj:\n key_phrases = set((' '.join(lib.KeyPhrase(x).words).lower() for x in json_obj['KeyPhrases']))\n assert len(key_phrases) <= 3\nelse:\n key_phrases = None\nreturn cls(url=json_obj['url'], words=json_obj['text'].split(' '), key_phrases=key_phras... | <|body_start_0|>
json_obj = json.loads(json_str)
if 'KeyPhrases' in json_obj:
key_phrases = set((' '.join(lib.KeyPhrase(x).words).lower() for x in json_obj['KeyPhrases']))
assert len(key_phrases) <= 3
else:
key_phrases = None
return cls(url=json_obj['u... | A text-only representation of an OpenKP example for eval/inference. | OpenKpTextExample | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenKpTextExample:
"""A text-only representation of an OpenKP example for eval/inference."""
def from_json(cls, json_str: Text) -> 'OpenKpTextExample':
"""Constructs a `OpenKpTextExample` from a json string."""
<|body_0|>
def to_json_string(self) -> Text:
"""Seri... | stack_v2_sparse_classes_36k_train_011593 | 7,978 | permissive | [
{
"docstring": "Constructs a `OpenKpTextExample` from a json string.",
"name": "from_json",
"signature": "def from_json(cls, json_str: Text) -> 'OpenKpTextExample'"
},
{
"docstring": "Serializes this instance to a JSON string.",
"name": "to_json_string",
"signature": "def to_json_string(... | 5 | stack_v2_sparse_classes_30k_train_009911 | Implement the Python class `OpenKpTextExample` described below.
Class description:
A text-only representation of an OpenKP example for eval/inference.
Method signatures and docstrings:
- def from_json(cls, json_str: Text) -> 'OpenKpTextExample': Constructs a `OpenKpTextExample` from a json string.
- def to_json_strin... | Implement the Python class `OpenKpTextExample` described below.
Class description:
A text-only representation of an OpenKP example for eval/inference.
Method signatures and docstrings:
- def from_json(cls, json_str: Text) -> 'OpenKpTextExample': Constructs a `OpenKpTextExample` from a json string.
- def to_json_strin... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class OpenKpTextExample:
"""A text-only representation of an OpenKP example for eval/inference."""
def from_json(cls, json_str: Text) -> 'OpenKpTextExample':
"""Constructs a `OpenKpTextExample` from a json string."""
<|body_0|>
def to_json_string(self) -> Text:
"""Seri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenKpTextExample:
"""A text-only representation of an OpenKP example for eval/inference."""
def from_json(cls, json_str: Text) -> 'OpenKpTextExample':
"""Constructs a `OpenKpTextExample` from a json string."""
json_obj = json.loads(json_str)
if 'KeyPhrases' in json_obj:
... | the_stack_v2_python_sparse | etcmodel/models/openkp/eval_utils.py | Jimmy-INL/google-research | train | 1 |
2b88076fae52ade5de17e2de5d7a3fd09a1773a7 | [
"if rowIndex < 0:\n return []\nbuild = [0 for i in range(rowIndex + 1)]\nbuild[0] = 1\nfor row in range(1, rowIndex + 1):\n pre = build[0]\n for i in range(1, row + 1):\n temp = build[i]\n build[i] += pre\n pre = temp\n build[row] = 1\nreturn build",
"res = [1] * (rowIndex + 1)\nf... | <|body_start_0|>
if rowIndex < 0:
return []
build = [0 for i in range(rowIndex + 1)]
build[0] = 1
for row in range(1, rowIndex + 1):
pre = build[0]
for i in range(1, row + 1):
temp = build[i]
build[i] += pre
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_0|>
def getRow2(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if rowIndex < 0:
return []... | stack_v2_sparse_classes_36k_train_011594 | 1,538 | no_license | [
{
"docstring": ":type rowIndex: int :rtype: List[int]",
"name": "getRow",
"signature": "def getRow(self, rowIndex)"
},
{
"docstring": ":type rowIndex: int :rtype: List[int]",
"name": "getRow2",
"signature": "def getRow2(self, rowIndex)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getRow(self, rowIndex): :type rowIndex: int :rtype: List[int]
- def getRow2(self, rowIndex): :type rowIndex: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getRow(self, rowIndex): :type rowIndex: int :rtype: List[int]
- def getRow2(self, rowIndex): :type rowIndex: int :rtype: List[int]
<|skeleton|>
class Solution:
def getR... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_0|>
def getRow2(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
if rowIndex < 0:
return []
build = [0 for i in range(rowIndex + 1)]
build[0] = 1
for row in range(1, rowIndex + 1):
pre = build[0]
for i in range(1, row... | the_stack_v2_python_sparse | code119PascalsTriangleII.py | cybelewang/leetcode-python | train | 0 | |
c27faffcc5f7b4b2bbc782246fb65ffd51045eb8 | [
"if isinstance(shape, dict):\n self._data = {k: ShmBufferContainer(dtype, v) for k, v in shape.items()}\nelif isinstance(shape, (tuple, list)):\n self._data = ShmBuffer(dtype, shape)\nelse:\n raise RuntimeError('not support shape: {}'.format(shape))\nself._shape = shape",
"if isinstance(self._shape, dict... | <|body_start_0|>
if isinstance(shape, dict):
self._data = {k: ShmBufferContainer(dtype, v) for k, v in shape.items()}
elif isinstance(shape, (tuple, list)):
self._data = ShmBuffer(dtype, shape)
else:
raise RuntimeError('not support shape: {}'.format(shape))
... | Overview: Support multiple shared memory buffers. Each key-value is name-buffer. | ShmBufferContainer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShmBufferContainer:
"""Overview: Support multiple shared memory buffers. Each key-value is name-buffer."""
def __init__(self, dtype: np.generic, shape: Union[Dict[Any, tuple], tuple]) -> None:
"""Overview: Initialize the buffer container. Arguments: - dtype (:obj:`np.generic`): dtype... | stack_v2_sparse_classes_36k_train_011595 | 32,547 | permissive | [
{
"docstring": "Overview: Initialize the buffer container. Arguments: - dtype (:obj:`np.generic`): dtype of the data to limit the size of the buffer. - shape (:obj:`Union[Dict[Any, tuple], tuple]`): If `Dict[Any, tuple]`, use a dict to manage multiple buffers; If `tuple`, use single buffer.",
"name": "__ini... | 3 | null | Implement the Python class `ShmBufferContainer` described below.
Class description:
Overview: Support multiple shared memory buffers. Each key-value is name-buffer.
Method signatures and docstrings:
- def __init__(self, dtype: np.generic, shape: Union[Dict[Any, tuple], tuple]) -> None: Overview: Initialize the buffer... | Implement the Python class `ShmBufferContainer` described below.
Class description:
Overview: Support multiple shared memory buffers. Each key-value is name-buffer.
Method signatures and docstrings:
- def __init__(self, dtype: np.generic, shape: Union[Dict[Any, tuple], tuple]) -> None: Overview: Initialize the buffer... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class ShmBufferContainer:
"""Overview: Support multiple shared memory buffers. Each key-value is name-buffer."""
def __init__(self, dtype: np.generic, shape: Union[Dict[Any, tuple], tuple]) -> None:
"""Overview: Initialize the buffer container. Arguments: - dtype (:obj:`np.generic`): dtype... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShmBufferContainer:
"""Overview: Support multiple shared memory buffers. Each key-value is name-buffer."""
def __init__(self, dtype: np.generic, shape: Union[Dict[Any, tuple], tuple]) -> None:
"""Overview: Initialize the buffer container. Arguments: - dtype (:obj:`np.generic`): dtype of the data ... | the_stack_v2_python_sparse | ding/envs/env_manager/subprocess_env_manager.py | shengxuesun/DI-engine | train | 1 |
7430fb3fc614b445f337d2cc41ea219d49ab2751 | [
"data = 281 * np.ones((3, 3, 3), dtype=np.float32)\nself.cube = set_up_variable_cube(data, realizations=[0, 1, 2])\nself.expected_data = self.cube.collapsed(['realization'], iris.analysis.MEAN).data",
"result = collapsed(self.cube, 'realization', iris.analysis.MEAN)\nself.assertTupleEqual(result.cell_methods, ())... | <|body_start_0|>
data = 281 * np.ones((3, 3, 3), dtype=np.float32)
self.cube = set_up_variable_cube(data, realizations=[0, 1, 2])
self.expected_data = self.cube.collapsed(['realization'], iris.analysis.MEAN).data
<|end_body_0|>
<|body_start_1|>
result = collapsed(self.cube, 'realization... | Test the collapsed utility. | Test_collapsed | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_collapsed:
"""Test the collapsed utility."""
def setUp(self):
"""Use temperature cube to test with."""
<|body_0|>
def test_single_method(self):
"""Test that a collapsed cube is returned with no cell method added"""
<|body_1|>
def test_two_method... | stack_v2_sparse_classes_36k_train_011596 | 3,649 | permissive | [
{
"docstring": "Use temperature cube to test with.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that a collapsed cube is returned with no cell method added",
"name": "test_single_method",
"signature": "def test_single_method(self)"
},
{
"docstring": "... | 4 | stack_v2_sparse_classes_30k_train_012613 | Implement the Python class `Test_collapsed` described below.
Class description:
Test the collapsed utility.
Method signatures and docstrings:
- def setUp(self): Use temperature cube to test with.
- def test_single_method(self): Test that a collapsed cube is returned with no cell method added
- def test_two_methods(se... | Implement the Python class `Test_collapsed` described below.
Class description:
Test the collapsed utility.
Method signatures and docstrings:
- def setUp(self): Use temperature cube to test with.
- def test_single_method(self): Test that a collapsed cube is returned with no cell method added
- def test_two_methods(se... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_collapsed:
"""Test the collapsed utility."""
def setUp(self):
"""Use temperature cube to test with."""
<|body_0|>
def test_single_method(self):
"""Test that a collapsed cube is returned with no cell method added"""
<|body_1|>
def test_two_method... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_collapsed:
"""Test the collapsed utility."""
def setUp(self):
"""Use temperature cube to test with."""
data = 281 * np.ones((3, 3, 3), dtype=np.float32)
self.cube = set_up_variable_cube(data, realizations=[0, 1, 2])
self.expected_data = self.cube.collapsed(['realizati... | the_stack_v2_python_sparse | improver_tests/utilities/cube_manipulation/test_collapsed.py | metoppv/improver | train | 101 |
27af8533aaac29ce768f39ae4b6bb4e3fb377d8c | [
"legalMoves = gameState.getLegalActions()\nscores = [self.evaluationFunction(gameState, action) for action in legalMoves]\nbestScore = max(scores)\nbestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\nchosenIndex = random.choice(bestIndices)\n'Add more of your code here if you want t... | <|body_start_0|>
legalMoves = gameState.getLegalActions()
scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
chosenIndex = random.choice(bestInd... | A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. | ReflexAgent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReflexAgent:
"""A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers."""
def getAction(sel... | stack_v2_sparse_classes_36k_train_011597 | 12,697 | no_license | [
{
"docstring": "You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop}",
"... | 2 | stack_v2_sparse_classes_30k_train_020757 | Implement the Python class `ReflexAgent` described below.
Class description:
A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our me... | Implement the Python class `ReflexAgent` described below.
Class description:
A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our me... | 698d39c4677d5874dec1002d5315bd46a609a833 | <|skeleton|>
class ReflexAgent:
"""A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers."""
def getAction(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReflexAgent:
"""A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers."""
def getAction(self, gameState)... | the_stack_v2_python_sparse | cs188.1x-artificial-intelligence/week4-project2/multiagent/multiAgents.py | alejandroclaro/courses | train | 1 |
f0fd07a7f77359ef4b7d12eeac927eb6df6e2d35 | [
"simplified = u'来自Bandai Namco Games TW/HK 官方FACEBOOK情报,PS3/PSV平台动漫改编作品《刀剑神域:失落之歌》繁体中文版正式公开!预定于2015年发售,并一同公开了繁体中文版宣传片,下面来欣赏了解一下。'\ntraditional = u'來自Bandai Namco Games TW/HK 官方FACEBOOK情報,PS3/PSV平臺動漫改編作品《刀劍神域:失落之歌》繁體中文版正式公開!預定於2015年發售,並一同公開了繁體中文版宣傳片,下面來欣賞了解一下。'\nsimp_is_simp = zhi.is_simplified(simplified)\nself.ass... | <|body_start_0|>
simplified = u'来自Bandai Namco Games TW/HK 官方FACEBOOK情报,PS3/PSV平台动漫改编作品《刀剑神域:失落之歌》繁体中文版正式公开!预定于2015年发售,并一同公开了繁体中文版宣传片,下面来欣赏了解一下。'
traditional = u'來自Bandai Namco Games TW/HK 官方FACEBOOK情報,PS3/PSV平臺動漫改編作品《刀劍神域:失落之歌》繁體中文版正式公開!預定於2015年發售,並一同公開了繁體中文版宣傳片,下面來欣賞了解一下。'
simp_is_simp = zhi.i... | ZhiTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZhiTest:
def test_translate(self):
"""Test simplified to tradiational translation"""
<|body_0|>
def test_strip(self):
"""Test replacement of unwanted characters"""
<|body_1|>
def test_unicode_sub(self):
"""Test unicode (specialized) semantic vari... | stack_v2_sparse_classes_36k_train_011598 | 2,438 | permissive | [
{
"docstring": "Test simplified to tradiational translation",
"name": "test_translate",
"signature": "def test_translate(self)"
},
{
"docstring": "Test replacement of unwanted characters",
"name": "test_strip",
"signature": "def test_strip(self)"
},
{
"docstring": "Test unicode (... | 3 | stack_v2_sparse_classes_30k_train_019110 | Implement the Python class `ZhiTest` described below.
Class description:
Implement the ZhiTest class.
Method signatures and docstrings:
- def test_translate(self): Test simplified to tradiational translation
- def test_strip(self): Test replacement of unwanted characters
- def test_unicode_sub(self): Test unicode (sp... | Implement the Python class `ZhiTest` described below.
Class description:
Implement the ZhiTest class.
Method signatures and docstrings:
- def test_translate(self): Test simplified to tradiational translation
- def test_strip(self): Test replacement of unwanted characters
- def test_unicode_sub(self): Test unicode (sp... | 48333360d71a49fee237e078892b57a658b1881b | <|skeleton|>
class ZhiTest:
def test_translate(self):
"""Test simplified to tradiational translation"""
<|body_0|>
def test_strip(self):
"""Test replacement of unwanted characters"""
<|body_1|>
def test_unicode_sub(self):
"""Test unicode (specialized) semantic vari... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZhiTest:
def test_translate(self):
"""Test simplified to tradiational translation"""
simplified = u'来自Bandai Namco Games TW/HK 官方FACEBOOK情报,PS3/PSV平台动漫改编作品《刀剑神域:失落之歌》繁体中文版正式公开!预定于2015年发售,并一同公开了繁体中文版宣传片,下面来欣赏了解一下。'
traditional = u'來自Bandai Namco Games TW/HK 官方FACEBOOK情報,PS3/PSV平臺動漫改編作品《... | the_stack_v2_python_sparse | preprocessing/language_standardizer/tests.py | gnarph/DIRT | train | 1 | |
d7bd582f19fca523ea8fb6c125588eea41f29403 | [
"responder = HttpResponder(handler)\nsock.settimeout(None)\nsock.setblocking(0)\nrequest_msg_reader = None\nforce_close = True\nlogging.debug('Connection from %s:%s', client_addr[0], client_addr[1])\ntry:\n try:\n if server.using_ssl:\n sock.set_accept_state()\n try:\n ... | <|body_start_0|>
responder = HttpResponder(handler)
sock.settimeout(None)
sock.setblocking(0)
request_msg_reader = None
force_close = True
logging.debug('Connection from %s:%s', client_addr[0], client_addr[1])
try:
try:
if server.using_... | Implements server side of HTTP. This class implements the server side of HTTP. It's based on code of Python's BaseHTTPServer, from both version 2.4 and 3k. It does not support non-ASCII character encodings. Keep-alive connections are not supported. | HttpServerRequestExecutor | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpServerRequestExecutor:
"""Implements server side of HTTP. This class implements the server side of HTTP. It's based on code of Python's BaseHTTPServer, from both version 2.4 and 3k. It does not support non-ASCII character encodings. Keep-alive connections are not supported."""
def __init... | stack_v2_sparse_classes_36k_train_011599 | 20,673 | permissive | [
{
"docstring": "Initializes this class.",
"name": "__init__",
"signature": "def __init__(self, server, handler, sock, client_addr)"
},
{
"docstring": "Reads a request sent by client.",
"name": "_ReadRequest",
"signature": "def _ReadRequest(sock, timeout)"
},
{
"docstring": "Sends... | 3 | null | Implement the Python class `HttpServerRequestExecutor` described below.
Class description:
Implements server side of HTTP. This class implements the server side of HTTP. It's based on code of Python's BaseHTTPServer, from both version 2.4 and 3k. It does not support non-ASCII character encodings. Keep-alive connection... | Implement the Python class `HttpServerRequestExecutor` described below.
Class description:
Implements server side of HTTP. This class implements the server side of HTTP. It's based on code of Python's BaseHTTPServer, from both version 2.4 and 3k. It does not support non-ASCII character encodings. Keep-alive connection... | 456ea285a7583183c2c8e5bcffe9006ec8a9d658 | <|skeleton|>
class HttpServerRequestExecutor:
"""Implements server side of HTTP. This class implements the server side of HTTP. It's based on code of Python's BaseHTTPServer, from both version 2.4 and 3k. It does not support non-ASCII character encodings. Keep-alive connections are not supported."""
def __init... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpServerRequestExecutor:
"""Implements server side of HTTP. This class implements the server side of HTTP. It's based on code of Python's BaseHTTPServer, from both version 2.4 and 3k. It does not support non-ASCII character encodings. Keep-alive connections are not supported."""
def __init__(self, serv... | the_stack_v2_python_sparse | lib/http/server.py | ganeti/ganeti | train | 465 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.