id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
140,848 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_selectlist.py
|
pykechain.models.property_selectlist.MultiSelectListProperty
|
class MultiSelectListProperty(_SelectListProperty):
"""A virtual object representing a KE-chain multi-select list property."""
def _check_new_value(self, value: Iterable[Any]):
if not isinstance(value, (list, tuple)):
raise IllegalArgumentError(
f'The new values must be provided as a list or tuple, "{value}" is not.'
)
if not all(v in self.options for v in value):
raise IllegalArgumentError(
'The new values "{}" of the Property should be in the list of options:\n{}'.format(
value, self.options
)
)
|
class MultiSelectListProperty(_SelectListProperty):
'''A virtual object representing a KE-chain multi-select list property.'''
def _check_new_value(self, value: Iterable[Any]):
pass
| 2 | 1 | 12 | 1 | 11 | 0 | 3 | 0.08 | 1 | 4 | 1 | 1 | 1 | 0 | 1 | 48 | 15 | 2 | 12 | 2 | 10 | 1 | 6 | 2 | 4 | 3 | 4 | 1 | 3 |
140,849 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_selectlist.py
|
pykechain.models.property_selectlist.SelectListProperty
|
class SelectListProperty(_SelectListProperty):
"""A virtual object representing a KE-chain single-select list property."""
def _check_new_value(self, value: Any):
if value not in self.options:
raise IllegalArgumentError(
'The new value "{}" of the Property should be in the list of options:\n{}'.format(
value, self.options
)
)
|
class SelectListProperty(_SelectListProperty):
'''A virtual object representing a KE-chain single-select list property.'''
def _check_new_value(self, value: Any):
pass
| 2 | 1 | 7 | 0 | 7 | 0 | 2 | 0.13 | 1 | 2 | 1 | 1 | 1 | 0 | 1 | 48 | 10 | 1 | 8 | 2 | 6 | 1 | 4 | 2 | 2 | 2 | 4 | 1 | 2 |
140,850 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/representations/component.py
|
pykechain.models.representations.component.RepresentationsComponent
|
class RepresentationsComponent:
"""
Aggregate class to use representations on an object.
To add representations to a Pykechain class, create an instance of this class in its __init__() method.
.. versionadded:: 3.7
"""
def __init__(
self, parent_object, representation_options: Dict, update_method: Callable
):
"""
Extract the json with the representation options.
:param parent_object: Object to which this representation component is attached
:param representation_options: json with list of representations
:param update_method: method of the parent_object that is used to update the representations
"""
self._parent_object = parent_object
self._repr_options = representation_options
self._update_method: Callable = update_method
# Construct representation objects
self._representations: List["AnyRepresentation"] = []
representations_json = self._repr_options
for representation_json in representations_json:
self._representations.append(
BaseRepresentation.parse(
obj=self._parent_object, json=representation_json
)
)
def get_representations(self) -> List["AnyRepresentation"]:
"""
Get list of representation objects.
:return: list of Representations
:raises IllegalArgumentError if representations are set with incorrect options
"""
return self._representations
def set_representations(self, representations: List["AnyRepresentation"]) -> None:
"""Set the representations."""
self._validate_representations(representations)
# set the internal representation list
self._representations = list(set(representations))
# dump to _json options
self._dump_representations()
# update the options to KE-chain backend
self._update_method(self._repr_options)
def _validate_representations(self, representations: Any):
"""Check provided representation inputs."""
if not isinstance(representations, (tuple, list)):
raise IllegalArgumentError(
"Should be a list or tuple with Representation objects, got {}".format(
type(representations)
)
)
for r in representations:
if not isinstance(r, BaseRepresentation):
raise IllegalArgumentError(
f"Representation '{r}' should be a Representation object"
)
if not _valid_object_type(r, self._parent_object):
raise IllegalArgumentError(
f"Representation '{r}' can not be added to "
f"'{self._parent_object}' as the representation is not "
"allowed on that propertyType. Please check relation between allowed"
"representation and property type accordingly."
)
r.validate_json()
def _dump_representations(self):
"""Dump the representations as json inside the _repr_options dictionary."""
representations_json = []
for r in self._representations:
json_format = r.as_json()
validate(json_format, representation_jsonschema_stub)
representations_json.append(json_format)
self._repr_options = representations_json
|
class RepresentationsComponent:
'''
Aggregate class to use representations on an object.
To add representations to a Pykechain class, create an instance of this class in its __init__() method.
.. versionadded:: 3.7
'''
def __init__(
self, parent_object, representation_options: Dict, update_method: Callable
):
'''
Extract the json with the representation options.
:param parent_object: Object to which this representation component is attached
:param representation_options: json with list of representations
:param update_method: method of the parent_object that is used to update the representations
'''
pass
def get_representations(self) -> List["AnyRepresentation"]:
'''
Get list of representation objects.
:return: list of Representations
:raises IllegalArgumentError if representations are set with incorrect options
'''
pass
def set_representations(self, representations: List["AnyRepresentation"]) -> None:
'''Set the representations.'''
pass
def _validate_representations(self, representations: Any):
'''Check provided representation inputs.'''
pass
def _dump_representations(self):
'''Dump the representations as json inside the _repr_options dictionary.'''
pass
| 6 | 6 | 15 | 2 | 10 | 4 | 2 | 0.47 | 0 | 7 | 2 | 0 | 5 | 4 | 5 | 5 | 87 | 15 | 49 | 18 | 41 | 23 | 32 | 16 | 26 | 5 | 0 | 2 | 11 |
140,851 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/representations/representations.py
|
pykechain.models.representations.representations.Autofill
|
class Autofill(BaseRepresentation):
"""Representation for date(time) properties."""
rtype = PropertyRepresentation.AUTOFILL
_config_value_key = PropertyRepresentation.AUTOFILL
def validate_representation(self, value: bool) -> None:
"""
Validate whether the representation value can be set.
:param value: representation value to set.
:type value: bool
:return: None
"""
check_type(value, bool, "autofill")
|
class Autofill(BaseRepresentation):
'''Representation for date(time) properties.'''
def validate_representation(self, value: bool) -> None:
'''
Validate whether the representation value can be set.
:param value: representation value to set.
:type value: bool
:return: None
'''
pass
| 2 | 2 | 9 | 1 | 2 | 6 | 1 | 1.4 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 9 | 15 | 3 | 5 | 4 | 3 | 7 | 5 | 4 | 3 | 1 | 1 | 0 | 1 |
140,852 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/representations/representations.py
|
pykechain.models.representations.representations.ButtonRepresentation
|
class ButtonRepresentation(BaseRepresentation):
"""Representation for single-select list properties."""
rtype = PropertyRepresentation.BUTTON
_config_value_key = PropertyRepresentation.BUTTON
def validate_representation(self, value: SelectListRepresentations) -> None:
"""
Validate whether the representation value can be set.
:param value: representation value to set.
:type value: SelectListRepresentations
:return: None
"""
if value not in SelectListRepresentations.values():
raise IllegalArgumentError(
'{} value "{}" is not correct: Not a SelectListRepresentations option.'.format(
self.__class__.__name__, value
)
)
|
class ButtonRepresentation(BaseRepresentation):
'''Representation for single-select list properties.'''
def validate_representation(self, value: SelectListRepresentations) -> None:
'''
Validate whether the representation value can be set.
:param value: representation value to set.
:type value: SelectListRepresentations
:return: None
'''
pass
| 2 | 2 | 14 | 1 | 7 | 6 | 2 | 0.7 | 1 | 2 | 2 | 0 | 1 | 0 | 1 | 9 | 20 | 3 | 10 | 4 | 8 | 7 | 6 | 4 | 4 | 2 | 1 | 1 | 2 |
140,853 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/representations/representations.py
|
pykechain.models.representations.representations.CameraScannerInputRepresentation
|
class CameraScannerInputRepresentation(SimpleConfigValueKeyRepresentation):
"""Representation for text and number inputs to be able to use the camera as scanner."""
rtype = PropertyRepresentation.CAMERA_SCANNER_INPUT
_config_value_key = "camera_scanner"
|
class CameraScannerInputRepresentation(SimpleConfigValueKeyRepresentation):
'''Representation for text and number inputs to be able to use the camera as scanner.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.33 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 9 | 5 | 1 | 3 | 3 | 2 | 1 | 3 | 3 | 2 | 0 | 2 | 0 | 0 |
140,854 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/representations/representations.py
|
pykechain.models.representations.representations.CustomIconRepresentation
|
class CustomIconRepresentation(BaseRepresentation):
"""Representation for scope and activities to display a custom Font Awesome icon."""
rtype = "customIcon"
_config_value_key = "displayIcon"
_display_mode_key = "displayIconMode"
def __init__(self, *args, **kwargs):
"""
Create a custom icon representation.
Display mode of the icon will be `regular` by default.
"""
super().__init__(*args, **kwargs)
if self._display_mode_key not in self._config:
self._config[self._display_mode_key] = FontAwesomeMode.REGULAR
def validate_representation(self, value: str):
"""
Validate whether the representation value can be set.
:param value: representation value to set.
:type value: str
:return: None
"""
if not isinstance(value, str):
raise IllegalArgumentError(
'{} value "{}" is not correct: not a string'.format(
self.__class__.__name__, value
)
)
@property
def display_mode(self):
"""Get the the display mode of the custom icon representation."""
return self._config[self._display_mode_key]
@display_mode.setter
def display_mode(self, mode: FontAwesomeMode) -> None:
"""
Set the the display mode of the custom icon representation.
:param mode: FontAwesome display mode
:type mode: FontAwesomeMode
"""
if mode not in set(FontAwesomeMode.values()):
raise IllegalArgumentError(
'{} mode "{}" is not a FontAwesomeMode option.'.format(
self.__class__.__name__, mode
)
)
self._config[self._display_mode_key] = mode
self.value = self.value
|
class CustomIconRepresentation(BaseRepresentation):
'''Representation for scope and activities to display a custom Font Awesome icon.'''
def __init__(self, *args, **kwargs):
'''
Create a custom icon representation.
Display mode of the icon will be `regular` by default.
'''
pass
def validate_representation(self, value: str):
'''
Validate whether the representation value can be set.
:param value: representation value to set.
:type value: str
:return: None
'''
pass
@property
def display_mode(self):
'''Get the the display mode of the custom icon representation.'''
pass
@display_mode.setter
def display_mode(self):
'''
Set the the display mode of the custom icon representation.
:param mode: FontAwesome display mode
:type mode: FontAwesomeMode
'''
pass
| 7 | 5 | 11 | 1 | 6 | 4 | 2 | 0.64 | 1 | 5 | 2 | 0 | 4 | 1 | 4 | 12 | 54 | 9 | 28 | 11 | 21 | 18 | 18 | 9 | 13 | 2 | 1 | 1 | 7 |
140,855 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/representations/representations.py
|
pykechain.models.representations.representations.DecimalPlaces
|
class DecimalPlaces(BaseRepresentation):
"""Representation for floating-point value properties."""
rtype = PropertyRepresentation.DECIMAL_PLACES
_config_value_key = "amount"
def validate_representation(self, value: int) -> None:
"""
Validate whether the representation value can be set.
:param value: representation value to set.
:type value: int
:return: None
"""
if not isinstance(value, int):
raise IllegalArgumentError(
'{} value "{}" is not correct: not an integer'.format(
self.__class__.__name__, value
)
)
|
class DecimalPlaces(BaseRepresentation):
'''Representation for floating-point value properties.'''
def validate_representation(self, value: int) -> None:
'''
Validate whether the representation value can be set.
:param value: representation value to set.
:type value: int
:return: None
'''
pass
| 2 | 2 | 14 | 1 | 7 | 6 | 2 | 0.7 | 1 | 2 | 1 | 1 | 1 | 0 | 1 | 9 | 20 | 3 | 10 | 4 | 8 | 7 | 6 | 4 | 4 | 2 | 1 | 1 | 2 |
140,856 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_reference.py
|
pykechain.models.property_reference.UserReferencesProperty
|
class UserReferencesProperty(_ReferenceProperty):
"""A virtual object representing a KE-chain User References property.
.. versionadded: 3.9
"""
REFERENCED_CLASS = user.User
def _validate_values(self) -> List[str]:
"""
Check if the `_value` attribute has valid content.
:return list of UUIDs:
:rtype list
"""
if not self._value:
return []
object_ids = []
for value in self._value:
if isinstance(value, dict) and "pk" in value or "id" in value:
pk = str(value.get("pk", value.get("id")))
object_ids.append(pk)
elif isinstance(value, (int, str)):
object_ids.append(str(value))
else: # pragma: no cover
raise ValueError(
f'Value "{value}" must be a dict with field `pk` or a UUID.'
)
return object_ids
def _retrieve_objects(self, **kwargs) -> List[user.User]:
"""
Retrieve a list of Users.
:param kwargs: optional inputs
:return: list of User objects
"""
user_ids = self._validate_values()
users = []
if user_ids:
users = list()
for chunk in get_in_chunks(user_ids, PARTS_BATCH_LIMIT):
users.extend(list(self._client.users(id__in=",".join(chunk))))
return users
def value_ids(self) -> Optional[List[int]]:
"""
Retrieve the referenced object UUIDs only.
:return: list of UUIDs
:rtype list
"""
return [value.get("pk") for value in self._value] if self.has_value() else None
|
class UserReferencesProperty(_ReferenceProperty):
'''A virtual object representing a KE-chain User References property.
.. versionadded: 3.9
'''
def _validate_values(self) -> List[str]:
'''
Check if the `_value` attribute has valid content.
:return list of UUIDs:
:rtype list
'''
pass
def _retrieve_objects(self, **kwargs) -> List[user.User]:
'''
Retrieve a list of Users.
:param kwargs: optional inputs
:return: list of User objects
'''
pass
def value_ids(self) -> Optional[List[int]]:
'''
Retrieve the referenced object UUIDs only.
:return: list of UUIDs
:rtype list
'''
pass
| 4 | 4 | 15 | 2 | 8 | 5 | 3 | 0.7 | 1 | 6 | 1 | 0 | 3 | 0 | 3 | 12 | 56 | 11 | 27 | 11 | 23 | 19 | 23 | 11 | 19 | 5 | 2 | 2 | 10 |
140,857 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.ValidatorEffectTypes
|
class ValidatorEffectTypes(Enum):
"""The effects that can be attached to a validator.
.. versionadded:: 2.2
:cvar NONE_EFFECT: noneEffect
:cvar VISUALEFFECT: visualEffect
:cvar TEXT_EFFECT: textEffect
:cvar ERRORTEXT_EFFECT: errorTextEffect
:cvar HELPTEXT_EFFECT: helpTextEffect
"""
NONE_EFFECT = "noneEffect"
VISUALEFFECT = "visualEffect"
TEXT_EFFECT = "textEffect"
ERRORTEXT_EFFECT = "errorTextEffect"
HELPTEXT_EFFECT = "helpTextEffect"
|
class ValidatorEffectTypes(Enum):
'''The effects that can be attached to a validator.
.. versionadded:: 2.2
:cvar NONE_EFFECT: noneEffect
:cvar VISUALEFFECT: visualEffect
:cvar TEXT_EFFECT: textEffect
:cvar ERRORTEXT_EFFECT: errorTextEffect
:cvar HELPTEXT_EFFECT: helpTextEffect
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.33 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 17 | 3 | 6 | 6 | 5 | 8 | 6 | 6 | 5 | 0 | 1 | 0 | 0 |
140,858 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property2_selectlist.py
|
pykechain.models.property2_selectlist.SelectListProperty2
|
class SelectListProperty2(SelectListProperty, _DeprecationMixin):
"""A virtual object representing a KE-chain single-select list property."""
pass
|
class SelectListProperty2(SelectListProperty, _DeprecationMixin):
'''A virtual object representing a KE-chain single-select list property.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
140,859 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property2_multi_reference.py
|
pykechain.models.property2_multi_reference.MultiReferenceProperty2
|
class MultiReferenceProperty2(MultiReferenceProperty, _DeprecationMixin):
"""A virtual object representing a KE-chain multi-references property.
.. versionadded:: 1.14
"""
pass
|
class MultiReferenceProperty2(MultiReferenceProperty, _DeprecationMixin):
'''A virtual object representing a KE-chain multi-references property.
.. versionadded:: 1.14
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 40 | 7 | 2 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 6 | 0 | 0 |
140,860 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/base.py
|
pykechain.models.base.NameDescriptionTranslationMixin
|
class NameDescriptionTranslationMixin:
"""Mixin that includes translations of the name and description of an object."""
pass
|
class NameDescriptionTranslationMixin:
'''Mixin that includes translations of the name and description of an object.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 0 | 0 | 0 | 4 | 0 | 0 | 0 | 0 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 0 | 0 | 0 |
140,861 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/base.py
|
pykechain.models.base.TooManyArgumentsWarning
|
class TooManyArgumentsWarning(UserWarning):
"""Warn a developer that too many arguments are used in the method call."""
pass
|
class TooManyArgumentsWarning(UserWarning):
'''Warn a developer that too many arguments are used in the method call.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
140,862 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/context.py
|
pykechain.models.context.Context
|
class Context(
BaseInScope, CrudActionsMixin, TagsMixin, NameDescriptionTranslationMixin
):
"""
A virtual object representing a KE-chain Context.
.. versionadded:: 3.12
"""
url_detail_name = "context"
url_list_name = "contexts"
url_pk_name = "context_id"
def __init__(self, json, **kwargs):
"""Construct a service from provided json data."""
super().__init__(json, **kwargs)
self.ref: str = json.get("ref")
self.description: str = json.get("description", "")
self.context_type: ContextType = json.get("context_type")
self.options: dict = json.get("options", dict())
self.context_group: ContextGroup = json.get("context_group", "")
self._tags = json.get("tags")
# associated activities
self.activities: ObjectIDs = json.get("activities")
# associated forms
self.forms: ObjectIDs = json.get("form_collections")
# LocationContext
# these attributes are enabled when context_type == STATIC_LOCATION
self.feature_collection: dict = json.get("feature_collection", dict())
# TimeperiodContext
# these attributes are enabled when context_type == TIME_PERIOD
self.start_date: Optional[datetime] = parse_datetime(json.get("start_date"))
self.due_date: Optional[datetime] = parse_datetime(json.get("due_date"))
@classmethod
def list(cls, client: "Client", **kwargs) -> List["Context"]:
"""List Context objects."""
return super().list(client=client, **kwargs)
@classmethod
def get(cls, client: "Client", **kwargs) -> "Context":
"""Retrieve a single Context object."""
return super().get(client=client, **kwargs)
def edit(
self,
name: Optional[Union[str, Empty]] = empty,
description: Optional[Union[str, Empty]] = empty,
tags: Optional[List[Union[str, Empty]]] = empty,
context_group: Optional[Union[ContextGroup, Empty]] = empty,
scope: Optional[Union["Scope", ObjectID]] = empty,
options: Optional[dict] = empty,
activities: Optional[Union[List["Activity"], ObjectIDs]] = empty,
feature_collection: Optional[dict] = empty,
start_date: Optional[datetime] = empty,
due_date: Optional[datetime] = empty,
**kwargs,
) -> "Context":
"""
Edit the Context.
:param name: Name of the Context to be displayed to the end-user.
:param scope: Scope object or Scope Id where the Context is active on.
:param description: (optional) description of the Context
:param activities: (optional) associated list of Activity or activity object ID
:param tags: (optional) tags
:param context_group: (optional) a context context_group of the choices of `ContextGroup`
:param options: (optional) dictionary with options.
:param feature_collection: (optional) dict with a geojson feature collection to store for a STATIC_LOCATION
:param start_date: (optional) start datetime for a TIME_PERIOD context
:param due_date: (optional) start datetime for a TIME_PERIOD context
:return: a created Context Object
:return: The updated Context object
"""
from pykechain.models import Activity, Scope
update_dict = {
"name": check_text(name, "name"),
"description": check_text(description, "description"),
"scope": check_base(scope, Scope, "scope"),
"tags": check_list_of_text(tags, "tags"),
"context_group": check_enum(context_group, ContextGroup, "context_group"),
"activities": check_list_of_base(activities, Activity, "activities"),
"options": check_type(options, dict, "options"),
"feature_collection": check_type(
feature_collection, dict, "feature_collection"
),
"start_date": check_datetime(start_date, "start_date"),
"due_date": check_datetime(due_date, "due_date"),
}
if feature_collection is None:
update_dict["feature_collection"] = {}
if kwargs: # pragma: no cover
update_dict.update(kwargs)
update_dict = clean_empty_values(update_dict=update_dict)
url = self._client._build_url("context", context_id=self.id)
response = self._client._request("PUT", url, json=update_dict)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Context: {self}", response=response)
return self.refresh(json=response.json().get("results")[0])
def link_activities(
self, activities: Optional[List[Union["Activity", ObjectIDs]]] = empty, **kwargs
):
"""
Link a context to one or more activities.
:param activities: optional list of Activities or object Id's from activities.
:returns: updated context objects
"""
from pykechain.models import Activity
update_dict = {
"activities": check_list_of_base(activities, Activity, "activities"),
}
if kwargs: # pragma: no cover
update_dict.update(kwargs)
url = self._client._build_url("context_link_activities", context_id=self.id)
response = self._client._request("POST", url, json=update_dict)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Context: {self}", response=response)
return self.refresh(json=response.json().get("results")[0])
def unlink_activities(
self, activities: Optional[List[Union["Activity", ObjectIDs]]] = empty, **kwargs
):
"""
Unlink a context to one or more activities.
:param activities: optional list of Activities or object Id's from activities.
:returns: updated context objects
"""
from pykechain.models import Activity
update_dict = {
"activities": check_list_of_base(activities, Activity, "activities"),
}
if kwargs: # pragma: no cover
update_dict.update(kwargs)
url = self._client._build_url("context_unlink_activities", context_id=self.id)
response = self._client._request("POST", url, json=update_dict)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Context: {self}", response=response)
return self.refresh(json=response.json().get("results")[0])
def delete(self):
"""Delete the Context."""
return self._client.delete_context(self)
|
class Context(
BaseInScope, CrudActionsMixin, TagsMixin, NameDescriptionTranslationMixin
):
'''
A virtual object representing a KE-chain Context.
.. versionadded:: 3.12
'''
def __init__(self, json, **kwargs):
'''Construct a service from provided json data.'''
pass
@classmethod
def list(cls, client: "Client", **kwargs) -> List["Context"]:
'''List Context objects.'''
pass
@classmethod
def get(cls, client: "Client", **kwargs) -> "Context":
'''Retrieve a single Context object.'''
pass
def edit(
self,
name: Optional[Union[str, Empty]] = empty,
description: Optional[Union[str, Empty]] = empty,
tags: Optional[List[Union[str, Empty]]] = empty,
context_group: Optional[Union[ContextGroup, Empty]] = empty,
scope: Optional[Union["Scope", ObjectID]] = empty,
options: Optional[dict] = empty,
activities: Optional[Union[List["Activity"], ObjectIDs]] = empty,
feature_collection: Optional[dict] = empty,
start_date: Optional[datetime] = empty,
due_date: Optional[datetime] = empty,
**kwargs,
) -> "Context":
'''
Edit the Context.
:param name: Name of the Context to be displayed to the end-user.
:param scope: Scope object or Scope Id where the Context is active on.
:param description: (optional) description of the Context
:param activities: (optional) associated list of Activity or activity object ID
:param tags: (optional) tags
:param context_group: (optional) a context context_group of the choices of `ContextGroup`
:param options: (optional) dictionary with options.
:param feature_collection: (optional) dict with a geojson feature collection to store for a STATIC_LOCATION
:param start_date: (optional) start datetime for a TIME_PERIOD context
:param due_date: (optional) start datetime for a TIME_PERIOD context
:return: a created Context Object
:return: The updated Context object
'''
pass
def link_activities(
self, activities: Optional[List[Union["Activity", ObjectIDs]]] = empty, **kwargs
):
'''
Link a context to one or more activities.
:param activities: optional list of Activities or object Id's from activities.
:returns: updated context objects
'''
pass
def unlink_activities(
self, activities: Optional[List[Union["Activity", ObjectIDs]]] = empty, **kwargs
):
'''
Unlink a context to one or more activities.
:param activities: optional list of Activities or object Id's from activities.
:returns: updated context objects
'''
pass
def delete(self):
'''Delete the Context.'''
pass
| 10 | 8 | 21 | 3 | 12 | 6 | 2 | 0.48 | 4 | 8 | 4 | 0 | 5 | 11 | 7 | 23 | 166 | 33 | 94 | 55 | 62 | 45 | 56 | 34 | 45 | 4 | 2 | 1 | 14 |
140,863 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property2_selectlist.py
|
pykechain.models.property2_selectlist.MultiSelectListProperty2
|
class MultiSelectListProperty2(MultiSelectListProperty, _DeprecationMixin):
"""A virtual object representing a KE-chain multi-select list property."""
pass
|
class MultiSelectListProperty2(MultiSelectListProperty, _DeprecationMixin):
'''A virtual object representing a KE-chain multi-select list property.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
140,864 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/form.py
|
pykechain.models.form.Form
|
class Form(BaseInScope, CrudActionsMixin, TagsMixin, NameDescriptionTranslationMixin):
"""
A virtual object representing a KE-chain Form Collection.
.. versionadded:: v3.20
:ivar id: id of the form
:ivar name: name of the form
:ivar description: description of the form
:ivar ref: reference (slugified name) of the form
:ivar category: the category of the form (FormCategory.MODEL or FormCategory.INSTANCE)
:ivar active_status: current active Status of the form
:ivar form_model_root: the form model root Part
:ivar form_instance_root: the form instance root Part
:ivar model_id: the pk of the model of this form instance
:ivar status_forms: The StatusForms of this form
:ivar prefill_parts: The parts to prefill when a Form Model is isntantiated.
:ivar created_at: datetime in UTC timezone when the form was created
:ivar updated_at: datetime in UTC timezone when the form was last updated
:ivar derived_from_id: (optional) id where the objects is derived from.
"""
url_detail_name = "form"
url_list_name = "forms"
url_pk_name = "form_id"
def __init__(self, json, **kwargs):
"""Construct a service from provided json data."""
super().__init__(json, **kwargs)
self.description: str = json.get("description", "")
self.ref: str = json.get("ref", "")
self._workflow = json.get("workflow")
self.active_status: "Status" = json.get("active_status")
self.form_model_root: "Part" = json.get("form_model_root")
self.form_instance_root: "Part" = json.get("form_instance_root")
self.model_id: "Form" = json.get("model")
self._prefill_parts: dict = json.get("prefill_parts")
self.derived_from_id: Optional[ObjectID] = json.get("derived_from_id")
self.active: bool = json.get("active")
self.category: FormCategory = json.get("category")
self._status_forms: List[Dict] = json.get("status_forms", [])
self._status_assignees: List[Dict] = json.get(
"status_assignees_has_widgets", []
)
self.contexts = json.get("contexts", [])
self.context_groups = json.get("context_groups", [])
def __repr__(self): # pragma: no cover
return f"<pyke Form '{self.name}' '{self.category}' id {self.id[-8:]}>"
@classmethod
def create_model(
cls,
client: "Client",
name: str,
scope: Union[Scope, ObjectID],
workflow: Union["Workflow", ObjectID],
contexts: List[Union[Context, ObjectID]],
**kwargs: dict,
) -> "Form":
"""Create a new form model.
Needs scope, name, workflow.
:param client: The client connection to KE-chain API
:param name: Name of the new form model
:param scope: Scope or scope_id where to create the form model
:param workflow: Workflow or workflow_id of the workflow associated to the form model,
should be in scope.
:param contexts: A list of Context or context id's to link to the Form model.
:param kwargs: Additional kwargs such as contexts.
"""
from pykechain.models.workflow import Workflow
data = {
"name": check_text(name, "name"),
"scope": check_base(scope, Scope, "scope"),
"workflow": check_base(workflow, Workflow, "workflow"),
"contexts": check_list_of_base(contexts, Context, "contexts"),
}
kwargs.update(API_EXTRA_PARAMS[cls.url_list_name])
response = client._request(
"POST", client._build_url(cls.url_list_name), params=kwargs, json=data
)
if response.status_code != requests.codes.created: # pragma: no cover
raise APIError(f"Could not create {cls.__name__}", response=response)
return cls(json=response.json()["results"][0], client=client)
#
# Concepts underneath the Form
# StatusForms
@property
def status_forms(self):
"""Retrieve the Status Forms of this Form."""
return [StatusForm(s, client=self._client) for s in self._status_forms]
#
# @classmethod
# def list(cls, client: "Client", **kwargs) -> List["Form"]:
# """Retrieve a list of Form objects through the client."""
# return super().list(client=client, **kwargs)
#
# @classmethod
# def get(cls, client: "Client", **kwargs) -> "Form":
# """Retrieve a Form object through the client."""
# return super().get(client=client, **kwargs)
@property
def is_model(self) -> bool:
"""Form is a Form Model or Form Template."""
return self.category == FormCategory.MODEL
@property
def is_instance(self) -> bool:
"""Form is a Form Instance."""
return self.category == FormCategory.INSTANCE
@property
def is_active(self) -> bool:
"""Form is an active Form."""
return self.active is not None and self.active
#
# Form Model finders and searchers.
#
def instances(self, **kwargs) -> [List["Form"]]:
"""Retrieve the instances of this Form Model."""
if self.category == FormCategory.MODEL:
return self._client.forms(
model=self, category=FormCategory.INSTANCE, **kwargs
)
else:
raise FileNotFoundError(
f"Form '{self}' is not a model, hence it has no instances."
)
def instance(self, **kwargs) -> "Form":
"""Retrieve a single instance of a Form Model."""
return self._client._retrieve_singular(self.instances, **kwargs)
def edit(
self,
name: Optional[Union[str, Empty]] = empty,
description: Optional[Union[str, Empty]] = empty,
**kwargs,
) -> None:
"""Edit the details of a Form (model or instance).
Setting an input to None will clear out the value (exception being name).
:param name: optional name of the form to edit. Cannot be cleared.
:type name: basestring or None or Empty
:param description: (optional) description of the form. Can be cleared.
:type description: basestring or None or Empty
:param kwargs: (optional) additional kwargs that will be passed in the during the edit/update request
:return: None
:raises IllegalArgumentError: when the type or value of an argument provided is incorrect
:raises APIError: in case an Error occurs
"""
update_dict = {
"id": self.id,
"name": check_text(name, "name") or self.name,
"description": check_text(description, "description") or "",
}
if kwargs: # pragma: no cover
update_dict.update(**kwargs)
update_dict = clean_empty_values(update_dict=update_dict)
try:
response = self._client._request(
"PUT",
self._client._build_url("form", form_id=self.id),
params=API_EXTRA_PARAMS["form"],
json=update_dict,
)
except ForbiddenError:
raise ForbiddenError("A form model with instances created cannot be edited")
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Form {self}", response=response)
self.refresh(json=response.json().get("results")[0])
def delete(self) -> None:
"""Delete this Form.
:raises APIError: if delete was not successful.
"""
response = self._client._request(
"DELETE", self._client._build_url(self.url_detail_name, form_id=self.id)
)
if response.status_code != requests.codes.no_content: # pragma: no cover
raise APIError(f"Could not delete Form {self}", response=response)
def instantiate(self, name: Optional[str], **kwargs) -> "Form":
"""Create a new Form instance based on a model."""
if self.category != FormCategory.MODEL:
raise APIError("Form should be of category MODEL")
data_dict = {
"name": check_text(name, "name") or self.name,
"description": check_text(kwargs.get("description"), "description")
or self.description,
"contexts": check_list_of_base(kwargs.get("contexts"), Context, "contexts")
or [],
}
url = self._client._build_url("form_instantiate", form_id=self.id)
query_params = API_EXTRA_PARAMS["forms"]
response = self._client._request(
"POST", url, params=query_params, json=data_dict
)
if response.status_code != requests.codes.created:
raise APIError(
f"Could not instantiate this Form: {self}", response=response
)
instantiated_form = Form(response.json()["results"][0], client=self._client)
return instantiated_form
def clone(
self, name: Optional[str], target_scope: Optional[Scope] = None, **kwargs
) -> Optional["Form"]:
"""Clone a new Form model based on a model.
If target_scope is specified and different from the scope of the form, then use the
`clone_cross_scope` endpoint. Otherwise, use the basic `clone` endpoint.
"""
if self.category != FormCategory.MODEL:
raise APIError("Form should be of category MODEL")
data_dict = {
"name": check_text(name, "name") or f"{self.name}",
"contexts": check_list_of_base(kwargs.get("contexts"), Context, "contexts")
or [],
}
if "description" in kwargs:
data_dict.update(
{"description": check_text(kwargs.get("description"), "description")}
)
if not target_scope or target_scope.id == self.scope_id:
response = self._client._request(
"POST",
self._client._build_url("form_clone", form_id=self.id),
params=API_EXTRA_PARAMS["forms"],
json=data_dict,
)
else:
data_dict.update({"target_scope": check_base(target_scope, Scope, "scope")})
response = self._client._request(
"POST",
self._client._build_url("form_clone_cross_scope", form_id=self.id),
params=API_EXTRA_PARAMS["forms"],
json=data_dict,
)
if response.status_code != requests.codes.created:
raise APIError(f"Could not clone this Form: {self}", response=response)
return Form(response.json()["results"][0], client=self._client)
def activate(self):
"""Put the form to active.
Model Forms can be put to inactive. When the Form model is not active the form cannot be
instantiated. This methods sets the form to active.
"""
if not self.active:
url = self._client._build_url("form_activate", form_id=self.id)
response = self._client._request("PUT", url=url)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError("Could not activate the form", response=response)
# we need to do a full refresh here from the server as the
# API of form/<id>/activate does not return the full object as response.
self.refresh(
url=self._client._build_url("form", form_id=self.id),
extra_params=API_EXTRA_PARAMS.get(self.url_list_name),
)
def deactivate(self):
"""Put the form to inactive.
Model Forms can be put to inactive. When the Form model is not active the form cannot be
instantiated.
"""
if self.active:
url = self._client._build_url("form_deactivate", form_id=self.id)
response = self._client._request("PUT", url=url)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError("Could not activate the form", response=response)
# we need to do a full refresh here from the server as the
# API of form/<id>/deactivate does not return the full object as response.
self.refresh(
url=self._client._build_url("form", form_id=self.id),
extra_params=API_EXTRA_PARAMS.get(self.url_list_name),
)
def link_contexts(self, contexts: List[Union[Context, ObjectID]]):
"""
Link a list of Contexts to a Form.
:param contexts: a list of Context Objects or context_ids to link to the form.
:raises APIError: in case an Error occurs when linking
"""
data = {"contexts": check_list_of_base(contexts, Context)}
url = self._client._build_url("form_link_contexts", form_id=self.id)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request(
"POST", url=url, params=query_params, json=data
)
if response.status_code != requests.codes.ok:
raise APIError(
"Could not link the specific contexts to the form",
response=response,
)
self.refresh(json=response.json()["results"][0])
def unlink_contexts(self, contexts: List[Union[Context, ObjectID]]):
"""
Unlink a list of Contexts from a Form.
:param contexts: a list of Context Objects or context_ids to unlink from the form.
:raises APIError: in case an Error occurs when unlinking
"""
data = {"contexts": check_list_of_base(contexts, Context)}
url = self._client._build_url("form_unlink_contexts", form_id=self.id)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request(
"POST", url=url, params=query_params, json=data
)
if response.status_code != requests.codes.ok:
raise APIError(
"Could not unlink the specific contexts from the form",
response=response,
)
self.refresh(json=response.json()["results"][0])
def set_status_assignees(self, statuses: List[dict]):
"""
Set a list of assignees on each status of a Form.
:param statuses: a list of dicts, each one contains the status_id and the list of
assignees. Available fields per dict:
:param status: Status object
:param assignees: List of User objects
:raises APIError: in case an Error occurs when setting the status assignees
Example
-------
When the `Form` is known, one can easily access its status forms ids and build a
dictionary, as such:
>>> for status_form in form.status_forms:
>>> status_dict = {
>>> "status": status_form.status,
>>> "assignees": [user_1, user_2]
>>> }
>>> status_assignees_list.append(status_dict)
>>> self.form.set_status_assignees(statuses=status_assignees_list)
"""
from pykechain.models import User
check_list_of_dicts(
statuses,
"statuses",
[
"status",
"assignees",
],
)
for status in statuses:
status["status"] = check_base(status["status"], Status)
status["assignees"] = check_list_of_base(status["assignees"], User)
url = self._client._build_url("form_set_status_assignees", form_id=self.id)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request(
"POST", url=url, params=query_params, json=statuses
)
if response.status_code != requests.codes.ok:
raise APIError(
"Could not set the list of status assignees to the form",
response=response,
)
self.refresh(json=response.json()["results"][0])
def possible_transitions(self) -> List[Transition]:
"""Retrieve the possible transitions that may be applied on the Form.
It will return the Transitions from the associated workflow are can be applied
on the Form in the current status.
:returns: A list with possible Transitions that may be applied on the Form.
"""
workflow = self._client.workflow(id=self._workflow["id"])
return workflow.transitions
def apply_transition(self, transition: Transition):
"""Apply the transition to put the form in another state following a transition.
Apply transition is to put the Form in another state. Only transitions that
can apply to the form should have the 'from_status' to the current state. (or
it is a Global transition). If applied the Form will be set in the 'to_state' of
the Transition.
:param transition: a Transition object belonging to the workflow of the Form
:raises APIError: in case an Error occurs when applying the transition
Example
-------
When the `Form` and `Workflow` is known, one can easily apply a transition on it, as such:
>>> transition = workflow.transition("In progress")
>>> form.apply_transition(transition=transition)
"""
check_base(transition, Transition)
url = self._client._build_url(
"form_apply_transition", form_id=self.id, transition_id=transition.id
)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request(
"POST",
url=url,
params=query_params,
)
if response.status_code != requests.codes.ok:
raise APIError(
"Could not transition the form",
response=response,
)
self.refresh(json=response.json()["results"][0])
def has_part(self, part: Part) -> bool:
"""Return boolean if given Part is part of the Form tree.
Based on the Parts category, either the model or the instance tree is checked.
:param part: a Part object
:raises IllegalArgumentError: in case not a `Part` object is used when calling the method
:raises APIError: in case an Error occurs when checking whether `Form` contains the `Part`
"""
part_id = check_base(part, Part)
url = self._client._build_url(
"forms_has_part", form_id=self.id, part_id=part_id
)
response = self._client._request("GET", url=url)
if response.status_code != requests.codes.ok:
raise APIError(
f"Could not process whether `Form` {self.id} has part {part_id}",
response=response,
)
return response.json()["results"][0]["has_part"]
def set_prefill_parts(self, prefill_parts: dict) -> None:
"""Set the prefill_parts on the Form.
Prefill parts are insatnces of a part model that are stored on the
Form Model (only for models) and these instances of the parts are
instantiated by the backend when the Form is also instantiated.
Set the prefill_parts on the form collection model using a special
structure. The structure is jsonschema validated by the backend before
the `Form` is updated.
The prefill_parts on the form should be in the following structure:
```
{
<uuid of the part_model> : [
{
# an individual instance with 'partname'='name'
name: null_string,
part_properties: [
{
property_id: <uuid>,
value: <null_string>
},{...}
]
}, {...}
],
<uuid of another part_model>: [...]
}
```
:param prefill_parts: dictionary of `<part_model_id>: [array of instances to create]`
:raises APIError: When the prefill_parts is tried to be set on Form Instances
:raises APIError: WHen the update of the prefill_parts on the Form does not succeed.
"""
# only works for Form Models.
if not self.is_model:
raise APIError(
"The update of the prefill parts is only applicable to Form Models."
)
payload = dict(
prefill_parts=check_json(
value=prefill_parts,
schema=form_collection_prefill_parts_schema,
key="prefill_parts",
)
)
url = self._client._build_url("form", form_id=self.id)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request(
"PATCH", url=url, params=query_params, json=payload
)
if response.status_code != requests.codes.ok:
raise APIError(
"Could not update the prefill_parts dictionary on the form collection",
response=response,
)
self.refresh(json=response.json()["results"][0])
def workflows_compatible_with_scope(self, scope: Scope):
"""Return workflows from target scope that are compatible with source workflow.
:param scope: a Scope object
:raises IllegalArgumentError: in case not a `Scope` object is used when calling the method
:raises APIError: in case an Error occurs
"""
scope_id = check_base(scope, Scope)
url = self._client._build_url(
"forms_compatible_within_scope", form_id=self.id, scope_id=scope_id
)
response = self._client._request("GET", url=url)
if response.status_code != requests.codes.ok:
raise APIError(
"Could not retrieve the compatible workflows",
response=response,
)
return response.json()["results"]
|
class Form(BaseInScope, CrudActionsMixin, TagsMixin, NameDescriptionTranslationMixin):
'''
A virtual object representing a KE-chain Form Collection.
.. versionadded:: v3.20
:ivar id: id of the form
:ivar name: name of the form
:ivar description: description of the form
:ivar ref: reference (slugified name) of the form
:ivar category: the category of the form (FormCategory.MODEL or FormCategory.INSTANCE)
:ivar active_status: current active Status of the form
:ivar form_model_root: the form model root Part
:ivar form_instance_root: the form instance root Part
:ivar model_id: the pk of the model of this form instance
:ivar status_forms: The StatusForms of this form
:ivar prefill_parts: The parts to prefill when a Form Model is isntantiated.
:ivar created_at: datetime in UTC timezone when the form was created
:ivar updated_at: datetime in UTC timezone when the form was last updated
:ivar derived_from_id: (optional) id where the objects is derived from.
'''
def __init__(self, json, **kwargs):
'''Construct a service from provided json data.'''
pass
def __repr__(self):
pass
@classmethod
def create_model(
cls,
client: "Client",
name: str,
scope: Union[Scope, ObjectID],
workflow: Union["Workflow", ObjectID],
contexts: List[Union[Context, ObjectID]],
**kwargs: dict,
) -> "Form":
'''Create a new form model.
Needs scope, name, workflow.
:param client: The client connection to KE-chain API
:param name: Name of the new form model
:param scope: Scope or scope_id where to create the form model
:param workflow: Workflow or workflow_id of the workflow associated to the form model,
should be in scope.
:param contexts: A list of Context or context id's to link to the Form model.
:param kwargs: Additional kwargs such as contexts.
'''
pass
@property
def status_forms(self):
'''Retrieve the Status Forms of this Form.'''
pass
@property
def is_model(self) -> bool:
'''Form is a Form Model or Form Template.'''
pass
@property
def is_instance(self) -> bool:
'''Form is a Form Instance.'''
pass
@property
def is_active(self) -> bool:
'''Form is an active Form.'''
pass
def instances(self, **kwargs) -> [List["Form"]]:
'''Retrieve the instances of this Form Model.'''
pass
def instances(self, **kwargs) -> [List["Form"]]:
'''Retrieve a single instance of a Form Model.'''
pass
def edit(
self,
name: Optional[Union[str, Empty]] = empty,
description: Optional[Union[str, Empty]] = empty,
**kwargs,
) -> None:
'''Edit the details of a Form (model or instance).
Setting an input to None will clear out the value (exception being name).
:param name: optional name of the form to edit. Cannot be cleared.
:type name: basestring or None or Empty
:param description: (optional) description of the form. Can be cleared.
:type description: basestring or None or Empty
:param kwargs: (optional) additional kwargs that will be passed in the during the edit/update request
:return: None
:raises IllegalArgumentError: when the type or value of an argument provided is incorrect
:raises APIError: in case an Error occurs
'''
pass
def delete(self) -> None:
'''Delete this Form.
:raises APIError: if delete was not successful.
'''
pass
def instantiate(self, name: Optional[str], **kwargs) -> "Form":
'''Create a new Form instance based on a model.'''
pass
def clone(
self, name: Optional[str], target_scope: Optional[Scope] = None, **kwargs
) -> Optional["Form"]:
'''Clone a new Form model based on a model.
If target_scope is specified and different from the scope of the form, then use the
`clone_cross_scope` endpoint. Otherwise, use the basic `clone` endpoint.
'''
pass
def activate(self):
'''Put the form to active.
Model Forms can be put to inactive. When the Form model is not active the form cannot be
instantiated. This methods sets the form to active.
'''
pass
def deactivate(self):
'''Put the form to inactive.
Model Forms can be put to inactive. When the Form model is not active the form cannot be
instantiated.
'''
pass
def link_contexts(self, contexts: List[Union[Context, ObjectID]]):
'''
Link a list of Contexts to a Form.
:param contexts: a list of Context Objects or context_ids to link to the form.
:raises APIError: in case an Error occurs when linking
'''
pass
def unlink_contexts(self, contexts: List[Union[Context, ObjectID]]):
'''
Unlink a list of Contexts from a Form.
:param contexts: a list of Context Objects or context_ids to unlink from the form.
:raises APIError: in case an Error occurs when unlinking
'''
pass
def set_status_assignees(self, statuses: List[dict]):
'''
Set a list of assignees on each status of a Form.
:param statuses: a list of dicts, each one contains the status_id and the list of
assignees. Available fields per dict:
:param status: Status object
:param assignees: List of User objects
:raises APIError: in case an Error occurs when setting the status assignees
Example
-------
When the `Form` is known, one can easily access its status forms ids and build a
dictionary, as such:
>>> for status_form in form.status_forms:
>>> status_dict = {
>>> "status": status_form.status,
>>> "assignees": [user_1, user_2]
>>> }
>>> status_assignees_list.append(status_dict)
>>> self.form.set_status_assignees(statuses=status_assignees_list)
'''
pass
def possible_transitions(self) -> List[Transition]:
'''Retrieve the possible transitions that may be applied on the Form.
It will return the Transitions from the associated workflow are can be applied
on the Form in the current status.
:returns: A list with possible Transitions that may be applied on the Form.
'''
pass
def apply_transition(self, transition: Transition):
'''Apply the transition to put the form in another state following a transition.
Apply transition is to put the Form in another state. Only transitions that
can apply to the form should have the 'from_status' to the current state. (or
it is a Global transition). If applied the Form will be set in the 'to_state' of
the Transition.
:param transition: a Transition object belonging to the workflow of the Form
:raises APIError: in case an Error occurs when applying the transition
Example
-------
When the `Form` and `Workflow` is known, one can easily apply a transition on it, as such:
>>> transition = workflow.transition("In progress")
>>> form.apply_transition(transition=transition)
'''
pass
def has_part(self, part: Part) -> bool:
'''Return boolean if given Part is part of the Form tree.
Based on the Parts category, either the model or the instance tree is checked.
:param part: a Part object
:raises IllegalArgumentError: in case not a `Part` object is used when calling the method
:raises APIError: in case an Error occurs when checking whether `Form` contains the `Part`
'''
pass
def set_prefill_parts(self, prefill_parts: dict) -> None:
'''Set the prefill_parts on the Form.
Prefill parts are insatnces of a part model that are stored on the
Form Model (only for models) and these instances of the parts are
instantiated by the backend when the Form is also instantiated.
Set the prefill_parts on the form collection model using a special
structure. The structure is jsonschema validated by the backend before
the `Form` is updated.
The prefill_parts on the form should be in the following structure:
```
{
<uuid of the part_model> : [
{
# an individual instance with 'partname'='name'
name: null_string,
part_properties: [
{
property_id: <uuid>,
value: <null_string>
},{...}
]
}, {...}
],
<uuid of another part_model>: [...]
}
```
:param prefill_parts: dictionary of `<part_model_id>: [array of instances to create]`
:raises APIError: When the prefill_parts is tried to be set on Form Instances
:raises APIError: WHen the update of the prefill_parts on the Form does not succeed.
'''
pass
def workflows_compatible_with_scope(self, scope: Scope):
'''Return workflows from target scope that are compatible with source workflow.
:param scope: a Scope object
:raises IllegalArgumentError: in case not a `Scope` object is used when calling the method
:raises APIError: in case an Error occurs
'''
pass
| 29 | 23 | 21 | 2 | 12 | 6 | 2 | 0.6 | 4 | 14 | 9 | 0 | 22 | 16 | 23 | 39 | 546 | 82 | 294 | 107 | 248 | 177 | 162 | 86 | 136 | 5 | 2 | 2 | 48 |
140,865 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/form.py
|
pykechain.models.form.StatusForm
|
class StatusForm(Base):
"""A virtual object representing a KE-chain StatusForm.
A StatusForm is an intermediate object linking the Forms to its 'subforms', where each
status of a form has a link to its Activity.
"""
def __init__(self, json, **kwargs):
"""Construct a status form from provided json data."""
super().__init__(json, **kwargs)
self.description: str = json.get("description", "")
self.ref: str = json.get("ref", "")
self.status: Status = Status(json.get("status"), client=self._client)
self.activity: Activity = Activity(json.get("activity"), client=self._client)
self.form: str = json.get("form")
def __repr__(self): # pragma: no cover
return f"<pyke StatusForm '{self.status}' id {self.id[-8:]}>"
|
class StatusForm(Base):
'''A virtual object representing a KE-chain StatusForm.
A StatusForm is an intermediate object linking the Forms to its 'subforms', where each
status of a form has a link to its Activity.
'''
def __init__(self, json, **kwargs):
'''Construct a status form from provided json data.'''
pass
def __repr__(self):
pass
| 3 | 2 | 5 | 0 | 5 | 1 | 1 | 0.6 | 1 | 3 | 1 | 0 | 2 | 5 | 2 | 7 | 18 | 3 | 10 | 8 | 7 | 6 | 10 | 8 | 7 | 1 | 1 | 0 | 2 |
140,866 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/expiring_download.py
|
pykechain.models.expiring_download.ExpiringDownload
|
class ExpiringDownload(Base):
"""Expiring Download class."""
def __init__(self, json: Dict, **kwargs) -> None:
"""
Init function.
:param json: the json response to construct the :class:`ExpiringDownload` from
:type json: dict
"""
super().__init__(json, **kwargs)
self.filename = json.get("content_file_name")
self.expires_in = json.get("expires_in")
self.expires_at = json.get("expires_at")
self.token_hint = json.get("token_hint")
def __repr__(self): # pragma: no cover
return f"<pyke ExpiringDownload id {self.id[-8:]}>"
def save_as(self, target_dir: Optional[str] = None) -> None:
"""
Save the Expiring Download content.
:param target_dir: the target directory where the file will be stored
:type target_dir: str
"""
full_path = os.path.join(target_dir or os.getcwd(), self.filename)
url = self._client._build_url("expiring_download_download", download_id=self.id)
response = self._client._request("GET", url)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(
f"Could not download file from Expiring download {self}",
response=response,
)
with open(full_path, "w+b") as f:
for chunk in response:
f.write(chunk)
def delete(self) -> None:
"""Delete this expiring download.
:raises APIError: if delete was not successful.
"""
response = self._client._request(
"DELETE", self._client._build_url("expiring_download", download_id=self.id)
)
if response.status_code != requests.codes.no_content: # pragma: no cover
raise APIError(
f"Could not delete Expiring Download {self}", response=response
)
def edit(
self,
expires_at: Optional[datetime.datetime] = empty,
expires_in: Optional[int] = empty,
**kwargs,
) -> None:
"""
Edit Expiring Download details.
:param expires_at: The moment at which the ExpiringDownload will expire
:type expires_at: datetime.datetime
:param expires_in: The amount of time (in seconds) in which the ExpiringDownload will expire
:type expires_in: int
"""
update_dict = {
"id": self.id,
"expires_at": check_type(expires_at, datetime.datetime, "expires_at")
or self.expires_at,
"expires_in": check_type(expires_in, int, "expires_in") or self.expires_in,
}
if kwargs: # pragma: no cover
update_dict.update(**kwargs)
update_dict = clean_empty_values(update_dict=update_dict)
response = self._client._request(
"PUT",
self._client._build_url("expiring_download", download_id=self.id),
json=update_dict,
)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(
f"Could not update Expiring Download {self}", response=response
)
self.refresh(json=response.json()["results"][0])
def upload(self, content_path):
"""
Upload a file to the Expiring Download.
.. versionadded:: 3.10.0
:param content_path: path to the file to upload.
:type content_path: basestring
:raises APIError: if the file could not be uploaded.
:raises OSError: if the file could not be located on disk.
"""
if os.path.exists(content_path):
self._upload(content_path=content_path)
else:
raise OSError(f"Could not locate file to upload in '{content_path}'")
def _upload(self, content_path):
url = self._client._build_url("expiring_download_upload", download_id=self.id)
with open(content_path, "rb") as file:
response = self._client._request(
"POST",
url,
files={"attachment": (os.path.basename(content_path), file)},
)
if response.status_code not in (
requests.codes.accepted,
requests.codes.ok,
): # pragma: no cover
raise APIError(
f"Could not upload file to Expiring Download {self}", response=response
)
self.refresh(json=response.json()["results"][0])
|
class ExpiringDownload(Base):
'''Expiring Download class.'''
def __init__(self, json: Dict, **kwargs) -> None:
'''
Init function.
:param json: the json response to construct the :class:`ExpiringDownload` from
:type json: dict
'''
pass
def __repr__(self):
pass
def save_as(self, target_dir: Optional[str] = None) -> None:
'''
Save the Expiring Download content.
:param target_dir: the target directory where the file will be stored
:type target_dir: str
'''
pass
def delete(self) -> None:
'''Delete this expiring download.
:raises APIError: if delete was not successful.
'''
pass
def edit(
self,
expires_at: Optional[datetime.datetime] = empty,
expires_in: Optional[int] = empty,
**kwargs,
) -> None:
'''
Edit Expiring Download details.
:param expires_at: The moment at which the ExpiringDownload will expire
:type expires_at: datetime.datetime
:param expires_in: The amount of time (in seconds) in which the ExpiringDownload will expire
:type expires_in: int
'''
pass
def upload(self, content_path):
'''
Upload a file to the Expiring Download.
.. versionadded:: 3.10.0
:param content_path: path to the file to upload.
:type content_path: basestring
:raises APIError: if the file could not be uploaded.
:raises OSError: if the file could not be located on disk.
'''
pass
def _upload(self, content_path):
pass
| 8 | 6 | 17 | 2 | 11 | 5 | 2 | 0.47 | 1 | 6 | 1 | 0 | 7 | 5 | 7 | 7 | 128 | 24 | 75 | 29 | 62 | 35 | 42 | 21 | 34 | 3 | 1 | 2 | 14 |
140,867 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/part.py
|
pykechain.models.part.Part
|
class Part(TreeObject):
"""A virtual object representing a KE-chain part.
:ivar id: UUID of the part
:type id: basestring
:ivar name: Name of the part
:type name: basestring
:ivar ref: Reference of the part (slug of the original name)
:type ref: basestring
:ivar description: description of the part
:type description: basestring or None
:ivar created_at: the datetime when the object was created if available (otherwise None)
:type created_at: datetime or None
:ivar updated_at: the datetime when the object was last updated if available (otherwise None)
:type updated_at: datetime or None
:ivar category: The category of the part, either 'MODEL' or 'INSTANCE' (of :class:`pykechain.enums.Category`)
:type category: basestring
:ivar parent_id: The UUID of the parent of this part
:type parent_id: basestring or None
:ivar properties: The list of :class:`Property` objects belonging to this part.
:type properties: List[Property]
:ivar multiplicity: The multiplicity of the part being one of the following options: ZERO_ONE, ONE, ZERO_MANY,
ONE_MANY, (reserved) M_N (of :class:`pykechain.enums.Multiplicity`)
:type multiplicity: basestring
:ivar scope_id: scope UUID of the Part
:type scope_id: basestring
:ivar properties: the list of properties of this part
:type properties: List[AnyProperty]
Examples
--------
For the category property
>>> bike = project.part('Bike')
>>> bike.category
'INSTANCE'
>>> bike_model = project.model('Bike')
>>> bike_model.category
'MODEL'
>>> bike_model == Category.MODEL
True
>>> bike == Category.INSTANCE
True
For the multiplicity property
>>> bike = project.models('Bike')
>>> bike.multiplicity
ONE_MANY
>>> from pykechain.enums import Multiplicity
>>> bike.multiplicity == Multiplicity.ONE_MANY
True
"""
def __init__(self, json: Dict, **kwargs):
"""Construct a part from a KE-chain 2 json response.
:param json: the json response to construct the :class:`Part` from
:type json: dict
"""
# we need to run the init of 'Base' instead of 'Part' as we do not need the instantiation of properties
super().__init__(json, **kwargs)
self.ref: str = json.get("ref")
self.model_id: str = json.get("model_id")
self.category: Category = json.get("category")
self.description: str = json.get("description")
self.multiplicity: str = json.get("multiplicity")
self.classification: Classification = json.get("classification")
sorted_properties: List[Dict] = sorted(
json["properties"], key=lambda p: p.get("order", 0)
)
self.properties: List[Property] = [
Property.create(p, client=self._client) for p in sorted_properties
]
proxy_data: Optional[Dict] = json.get("proxy_source_id_name", dict())
self._proxy_model_id: Optional[str] = (
proxy_data.get("id") if proxy_data else None
)
def __call__(self, *args, **kwargs) -> "Part":
"""Short-hand version of the `child` method."""
return self.child(*args, **kwargs)
def refresh(
self,
json: Optional[Dict] = None,
url: Optional[str] = None,
extra_params: Optional[Dict] = None,
):
"""Refresh the object in place."""
if extra_params is None:
extra_params = {}
extra_params.update(API_EXTRA_PARAMS["part"])
existing_properties = {p.id: p for p in self.properties}
super().refresh(
json=json,
url=self._client._build_url("part", part_id=self.id),
extra_params=extra_params,
)
# The properties have been recreated anew when refreshing the part, but should be refreshed in-place.
new_properties = list(self.properties)
self.properties = []
for new_prop in new_properties:
if new_prop.id in existing_properties:
prop = existing_properties.pop(new_prop.id)
prop.refresh(json=new_prop._json_data)
else:
prop = new_prop
self.properties.append(prop)
#
# Family and structure methods
#
def property(self, name: str = None) -> "AnyProperty":
"""Retrieve the property belonging to this part based on its name, ref or uuid.
:param name: property name, ref or UUID to search for
:return: a single :class:`Property`
:raises NotFoundError: if the `Property` is not part of the `Part`
:raises MultipleFoundError
Example
-------
>>> part = project.part('Bike')
>>> part.properties
[<pyke Property ...>, ...]
# this returns a list of all properties of this part
>>> gears = part.property('Gears')
>>> gears.value
6
>>> gears = part.property('123e4567-e89b-12d3-a456-426655440000')
>>> gears.value
6
"""
return find_obj_in_list(name, iterable=self.properties)
def scope(self) -> "Scope":
"""Scope this Part belongs to.
This property will return a `Scope` object. It will make an additional call to the KE-chain API.
:return: the scope
:rtype: :class:`pykechain.models.Scope`
:raises NotFoundError: if the scope could not be found
"""
return super().scope
def parent(self) -> "Part":
"""Retrieve the parent of this `Part`.
:return: the parent :class:`Part` of this part
:raises APIError: if an Error occurs
Example
-------
>>> part = project.part('Frame')
>>> bike = part.parent()
"""
if self._parent is None and self.parent_id:
self._parent = self._client.part(pk=self.parent_id, category=self.category)
return self._parent
def children(self, **kwargs) -> Union["PartSet", List["Part"]]:
"""Retrieve the children of this `Part` as `PartSet`.
When you call the :func:`Part.children()` method without any additional filtering options for the children,
the children are cached to help speed up subsequent calls to retrieve the children. The cached children are
returned as a list and not as a `Partset`.
When you *do provide* additional keyword arguments (kwargs) that act as a specific children filter, the
cached children are _not_ used and a separate API call is made to retrieve only those children.
:param kwargs: Additional search arguments to search for, check :class:`pykechain.Client.parts`
for additional info
:return: a set of `Parts` as a :class:`PartSet`. Will be empty if no children. Will be a `List` if the
children are retrieved from the cached children.
:raises APIError: When an error occurs.
Example
-------
A normal call, which caches all children of the bike. If you call `bike.children` twice only 1 API call is made.
>>> bike = project.part('Bike')
>>> direct_descendants_of_bike = bike.children()
An example with providing additional part search parameters 'name__icontains'. Children are retrieved from the
API, not the bike's internal (already cached in previous example) cache.
>>> bike = project.part('Bike')
>>> wheel_children_of_bike = bike.children(name__icontains='wheel')
"""
if not kwargs:
# no kwargs provided is the default, we aim to cache it.
if self._cached_children is None:
self._cached_children = list(
self._client.parts(parent=self.id, category=self.category)
)
for child in self._cached_children:
child._parent = self
return self._cached_children
else:
# if kwargs are provided, we assume no use of cache as specific filtering on the children is performed.
return self._client.parts(parent=self.id, category=self.category, **kwargs)
def child(
self, name: Optional[str] = None, pk: Optional[str] = None, **kwargs
) -> "Part":
"""
Retrieve a child object.
:param name: optional, name of the child
:type name: str
:param pk: optional, UUID of the child
:type: pk: str
:return: Child object
:raises MultipleFoundError: whenever multiple children fit match inputs.
:raises NotFoundError: whenever no child matching the inputs could be found.
"""
if not (name or pk):
raise IllegalArgumentError('You need to provide either "name" or "pk".')
if self._cached_children:
# First try to find the child without calling KE-chain.
if name:
part_list = [c for c in self.children() if c.name == name]
else:
part_list = [c for c in self.children() if c.id == pk]
else:
part_list = []
if not part_list:
# Refresh children list from KE-chain by using a keyword-argument.
if name:
part_list = self.children(name=name)
else:
part_list = self.children(pk=pk)
criteria = f"\nname: {name}\npk: {pk}\nkwargs: {kwargs}"
# If there is only one, then that is the part you are looking for
if len(part_list) == 1:
part = part_list[0]
# Otherwise raise the appropriate error
elif len(part_list) > 1:
raise MultipleFoundError(
f"{self} has more than one matching child.{criteria}"
)
else:
raise NotFoundError(f"{self} has no matching child.{criteria}")
return part
def populate_descendants(self, batch: int = PARTS_BATCH_LIMIT) -> None:
"""
Retrieve the descendants of a specific part in a list of dicts and populate the :func:`Part.children()` method.
Each `Part` has a :func:`Part.children()` method to retrieve the children on the go. This function
prepopulates the children and the children's children with its children in one call, making the traversal
through the parttree blazingly fast.
.. versionadded:: 2.1
.. versionchanged:: 3.3.2 now populates child parts instead of this part
:param batch: Number of Parts to be retrieved in a batch
:type batch: int (defaults to 100)
:returns: None
:raises APIError: if you cannot create the children tree.
Example
-------
>>> bike = project.part('Bike')
>>> bike.populate_descendants(batch=150)
"""
all_descendants = list(
self._client.parts(
category=self.category,
batch=batch,
descendants=self.id,
)
)
try:
all_descendants.remove(
self
) # remove the part itself because it is not needed for the direct descendants
except ValueError:
pass
self._populate_cached_children(all_descendants=all_descendants, overwrite=True)
return None
def all_children(self) -> List["Part"]:
"""
Retrieve a flat list of all descendants, sorted depth-first. Also populates all descendants.
:returns list of child objects
:rtype List
"""
if self._cached_children is None:
self.populate_descendants()
return super().all_children()
def siblings(self, **kwargs) -> Union["PartSet", List["Part"]]:
"""Retrieve the siblings of this `Part` as `PartSet`.
Siblings are other Parts sharing the same parent of this `Part`, including the part itself.
:param kwargs: Additional search arguments to search for, check :class:`pykechain.Client.parts`
for additional info
:return: a set of `Parts` as a :class:`PartSet`. Will be empty if no siblings.
:raises APIError: When an error occurs.
"""
if self.parent_id:
return self._client.parts(
parent=self.parent_id, category=self.category, **kwargs
)
else:
from pykechain.models.partset import PartSet
return PartSet(parts=[])
#
# Model and Instance(s) methods
#
def model(self) -> "Part":
"""
Retrieve the model of this `Part` as `Part`.
For instance, you can get the part model of a part instance. But trying to get the model of a part that
has no model, like a part model, will raise a :exc:`NotFoundError`.
.. versionadded:: 1.8
:return: the model of this part instance as :class:`Part` with category `MODEL`
:raises NotFoundError: if no model found
Example
-------
>>> front_fork = project.part('Front Fork')
>>> front_fork_model = front_fork.model()
"""
if self.category == Category.INSTANCE:
return self._client.model(pk=self.model_id)
else:
raise NotFoundError(f'Part "{self}" already is a model')
def instances(self, **kwargs) -> Union["PartSet", List["Part"]]:
"""
Retrieve the instances of this `Part` as a `PartSet`.
For instance, if you have a model part, you can get the list of instances that are created based on this
moodel. If there are no instances (only possible if the multiplicity is :attr:`enums.Multiplicity.ZERO_MANY`)
than a :exc:`NotFoundError` is returned
.. versionadded:: 1.8
:return: the instances of this part model :class:`PartSet` with category `INSTANCE`
:raises NotFoundError: if no instances found
Example
-------
>>> wheel_model = project.model('Wheel')
>>> wheel_instance_set = wheel_model.instances()
An example with retrieving the front wheels only using the 'name__contains' search argument.
>>> wheel_model = project.model('Wheel')
>>> front_wheel_instances = wheel_model.instances(name__contains='Front')
"""
if self.category == Category.MODEL:
return self._client.parts(model=self, category=Category.INSTANCE, **kwargs)
else:
raise NotFoundError(
f"Part '{self}' is not a model, hence it has no instances."
)
def instance(self) -> "Part":
"""
Retrieve the single (expected) instance of this 'Part' (of `Category.MODEL`) as a 'Part'.
See :func:`Part.instances()` method for documentation.
:return: :class:`Part` with category `INSTANCE`
:raises NotFoundError: if the instance does not exist
:raises MultipleFoundError: if there are more than a single instance returned
"""
instances_list = list(self.instances())
if len(instances_list) == 1:
return instances_list[0]
elif len(instances_list) > 1:
raise MultipleFoundError(
"Part {} has more than a single instance. "
"Use the `Part.instances()` method".format(self)
)
else:
raise NotFoundError(f"Part {self} has no instance")
def count_instances(self) -> int:
"""
Retrieve the number of instances of this Part model without the parts themselves.
:return: number of Part instances
:rtype
"""
if not self.category == Category.MODEL:
raise IllegalArgumentError(
"You can only count the number of instances of a Part with category MODEL"
)
response = self._client._request(
"GET",
self._client._build_url("parts"),
params={
"scope_id": self.scope_id,
"model_id": self.id,
"limit": 1,
},
)
if response.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not retrieve Parts instances")
count = response.json()["count"]
return count
def count_children(self, **kwargs) -> int:
"""
Retrieve the number of child parts using a light-weight request.
:return: number of Parts
:rtype int
"""
return super().count_children(method="parts", category=self.category, **kwargs)
#
# CRUD operations
#
def edit(
self,
name: Optional[Union[str, Empty]] = empty,
description: Optional[Union[str, Empty]] = empty,
**kwargs,
) -> None:
"""Edit the details of a part (model or instance).
Setting an input to None will clear out the value (exception being name).
For an instance you can edit the Part instance name and the part instance description. To alter the values
of properties use :func:`Part.update()`.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:param name: optional name of the part to edit. Cannot be cleared.
:type name: basestring or None or Empty
:param description: (optional) description of the part. Can be cleared.
:type description: basestring or None or Empty
:param kwargs: (optional) additional kwargs that will be passed in the during the edit/update request
:return: None
:raises IllegalArgumentError: when the type or value of an argument provided is incorrect
:raises APIError: in case an Error occurs
Example
-------
For changing a part:
>>> front_fork = project.part('Front Fork')
>>> front_fork.edit(name='Front Fork - updated')
>>> front_fork.edit(name='Front Fork cruizer',description='With my ragtop down so my hair can blow')
for changing a model:
>>> front_fork = project.model('Front Fork')
>>> front_fork.edit(name='Front Fork basemodel',description='Some description here')
Not mentioning an input parameter in the function will leave it unchanged. Setting a parameter as None will
clear its value (where that is possible). The example below will clear the description and edit the name.
>>> front_fork.edit(name="Front spoon",description=None)
"""
update_dict = {
"id": self.id,
"name": check_text(name, "name") or self.name,
"description": check_text(description, "description") or "",
}
if kwargs: # pragma: no cover
update_dict.update(**kwargs)
update_dict = clean_empty_values(update_dict=update_dict)
response = self._client._request(
"PUT",
self._client._build_url("part", part_id=self.id),
params=API_EXTRA_PARAMS["part"],
json=update_dict,
)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Part {self}", response=response)
self.refresh(json=response.json().get("results")[0])
def proxy_model(self) -> "Part":
"""
Retrieve the proxy model of this proxied `Part` as a `Part`.
Allows you to retrieve the model of a proxy. But trying to get the catalog model of a part that
has no proxy, will raise an :exc:`NotFoundError`. Only models can have a proxy.
.. versionchanged:: 3.0
Added compatibility with KE-chain 3 backend.
:return: :class:`Part` with category `MODEL` and from which the current part is proxied
:raises NotFoundError: When no proxy model is found
Example
-------
>>> proxy_part = project.model('Proxy based on catalog model')
>>> catalog_model_of_proxy_part = proxy_part.proxy_model()
>>> proxied_material_of_the_bolt_model = project.model('Bolt Material')
>>> proxy_basis_for_the_material_model = proxied_material_of_the_bolt_model.proxy_model()
"""
if self.category != Category.MODEL:
raise IllegalArgumentError(
f'Part "{self}" is not a product model, therefore it cannot have a proxy model'
)
if self.classification != Classification.PRODUCT or not self._proxy_model_id:
raise NotFoundError(
f'Part "{self}" is not a product model, therefore it cannot have a proxy model'
)
return self._client.model(pk=self._proxy_model_id)
def add(self, model: "Part", **kwargs) -> "Part":
"""Add a new child instance, based on a model, to this part.
This can only act on instances. It needs a model from which to create the child instance.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:param model: `Part` object with category `MODEL`.
:type model: :class:`Part`
:param kwargs: (optional) additional keyword=value arguments
:return: :class:`Part` with category `INSTANCE`.
:raises APIError: if unable to add the new child instance
Example
-------
>>> bike = project.part('Bike')
>>> wheel_model = project.model('Wheel')
>>> bike.add(wheel_model)
"""
if self.category != Category.INSTANCE:
raise APIError("Part should be of category INSTANCE")
new_instance = self._client.create_part(self, model, **kwargs)
if self._cached_children is not None:
self._cached_children.append(new_instance)
return new_instance
def add_to(self, parent: "Part", **kwargs) -> "Part":
"""Add a new instance of this model to a part.
This works if the current part is a model and an instance of this model is to be added
to a part instances in the tree.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:param parent: part to add the new instance to
:type parent: :class:`Part`
:param kwargs: (optional) additional kwargs that will be passed in the during the edit/update request
:return: :class:`Part` with category `INSTANCE`
:raises APIError: if unable to add the new child instance
Example
-------
>>> wheel_model = project.model('wheel')
>>> bike = project.part('Bike')
>>> wheel_model.add_to(bike)
"""
if self.category != Category.MODEL:
raise APIError("Part should be of category MODEL")
new_instance = self._client.create_part(parent, self, **kwargs)
if parent._cached_children is not None:
parent._cached_children.append(new_instance)
return new_instance
def add_model(self, *args, **kwargs) -> "Part":
"""Add a new child model to this model.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:return: a :class:`Part` of category `MODEL`
"""
if self.category != Category.MODEL:
raise APIError("Part should be of category MODEL")
new_model = self._client.create_model(self, *args, **kwargs)
if self._cached_children is not None:
self._cached_children.append(new_model)
return new_model
def add_proxy_to(
self,
parent: "Part",
name: str,
multiplicity: Multiplicity = Multiplicity.ONE_MANY,
**kwargs,
) -> "Part":
"""Add this model as a proxy to another parent model.
This will add the current model as a proxy model to another parent model. It ensure that it will copy the
whole subassembly to the 'parent' model.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:param name: Name of the new proxy model
:type name: basestring
:param parent: parent of the to be proxied model
:type parent: :class:`Part`
:param multiplicity: the multiplicity of the new proxy model (default ONE_MANY)
:type multiplicity: basestring or None
:param kwargs: (optional) additional kwargs that will be passed in the during the edit/update request
:return: the new proxied :class:`Part`.
:raises APIError: in case an Error occurs
Examples
--------
>>> from pykechain.enums import Multiplicity
>>> bike_model = project.model('Bike')
# find the catalog model container, the highest parent to create catalog models under
>>> catalog_model_container = project.model('Catalog container')
>>> new_wheel_model = project.create_model(catalog_model_container, 'Wheel Catalog',
... multiplicity=Multiplicity.ZERO_MANY)
>>> new_wheel_model.add_proxy_to(bike_model, "Wheel", multiplicity=Multiplicity.ONE_MANY)
"""
return self._client.create_proxy_model(
self, parent, name, multiplicity, **kwargs
)
def add_property(self, *args, **kwargs) -> "AnyProperty":
"""Add a new property to this model.
See :class:`pykechain.Client.create_property` for available parameters.
:return: :class:`Property`
:raises APIError: in case an Error occurs
"""
if self.category != Category.MODEL:
raise APIError("Part should be of category MODEL")
return self._client.create_property(self, *args, **kwargs)
@staticmethod
def _parse_update_dict(
part: "Part",
properties_fvalues: List[Dict[str, Any]],
update_dict: Dict,
creating: bool = False,
) -> Tuple[List[Dict], List[Dict], Dict]:
"""
Check the content of the update dict and insert them into the properties_fvalues list.
:param part: Depending on whether you add to or update a part, this is the model or the part itself, resp.
:param properties_fvalues: list of property values
:param update_dict: dictionary with property values, keyed by property names
:param creating: flag to indicate creation of new properties, hence using the `model_id` instead of `id`
:return: Tuple with 2 lists of dicts
:rtype tuple
"""
properties_fvalues = (
check_list_of_dicts(properties_fvalues, "properties_fvalues") or list()
)
check_type(update_dict, dict, "update_dict")
exception_fvalues = list()
update_dict = update_dict or dict()
key = "model_id" if creating else "id"
parsed_dict = dict()
for prop_name_or_id, property_value in update_dict.items():
property_to_update: Property = part.property(prop_name_or_id)
updated_p = {
"value": property_to_update.serialize_value(property_value),
key: property_to_update.id,
}
parsed_dict[property_to_update.id] = property_value
if property_to_update.type == PropertyType.ATTACHMENT_VALUE:
exception_fvalues.append(updated_p)
else:
properties_fvalues.append(updated_p)
return properties_fvalues, exception_fvalues, parsed_dict
def add_with_properties(
self,
model: "Part",
name: Optional[str] = None,
update_dict: Optional[Dict] = None,
properties_fvalues: Optional[List[Dict]] = None,
**kwargs,
) -> "Part":
"""
Add a new part instance of a model as a child of this part instance and update its properties in one go.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
With KE-chain 3 backends you may now provide a whole set of properties to update using a `properties_fvalues`
list of dicts. This will be merged with the `update_dict` optionally provided.
The `properties_fvalues` list is a list of dicts containing at least the `id` and a `value`, but other keys
may provided as well in the single update eg. `value_options`. Example::
`properties_fvalues = [ {"id":<uuid of prop>, "value":<new_prop_value>}, {...}, ...]`
.. versionchanged:: 3.0
Added compatibility with KE-chain 3 backend. You may provide properties_fvalues as kwarg.
Bulk option removed.
.. versionchanged:: 3.3
The 'refresh' flag is pending deprecation in version 3.4.. This flag had an effect of refreshing
the list of children of the current part and was default set to True. This resulted in large
processing times int he API as every `add_with_properties()` the children of the parent where all
retrieved. The default is now 'False'. The part just created is however to the internal list of children
once these children are retrieved earlier.
:param model: model of the part which to add a new instance, should follow the model tree in KE-chain
:type model: :class:`Part`
:param name: (optional) name provided for the new instance as string otherwise use the name of the model
:type name: basestring or None
:param update_dict: dictionary with keys being property names (str) or property_id (from the property models)
and values being property values
:type update_dict: dict or None
:param properties_fvalues: (optional) keyword argument with raw list of properties update dicts
:type properties_fvalues: list of dict or None
:param kwargs: (optional) additional keyword arguments that will be passed inside the update request
:return: the newly created :class:`Part`
:raises NotFoundError: when the property name is not a valid property of this part
:raises APIError: in case an Error occurs
:raises IllegalArgumentError: in case of illegal arguments.
Examples
--------
>>> bike = project.part('Bike')
>>> wheel_model = project.model('Wheel')
>>> bike.add_with_properties(wheel_model, 'Wooden Wheel', {'Spokes': 11, 'Material': 'Wood'})
"""
if self.category != Category.INSTANCE:
raise APIError("Part should be of category INSTANCE")
if not isinstance(model, Part) or model.category != Category.MODEL:
raise IllegalArgumentError(
f'`model` must be a Part object of category MODEL, "{model}" is not.'
)
instance_name = check_text(name, "name") or model.name
properties_fvalues, exception_fvalues, _ = self._parse_update_dict(
model,
properties_fvalues,
update_dict,
creating=True,
)
url = self._client._build_url("parts_new_instance")
response = self._client._request(
"POST",
url,
params=API_EXTRA_PARAMS["parts"],
json=dict(
name=instance_name,
model_id=model.id,
parent_id=self.id,
properties_fvalues=properties_fvalues,
**kwargs,
),
)
if response.status_code != requests.codes.created: # pragma: no cover
raise APIError(f"Could not add to Part {self}", response=response)
new_part_instance: Part = Part(
response.json()["results"][0], client=self._client
)
# ensure that cached children are updated
if self._cached_children is not None:
self._cached_children.append(new_part_instance)
# If any values were not set via the json, set them individually
for exception_fvalue in exception_fvalues:
property_model_id = exception_fvalue["model_id"]
property_instance = find(
new_part_instance.properties, lambda p: p.model_id == property_model_id
)
property_instance.value = exception_fvalue["value"]
return new_part_instance
def clone(self, **kwargs) -> "Part":
"""
Clone a part.
An optional name of the cloned part may be provided. If not provided the name will be set
to "CLONE - <part name>". (available for KE-chain 3 backends only)
An optional multiplicity, may be added as paremeter for the cloning of models. If not
provided the multiplicity of the part will be used. (available for KE-chain 3 backends only)
.. versionadded:: 2.3
.. versionchanged:: 3.0
Added optional paramenters the name and multiplicity for KE-chain 3 backends.
:param kwargs: (optional) additional keyword=value arguments
:return: cloned :class:`models.Part`
:raises APIError: if the `Part` could not be cloned
Example
-------
>>> bike = project.model('Bike')
>>> bike2 = bike.clone()
For KE-chain 3 backends
>>> bike = project.model('Bike')
>>> bike2 = bike.clone(name='Trike', multiplicity=Multiplicity.ZERO_MANY)
"""
parent = self.parent()
return self._client._create_clone(parent=parent, part=self, **kwargs)
def copy(
self,
target_parent: "Part",
name: Optional[str] = None,
include_children: bool = True,
include_instances: bool = True,
) -> "Part":
"""
Copy the `Part` to target parent, both of them having the same category.
.. versionadded:: 2.3
:param target_parent: `Part` object under which the desired `Part` is copied
:type target_parent: :class:`Part`
:param name: how the copied top-level `Part` should be called
:type name: basestring
:param include_children: True to copy also the descendants of `Part`.
:type include_children: bool
:param include_instances: True to copy also the instances of `Part` to ALL the instances of target_parent.
:type include_instances: bool
:returns: copied :class:`Part` model.
:raises IllegalArgumentError: if part and target_parent have different `Category`
:raises IllegalArgumentError: if part and target_parent are identical
Example
-------
>>> model_to_copy = project.model(name='Model to be copied')
>>> bike = project.model('Bike')
>>> model_to_copy.copy(target_parent=bike, name='Copied model',
>>> include_children=True,
>>> include_instances=True)
"""
check_type(target_parent, Part, "target_parent")
if self.category != target_parent.category:
# Cannot add a model under an instance or vice versa
raise IllegalArgumentError(
"part `{}` and target parent `{}`` must have the same category".format(
self, target_parent
)
)
# to ensure that all properties are retrieved from the backend
# as it might be the case that a part is retrieved in the context of a widget and there could be a possibility
# that not all properties are retrieved we perform a refresh of the part itself first.
self.refresh()
from pykechain.extra_utils import _copy_part
copied_part = _copy_part(
part=self,
target_parent=target_parent,
name=name,
include_children=include_children,
include_instances=include_instances,
)
return copied_part
def move(
self,
target_parent: "Part",
name: Optional[str] = None,
include_children: bool = True,
include_instances: bool = True,
) -> "Part":
"""
Move the `Part` to target parent, both of them the same category.
.. versionadded:: 2.3
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: :class:`Part`
:param name: how the moved top-level `Part` should be called
:type name: basestring
:param include_children: True to move also the descendants of `Part`. If False, the children will be lost.
:type include_children: bool
:param include_instances: True to move also the instances of `Part` to ALL the instances of target_parent.
:type include_instances: bool
:returns: moved :class:`Part` model.
:raises IllegalArgumentError: if part and target_parent have different `Category`
:raises IllegalArgumentError: if target_parent is descendant of part
Example
-------
>>> model_to_move = project.model(name='Model to be moved')
>>> bike = project.model('Bike')
>>> model_to_move.move(target_parent=bike, name='Moved model',
>>> include_children=True,
>>> include_instances=True)
"""
copied_part = self.copy(
target_parent=target_parent,
name=name,
include_children=include_children,
include_instances=include_instances,
)
try:
self.delete()
except APIError:
# In case of Part instances where the model has multiplicity 1 or 1-or-many, the model must be deleted
model_of_instance = self.model()
model_of_instance.delete()
return copied_part
def update(
self,
name: Optional[str] = None,
update_dict: Optional[Dict] = None,
properties_fvalues: Optional[List[Dict]] = None,
**kwargs,
) -> None:
"""
Edit part name and property values in one go.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
With KE-chain 3 backends you may now provide a whole set of properties to update using a `properties_fvalues`
list of dicts. This will be merged with the `update_dict` optionally provided.
The `properties_fvalues` list is a list of dicts containing at least the `id` and a `value`, but other keys
may provided as well in the single update eg. `value_options`. Example::
`properties_fvalues = [ {"id":<uuid of prop>, "value":<new_prop_value>}, {...}, ...]`
.. versionchanged:: 3.0
Added compatibility with KE-chain 3 backend. You may provide properties_fvalues as kwarg.
Bulk option removed.
:param name: new part name (defined as a string)
:type name: basestring or None
:param update_dict: dictionary with keys being property names (str) or property ids (uuid)
and values being property values
:type update_dict: dict or None
:param properties_fvalues: (optional) keyword argument with raw list of properties update dicts
:type properties_fvalues: list of dict or None
:param kwargs: additional keyword-value arguments that will be passed into the part update request.
:return: the updated :class:`Part`
:raises NotFoundError: when the property name is not a valid property of this part
:raises IllegalArgumentError: when the type or value of an argument provided is incorrect
:raises APIError: in case an Error occurs
Example
-------
>>> bike = project.part('Bike')
>>> bike.update(name='Good name', update_dict={'Gears': 11, 'Total Height': 56.3})
Example with properties_fvalues: <pyke Part 'Copied model under Bike' id 95d35be6>
>>> bike = project.part('Bike')
>>> bike.update(name='Good name',
... properties_fvalues=[{'id': '95d35be6...', 'value': 11},
... {'id': '7893cba4...', 'value': 56.3, 'value_options': {...}})
"""
# dict(name=name, properties=json.dumps(update_dict))) with property ids:value
# action = 'bulk_update_properties' # not for KEC3
check_text(name, "name")
properties_fvalues, exception_fvalues, update_dict = self._parse_update_dict(
self, properties_fvalues, update_dict
)
payload_json = dict(properties_fvalues=properties_fvalues, **kwargs)
if name:
payload_json.update(name=name)
if Property._USE_BULK_UPDATE and not (name or kwargs):
# Send updates to the property value in case of bulk updates while no part update is required
for prop in self.properties:
if prop.id in update_dict:
prop.value = update_dict[prop.id]
else:
response = self._client._request(
"PUT",
self._client._build_url("part", part_id=self.id),
params=API_EXTRA_PARAMS["part"],
json=payload_json,
)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Part {self}", response=response)
# update local properties (without a call)
self.refresh(json=response.json()["results"][0])
# If any values can not be set via the json, set them individually
for exception_fvalue in exception_fvalues:
self.property(exception_fvalue["id"]).value = exception_fvalue["value"]
def delete(self) -> None:
"""Delete this part.
:return: None
:raises APIError: in case an Error occurs
"""
response = self._client._request(
"DELETE", self._client._build_url("part", part_id=self.id)
)
if response.status_code != requests.codes.no_content: # pragma: no cover
raise APIError(f"Could not delete Part {self}", response=response)
def order_properties(
self, property_list: Optional[List[Union["AnyProperty", str]]] = None
) -> None:
"""
Order the properties of a part model using a list of property objects or property names or property id's.
For KE-chain 3 backends, the order can also directly provided as a unique integer for each property in the
`Part.update()` function if you provide the `properties_fvalues` list of dicts yourself. For more information
please refer to the `Part.update()` documentation.
.. versionchanged:: 3.0
For KE-chain 3 backend the `Part.update()` method is used with a properties_fvalues list of dicts.
:param property_list: ordered list of property names (basestring) or property id's (uuid) or
a `Property` object.
:type property_list: list(basestring)
:returns: the :class:`Part` with the reordered list of properties
:raises APIError: when an Error occurs
:raises IllegalArgumentError: When provided a wrong argument
Examples
--------
>>> front_fork = project.model('Front Fork')
>>> front_fork.order_properties(['Material', 'Height (mm)', 'Color'])
>>> front_fork = project.model('Front Fork')
>>> material = front_fork.property('Material')
>>> height = front_fork.property('Height (mm)')
>>> color = front_fork.property('Color')
>>> front_fork.order_properties([material, height, color])
Alternatively you may use the `Part.update()` function to directly alter the order of the properties and
eventually even more (defaut) model values.
>>> front_fork.update(properties_fvalues= [{'id': material.id, 'order':10},
... {'id': height.id, 'order': 20, 'value':13.37}
... {'id': color.id, 'order': 30, 'name': 'Colour'}])
"""
if self.category != Category.MODEL:
raise APIError(
f"Ordering of properties must be done on a Part of category {Category.MODEL}."
)
property_ids = check_list_of_base(
property_list, Property, "property_list", method=self.property
)
properties_fvalues = [dict(id=pk) for pk in property_ids]
response = self._client._request(
"POST",
self._client._build_url("order_properties", part_id=self.id),
json=properties_fvalues,
)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(
f"Could not reorder Properties of Part {self}", response=response
)
return
#
# Utility Functions
#
def _repr_html_(self) -> str:
"""
Represent the part in a HTML table for the use in notebooks.
:return: html text
:rtype: Text
"""
html = [
"<table width=100%>",
f"<caption>{self.name}</caption>",
"<tr>",
"<th>Property</th>",
"<th>Value</th>",
"</tr>",
]
for prop in self.properties:
style = "color:blue;" if prop._json_data.get("output", False) else ""
html.append(f'<tr style="{style}">')
html.append(f"<td>{prop.name}</td>")
html.append(f"<td>{prop.value}</td>")
html.append("</tr>")
html.append("</table>")
return "".join(html)
def as_dict(self) -> Dict:
"""
Retrieve the properties of a part inside a dict in this structure: {property_name: property_value}.
.. versionadded:: 1.9
:returns: the values of the properties as a `dict`
:rtype: dict
Example
-------
>>> front_wheel = project.part('Front Wheel')
>>> front_wheel_properties = front_wheel.as_dict()
{'Diameter': 60.8,
'Spokes': 24,
'Rim Material': 'Aluminium',
'Tire Thickness': 4.2}
"""
properties_dict = dict()
for prop in self.properties:
properties_dict[prop.name] = prop.value
return properties_dict
|
class Part(TreeObject):
'''A virtual object representing a KE-chain part.
:ivar id: UUID of the part
:type id: basestring
:ivar name: Name of the part
:type name: basestring
:ivar ref: Reference of the part (slug of the original name)
:type ref: basestring
:ivar description: description of the part
:type description: basestring or None
:ivar created_at: the datetime when the object was created if available (otherwise None)
:type created_at: datetime or None
:ivar updated_at: the datetime when the object was last updated if available (otherwise None)
:type updated_at: datetime or None
:ivar category: The category of the part, either 'MODEL' or 'INSTANCE' (of :class:`pykechain.enums.Category`)
:type category: basestring
:ivar parent_id: The UUID of the parent of this part
:type parent_id: basestring or None
:ivar properties: The list of :class:`Property` objects belonging to this part.
:type properties: List[Property]
:ivar multiplicity: The multiplicity of the part being one of the following options: ZERO_ONE, ONE, ZERO_MANY,
ONE_MANY, (reserved) M_N (of :class:`pykechain.enums.Multiplicity`)
:type multiplicity: basestring
:ivar scope_id: scope UUID of the Part
:type scope_id: basestring
:ivar properties: the list of properties of this part
:type properties: List[AnyProperty]
Examples
--------
For the category property
>>> bike = project.part('Bike')
>>> bike.category
'INSTANCE'
>>> bike_model = project.model('Bike')
>>> bike_model.category
'MODEL'
>>> bike_model == Category.MODEL
True
>>> bike == Category.INSTANCE
True
For the multiplicity property
>>> bike = project.models('Bike')
>>> bike.multiplicity
ONE_MANY
>>> from pykechain.enums import Multiplicity
>>> bike.multiplicity == Multiplicity.ONE_MANY
True
'''
def __init__(self, json: Dict, **kwargs):
'''Construct a part from a KE-chain 2 json response.
:param json: the json response to construct the :class:`Part` from
:type json: dict
'''
pass
def __call__(self, *args, **kwargs) -> "Part":
'''Short-hand version of the `child` method.'''
pass
def refresh(
self,
json: Optional[Dict] = None,
url: Optional[str] = None,
extra_params: Optional[Dict] = None,
):
'''Refresh the object in place.'''
pass
def property(self, name: str = None) -> "AnyProperty":
'''Retrieve the property belonging to this part based on its name, ref or uuid.
:param name: property name, ref or UUID to search for
:return: a single :class:`Property`
:raises NotFoundError: if the `Property` is not part of the `Part`
:raises MultipleFoundError
Example
-------
>>> part = project.part('Bike')
>>> part.properties
[<pyke Property ...>, ...]
# this returns a list of all properties of this part
>>> gears = part.property('Gears')
>>> gears.value
6
>>> gears = part.property('123e4567-e89b-12d3-a456-426655440000')
>>> gears.value
6
'''
pass
def scope(self) -> "Scope":
'''Scope this Part belongs to.
This property will return a `Scope` object. It will make an additional call to the KE-chain API.
:return: the scope
:rtype: :class:`pykechain.models.Scope`
:raises NotFoundError: if the scope could not be found
'''
pass
def parent(self) -> "Part":
'''Retrieve the parent of this `Part`.
:return: the parent :class:`Part` of this part
:raises APIError: if an Error occurs
Example
-------
>>> part = project.part('Frame')
>>> bike = part.parent()
'''
pass
def children(self, **kwargs) -> Union["PartSet", List["Part"]]:
'''Retrieve the children of this `Part` as `PartSet`.
When you call the :func:`Part.children()` method without any additional filtering options for the children,
the children are cached to help speed up subsequent calls to retrieve the children. The cached children are
returned as a list and not as a `Partset`.
When you *do provide* additional keyword arguments (kwargs) that act as a specific children filter, the
cached children are _not_ used and a separate API call is made to retrieve only those children.
:param kwargs: Additional search arguments to search for, check :class:`pykechain.Client.parts`
for additional info
:return: a set of `Parts` as a :class:`PartSet`. Will be empty if no children. Will be a `List` if the
children are retrieved from the cached children.
:raises APIError: When an error occurs.
Example
-------
A normal call, which caches all children of the bike. If you call `bike.children` twice only 1 API call is made.
>>> bike = project.part('Bike')
>>> direct_descendants_of_bike = bike.children()
An example with providing additional part search parameters 'name__icontains'. Children are retrieved from the
API, not the bike's internal (already cached in previous example) cache.
>>> bike = project.part('Bike')
>>> wheel_children_of_bike = bike.children(name__icontains='wheel')
'''
pass
def children(self, **kwargs) -> Union["PartSet", List["Part"]]:
'''
Retrieve a child object.
:param name: optional, name of the child
:type name: str
:param pk: optional, UUID of the child
:type: pk: str
:return: Child object
:raises MultipleFoundError: whenever multiple children fit match inputs.
:raises NotFoundError: whenever no child matching the inputs could be found.
'''
pass
def populate_descendants(self, batch: int = PARTS_BATCH_LIMIT) -> None:
'''
Retrieve the descendants of a specific part in a list of dicts and populate the :func:`Part.children()` method.
Each `Part` has a :func:`Part.children()` method to retrieve the children on the go. This function
prepopulates the children and the children's children with its children in one call, making the traversal
through the parttree blazingly fast.
.. versionadded:: 2.1
.. versionchanged:: 3.3.2 now populates child parts instead of this part
:param batch: Number of Parts to be retrieved in a batch
:type batch: int (defaults to 100)
:returns: None
:raises APIError: if you cannot create the children tree.
Example
-------
>>> bike = project.part('Bike')
>>> bike.populate_descendants(batch=150)
'''
pass
def all_children(self) -> List["Part"]:
'''
Retrieve a flat list of all descendants, sorted depth-first. Also populates all descendants.
:returns list of child objects
:rtype List
'''
pass
def siblings(self, **kwargs) -> Union["PartSet", List["Part"]]:
'''Retrieve the siblings of this `Part` as `PartSet`.
Siblings are other Parts sharing the same parent of this `Part`, including the part itself.
:param kwargs: Additional search arguments to search for, check :class:`pykechain.Client.parts`
for additional info
:return: a set of `Parts` as a :class:`PartSet`. Will be empty if no siblings.
:raises APIError: When an error occurs.
'''
pass
def model(self) -> "Part":
'''
Retrieve the model of this `Part` as `Part`.
For instance, you can get the part model of a part instance. But trying to get the model of a part that
has no model, like a part model, will raise a :exc:`NotFoundError`.
.. versionadded:: 1.8
:return: the model of this part instance as :class:`Part` with category `MODEL`
:raises NotFoundError: if no model found
Example
-------
>>> front_fork = project.part('Front Fork')
>>> front_fork_model = front_fork.model()
'''
pass
def instances(self, **kwargs) -> Union["PartSet", List["Part"]]:
'''
Retrieve the instances of this `Part` as a `PartSet`.
For instance, if you have a model part, you can get the list of instances that are created based on this
moodel. If there are no instances (only possible if the multiplicity is :attr:`enums.Multiplicity.ZERO_MANY`)
than a :exc:`NotFoundError` is returned
.. versionadded:: 1.8
:return: the instances of this part model :class:`PartSet` with category `INSTANCE`
:raises NotFoundError: if no instances found
Example
-------
>>> wheel_model = project.model('Wheel')
>>> wheel_instance_set = wheel_model.instances()
An example with retrieving the front wheels only using the 'name__contains' search argument.
>>> wheel_model = project.model('Wheel')
>>> front_wheel_instances = wheel_model.instances(name__contains='Front')
'''
pass
def instances(self, **kwargs) -> Union["PartSet", List["Part"]]:
'''
Retrieve the single (expected) instance of this 'Part' (of `Category.MODEL`) as a 'Part'.
See :func:`Part.instances()` method for documentation.
:return: :class:`Part` with category `INSTANCE`
:raises NotFoundError: if the instance does not exist
:raises MultipleFoundError: if there are more than a single instance returned
'''
pass
def count_instances(self) -> int:
'''
Retrieve the number of instances of this Part model without the parts themselves.
:return: number of Part instances
:rtype
'''
pass
def count_children(self, **kwargs) -> int:
'''
Retrieve the number of child parts using a light-weight request.
:return: number of Parts
:rtype int
'''
pass
def edit(
self,
name: Optional[Union[str, Empty]] = empty,
description: Optional[Union[str, Empty]] = empty,
**kwargs,
) -> None:
'''Edit the details of a part (model or instance).
Setting an input to None will clear out the value (exception being name).
For an instance you can edit the Part instance name and the part instance description. To alter the values
of properties use :func:`Part.update()`.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:param name: optional name of the part to edit. Cannot be cleared.
:type name: basestring or None or Empty
:param description: (optional) description of the part. Can be cleared.
:type description: basestring or None or Empty
:param kwargs: (optional) additional kwargs that will be passed in the during the edit/update request
:return: None
:raises IllegalArgumentError: when the type or value of an argument provided is incorrect
:raises APIError: in case an Error occurs
Example
-------
For changing a part:
>>> front_fork = project.part('Front Fork')
>>> front_fork.edit(name='Front Fork - updated')
>>> front_fork.edit(name='Front Fork cruizer',description='With my ragtop down so my hair can blow')
for changing a model:
>>> front_fork = project.model('Front Fork')
>>> front_fork.edit(name='Front Fork basemodel',description='Some description here')
Not mentioning an input parameter in the function will leave it unchanged. Setting a parameter as None will
clear its value (where that is possible). The example below will clear the description and edit the name.
>>> front_fork.edit(name="Front spoon",description=None)
'''
pass
def proxy_model(self) -> "Part":
'''
Retrieve the proxy model of this proxied `Part` as a `Part`.
Allows you to retrieve the model of a proxy. But trying to get the catalog model of a part that
has no proxy, will raise an :exc:`NotFoundError`. Only models can have a proxy.
.. versionchanged:: 3.0
Added compatibility with KE-chain 3 backend.
:return: :class:`Part` with category `MODEL` and from which the current part is proxied
:raises NotFoundError: When no proxy model is found
Example
-------
>>> proxy_part = project.model('Proxy based on catalog model')
>>> catalog_model_of_proxy_part = proxy_part.proxy_model()
>>> proxied_material_of_the_bolt_model = project.model('Bolt Material')
>>> proxy_basis_for_the_material_model = proxied_material_of_the_bolt_model.proxy_model()
'''
pass
def add(self, model: "Part", **kwargs) -> "Part":
'''Add a new child instance, based on a model, to this part.
This can only act on instances. It needs a model from which to create the child instance.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:param model: `Part` object with category `MODEL`.
:type model: :class:`Part`
:param kwargs: (optional) additional keyword=value arguments
:return: :class:`Part` with category `INSTANCE`.
:raises APIError: if unable to add the new child instance
Example
-------
>>> bike = project.part('Bike')
>>> wheel_model = project.model('Wheel')
>>> bike.add(wheel_model)
'''
pass
def add_to(self, parent: "Part", **kwargs) -> "Part":
'''Add a new instance of this model to a part.
This works if the current part is a model and an instance of this model is to be added
to a part instances in the tree.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:param parent: part to add the new instance to
:type parent: :class:`Part`
:param kwargs: (optional) additional kwargs that will be passed in the during the edit/update request
:return: :class:`Part` with category `INSTANCE`
:raises APIError: if unable to add the new child instance
Example
-------
>>> wheel_model = project.model('wheel')
>>> bike = project.part('Bike')
>>> wheel_model.add_to(bike)
'''
pass
def add_model(self, *args, **kwargs) -> "Part":
'''Add a new child model to this model.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:return: a :class:`Part` of category `MODEL`
'''
pass
def add_proxy_to(
self,
parent: "Part",
name: str,
multiplicity: Multiplicity = Multiplicity.ONE_MANY,
**kwargs,
) -> "Part":
'''Add this model as a proxy to another parent model.
This will add the current model as a proxy model to another parent model. It ensure that it will copy the
whole subassembly to the 'parent' model.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:param name: Name of the new proxy model
:type name: basestring
:param parent: parent of the to be proxied model
:type parent: :class:`Part`
:param multiplicity: the multiplicity of the new proxy model (default ONE_MANY)
:type multiplicity: basestring or None
:param kwargs: (optional) additional kwargs that will be passed in the during the edit/update request
:return: the new proxied :class:`Part`.
:raises APIError: in case an Error occurs
Examples
--------
>>> from pykechain.enums import Multiplicity
>>> bike_model = project.model('Bike')
# find the catalog model container, the highest parent to create catalog models under
>>> catalog_model_container = project.model('Catalog container')
>>> new_wheel_model = project.create_model(catalog_model_container, 'Wheel Catalog',
... multiplicity=Multiplicity.ZERO_MANY)
>>> new_wheel_model.add_proxy_to(bike_model, "Wheel", multiplicity=Multiplicity.ONE_MANY)
'''
pass
def add_property(self, *args, **kwargs) -> "AnyProperty":
'''Add a new property to this model.
See :class:`pykechain.Client.create_property` for available parameters.
:return: :class:`Property`
:raises APIError: in case an Error occurs
'''
pass
@staticmethod
def _parse_update_dict(
part: "Part",
properties_fvalues: List[Dict[str, Any]],
update_dict: Dict,
creating: bool = False,
) -> Tuple[List[Dict], List[Dict], Dict]:
'''
Check the content of the update dict and insert them into the properties_fvalues list.
:param part: Depending on whether you add to or update a part, this is the model or the part itself, resp.
:param properties_fvalues: list of property values
:param update_dict: dictionary with property values, keyed by property names
:param creating: flag to indicate creation of new properties, hence using the `model_id` instead of `id`
:return: Tuple with 2 lists of dicts
:rtype tuple
'''
pass
def add_with_properties(
self,
model: "Part",
name: Optional[str] = None,
update_dict: Optional[Dict] = None,
properties_fvalues: Optional[List[Dict]] = None,
**kwargs,
) -> "Part":
'''
Add a new part instance of a model as a child of this part instance and update its properties in one go.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
With KE-chain 3 backends you may now provide a whole set of properties to update using a `properties_fvalues`
list of dicts. This will be merged with the `update_dict` optionally provided.
The `properties_fvalues` list is a list of dicts containing at least the `id` and a `value`, but other keys
may provided as well in the single update eg. `value_options`. Example::
`properties_fvalues = [ {"id":<uuid of prop>, "value":<new_prop_value>}, {...}, ...]`
.. versionchanged:: 3.0
Added compatibility with KE-chain 3 backend. You may provide properties_fvalues as kwarg.
Bulk option removed.
.. versionchanged:: 3.3
The 'refresh' flag is pending deprecation in version 3.4.. This flag had an effect of refreshing
the list of children of the current part and was default set to True. This resulted in large
processing times int he API as every `add_with_properties()` the children of the parent where all
retrieved. The default is now 'False'. The part just created is however to the internal list of children
once these children are retrieved earlier.
:param model: model of the part which to add a new instance, should follow the model tree in KE-chain
:type model: :class:`Part`
:param name: (optional) name provided for the new instance as string otherwise use the name of the model
:type name: basestring or None
:param update_dict: dictionary with keys being property names (str) or property_id (from the property models)
and values being property values
:type update_dict: dict or None
:param properties_fvalues: (optional) keyword argument with raw list of properties update dicts
:type properties_fvalues: list of dict or None
:param kwargs: (optional) additional keyword arguments that will be passed inside the update request
:return: the newly created :class:`Part`
:raises NotFoundError: when the property name is not a valid property of this part
:raises APIError: in case an Error occurs
:raises IllegalArgumentError: in case of illegal arguments.
Examples
--------
>>> bike = project.part('Bike')
>>> wheel_model = project.model('Wheel')
>>> bike.add_with_properties(wheel_model, 'Wooden Wheel', {'Spokes': 11, 'Material': 'Wood'})
'''
pass
def clone(self, **kwargs) -> "Part":
'''
Clone a part.
An optional name of the cloned part may be provided. If not provided the name will be set
to "CLONE - <part name>". (available for KE-chain 3 backends only)
An optional multiplicity, may be added as paremeter for the cloning of models. If not
provided the multiplicity of the part will be used. (available for KE-chain 3 backends only)
.. versionadded:: 2.3
.. versionchanged:: 3.0
Added optional paramenters the name and multiplicity for KE-chain 3 backends.
:param kwargs: (optional) additional keyword=value arguments
:return: cloned :class:`models.Part`
:raises APIError: if the `Part` could not be cloned
Example
-------
>>> bike = project.model('Bike')
>>> bike2 = bike.clone()
For KE-chain 3 backends
>>> bike = project.model('Bike')
>>> bike2 = bike.clone(name='Trike', multiplicity=Multiplicity.ZERO_MANY)
'''
pass
def copy(
self,
target_parent: "Part",
name: Optional[str] = None,
include_children: bool = True,
include_instances: bool = True,
) -> "Part":
'''
Copy the `Part` to target parent, both of them having the same category.
.. versionadded:: 2.3
:param target_parent: `Part` object under which the desired `Part` is copied
:type target_parent: :class:`Part`
:param name: how the copied top-level `Part` should be called
:type name: basestring
:param include_children: True to copy also the descendants of `Part`.
:type include_children: bool
:param include_instances: True to copy also the instances of `Part` to ALL the instances of target_parent.
:type include_instances: bool
:returns: copied :class:`Part` model.
:raises IllegalArgumentError: if part and target_parent have different `Category`
:raises IllegalArgumentError: if part and target_parent are identical
Example
-------
>>> model_to_copy = project.model(name='Model to be copied')
>>> bike = project.model('Bike')
>>> model_to_copy.copy(target_parent=bike, name='Copied model',
>>> include_children=True,
>>> include_instances=True)
'''
pass
def move(
self,
target_parent: "Part",
name: Optional[str] = None,
include_children: bool = True,
include_instances: bool = True,
) -> "Part":
'''
Move the `Part` to target parent, both of them the same category.
.. versionadded:: 2.3
:param target_parent: `Part` object under which the desired `Part` is moved
:type target_parent: :class:`Part`
:param name: how the moved top-level `Part` should be called
:type name: basestring
:param include_children: True to move also the descendants of `Part`. If False, the children will be lost.
:type include_children: bool
:param include_instances: True to move also the instances of `Part` to ALL the instances of target_parent.
:type include_instances: bool
:returns: moved :class:`Part` model.
:raises IllegalArgumentError: if part and target_parent have different `Category`
:raises IllegalArgumentError: if target_parent is descendant of part
Example
-------
>>> model_to_move = project.model(name='Model to be moved')
>>> bike = project.model('Bike')
>>> model_to_move.move(target_parent=bike, name='Moved model',
>>> include_children=True,
>>> include_instances=True)
'''
pass
def update(
self,
name: Optional[str] = None,
update_dict: Optional[Dict] = None,
properties_fvalues: Optional[List[Dict]] = None,
**kwargs,
) -> None:
'''
Edit part name and property values in one go.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
With KE-chain 3 backends you may now provide a whole set of properties to update using a `properties_fvalues`
list of dicts. This will be merged with the `update_dict` optionally provided.
The `properties_fvalues` list is a list of dicts containing at least the `id` and a `value`, but other keys
may provided as well in the single update eg. `value_options`. Example::
`properties_fvalues = [ {"id":<uuid of prop>, "value":<new_prop_value>}, {...}, ...]`
.. versionchanged:: 3.0
Added compatibility with KE-chain 3 backend. You may provide properties_fvalues as kwarg.
Bulk option removed.
:param name: new part name (defined as a string)
:type name: basestring or None
:param update_dict: dictionary with keys being property names (str) or property ids (uuid)
and values being property values
:type update_dict: dict or None
:param properties_fvalues: (optional) keyword argument with raw list of properties update dicts
:type properties_fvalues: list of dict or None
:param kwargs: additional keyword-value arguments that will be passed into the part update request.
:return: the updated :class:`Part`
:raises NotFoundError: when the property name is not a valid property of this part
:raises IllegalArgumentError: when the type or value of an argument provided is incorrect
:raises APIError: in case an Error occurs
Example
-------
>>> bike = project.part('Bike')
>>> bike.update(name='Good name', update_dict={'Gears': 11, 'Total Height': 56.3})
Example with properties_fvalues: <pyke Part 'Copied model under Bike' id 95d35be6>
>>> bike = project.part('Bike')
>>> bike.update(name='Good name',
... properties_fvalues=[{'id': '95d35be6...', 'value': 11},
... {'id': '7893cba4...', 'value': 56.3, 'value_options': {...}})
'''
pass
def delete(self) -> None:
'''Delete this part.
:return: None
:raises APIError: in case an Error occurs
'''
pass
def order_properties(
self, property_list: Optional[List[Union["AnyProperty", str]]] = None
) -> None:
'''
Order the properties of a part model using a list of property objects or property names or property id's.
For KE-chain 3 backends, the order can also directly provided as a unique integer for each property in the
`Part.update()` function if you provide the `properties_fvalues` list of dicts yourself. For more information
please refer to the `Part.update()` documentation.
.. versionchanged:: 3.0
For KE-chain 3 backend the `Part.update()` method is used with a properties_fvalues list of dicts.
:param property_list: ordered list of property names (basestring) or property id's (uuid) or
a `Property` object.
:type property_list: list(basestring)
:returns: the :class:`Part` with the reordered list of properties
:raises APIError: when an Error occurs
:raises IllegalArgumentError: When provided a wrong argument
Examples
--------
>>> front_fork = project.model('Front Fork')
>>> front_fork.order_properties(['Material', 'Height (mm)', 'Color'])
>>> front_fork = project.model('Front Fork')
>>> material = front_fork.property('Material')
>>> height = front_fork.property('Height (mm)')
>>> color = front_fork.property('Color')
>>> front_fork.order_properties([material, height, color])
Alternatively you may use the `Part.update()` function to directly alter the order of the properties and
eventually even more (defaut) model values.
>>> front_fork.update(properties_fvalues= [{'id': material.id, 'order':10},
... {'id': height.id, 'order': 20, 'value':13.37}
... {'id': color.id, 'order': 30, 'name': 'Colour'}])
'''
pass
def _repr_html_(self) -> str:
'''
Represent the part in a HTML table for the use in notebooks.
:return: html text
:rtype: Text
'''
pass
def as_dict(self) -> Dict:
'''
Retrieve the properties of a part inside a dict in this structure: {property_name: property_value}.
.. versionadded:: 1.9
:returns: the values of the properties as a `dict`
:rtype: dict
Example
-------
>>> front_wheel = project.part('Front Wheel')
>>> front_wheel_properties = front_wheel.as_dict()
{'Diameter': 60.8,
'Spokes': 24,
'Rim Material': 'Aluminium',
'Tire Thickness': 4.2}
'''
pass
| 35 | 34 | 33 | 6 | 13 | 15 | 3 | 1.27 | 1 | 19 | 11 | 0 | 32 | 12 | 33 | 69 | 1,211 | 243 | 430 | 149 | 343 | 546 | 243 | 97 | 207 | 8 | 5 | 3 | 90 |
140,868 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property.py
|
pykechain.models.property.Property
|
class Property(BaseInScope):
"""A virtual object representing a KE-chain property.
.. versionadded: 3.0
This is a `Property` to communicate with a KE-chain 3 backend.
:cvar bulk_update: flag to postpone update of properties until manually requested
:type bulk_update: bool
:ivar type: The property type of the property. One of the types described in :class:`pykechain.enums.PropertyType`
:type type: str
:ivar category: The category of the property, either `Category.MODEL` of `Category.INSTANCE`
:type category: str
:ivar description: description of the property
:type description: str or None
:ivar unit: unit of measure of the property
:type unit: str or None
:ivar model: the id of the model (not the model object)
:type model: str
:ivar output: a boolean if the value is configured as an output (in an activity)
:type output: bool
:ivar part: The (parent) part in which this property is available
:type part: :class:`Part`
:ivar value: the property value, can be set as well as property
:type value: Any
:ivar validators: the list of validators that are available in the property
:type validators: List[PropertyValidator]
:ivar is_valid: if the property conforms to the validators
:type is_valid: bool
:ivar is_invalid: if the property does not conform to the validator
:type is_invalid: bool
"""
_USE_BULK_UPDATE = False
_update_package = dict()
def __init__(self, json, **kwargs):
"""Construct a Property from a json object."""
super().__init__(json, **kwargs)
self.output: bool = json.get("output")
self.model_id: Optional[str] = json.get("model_id")
self.part_id = json.get("part_id")
self.ref = json.get("ref")
self.type = json.get("property_type")
self.category = json.get("category")
self.description = json.get("description", None)
self.unit = json.get("unit", None)
self.order = json.get("order")
# Create protected variables
self._value: Any = json.get("value")
self._options: Dict = json.get("value_options", {})
self._part: Optional["Part"] = None
self._model: Optional["Property"] = None
self._validators: List[PropertyValidator] = []
self._validation_results: List = []
self._validation_reasons: List = []
self._representations_container = RepresentationsComponent(
self,
self._options.get("representations", {}),
self._save_representations,
)
if "validators" in self._options:
self._parse_validators()
def _options_valid(self) -> bool:
"""Validate the options of the Property object.
It will validate if the Property options are valid against the options JSON schema.
:raises jsonschema.exceptions.ValidationError: if the options value is invalid
:raises jsonschema.exceptions.SchemaError: if the JSON schema of the options is invalid
:returns: Boolean True if valid
"""
validate(self._options, options_json_schema)
return True
def refresh(
self,
json: Optional[Dict] = None,
url: Optional[str] = None,
extra_params: Optional = None,
) -> None:
"""Refresh the object in place."""
super().refresh(
json=json,
url=self._client._build_url("property", property_id=self.id),
extra_params=API_EXTRA_PARAMS["property"],
)
def has_value(self) -> bool:
"""Predicate to indicate if the property has a value set.
This predicate determines if the property has a value set. It will not make a call to KE-chain API (in case
of reference properties). So it is a tiny fraction 'cheaper' in terms of processing time than checking the
`Property.value` itself.
It will return True if the property_type is a Boolean and set to a value of False.
:returns: True if the property has a value set, otherwise (also when value is None) returns False
:rtype: Bool
"""
if isinstance(self._value, (float, int, bool)):
return True # to prevent "bool(0.00) = False" or "False = False"
else:
return bool(self._value)
@property
def use_bulk_update(self):
"""Set or get the toggle to asynchronously update property values."""
# set the class attribute to make this value a singleton
return self.__class__._USE_BULK_UPDATE
@use_bulk_update.setter
def use_bulk_update(self, value):
self.__class__.set_bulk_update(value)
@classmethod
def set_bulk_update(cls, value):
"""Set global class attribute to toggle the use of bulk-updates of properties."""
assert isinstance(value, bool), (
f"`bulk_update` must be set to a boolean, not {type(value)}"
)
cls._USE_BULK_UPDATE = value
@property
def value(self) -> Any:
"""Retrieve the data value of a property.
Setting this value will immediately update the property in KE-chain.
:returns: the value
"""
return self._value
@value.setter
def value(self, value: Any) -> None:
value = self.serialize_value(value)
# check if the options are valid
self._options_valid()
if self.use_bulk_update:
self._pend_update(dict(value=value))
self._value = value
else:
self._put_value(value)
@classmethod
def update_values(cls, client: "Client", use_bulk_update: bool = False) -> None:
"""
Perform the bulk update of property values using the stored values in the `Property` class.
:param client: Client object
:type client: Client
:param use_bulk_update: set the class attribute, defaults to False.
:type use_bulk_update: bool
:return: None
"""
if cls._USE_BULK_UPDATE:
properties = [
dict(id=key, **values) for key, values in cls._update_package.items()
]
client.update_properties(properties=properties)
cls._update_package = dict()
cls.set_bulk_update(use_bulk_update)
def _pend_update(self, data):
"""Store the value to be send at a later point in time using `update_values`."""
existing_data = self.__class__._update_package.get(self.id, None)
if existing_data:
existing_data.update(data)
else:
self.__class__._update_package[self.id] = data
def _put_value(self, value):
"""Send the value to KE-chain."""
url = self._client._build_url("property", property_id=self.id)
response = self._client._request(
"PUT", url, params=API_EXTRA_PARAMS["property"], json={"value": value}
)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Property {self}", response=response)
self.refresh(json=response.json()["results"][0])
def serialize_value(self, value: [T]) -> T:
"""
Serialize the value to be set on the property.
:param value: non-serialized value
:type value: Any
:return: serialized value
"""
return value.id if isinstance(value, Base) else value
@property
def part(self) -> "Part":
"""
Retrieve the part that holds this Property.
:returns: The :class:`Part` associated to this property
:raises APIError: if the `Part` is not found
"""
if self._part is None:
self._part = self._client.part(pk=self.part_id, category=self.category)
return self._part
def model(self) -> "AnyProperty":
"""
Model object of the property if the property is an instance otherwise itself.
Will cache the model object in order to not generate too many API calls. Otherwise will make an API call
to the backend to retrieve its model object.
:return: `Property` model object if the current `Property` is an instance.
:rtype: :class:`pykechain.models.AnyProperty`
"""
if self.category == Category.MODEL:
return self
elif self._model is None:
self._model = self._client.property(
pk=self.model_id, category=Category.MODEL
)
return self._model
@property
def validators(self):
"""Provide list of Validator objects.
:returns: list of :class:`PropertyValidator` objects
:rtype: list(PropertyValidator)
"""
return self._validators
@validators.setter
def validators(self, validators: Iterable[PropertyValidator]) -> None:
if self.category != Category.MODEL:
raise IllegalArgumentError(
"To update the list of validators, it can only work on "
"`Property` of category 'MODEL'"
)
if not isinstance(validators, (tuple, list)) or not all(
isinstance(v, PropertyValidator) for v in validators
):
raise IllegalArgumentError(
"Should be a list or tuple with PropertyValidator objects, got {}".format(
type(validators)
)
)
for validator in validators:
validator.validate_json()
# set the internal validators list
self._validators = list(set(validators))
# dump to _json options
self._dump_validators()
# update the options to KE-chain backend
self.edit(options=self._options)
def _parse_validators(self):
"""Parse the validator in the options to validators."""
self._validators = []
validators_json = self._options.get("validators")
for validator_json in validators_json:
self._validators.append(PropertyValidator.parse(json=validator_json))
def _dump_validators(self):
"""Dump the validators as json inside the _options dictionary with the key `validators`."""
validators_json = []
for validator in self._validators:
if isinstance(validator, PropertyValidator):
validators_json.append(validator.as_json())
else:
raise APIError(f"validator is not a PropertyValidator: '{validator}'")
if self._options.get("validators", list()) == validators_json:
# no change
pass
else:
new_options = self._options.copy() # make a copy
new_options.update({"validators": validators_json})
validate(new_options, options_json_schema)
self._options = new_options
@property
def is_valid(self) -> Optional[bool]:
"""Determine if the value in the property is valid.
If the value of the property is validated as 'valid', than returns a True, otherwise a False.
When no validators are configured, returns a None. It checks against all configured validators
and returns a single boolean outcome.
:returns: True when the `value` is valid
:rtype: bool or None
"""
if not self._validators:
return None
else:
self.validate(reason=False)
if all([vr is None for vr in self._validation_results]):
return None
else:
return all(self._validation_results)
@property
def is_invalid(self) -> Optional[bool]:
"""Determine if the value in the property is invalid.
If the value of the property is validated as 'invalid', than returns a True, otherwise a False.
When no validators are configured, returns a None. It checks against all configured validators
and returns a single boolean outcome.
:returns: True when the `value` is invalid
:rtype: bool
"""
return not self.is_valid if self.is_valid is not None else None
def validate(self, reason: bool = True) -> List[Union[bool, Tuple]]:
"""Return the validation results and include an (optional) reason.
If reason keyword is true, the validation is returned for each validation
the [(<result: bool>, <reason:str>), ...]. If reason is False, only a single list of validation results
for each configured validator is returned.
:param reason: (optional) switch to indicate if the reason of the validation should be provided
:type reason: bool
:return: list of validation results [bool, bool, ...] or
a list of validation results, reasons [(bool, str), ...]
:rtype: list(bool) or list((bool, str))
:raises Exception: for incorrect validators or incompatible values
"""
self._validation_results = [
validator.is_valid(self._value) for validator in self._validators
]
self._validation_reasons = [
validator.get_reason() for validator in self._validators
]
if reason:
return list(zip(self._validation_results, self._validation_reasons))
else:
return self._validation_results
def has_validator(self, validator_klass: Type[PropertyValidator]) -> bool:
"""
Check if any validator matches the given class.
:param validator_klass: The class of the validator to check.
:type validator_klass: Type[PropertyValidator]
:return: True if a matching validator exists, False otherwise.
:rtype: bool
"""
return any(
isinstance(validator, validator_klass) for validator in self._validators
)
@property
def representations(self):
"""Get and set the property representations."""
return self._representations_container.get_representations()
@representations.setter
def representations(self, value):
if self.category != Category.MODEL:
raise IllegalArgumentError(
"To update the list of representations, it can only work on a "
"`Property` of category '{}'".format(Category.MODEL)
)
self._representations_container.set_representations(value)
def _save_representations(self, representation_options):
self._options.update({"representations": representation_options})
self.edit(options=self._options)
@classmethod
def create(cls, json: dict, **kwargs) -> "AnyProperty":
"""Create a property based on the json data.
This method will attach the right class to a property, enabling the use of type-specific methods.
It does not create a property object in KE-chain. But a pseudo :class:`Property` object.
:param json: the json from which the :class:`Property` object to create
:type json: dict
:return: a :class:`Property` object
"""
property_type = json.get("property_type")
from pykechain.models import property_type_to_class_map
# Get specific Property subclass, defaulting to Property itself
property_class = property_type_to_class_map.get(property_type, Property)
# Call constructor and return new object
return property_class(json, **kwargs)
def edit(
self,
name: Optional[str] = empty,
description: Optional[str] = empty,
unit: Optional[str] = empty,
options: Optional[Dict] = empty,
**kwargs,
) -> None:
"""Edit the details of a property (model).
Setting an input to None will clear out the value (exception being name).
:param name: (optional) new name of the property to edit. Cannot be cleared.
:type name: basestring or None or Empty
:param description: (optional) new description of the property. Can be cleared.
:type description: basestring or None or Empty
:param unit: (optional) new unit of the property. Can be cleared.
:type unit: basestring or None or Empty
:param options: (options) new options of the property. Can be cleared.
:type options: dict or None or Empty
:param kwargs: (optional) additional kwargs to be edited
:return: None
:raises APIError: When unable to edit the property
:raises IllegalArgumentError: when the type of the input is provided incorrect.
Examples
--------
>>> front_fork = project.part('Front Fork')
>>> color_property = front_fork.property(name='Color')
>>> color_property.edit(name='Shade',description='Could also be called tint, depending on mixture',unit='RGB')
>>> wheel_property_reference = self.project.model('Bike').property('Reference wheel')
>>> wheel_model = self.project.model('Wheel')
>>> diameter_property = wheel_model.property('Diameter')
>>> spokes_property = wheel_model.property('Spokes')
>>> prefilters = {'property_value': diameter_property.id + ":{}:lte".format(15)}
>>> propmodels_excl = [spokes_property.id]
>>> options = dict()
>>> options['prefilters'] = prefilters
>>> options['propmodels_excl'] = propmodels_excl
>>> wheel_property_reference.edit(options=options)
Not mentioning an input parameter in the function will leave it unchanged. Setting a parameter as None will
clear its value (where that is possible). The example below will clear the description, but leave everything
else unchanged.
>>> wheel_property.edit(description=None)
"""
update_dict = {
"name": check_text(name, "name") or self.name,
"description": check_text(description, "description") or "",
"unit": check_text(unit, "unit") or "",
"value_options": check_type(options, dict, "options") or dict(),
}
if kwargs: # pragma: no cover
update_dict.update(kwargs)
update_dict = clean_empty_values(update_dict=update_dict)
if self.use_bulk_update:
self._pend_update(data=update_dict)
else:
update_dict["id"] = self.id
response = self._client._request(
"PUT",
self._client._build_url("property", property_id=self.id),
params=API_EXTRA_PARAMS["property"],
json=update_dict,
)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Property {self}", response=response)
self.refresh(json=response.json()["results"][0])
def delete(self) -> None:
"""Delete this property.
:return: None
:raises APIError: if delete was not successful
"""
response = self._client._request(
"DELETE", self._client._build_url("property", property_id=self.id)
)
if response.status_code != requests.codes.no_content: # pragma: no cover
raise APIError(f"Could not delete Property {self}", response=response)
def copy(self, target_part: "Part", name: Optional[str] = None) -> "Property":
"""Copy a property model or instance.
:param target_part: `Part` object under which the desired `Property` is copied
:type target_part: :class:`Part`
:param name: how the copied `Property` should be called
:type name: basestring
:return: copied :class:`Property` model.
:raises IllegalArgumentError: if property and target_part have different `Category`
Example
-------
>>> property_to_copy = client.property(name='Diameter')
>>> bike = client.model('Bike')
>>> property_to_copy.copy(target_part=bike, name='Bike diameter?')
"""
from pykechain.models import Part
check_type(target_part, Part, "target_part")
name = check_text(name, "name") or self.name
if self.category == Category.MODEL and target_part.category == Category.MODEL:
# Cannot move a `Property` model under a `Part` instance or vice versa
copied_property_model = target_part.add_property(
name=name,
property_type=self.type,
description=self.description,
unit=self.unit,
default_value=self.value,
options=self._options,
)
return copied_property_model
elif (
self.category == Category.INSTANCE
and target_part.category == Category.INSTANCE
):
target_model = target_part.model()
self_model = self.model()
target_model.add_property(
name=name,
property_type=self_model.type,
description=self_model.description,
unit=self_model.unit,
default_value=self_model.value,
options=self_model._options,
)
target_part.refresh()
copied_property_instance = target_part.property(name=name)
copied_property_instance.value = self.value
return copied_property_instance
else:
raise IllegalArgumentError(
'property "{}" and target part "{}" must have the same category'.format(
self.name, target_part.name
)
)
def move(self, target_part: "Part", name: Optional[str] = None) -> "Property":
"""Move a property model or instance.
:param target_part: `Part` object under which the desired `Property` is moved
:type target_part: :class:`Part`
:param name: how the moved `Property` should be called
:type name: basestring
:return: copied :class:`Property` model.
:raises IllegalArgumentError: if property and target_part have different `Category`
Example
-------
>>> property_to_move = client.property(name='Diameter')
>>> bike = client.model('Bike')
>>> property_to_move.move(target_part=bike, name='Bike diameter?')
"""
moved_property = self.copy(target_part=target_part, name=name)
if self.category == Category.MODEL:
self.delete()
else:
self.model().delete()
return moved_property
|
class Property(BaseInScope):
'''A virtual object representing a KE-chain property.
.. versionadded: 3.0
This is a `Property` to communicate with a KE-chain 3 backend.
:cvar bulk_update: flag to postpone update of properties until manually requested
:type bulk_update: bool
:ivar type: The property type of the property. One of the types described in :class:`pykechain.enums.PropertyType`
:type type: str
:ivar category: The category of the property, either `Category.MODEL` of `Category.INSTANCE`
:type category: str
:ivar description: description of the property
:type description: str or None
:ivar unit: unit of measure of the property
:type unit: str or None
:ivar model: the id of the model (not the model object)
:type model: str
:ivar output: a boolean if the value is configured as an output (in an activity)
:type output: bool
:ivar part: The (parent) part in which this property is available
:type part: :class:`Part`
:ivar value: the property value, can be set as well as property
:type value: Any
:ivar validators: the list of validators that are available in the property
:type validators: List[PropertyValidator]
:ivar is_valid: if the property conforms to the validators
:type is_valid: bool
:ivar is_invalid: if the property does not conform to the validator
:type is_invalid: bool
'''
def __init__(self, json, **kwargs):
'''Construct a Property from a json object.'''
pass
def _options_valid(self) -> bool:
'''Validate the options of the Property object.
It will validate if the Property options are valid against the options JSON schema.
:raises jsonschema.exceptions.ValidationError: if the options value is invalid
:raises jsonschema.exceptions.SchemaError: if the JSON schema of the options is invalid
:returns: Boolean True if valid
'''
pass
def refresh(
self,
json: Optional[Dict] = None,
url: Optional[str] = None,
extra_params: Optional = None,
) -> None:
'''Refresh the object in place.'''
pass
def has_value(self) -> bool:
'''Predicate to indicate if the property has a value set.
This predicate determines if the property has a value set. It will not make a call to KE-chain API (in case
of reference properties). So it is a tiny fraction 'cheaper' in terms of processing time than checking the
`Property.value` itself.
It will return True if the property_type is a Boolean and set to a value of False.
:returns: True if the property has a value set, otherwise (also when value is None) returns False
:rtype: Bool
'''
pass
@property
def use_bulk_update(self):
'''Set or get the toggle to asynchronously update property values.'''
pass
@use_bulk_update.setter
def use_bulk_update(self):
pass
@classmethod
def set_bulk_update(cls, value):
'''Set global class attribute to toggle the use of bulk-updates of properties.'''
pass
@property
def value(self) -> Any:
'''Retrieve the data value of a property.
Setting this value will immediately update the property in KE-chain.
:returns: the value
'''
pass
@value.setter
def value(self) -> Any:
pass
@classmethod
def update_values(cls, client: "Client", use_bulk_update: bool = False) -> None:
'''
Perform the bulk update of property values using the stored values in the `Property` class.
:param client: Client object
:type client: Client
:param use_bulk_update: set the class attribute, defaults to False.
:type use_bulk_update: bool
:return: None
'''
pass
def _pend_update(self, data):
'''Store the value to be send at a later point in time using `update_values`.'''
pass
def _put_value(self, value):
'''Send the value to KE-chain.'''
pass
def serialize_value(self, value: [T]) -> T:
'''
Serialize the value to be set on the property.
:param value: non-serialized value
:type value: Any
:return: serialized value
'''
pass
@property
def part(self) -> "Part":
'''
Retrieve the part that holds this Property.
:returns: The :class:`Part` associated to this property
:raises APIError: if the `Part` is not found
'''
pass
def model(self) -> "AnyProperty":
'''
Model object of the property if the property is an instance otherwise itself.
Will cache the model object in order to not generate too many API calls. Otherwise will make an API call
to the backend to retrieve its model object.
:return: `Property` model object if the current `Property` is an instance.
:rtype: :class:`pykechain.models.AnyProperty`
'''
pass
@property
def validators(self):
'''Provide list of Validator objects.
:returns: list of :class:`PropertyValidator` objects
:rtype: list(PropertyValidator)
'''
pass
@validators.setter
def validators(self):
pass
def _parse_validators(self):
'''Parse the validator in the options to validators.'''
pass
def _dump_validators(self):
'''Dump the validators as json inside the _options dictionary with the key `validators`.'''
pass
@property
def is_valid(self) -> Optional[bool]:
'''Determine if the value in the property is valid.
If the value of the property is validated as 'valid', than returns a True, otherwise a False.
When no validators are configured, returns a None. It checks against all configured validators
and returns a single boolean outcome.
:returns: True when the `value` is valid
:rtype: bool or None
'''
pass
@property
def is_invalid(self) -> Optional[bool]:
'''Determine if the value in the property is invalid.
If the value of the property is validated as 'invalid', than returns a True, otherwise a False.
When no validators are configured, returns a None. It checks against all configured validators
and returns a single boolean outcome.
:returns: True when the `value` is invalid
:rtype: bool
'''
pass
def validate(self, reason: bool = True) -> List[Union[bool, Tuple]]:
'''Return the validation results and include an (optional) reason.
If reason keyword is true, the validation is returned for each validation
the [(<result: bool>, <reason:str>), ...]. If reason is False, only a single list of validation results
for each configured validator is returned.
:param reason: (optional) switch to indicate if the reason of the validation should be provided
:type reason: bool
:return: list of validation results [bool, bool, ...] or
a list of validation results, reasons [(bool, str), ...]
:rtype: list(bool) or list((bool, str))
:raises Exception: for incorrect validators or incompatible values
'''
pass
def has_validator(self, validator_klass: Type[PropertyValidator]) -> bool:
'''
Check if any validator matches the given class.
:param validator_klass: The class of the validator to check.
:type validator_klass: Type[PropertyValidator]
:return: True if a matching validator exists, False otherwise.
:rtype: bool
'''
pass
@property
def representations(self):
'''Get and set the property representations.'''
pass
@representations.setter
def representations(self):
pass
def _save_representations(self, representation_options):
pass
@classmethod
def create(cls, json: dict, **kwargs) -> "AnyProperty":
'''Create a property based on the json data.
This method will attach the right class to a property, enabling the use of type-specific methods.
It does not create a property object in KE-chain. But a pseudo :class:`Property` object.
:param json: the json from which the :class:`Property` object to create
:type json: dict
:return: a :class:`Property` object
'''
pass
def edit(
self,
name: Optional[str] = empty,
description: Optional[str] = empty,
unit: Optional[str] = empty,
options: Optional[Dict] = empty,
**kwargs,
) -> None:
'''Edit the details of a property (model).
Setting an input to None will clear out the value (exception being name).
:param name: (optional) new name of the property to edit. Cannot be cleared.
:type name: basestring or None or Empty
:param description: (optional) new description of the property. Can be cleared.
:type description: basestring or None or Empty
:param unit: (optional) new unit of the property. Can be cleared.
:type unit: basestring or None or Empty
:param options: (options) new options of the property. Can be cleared.
:type options: dict or None or Empty
:param kwargs: (optional) additional kwargs to be edited
:return: None
:raises APIError: When unable to edit the property
:raises IllegalArgumentError: when the type of the input is provided incorrect.
Examples
--------
>>> front_fork = project.part('Front Fork')
>>> color_property = front_fork.property(name='Color')
>>> color_property.edit(name='Shade',description='Could also be called tint, depending on mixture',unit='RGB')
>>> wheel_property_reference = self.project.model('Bike').property('Reference wheel')
>>> wheel_model = self.project.model('Wheel')
>>> diameter_property = wheel_model.property('Diameter')
>>> spokes_property = wheel_model.property('Spokes')
>>> prefilters = {'property_value': diameter_property.id + ":{}:lte".format(15)}
>>> propmodels_excl = [spokes_property.id]
>>> options = dict()
>>> options['prefilters'] = prefilters
>>> options['propmodels_excl'] = propmodels_excl
>>> wheel_property_reference.edit(options=options)
Not mentioning an input parameter in the function will leave it unchanged. Setting a parameter as None will
clear its value (where that is possible). The example below will clear the description, but leave everything
else unchanged.
>>> wheel_property.edit(description=None)
'''
pass
def delete(self) -> None:
'''Delete this property.
:return: None
:raises APIError: if delete was not successful
'''
pass
def copy(self, target_part: "Part", name: Optional[str] = None) -> "Property":
'''Copy a property model or instance.
:param target_part: `Part` object under which the desired `Property` is copied
:type target_part: :class:`Part`
:param name: how the copied `Property` should be called
:type name: basestring
:return: copied :class:`Property` model.
:raises IllegalArgumentError: if property and target_part have different `Category`
Example
-------
>>> property_to_copy = client.property(name='Diameter')
>>> bike = client.model('Bike')
>>> property_to_copy.copy(target_part=bike, name='Bike diameter?')
'''
pass
def move(self, target_part: "Part", name: Optional[str] = None) -> "Property":
'''Move a property model or instance.
:param target_part: `Part` object under which the desired `Property` is moved
:type target_part: :class:`Part`
:param name: how the moved `Property` should be called
:type name: basestring
:return: copied :class:`Property` model.
:raises IllegalArgumentError: if property and target_part have different `Category`
Example
-------
>>> property_to_move = client.property(name='Diameter')
>>> bike = client.model('Bike')
>>> property_to_move.move(target_part=bike, name='Bike diameter?')
'''
pass
| 46 | 27 | 16 | 2 | 8 | 6 | 2 | 0.73 | 1 | 17 | 5 | 2 | 28 | 18 | 31 | 38 | 577 | 99 | 280 | 100 | 220 | 204 | 174 | 73 | 140 | 4 | 2 | 2 | 60 |
140,869 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property2.py
|
pykechain.models.property2.Property2
|
class Property2(Property, _DeprecationMixin):
"""A virtual object representing a KE-chain property.
.. versionadded: 3.0
This is a `Property` to communicate with a KE-chain 3 backend.
:cvar bulk_update: flag to postpone update of properties until manually requested
:type bulk_update: bool
:ivar type: The property type of the property. One of the types described in :class:`pykechain.enums.PropertyType`
:type type: str
:ivar category: The category of the property, either `Category.MODEL` of `Category.INSTANCE`
:type category: str
:ivar description: description of the property
:type description: str or None
:ivar unit: unit of measure of the property
:type unit: str or None
:ivar model: the id of the model (not the model object)
:type model: str
:ivar output: a boolean if the value is configured as an output (in an activity)
:type output: bool
:ivar part: The (parent) part in which this property is available
:type part: :class:`Part2`
:ivar value: the property value, can be set as well as property
:type value: Any
:ivar validators: the list of validators that are available in the property
:type validators: List[PropertyValidator]
:ivar is_valid: if the property conforms to the validators
:type is_valid: bool
:ivar is_invalid: if the property does not conform to the validator
:type is_invalid: bool
"""
pass
|
class Property2(Property, _DeprecationMixin):
'''A virtual object representing a KE-chain property.
.. versionadded: 3.0
This is a `Property` to communicate with a KE-chain 3 backend.
:cvar bulk_update: flag to postpone update of properties until manually requested
:type bulk_update: bool
:ivar type: The property type of the property. One of the types described in :class:`pykechain.enums.PropertyType`
:type type: str
:ivar category: The category of the property, either `Category.MODEL` of `Category.INSTANCE`
:type category: str
:ivar description: description of the property
:type description: str or None
:ivar unit: unit of measure of the property
:type unit: str or None
:ivar model: the id of the model (not the model object)
:type model: str
:ivar output: a boolean if the value is configured as an output (in an activity)
:type output: bool
:ivar part: The (parent) part in which this property is available
:type part: :class:`Part2`
:ivar value: the property value, can be set as well as property
:type value: Any
:ivar validators: the list of validators that are available in the property
:type validators: List[PropertyValidator]
:ivar is_valid: if the property conforms to the validators
:type is_valid: bool
:ivar is_invalid: if the property does not conform to the validator
:type is_invalid: bool
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 14 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 33 | 3 | 2 | 1 | 1 | 28 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
140,870 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property2_activity_reference.py
|
pykechain.models.property2_activity_reference.ActivityReferencesProperty2
|
class ActivityReferencesProperty2(ActivityReferencesProperty, _DeprecationMixin):
"""A virtual object representing a KE-chain Activity References property.
.. versionadded:: 3.7
"""
pass
|
class ActivityReferencesProperty2(ActivityReferencesProperty, _DeprecationMixin):
'''A virtual object representing a KE-chain Activity References property.
.. versionadded:: 3.7
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 33 | 7 | 2 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 6 | 0 | 0 |
140,871 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property2_attachment.py
|
pykechain.models.property2_attachment.AttachmentProperty2
|
class AttachmentProperty2(AttachmentProperty, _DeprecationMixin):
"""A virtual object representing a KE-chain attachment property."""
pass
|
class AttachmentProperty2(AttachmentProperty, _DeprecationMixin):
'''A virtual object representing a KE-chain attachment property.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 50 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
140,872 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property2_datetime.py
|
pykechain.models.property2_datetime.DatetimeProperty2
|
class DatetimeProperty2(DatetimeProperty, _DeprecationMixin):
"""A virtual object representing a KE-chain datetime property."""
pass
|
class DatetimeProperty2(DatetimeProperty, _DeprecationMixin):
'''A virtual object representing a KE-chain datetime property.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 2 | 0 | 0 |
140,873 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/notification.py
|
pykechain.models.notification.Notification
|
class Notification(Base):
"""A virtual object representing a KE-chain notification.
:ivar id: UUID of the notification
:type id: basestring
:ivar subject: subject of the notification
:type subject: basestring or None
:ivar created_at: the datetime when the object was created if available (otherwise None)
:type created_at: datetime or None
:ivar updated_at: the datetime when the object was last updated if available (otherwise None)
:type updated_at: datetime or None
:ivar status: The status of the notification (see :class:`pykechain.enums.NotificationStatus`)
:type status: basestring or None
:ivar event: The event of the notification (see :class:`pykechain.enums.NotificationEvent`)
:type event: basestring or None
:ivar recipient_users: The list of ids of the users
:type recipient_users: List[User ids]
"""
def __init__(self, json: Dict, **kwargs) -> None:
"""Construct a notification from a KE-chain 2 json response.
:param json: the json response to construct the :class:`Notification` from
:type json: dict
"""
super().__init__(json, **kwargs)
self.message = json.get("message", "")
self.subject: str = json.get("subject", "")
self.status: str = json.get("status", "")
self.event: str = json.get("event", "")
self.channels: List = json.get("channels", list())
self.recipient_user_ids: List = json.get("recipient_users", list())
self.team_id: str = json.get("team", "")
self.from_user_id: str = json.get("from_user", "")
self._from_user: Optional["User"] = None
self._recipient_users: Optional[List["User"]] = None
self._team: Optional["Team"] = None
def __repr__(self): # pragma: no cover
return f"<pyke Notification id {self.id[-8:]}>"
def get_recipient_users(self) -> List["User"]:
"""Return the list of actual `User` objects based on recipient_users_ids."""
if self._recipient_users is None:
self._recipient_users = self._client.users(
id__in=",".join([str(pk) for pk in self.recipient_user_ids])
)
return self._recipient_users
def get_from_user(self) -> "User":
"""Return the actual `User` object based on the from_user_id."""
if self._from_user is None and self.from_user_id:
self._from_user = self._client.user(pk=self.from_user_id)
return self._from_user
def get_team(self) -> "Team":
"""Return the actual `Team` object based on the team_id."""
if self._team is None and self.team_id:
self._team = self._client.team(pk=self.team_id)
return self._team
def delete(self):
"""Delete the notification."""
return self._client.delete_notification(notification=self)
def edit(
self,
subject: Optional[Union[str, Empty]] = empty,
message: Optional[Union[str, Empty]] = empty,
status: Optional[Union[NotificationStatus, Empty]] = empty,
recipients: Optional[Union[List[Union["User", str, int]], Empty]] = empty,
team: Optional[Union["Team", str, Empty]] = empty,
from_user: Optional[Union["User", str, Empty]] = empty,
event: Optional[Union[NotificationEvent, Empty]] = empty,
channel: Optional[Union[NotificationChannels, Empty]] = empty,
**kwargs,
) -> None:
"""
Update the current `Notification` attributes.
Setting an input to None will clear out the value (only applicable to recipients and from_user).
:param subject: (O) Header text of the notification. Cannot be cleared.
:type subject: basestring or None or Empty
:param message: (O) Content message of the notification. Cannot be cleared.
:type message: basestring or None or Empty
:param status: (O) life-cycle status of the notification, defaults to "DRAFT". Cannot be cleared.
:type status: NotificationStatus
:param recipients: (O) list of recipients, each being a User object, user ID or an email address.
:type recipients: list or None or Empty
:param team: (O) team object to which the notification is constrained
:type team: Team object or Team UUID
:param from_user: (O) Sender of the notification, either a User object or user ID. Defaults to script user.
:type from_user: User or user ID or None or Empty
:param event: (O) originating event of the notification. Cannot be cleared.
:type event: NotificationEvent
:param channel: (O) method used to send the notification, defaults to "EMAIL". Cannot be cleared.
:type channel: NotificationChannels
:param kwargs: (optional) keyword=value arguments
:return: None
:raises: APIError: when the `Notification` could not be updated
Not mentioning an input parameter in the function will leave it unchanged. Setting a parameter as None will
clear its value (where that is possible). The example below will clear the from_user, but leave everything
else unchanged.
>>> notification.edit(from_user=None)
"""
from pykechain.models import Team, User
recipient_users = list()
recipient_emails = list()
if recipients is not None:
if isinstance(recipients, list) and all(
isinstance(r, (str, int, User)) for r in recipients
):
for recipient in recipients:
if is_valid_email(recipient):
recipient_emails.append(recipient)
else:
recipient_users.append(check_user(recipient, User, "recipient"))
elif isinstance(recipients, Empty):
recipient_emails = empty
recipient_users = empty
else:
raise IllegalArgumentError(
"`recipients` must be a list of User objects, IDs or email addresses, "
'"{}" ({}) is not.'.format(recipients, type(recipients))
)
if isinstance(channel, Empty):
channels = empty
elif check_enum(channel, NotificationChannels, "channel"):
channels = [channel]
else:
channels = list()
update_dict = {
"status": check_enum(status, NotificationStatus, "status") or self.status,
"event": check_enum(event, NotificationEvent, "event") or self.event,
"subject": check_text(subject, "subject") or self.subject,
"message": check_text(message, "message") or self.message,
"recipient_users": recipient_users,
"recipient_emails": recipient_emails,
"team": check_base(team, Team, "team"),
"from_user": check_user(from_user, User, "from_user"),
"channels": channels or self.channels,
}
if kwargs:
update_dict.update(kwargs)
update_dict = clean_empty_values(update_dict=update_dict)
url = self._client._build_url("notification", notification_id=self.id)
response = self._client._request("PUT", url, json=update_dict)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Notification {self}", response=response)
self.refresh(json=response.json().get("results")[0])
|
class Notification(Base):
'''A virtual object representing a KE-chain notification.
:ivar id: UUID of the notification
:type id: basestring
:ivar subject: subject of the notification
:type subject: basestring or None
:ivar created_at: the datetime when the object was created if available (otherwise None)
:type created_at: datetime or None
:ivar updated_at: the datetime when the object was last updated if available (otherwise None)
:type updated_at: datetime or None
:ivar status: The status of the notification (see :class:`pykechain.enums.NotificationStatus`)
:type status: basestring or None
:ivar event: The event of the notification (see :class:`pykechain.enums.NotificationEvent`)
:type event: basestring or None
:ivar recipient_users: The list of ids of the users
:type recipient_users: List[User ids]
'''
def __init__(self, json: Dict, **kwargs) -> None:
'''Construct a notification from a KE-chain 2 json response.
:param json: the json response to construct the :class:`Notification` from
:type json: dict
'''
pass
def __repr__(self):
pass
def get_recipient_users(self) -> List["User"]:
'''Return the list of actual `User` objects based on recipient_users_ids.'''
pass
def get_from_user(self) -> "User":
'''Return the actual `User` object based on the from_user_id.'''
pass
def get_team(self) -> "Team":
'''Return the actual `Team` object based on the team_id.'''
pass
def delete(self):
'''Delete the notification.'''
pass
def edit(
self,
subject: Optional[Union[str, Empty]] = empty,
message: Optional[Union[str, Empty]] = empty,
status: Optional[Union[NotificationStatus, Empty]] = empty,
recipients: Optional[Union[List[Union["User", str, int]], Empty]] = empty,
team: Optional[Union["Team", str, Empty]] = empty,
from_user: Optional[Union["User", str, Empty]] = empty,
event: Optional[Union[NotificationEvent, Empty]] = empty,
channel: Optional[Union[NotificationChannels, Empty]] = empty,
**kwargs,
) -> None:
'''
Update the current `Notification` attributes.
Setting an input to None will clear out the value (only applicable to recipients and from_user).
:param subject: (O) Header text of the notification. Cannot be cleared.
:type subject: basestring or None or Empty
:param message: (O) Content message of the notification. Cannot be cleared.
:type message: basestring or None or Empty
:param status: (O) life-cycle status of the notification, defaults to "DRAFT". Cannot be cleared.
:type status: NotificationStatus
:param recipients: (O) list of recipients, each being a User object, user ID or an email address.
:type recipients: list or None or Empty
:param team: (O) team object to which the notification is constrained
:type team: Team object or Team UUID
:param from_user: (O) Sender of the notification, either a User object or user ID. Defaults to script user.
:type from_user: User or user ID or None or Empty
:param event: (O) originating event of the notification. Cannot be cleared.
:type event: NotificationEvent
:param channel: (O) method used to send the notification, defaults to "EMAIL". Cannot be cleared.
:type channel: NotificationChannels
:param kwargs: (optional) keyword=value arguments
:return: None
:raises: APIError: when the `Notification` could not be updated
Not mentioning an input parameter in the function will leave it unchanged. Setting a parameter as None will
clear its value (where that is possible). The example below will clear the from_user, but leave everything
else unchanged.
>>> notification.edit(from_user=None)
'''
pass
| 8 | 7 | 20 | 3 | 13 | 5 | 3 | 0.6 | 1 | 11 | 6 | 0 | 7 | 11 | 7 | 7 | 166 | 26 | 89 | 38 | 69 | 53 | 56 | 27 | 47 | 10 | 1 | 4 | 19 |
140,874 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.URITarget
|
class URITarget(Enum):
"""
Side-bar button redirect options.
:cvar INTERNAL: "internal"
:cvar EXTERNAL: "external"
:cvar NEW: "_new"
:cvar SELF: "_self"
:cvar BLANK: "_blank"
:cvar PARENT: "_parent"
:cvar TOP: "_top"
"""
INTERNAL = "internal"
EXTERNAL = "external"
NEW = "_new"
SELF = "_self"
BLANK = "_blank"
PARENT = "_parent"
TOP = "_top"
|
class URITarget(Enum):
'''
Side-bar button redirect options.
:cvar INTERNAL: "internal"
:cvar EXTERNAL: "external"
:cvar NEW: "_new"
:cvar SELF: "_self"
:cvar BLANK: "_blank"
:cvar PARENT: "_parent"
:cvar TOP: "_top"
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 20 | 2 | 8 | 8 | 7 | 10 | 8 | 8 | 7 | 0 | 1 | 0 | 0 |
140,875 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/test/kkboxapiTest.py
|
kkboxapiTest.TestSDK
|
class TestSDK(unittest.TestCase):
def test_api_members_exist(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
api = KKBOXAPI(token)
attributes = inspect.getmembers(api, lambda a:not(inspect.isroutine(a)))
properties = []
for (property, _) in attributes:
properties.append(property)
members = ('search_fetcher', 'track_fetcher', 'artist_fetcher',
'album_fetcher', 'shared_playlist_fetcher', 'chart_fetcher',
'new_release_category_fetcher', 'genre_station_fetcher',
'mood_station_fetcher', 'feature_playlist_fetcher',
'feature_playlist_category_fetcher', 'new_hits_playlist_fetcher')
for member in members:
assert member in properties, 'missing member ' + member
|
class TestSDK(unittest.TestCase):
def test_api_members_exist(self):
pass
| 2 | 0 | 15 | 0 | 15 | 0 | 3 | 0 | 1 | 2 | 2 | 0 | 1 | 0 | 1 | 73 | 17 | 1 | 16 | 10 | 14 | 0 | 12 | 10 | 10 | 3 | 2 | 1 | 3 |
140,876 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/track_fetcher.py
|
kkbox_developer_sdk.track_fetcher.KKBOXTrackFetcher
|
class KKBOXTrackFetcher(Fetcher):
'''
Get metadata of a track.
See `https://docs-en.kkbox.codes/v1.1/reference#tracks`.
'''
@assert_access_token
def fetch_track(self, track_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches a song track by given ID.
:param track_id: the track ID.
:type track_id: str
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#tracks-track_id`.
'''
url = 'https://api.kkbox.com/v1.1/tracks/%s' % track_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class KKBOXTrackFetcher(Fetcher):
'''
Get metadata of a track.
See `https://docs-en.kkbox.codes/v1.1/reference#tracks`.
'''
@assert_access_token
def fetch_track(self, track_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches a song track by given ID.
:param track_id: the track ID.
:type track_id: str
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#tracks-track_id`.
'''
pass
| 3 | 2 | 14 | 2 | 4 | 8 | 1 | 2 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 5 | 21 | 3 | 6 | 4 | 3 | 12 | 5 | 3 | 3 | 1 | 1 | 0 | 1 |
140,877 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/territory.py
|
kkbox_developer_sdk.territory.KKBOXTerritory
|
class KKBOXTerritory:
'''
The territory of the KKBOX's service.
'''
TAIWAN = 'TW'
HONGKONG = 'HK'
SINGAPORE = 'SG'
MALAYSIA = 'MA'
JAPAN = 'JP'
|
class KKBOXTerritory:
'''
The territory of the KKBOX's service.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 | 0 | 6 | 6 | 5 | 3 | 6 | 6 | 5 | 0 | 0 | 0 | 0 |
140,878 |
KKBOX/OpenAPI-Python
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KKBOX_OpenAPI-Python/test/authTest.py
|
authTest.TestAuthSDK
|
class TestAuthSDK(unittest.TestCase):
def test_fetch_access_token_by_client_credentials(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
auth.fetch_access_token_by_client_credentials()
access_token = auth.access_token
assert access_token.access_token != None
assert access_token.expires_in != None
assert access_token.token_type != None
|
class TestAuthSDK(unittest.TestCase):
def test_fetch_access_token_by_client_credentials(self):
pass
| 2 | 0 | 7 | 0 | 7 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 9 | 1 | 8 | 4 | 6 | 0 | 8 | 4 | 6 | 1 | 2 | 0 | 1 |
140,879 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/shared_playlist_fetcher.py
|
kkbox_developer_sdk.shared_playlist_fetcher.KKBOXSharedPlaylistFetcher
|
class KKBOXSharedPlaylistFetcher(Fetcher):
'''
Fetch metadata and tracks of a specific shared playlist.
See `https://docs-en.kkbox.codes/v1.1/reference#shared-playlists`.
'''
@assert_access_token
def fetch_shared_playlist(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches a shared playlist by given ID.
:param playlist_id: the playlist ID.
:type playlist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dictcd
See `https://docs-en.kkbox.codes/v1.1/reference#sharedplaylists-playlist_id`.
'''
url = 'https://api.kkbox.com/v1.1/shared-playlists/%s' % playlist_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_tracks_of_shared_playlists(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches track list of a playlist by given ID.
:param playlist_id: the playlist ID.
:type playlist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://kkbox.gelato.io/docs/versions/1.1/resources/shared-playlists/endpoints/get-shared-playlists-playlist_id-tracks`.
'''
url = 'https://api.kkbox.com/v1.1/shared-playlists/%s/tracks' % playlist_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class KKBOXSharedPlaylistFetcher(Fetcher):
'''
Fetch metadata and tracks of a specific shared playlist.
See `https://docs-en.kkbox.codes/v1.1/reference#shared-playlists`.
'''
@assert_access_token
def fetch_shared_playlist(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches a shared playlist by given ID.
:param playlist_id: the playlist ID.
:type playlist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dictcd
See `https://docs-en.kkbox.codes/v1.1/reference#sharedplaylists-playlist_id`.
'''
pass
@assert_access_token
def fetch_tracks_of_shared_playlists(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches track list of a playlist by given ID.
:param playlist_id: the playlist ID.
:type playlist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://kkbox.gelato.io/docs/versions/1.1/resources/shared-playlists/endpoints/get-shared-playlists-playlist_id-tracks`.
'''
pass
| 5 | 3 | 15 | 2 | 4 | 9 | 1 | 2 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 6 | 39 | 6 | 11 | 7 | 6 | 22 | 9 | 5 | 6 | 1 | 1 | 0 | 2 |
140,880 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/new_release_category_fetcher.py
|
kkbox_developer_sdk.new_release_category_fetcher.KKBOXNewReleaseCategoryFetcher
|
class KKBOXNewReleaseCategoryFetcher(Fetcher):
'''
List categories of new release category and get metadata of specific new release category.
See `https://docs-en.kkbox.codes/v1.1/reference#new-release-categories`.
'''
@assert_access_token
def fetch_all_new_release_categories(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches new release categories.
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#newreleasecategories`
'''
url = 'https://api.kkbox.com/v1.1/new-release-categories'
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_new_release_category(self, category_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches new release categories by given ID.
:param category_id: the station ID.
:type category_id: str
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#newreleasecategories-category_id`
'''
url = 'https://api.kkbox.com/v1.1/new-release-categories/%s' % category_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_albums_of_new_release_category(self, category_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches albums of new release category by given ID.
:param category_id: the category ID.
:type category_id: str
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#newreleasecategories-category_id-albums`
'''
url = 'https://api.kkbox.com/v1.1/new-release-categories/%s/albums' % category_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class KKBOXNewReleaseCategoryFetcher(Fetcher):
'''
List categories of new release category and get metadata of specific new release category.
See `https://docs-en.kkbox.codes/v1.1/reference#new-release-categories`.
'''
@assert_access_token
def fetch_all_new_release_categories(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches new release categories.
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#newreleasecategories`
'''
pass
@assert_access_token
def fetch_new_release_category(self, category_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches new release categories by given ID.
:param category_id: the station ID.
:type category_id: str
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#newreleasecategories-category_id`
'''
pass
@assert_access_token
def fetch_albums_of_new_release_category(self, category_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches albums of new release category by given ID.
:param category_id: the category ID.
:type category_id: str
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#newreleasecategories-category_id-albums`
'''
pass
| 7 | 4 | 14 | 2 | 4 | 8 | 1 | 1.81 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 7 | 54 | 9 | 16 | 10 | 9 | 29 | 13 | 7 | 9 | 1 | 1 | 0 | 3 |
140,881 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/search_fetcher.py
|
kkbox_developer_sdk.search_fetcher.KKBOXSearchFetcher
|
class KKBOXSearchFetcher(Fetcher):
'''
Search API, the types it can search includes artists, albums, tracks, or playlists.
Default to search all types, use "," to seperate types if you want to use multiple
types to search at the same time.
See `https://docs-en.kkbox.codes/v1.1/reference#search`.
'''
@assert_access_token
def search(self, keyword, types=[], terr=KKBOXTerritory.TAIWAN):
'''
Searches within KKBOX's database.
:param keyword: the keyword.
:type keyword: str
:param types: the search types.
:return: list
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#search_1`.
'''
url = 'https://api.kkbox.com/v1.1/search'
url += '?' + url_parse.urlencode({'q': keyword, 'territory': terr})
if len(types) > 0:
url += '&type=' + ','.join(types)
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class KKBOXSearchFetcher(Fetcher):
'''
Search API, the types it can search includes artists, albums, tracks, or playlists.
Default to search all types, use "," to seperate types if you want to use multiple
types to search at the same time.
See `https://docs-en.kkbox.codes/v1.1/reference#search`.
'''
@assert_access_token
def search(self, keyword, types=[], terr=KKBOXTerritory.TAIWAN):
'''
Searches within KKBOX's database.
:param keyword: the keyword.
:type keyword: str
:param types: the search types.
:return: list
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#search_1`.
'''
pass
| 3 | 2 | 19 | 2 | 6 | 11 | 2 | 2.13 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 5 | 28 | 3 | 8 | 4 | 5 | 17 | 7 | 3 | 5 | 2 | 1 | 1 | 2 |
140,882 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/test/apiTest.py
|
apiTest.TestAPISDK
|
class TestAPISDK(unittest.TestCase):
def _validate_image(self, image):
keys = ('url', 'width', 'height')
for key in keys:
assert key in image, 'missing key ' + key
def _validate_paging(self, paging):
assert 'offset', 'limit' in paging
assert 'previous', 'next' in paging
def _validate_artist(self, artist):
keys = ('id', 'name', 'url', 'images')
for key in keys:
assert key in artist, 'missing key ' + key
for image in artist['images']:
self._validate_image(image)
def _validate_artist_paging(self, artist_paging):
if artist_paging is None:
pass
else:
keys = ('paging', 'data', 'summary')
for key in keys:
assert key in artist_paging, 'missing key ' + key
for artist in artist_paging['data']:
self._validate_artist(artist)
for paging in artist_paging['paging']:
self._validate_paging(paging)
def _validate_album(self, album):
keys = ('id', 'name', 'url', 'explicitness', 'available_territories', 'images')
for key in keys:
assert key in album, 'missing key ' + key
for image in album['images']:
self._validate_image(image)
if 'artist' in album:
self._validate_artist(album['artist'])
def _validate_album_paging(self, album_paging):
if album_paging is None:
pass
else:
keys = ('paging', 'data', 'summary')
for key in keys:
assert key in album_paging, 'missing key ' + key
for album in album_paging['data']:
self._validate_album(album)
for paging in album_paging['paging']:
self._validate_paging(paging)
def _validate_track(self, track):
keys = ('id', 'name', 'url', 'track_number', 'explicitness', 'available_territories')
for key in keys:
assert key in track, 'missing key ' + key
if 'album' in track:
self._validate_album(track['album'])
if 'paging' in track:
self._validate_paging(track['paging'])
def _validate_track_paging(self, track_paging):
if track_paging is None:
pass
else:
keys = ('paging', 'data', 'summary')
for key in keys:
assert key in track_paging, 'missing key ' + key
for track in track_paging['data']:
self._validate_track(track)
for paging in track_paging['paging']:
self._validate_paging(paging)
def _validate_playlist(self, playlist):
if playlist is None:
pass
else:
keys = ('id', 'title', 'description', 'url', 'images', 'owner')
for key in keys:
assert key in playlist, 'missing key ' + key
for image in playlist['images']:
self._validate_image(image)
for owner in playlist['owner']:
assert 'id', 'name' in playlist['owner']
if 'tracks' in playlist:
track = playlist['tracks']
self._validate_track_paging(track)
if 'paging' in playlist:
self._validate_paging(playlist['paging'])
def _validate_playlist_paging(self, playlist_paging):
if playlist_paging is None:
pass
else:
keys = ('paging', 'data', 'summary')
for key in keys:
assert key in playlist_paging, 'missing key ' + key
for playlist in playlist_paging['data']:
self._validate_playlist(playlist)
for paging in playlist_paging['paging']:
self._validate_paging(playlist_paging['paging'])
def _validate_category(self, category):
if category is None:
pass
else:
keys = ('id', 'title')
for key in keys:
assert key in category, 'missing key ' + key
if 'albums' in category:
album = category['albums']
self._validate_album_paging(album)
if 'images' in category:
for image in category['images']:
self._validate_image(image)
def _validate_category_paging(self, category_paging):
if category_paging is None:
pass
else:
keys = ('paging', 'data', 'summary')
for key in keys:
assert key in category_paging, 'missing key ' + key
for category in category_paging['data']:
self._validate_category(category)
for paging in category_paging['paging']:
self._validate_paging(paging)
def _validate_genre_station_paging(self, station_paging):
if station_paging is None:
pass
else:
keys = ('paging', 'data', 'summary')
for key in keys:
assert key in station_paging, 'missing key ' + key
for station in station_paging['data']:
keys = ('category', 'id', 'name')
for key in keys:
assert key in station
for paging in station_paging['paging']:
self._validate_paging(paging)
def _validate_mood_station_paging(self, station_paging):
if station_paging is None:
pass
else:
keys = ('paging', 'data', 'summary')
for key in keys:
assert key in station_paging, 'missing key ' + key
for station in station_paging['data']:
keys = ('images', 'id', 'name')
for key in keys:
assert key in station
for image in station['images']:
self._validate_image(image)
for paging in station_paging['paging']:
self._validate_paging(paging)
def test_fetch_track(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXTrackFetcher(token)
track_id = '4kxvr3wPWkaL9_y3o_'
track = fetcher.fetch_track(track_id)
self._validate_track(track)
def test_fetch_artist(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXArtistFetcher(token)
artist_id = '8q3_xzjl89Yakn_7GB'
artist = fetcher.fetch_artist(artist_id)
self._validate_artist(artist)
def test_fetch_albums_of_artist(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXArtistFetcher(token)
artist_id = 'CluDKLYxr1GFQqLSZt'
albums = fetcher.fetch_albums_of_artist(artist_id)
self._validate_album_paging(albums)
next_page_data = fetcher.fetch_next_page(albums)
self._validate_album_paging(next_page_data)
def test_fetch_top_tracks_of_artist(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXArtistFetcher(token)
artist_id = 'CluDKLYxr1GFQqLSZt'
tracks = fetcher.fetch_top_tracks_of_artist(artist_id)
self._validate_track_paging(tracks)
next_page_data = fetcher.fetch_next_page(tracks)
self._validate_track_paging(next_page_data)
def test_fetch_related_artists(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXArtistFetcher(token)
artist_id = 'CluDKLYxr1GFQqLSZt'
artists = fetcher.fetch_related_artists(artist_id)
self._validate_artist_paging(artists)
next_page_data = fetcher.fetch_next_page(artists)
self._validate_artist_paging(next_page_data)
def test_fetch_album(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXAlbumFetcher(token)
album_id = 'WpTPGzNLeutVFHcFq6'
album = fetcher.fetch_album(album_id)
self._validate_album(album)
def test_fetch_tracks_in_album(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXAlbumFetcher(token)
album_id = 'WpTPGzNLeutVFHcFq6'
tracks = fetcher.fetch_tracks_in_album(album_id)
self._validate_track_paging(tracks)
next_page_data = fetcher.fetch_next_page(tracks)
self._validate_track_paging(next_page_data)
def test_fetch_shared_playlist(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXSharedPlaylistFetcher(token)
playlist_id = '4nUZM-TY2aVxZ2xaA-'
playlist = fetcher.fetch_shared_playlist(playlist_id)
self._validate_playlist(playlist)
next_page_data = fetcher.fetch_next_page(playlist['tracks'])
self._validate_track_paging(next_page_data)
def test_fetch_tracks_of_shared_playlist(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXSharedPlaylistFetcher(token)
playlist_id = '4nUZM-TY2aVxZ2xaA-'
tracks = fetcher.fetch_tracks_of_shared_playlists(playlist_id)
self._validate_track_paging(tracks)
next_page_data = fetcher.fetch_next_page(tracks)
self._validate_track_paging(next_page_data)
def test_search(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXSearchFetcher(token)
results = fetcher.search('love',
[KKBOXSearchTypes.ARTIST, KKBOXSearchTypes.ALBUM,
KKBOXSearchTypes.TRACK,
KKBOXSearchTypes.PLAYLIST])
artists = results.get('artists', [])
for artist in artists['data']:
self._validate_artist(artist)
albums = results.get('albums', [])
for album in albums['data']:
self._validate_album(album)
tracks = results.get('tracks', [])
for track in tracks['data']:
self._validate_track(track)
playlists = results.get('playlists', [])
for playlist in playlists['data']:
self._validate_playlist(playlist)
if results['tracks']['paging']['next'] != None:
next_url = results['tracks']['paging']['next']
next_result = fetcher.fetch_data(next_url)
assert(next_result != None)
def test_fetch_charts(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXChartFetcher(token)
charts = fetcher.fetch_charts()
self._validate_playlist_paging(charts)
next_page_data = fetcher.fetch_next_page(charts)
self._validate_playlist_paging(next_page_data)
def test_fetch_charts_playlist(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXChartFetcher(token)
playlist_id = '0kTVCy_kzou3AdOsAc'
playlist = fetcher.fetch_charts_playlist(playlist_id)
self._validate_playlist(playlist)
next_page_data = fetcher.fetch_next_page(playlist['tracks'])
self._validate_track_paging(next_page_data)
def test_fetch_charts_playlist_tracks(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXChartFetcher(token)
playlist_id = '0kTVCy_kzou3AdOsAc'
playlist = fetcher.fetch_charts_playlist_tracks(playlist_id)
self._validate_track_paging(playlist)
next_page_data = fetcher.fetch_next_page(playlist)
self._validate_track_paging(next_page_data)
def test_fetch_all_new_release_categories(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXNewReleaseCategoryFetcher(token)
categories = fetcher.fetch_all_new_release_categories()
self._validate_category_paging(categories)
next_page_data = fetcher.fetch_next_page(categories)
self._validate_category_paging(next_page_data)
def test_fetch_new_release_category(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXNewReleaseCategoryFetcher(token)
category_id = '1ZQwmFTaLE4p7BG-Ua'
category = fetcher.fetch_new_release_category(category_id)
self._validate_category(category)
next_page_data = fetcher.fetch_next_page(category['albums'])
self._validate_album_paging(next_page_data)
def test_fetch_albums_of_new_release_category(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXNewReleaseCategoryFetcher(token)
category_id = '1ZQwmFTaLE4p7BG-Ua'
albums = fetcher.fetch_albums_of_new_release_category(category_id)
self._validate_album_paging(albums)
next_page_data = fetcher.fetch_next_page(albums)
self._validate_album_paging(next_page_data)
def test_fetch_all_genre_stations(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXGenreStationFetcher(token)
genre_stations = fetcher.fetch_all_genre_stations()
self._validate_genre_station_paging(genre_stations)
next_page_data = fetcher.fetch_next_page(genre_stations)
self._validate_genre_station_paging(next_page_data)
def test_fetch_genre_station(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXGenreStationFetcher(token)
station_id = 'TYq3EHFTl-1EOvJM5Y'
station = fetcher.fetch_genre_station(station_id)
keys = ('category', 'tracks', 'id', 'name')
for key in keys:
assert key in station
tracks = station['tracks']['data']
for track in tracks:
self._validate_track(track)
def test_fetch_all_mood_stations(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXMoodStationFetcher(token)
mood_stations = fetcher.fetch_all_mood_stations()
self._validate_mood_station_paging(mood_stations)
next_page_data = fetcher.fetch_next_page(mood_stations)
self._validate_mood_station_paging(next_page_data)
def test_fetch_mood_station(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXMoodStationFetcher(token)
station_id = 'StGZp2ToWq92diPHS7'
station = fetcher.fetch_mood_station(station_id)
keys = ('tracks', 'id', 'name')
for key in keys:
assert key in station
for track in station['tracks']['data']:
self._validate_track(track)
def test_fetch_all_feature_playlists(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXFeaturePlaylistFetcher(token)
feature_playlists = fetcher.fetch_all_feature_playlists()
self._validate_playlist_paging(feature_playlists)
next_page_data = fetcher.fetch_next_page(feature_playlists)
self._validate_playlist_paging(next_page_data)
def test_fetch_feature_playlist(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXFeaturePlaylistFetcher(token)
playlist_id = 'Wt95My35CqR9hB_FW1'
feature_playlist = fetcher.fetch_feature_playlist(playlist_id)
self._validate_playlist(feature_playlist)
next_page_data = fetcher.fetch_next_page(feature_playlist['tracks'])
self._validate_track_paging(next_page_data)
def test_fetch_feature_playlist_tracks(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXFeaturePlaylistFetcher(token)
playlist_id = 'Wt95My35CqR9hB_FW1'
feature_playlist = fetcher.fetch_feature_playlist_tracks(playlist_id)
self._validate_track_paging(feature_playlist)
next_page_data = fetcher.fetch_next_page(feature_playlist)
self._validate_track_paging(next_page_data)
def test_fetch_categories_of_feature_playlist(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXFeaturePlaylistCategoryFetcher(token)
categories = fetcher.fetch_categories_of_feature_playlist()
self._validate_category_paging(categories)
next_page_data = fetcher.fetch_next_page(categories)
self._validate_category_paging(next_page_data)
def test_fetch_feature_playlist_by_category(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXFeaturePlaylistCategoryFetcher(token)
category_id = '9XQKD8BJx595ESs_rb'
category = fetcher.fetch_feature_playlist_by_category(category_id)
keys = ('id', 'title', 'images', 'playlists')
for key in keys:
assert key in category, 'missing key ' + key
for image in category['images']:
self._validate_image(image)
for playlist in category['playlists']['data']:
self._validate_playlist(playlist)
def test_fetch_playlists_of_feature_playlist_category(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXFeaturePlaylistCategoryFetcher(token)
category_id = '9XQKD8BJx595ESs_rb'
category = fetcher.fetch_playlists_of_feature_playlist_category(category_id)
self._validate_playlist_paging(category)
next_page_data = fetcher.fetch_next_page(category)
self._validate_playlist_paging(next_page_data)
def test_fetch_all_new_hits_playlists(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXNewHitsPlaylistFetcher(token)
new_hits = fetcher.fetch_all_new_hits_playlists()
self._validate_playlist_paging(new_hits)
next_page_data = fetcher.fetch_next_page(new_hits)
self._validate_playlist_paging(next_page_data)
def test_fetch_new_hits_playlist(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXNewHitsPlaylistFetcher(token)
playlist_id = 'DZrC8m29ciOFY2JAm3'
new_hits = fetcher.fetch_new_hits_playlist(playlist_id)
self._validate_playlist(new_hits)
next_page_data = fetcher.fetch_next_page(new_hits['tracks'])
self._validate_track_paging(next_page_data)
def test_fetch_new_hits_playlist_track(self):
auth = KKBOXOAuth(CLIENT_ID, CLIENT_SECRET)
token = auth.fetch_access_token_by_client_credentials()
fetcher = KKBOXNewHitsPlaylistFetcher(token)
playlist_id = 'DZrC8m29ciOFY2JAm3'
new_hits = fetcher.fetch_new_hits_playlist_tracks(playlist_id)
self._validate_track_paging(new_hits)
next_page_data = fetcher.fetch_next_page(new_hits)
self._validate_track_paging(next_page_data)
|
class TestAPISDK(unittest.TestCase):
def _validate_image(self, image):
pass
def _validate_paging(self, paging):
pass
def _validate_artist(self, artist):
pass
def _validate_artist_paging(self, artist_paging):
pass
def _validate_album(self, album):
pass
def _validate_album_paging(self, album_paging):
pass
def _validate_track(self, track):
pass
def _validate_track_paging(self, track_paging):
pass
def _validate_playlist(self, playlist):
pass
def _validate_playlist_paging(self, playlist_paging):
pass
def _validate_category(self, category):
pass
def _validate_category_paging(self, category_paging):
pass
def _validate_genre_station_paging(self, station_paging):
pass
def _validate_mood_station_paging(self, station_paging):
pass
def test_fetch_track(self):
pass
def test_fetch_artist(self):
pass
def test_fetch_albums_of_artist(self):
pass
def test_fetch_top_tracks_of_artist(self):
pass
def test_fetch_related_artists(self):
pass
def test_fetch_albums_of_artist(self):
pass
def test_fetch_tracks_in_album(self):
pass
def test_fetch_shared_playlist(self):
pass
def test_fetch_tracks_of_shared_playlist(self):
pass
def test_search(self):
pass
def test_fetch_charts(self):
pass
def test_fetch_charts_playlist(self):
pass
def test_fetch_charts_playlist_tracks(self):
pass
def test_fetch_all_new_release_categories(self):
pass
def test_fetch_new_release_category(self):
pass
def test_fetch_albums_of_new_release_category(self):
pass
def test_fetch_all_genre_stations(self):
pass
def test_fetch_genre_station(self):
pass
def test_fetch_all_mood_stations(self):
pass
def test_fetch_mood_station(self):
pass
def test_fetch_all_feature_playlists(self):
pass
def test_fetch_feature_playlist(self):
pass
def test_fetch_feature_playlist_tracks(self):
pass
def test_fetch_categories_of_feature_playlist(self):
pass
def test_fetch_feature_playlist_by_category(self):
pass
def test_fetch_playlists_of_feature_playlist_category(self):
pass
def test_fetch_all_new_hits_playlists(self):
pass
def test_fetch_new_hits_playlist(self):
pass
def test_fetch_new_hits_playlist_track(self):
pass
| 44 | 0 | 10 | 0 | 10 | 0 | 2 | 0 | 1 | 14 | 14 | 0 | 43 | 0 | 43 | 115 | 458 | 44 | 414 | 272 | 370 | 0 | 402 | 272 | 358 | 7 | 2 | 3 | 106 |
140,883 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/access_token.py
|
kkbox_developer_sdk.access_token.KKBOXAccessToken
|
class KKBOXAccessToken:
'''
The access token object for accessing KKBOX's API.
'''
def __init__(self, **kwargs):
assert kwargs.get('access_token', None) != None
#: The actual access token
self.access_token = kwargs.get('access_token', None)
#: The access token expiration date in unix timestamp
self.expires_in = kwargs.get('expires_in', None)
#: The token type
self.token_type = kwargs.get('token_type', None)
#: The scope of the token, may be none
self.scope = kwargs.get('scope', None)
#: The refresh token
self.refresh_token = kwargs.get('refresh_token', None)
|
class KKBOXAccessToken:
'''
The access token object for accessing KKBOX's API.
'''
def __init__(self, **kwargs):
pass
| 2 | 1 | 12 | 0 | 7 | 5 | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 5 | 1 | 1 | 16 | 0 | 8 | 7 | 6 | 8 | 8 | 7 | 6 | 1 | 0 | 0 | 1 |
140,884 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/album_fetcher.py
|
kkbox_developer_sdk.album_fetcher.KKBOXAlbumFetcher
|
class KKBOXAlbumFetcher(Fetcher):
'''
Get metadata and tracks of an album.
See `https://docs-en.kkbox.codes/v1.1/reference#albums`.
'''
@assert_access_token
def fetch_album(self, album_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches an album by given ID.
:param album_id: the album ID.
:type album_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#albums-album_id`.
'''
url = 'https://api.kkbox.com/v1.1/albums/%s' % album_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_tracks_in_album(self, album_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches tracks in an album by given ID.
:param album_id: the album ID.
:type album_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#albums-album_id-tracks`.
'''
url = 'https://api.kkbox.com/v1.1/albums/%s/tracks' % album_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class KKBOXAlbumFetcher(Fetcher):
'''
Get metadata and tracks of an album.
See `https://docs-en.kkbox.codes/v1.1/reference#albums`.
'''
@assert_access_token
def fetch_album(self, album_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches an album by given ID.
:param album_id: the album ID.
:type album_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#albums-album_id`.
'''
pass
@assert_access_token
def fetch_tracks_in_album(self, album_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches tracks in an album by given ID.
:param album_id: the album ID.
:type album_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#albums-album_id-tracks`.
'''
pass
| 5 | 3 | 15 | 2 | 4 | 9 | 1 | 2 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 6 | 39 | 6 | 11 | 7 | 6 | 22 | 9 | 5 | 6 | 1 | 1 | 0 | 2 |
140,885 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/api.py
|
kkbox_developer_sdk.api.KKBOXAPI
|
class KKBOXAPI:
'''
Create fetchers.
'''
def __init__(self, access_token):
#: The search related API fetcher
self.search_fetcher = KKBOXSearchFetcher(access_token)
#: The track related API fetcher
self.track_fetcher = KKBOXTrackFetcher(access_token)
#: The artist related API fetcher
self.artist_fetcher = KKBOXArtistFetcher(access_token)
#: The album related API fetcher
self.album_fetcher = KKBOXAlbumFetcher(access_token)
#: The shared playlist related API fetcher
self.shared_playlist_fetcher = KKBOXSharedPlaylistFetcher(access_token)
#: The chart related API fetcher
self.chart_fetcher = KKBOXChartFetcher(access_token)
#: The new release category related API fetcher
self.new_release_category_fetcher = KKBOXNewReleaseCategoryFetcher(access_token)
#: The genre station related API fetcher
self.genre_station_fetcher = KKBOXGenreStationFetcher(access_token)
#: The mood station related API fetcher
self.mood_station_fetcher = KKBOXMoodStationFetcher(access_token)
#: The feature playlist related API fetcher
self.feature_playlist_fetcher = KKBOXFeaturePlaylistFetcher(access_token)
#: The feature playlist category related API fetcher
self.feature_playlist_category_fetcher = KKBOXFeaturePlaylistCategoryFetcher(access_token)
#: The new hits playlist related API fetcher
self.new_hits_playlist_fetcher = KKBOXNewHitsPlaylistFetcher(access_token)
|
class KKBOXAPI:
'''
Create fetchers.
'''
def __init__(self, access_token):
pass
| 2 | 1 | 25 | 0 | 13 | 12 | 1 | 1.07 | 0 | 12 | 12 | 0 | 1 | 12 | 1 | 1 | 29 | 0 | 14 | 14 | 12 | 15 | 14 | 14 | 12 | 1 | 0 | 0 | 1 |
140,886 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/artist_fetcher.py
|
kkbox_developer_sdk.artist_fetcher.KKBOXArtistFetcher
|
class KKBOXArtistFetcher(Fetcher):
'''
Get metadata, albums, and top tracks of an artist.
See `https://docs-en.kkbox.codes/v1.1/reference#artists`.
'''
@assert_access_token
def fetch_artist(self, artist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches an artist by given ID.
:param artist_id: the artist ID.
:type artist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#artists-artist_id`.
'''
url = 'https://api.kkbox.com/v1.1/artists/%s' % artist_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_albums_of_artist(self, artist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches albums belong to an artist by given ID.
:param artist_id: the artist ID.
:type artist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#artists-artist_id-albums`.
'''
url = 'https://api.kkbox.com/v1.1/artists/%s/albums' % artist_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_top_tracks_of_artist(self, artist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetcher top tracks belong to an artist by given ID.
:param artist_id: the artist ID.
:type artist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See 'https://docs-en.kkbox.codes/v1.1/reference#artists-artist_id-toptracks'
'''
url = 'https://api.kkbox.com/v1.1/artists/%s/top-tracks' % artist_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_related_artists(self, artist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetcher related artists belong to an artist by given ID.
:param artist_id: the artist ID.
:type artist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See 'https://docs-en.kkbox.codes/v1.1/reference#artists-artist_id-relatedartists'
'''
url = 'https://api.kkbox.com/v1.1/artists/%s/related-artists' % artist_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class KKBOXArtistFetcher(Fetcher):
'''
Get metadata, albums, and top tracks of an artist.
See `https://docs-en.kkbox.codes/v1.1/reference#artists`.
'''
@assert_access_token
def fetch_artist(self, artist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches an artist by given ID.
:param artist_id: the artist ID.
:type artist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#artists-artist_id`.
'''
pass
@assert_access_token
def fetch_albums_of_artist(self, artist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches albums belong to an artist by given ID.
:param artist_id: the artist ID.
:type artist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#artists-artist_id-albums`.
'''
pass
@assert_access_token
def fetch_top_tracks_of_artist(self, artist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetcher top tracks belong to an artist by given ID.
:param artist_id: the artist ID.
:type artist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See 'https://docs-en.kkbox.codes/v1.1/reference#artists-artist_id-toptracks'
'''
pass
@assert_access_token
def fetch_related_artists(self, artist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetcher related artists belong to an artist by given ID.
:param artist_id: the artist ID.
:type artist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See 'https://docs-en.kkbox.codes/v1.1/reference#artists-artist_id-relatedartists'
'''
pass
| 9 | 5 | 15 | 2 | 4 | 9 | 1 | 1.9 | 1 | 1 | 1 | 0 | 4 | 0 | 4 | 8 | 73 | 12 | 21 | 13 | 12 | 40 | 17 | 9 | 12 | 1 | 1 | 0 | 4 |
140,887 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/auth_flow.py
|
kkbox_developer_sdk.auth_flow.KKBOXOAuth
|
class KKBOXOAuth:
'''
Implements various KKBOX Oauth 2.0 authorization flows.
See `https://docs-en.kkbox.codes/docs/appendix-b`.
'''
OAUTH_TOKEN_URL = 'https://account.kkbox.com/oauth2/token'
def __init__(self, client_id, client_secret):
#: The client ID
self.client_id = client_id
#: The client secret
self.client_secret = client_secret
#: The access token
self.access_token = None
#: The http client
self.http = KKBOXHTTP()
assert len(self.client_id) > 0, 'A client ID must be set.'
assert len(self.client_secret) > 0, 'A client secret must be set.'
def fetch_access_token_by_client_credentials(self):
'''
There are three ways to let you start using KKBOX's Open/Partner
API. The first way among them is to generate a client
credential to fetch an access token to let KKBOX identify
you. It allows you to access public data from KKBOX such as
public albums, playlists and so on.
However, you cannot use client credentials to access private
data of a user. You have to let users to log-in into KKBOX and
grant permissions for you to do so. You cannot use client
credentials to do media playback either, since it requires a
Premium Membership.
:return: an access token
:rtype: :class:`kkbox_sdk.KKBOXAccessToken`
See `https://docs-en.kkbox.codes/docs/appendix-a`.
'''
client_credential_base = '%s:%s' % (self.client_id, self.client_secret)
try:
client_credentials = base64.b64encode(
bytes(client_credential_base, 'utf-8'))
except:
client_credentials = base64.b64encode(client_credential_base)
client_credentials = client_credentials.decode('utf-8')
headers = {'Authorization': 'Basic ' + client_credentials,
'Content-type': 'application/x-www-form-urlencoded'}
post_parameters = {'grant_type': 'client_credentials'}
json_object = self.http._post_data(KKBOXOAuth.OAUTH_TOKEN_URL, post_parameters,
headers)
self.access_token = KKBOXAccessToken(**json_object)
return self.access_token
|
class KKBOXOAuth:
'''
Implements various KKBOX Oauth 2.0 authorization flows.
See `https://docs-en.kkbox.codes/docs/appendix-b`.
'''
def __init__(self, client_id, client_secret):
pass
def fetch_access_token_by_client_credentials(self):
'''
There are three ways to let you start using KKBOX's Open/Partner
API. The first way among them is to generate a client
credential to fetch an access token to let KKBOX identify
you. It allows you to access public data from KKBOX such as
public albums, playlists and so on.
However, you cannot use client credentials to access private
data of a user. You have to let users to log-in into KKBOX and
grant permissions for you to do so. You cannot use client
credentials to do media playback either, since it requires a
Premium Membership.
:return: an access token
:rtype: :class:`kkbox_sdk.KKBOXAccessToken`
See `https://docs-en.kkbox.codes/docs/appendix-a`.
'''
pass
| 3 | 2 | 22 | 2 | 11 | 10 | 2 | 0.96 | 0 | 3 | 2 | 0 | 2 | 4 | 2 | 2 | 54 | 7 | 24 | 13 | 21 | 23 | 21 | 13 | 18 | 2 | 0 | 1 | 3 |
140,888 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/search_fetcher.py
|
kkbox_developer_sdk.search_fetcher.KKBOXSearchTypes
|
class KKBOXSearchTypes:
'''
The Search types of the search API.
'''
ARTIST = 'artist'
ALBUM = 'album'
TRACK = 'track'
PLAYLIST = 'playlist'
|
class KKBOXSearchTypes:
'''
The Search types of the search API.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.6 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 0 | 5 | 5 | 4 | 3 | 5 | 5 | 4 | 0 | 0 | 0 | 0 |
140,889 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/chart_fetcher.py
|
kkbox_developer_sdk.chart_fetcher.KKBOXChartFetcher
|
class KKBOXChartFetcher(Fetcher):
'''
List chart playlist. Then can get tracks via shared playlist.
See `https://docs-en.kkbox.codes/v1.1/reference#charts`.
'''
@assert_access_token
def fetch_charts(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches list of song rankings.
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#charts_1`
'''
url = 'https://api.kkbox.com/v1.1/charts'
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_charts_playlist(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches chart categories.
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#charts-playlist_id`
'''
url = 'https://api.kkbox.com/v1.1/charts/%s' % playlist_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_charts_playlist_tracks(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches chart categories.
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#charts-playlist_id-tracks`
'''
url = 'https://api.kkbox.com/v1.1/charts/%s/tracks' % playlist_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class KKBOXChartFetcher(Fetcher):
'''
List chart playlist. Then can get tracks via shared playlist.
See `https://docs-en.kkbox.codes/v1.1/reference#charts`.
'''
@assert_access_token
def fetch_charts(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches list of song rankings.
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#charts_1`
'''
pass
@assert_access_token
def fetch_charts_playlist(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches chart categories.
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#charts-playlist_id`
'''
pass
@assert_access_token
def fetch_charts_playlist_tracks(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches chart categories.
:param terr: the current territory.
:return: API response.
:rtype: list
See `https://docs-en.kkbox.codes/v1.1/reference#charts-playlist_id-tracks`
'''
pass
| 7 | 4 | 13 | 2 | 4 | 7 | 1 | 1.56 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 7 | 50 | 9 | 16 | 10 | 9 | 25 | 13 | 7 | 9 | 1 | 1 | 0 | 3 |
140,890 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/feature_playlist_fetcher.py
|
kkbox_developer_sdk.feature_playlist_fetcher.KKBOXFeaturePlaylistFetcher
|
class KKBOXFeaturePlaylistFetcher(Fetcher):
'''
List all featured playlists metadata.
See `https://docs-en.kkbox.codes/v1.1/reference#featured-playlists`.
'''
@assert_access_token
def fetch_all_feature_playlists(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches featured playlists.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#featuredplaylists`.
'''
url = 'https://api.kkbox.com/v1.1/featured-playlists'
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_feature_playlist(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches featured playlists.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#featuredplaylists-playlist_id`.
'''
url = 'https://api.kkbox.com/v1.1/featured-playlists/%s' % playlist_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_feature_playlist_tracks(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches featured playlists.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#featuredplaylists-playlist_id-tracks`.
'''
url = 'https://api.kkbox.com/v1.1/featured-playlists/%s/tracks' % playlist_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class KKBOXFeaturePlaylistFetcher(Fetcher):
'''
List all featured playlists metadata.
See `https://docs-en.kkbox.codes/v1.1/reference#featured-playlists`.
'''
@assert_access_token
def fetch_all_feature_playlists(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches featured playlists.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#featuredplaylists`.
'''
pass
@assert_access_token
def fetch_feature_playlist(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches featured playlists.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#featuredplaylists-playlist_id`.
'''
pass
@assert_access_token
def fetch_feature_playlist_tracks(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches featured playlists.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#featuredplaylists-playlist_id-tracks`.
'''
pass
| 7 | 4 | 13 | 2 | 4 | 7 | 1 | 1.56 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 7 | 50 | 9 | 16 | 10 | 9 | 25 | 13 | 7 | 9 | 1 | 1 | 0 | 3 |
140,891 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/fetcher.py
|
kkbox_developer_sdk.fetcher.Fetcher
|
class Fetcher:
'''
Base class for various fetchers.
'''
@property
def access_token(self):
return self.http.access_token
def __init__(self, access_token):
#: The http client
self.http = KKBOXHTTP(access_token)
def fetch_next_page(self, data):
'''
Fetches next page based on previously fetched data.
Will get the next page url from data['paging']['next'].
:param data: previously fetched API response.
:type data: dict
:return: API response.
:rtype: dict
'''
next_url = data['paging']['next']
if next_url != None:
next_data = self.http._post_data(next_url, None, self.http._headers_with_access_token())
return next_data
else:
return None
def fetch_data(self, url):
'''
Fetches data from specific url.
:return: The response.
:rtype: dict
'''
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class Fetcher:
'''
Base class for various fetchers.
'''
@property
def access_token(self):
pass
def __init__(self, access_token):
pass
def fetch_next_page(self, data):
'''
Fetches next page based on previously fetched data.
Will get the next page url from data['paging']['next'].
:param data: previously fetched API response.
:type data: dict
:return: API response.
:rtype: dict
'''
pass
def fetch_data(self, url):
'''
Fetches data from specific url.
:return: The response.
:rtype: dict
'''
pass
| 6 | 3 | 7 | 1 | 3 | 4 | 1 | 1.13 | 0 | 1 | 1 | 12 | 4 | 1 | 4 | 4 | 37 | 5 | 15 | 9 | 9 | 17 | 13 | 8 | 8 | 2 | 0 | 1 | 5 |
140,892 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/genre_station_fetcher.py
|
kkbox_developer_sdk.genre_station_fetcher.KKBOXGenreStationFetcher
|
class KKBOXGenreStationFetcher(Fetcher):
'''
Fetch genre stations and get tracks for a specific genre station.
See `https://docs-en.kkbox.codes/v1.1/reference#genre-stations`.
'''
@assert_access_token
def fetch_all_genre_stations(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches all genre stations.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#genrestations`.
'''
url = 'https://api.kkbox.com/v1.1/genre-stations'
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_genre_station(self, station_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches a genre station by given ID.
:param station_id: the station ID
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#genrestations-station_id`.
'''
url = 'https://api.kkbox.com/v1.1/genre-stations/%s' % station_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class KKBOXGenreStationFetcher(Fetcher):
'''
Fetch genre stations and get tracks for a specific genre station.
See `https://docs-en.kkbox.codes/v1.1/reference#genre-stations`.
'''
@assert_access_token
def fetch_all_genre_stations(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches all genre stations.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#genrestations`.
'''
pass
@assert_access_token
def fetch_genre_station(self, station_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches a genre station by given ID.
:param station_id: the station ID
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#genrestations-station_id`.
'''
pass
| 5 | 3 | 14 | 2 | 4 | 8 | 1 | 1.73 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 6 | 36 | 6 | 11 | 7 | 6 | 19 | 9 | 5 | 6 | 1 | 1 | 0 | 2 |
140,893 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/http.py
|
kkbox_developer_sdk.http.KKBOXHTTP
|
class KKBOXHTTP:
'''
Do request to open api server with authorization header and error catch.
'''
USER_AGENT = 'KKBOX Open/Partner API Python SDK'
def __init__(self, access_token = None):
self.access_token = access_token
def _do_post(self, url, data, headers):
try: # Python 3
if data != None:
data = bytes(data, 'utf-8')
except: # Python 2
pass
try:
req = url_request.Request(url=url, data=data, headers=headers)
req.add_header('User-Agent', KKBOXHTTP.USER_AGENT)
f = url_request.urlopen(req)
r = f.read()
except url_request.HTTPError as e:
print(e.fp.read())
raise (e)
except Exception as e:
raise (e)
try: # Python 3
r = str(r, 'utf-8')
except: # Python 2
pass
json_object = json.loads(r)
return json_object
def _post_data(self, url, post_parameters, headers):
data = url_parse.urlencode(
post_parameters) if post_parameters != None else None
return self._do_post(url, data, headers)
def _headers_with_access_token(self):
return {'Authorization': 'Bearer %s' % self.access_token.access_token}
|
class KKBOXHTTP:
'''
Do request to open api server with authorization header and error catch.
'''
def __init__(self, access_token = None):
pass
def _do_post(self, url, data, headers):
pass
def _post_data(self, url, post_parameters, headers):
pass
def _headers_with_access_token(self):
pass
| 5 | 1 | 8 | 1 | 8 | 1 | 3 | 0.22 | 0 | 5 | 0 | 0 | 4 | 1 | 4 | 4 | 42 | 7 | 32 | 13 | 27 | 7 | 31 | 12 | 26 | 6 | 0 | 2 | 10 |
140,894 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/mood_station_fetcher.py
|
kkbox_developer_sdk.mood_station_fetcher.KKBOXMoodStationFetcher
|
class KKBOXMoodStationFetcher(Fetcher):
'''
Fetch mood stations and get tracks for a specific mood station.
See `https://docs-en.kkbox.codes/v1.1/reference#mood-stations`.
'''
@assert_access_token
def fetch_all_mood_stations(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches all mood stations.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#moodstations`.
'''
url = 'https://api.kkbox.com/v1.1/mood-stations'
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_mood_station(self, station_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches a mood station by given ID.
:param station_id: the station ID
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#moodstations-station_id`.
'''
url = 'https://api.kkbox.com/v1.1/mood-stations/%s' % station_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class KKBOXMoodStationFetcher(Fetcher):
'''
Fetch mood stations and get tracks for a specific mood station.
See `https://docs-en.kkbox.codes/v1.1/reference#mood-stations`.
'''
@assert_access_token
def fetch_all_mood_stations(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches all mood stations.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#moodstations`.
'''
pass
@assert_access_token
def fetch_mood_station(self, station_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches a mood station by given ID.
:param station_id: the station ID
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#moodstations-station_id`.
'''
pass
| 5 | 3 | 14 | 2 | 4 | 8 | 1 | 1.73 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 6 | 36 | 6 | 11 | 7 | 6 | 19 | 9 | 5 | 6 | 1 | 1 | 0 | 2 |
140,895 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/new_hits_playlist_fetcher.py
|
kkbox_developer_sdk.new_hits_playlist_fetcher.KKBOXNewHitsPlaylistFetcher
|
class KKBOXNewHitsPlaylistFetcher(Fetcher):
'''
List all new hits playlists and fetch tracks for specific new hit playlist.
See 'https://docs-en.kkbox.codes/v1.1/reference#new-hits-playlists'.
'''
@assert_access_token
def fetch_all_new_hits_playlists(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches all new hits playlists.
:param terr: the current territory.
:return: API response.
:rtype: dict
See 'https://docs-en.kkbox.codes/v1.1/reference#newhitsplaylists'
'''
url = 'https://api.kkbox.com/v1.1/new-hits-playlists'
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_new_hits_playlist(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches new hits playlist by given ID.
:param playlist_id: the playlist ID.
:type playlist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See 'https://docs-en.kkbox.codes/v1.1/reference#newhitsplaylists-playlist_id'
'''
url = 'https://api.kkbox.com/v1.1/new-hits-playlists/%s' % playlist_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_new_hits_playlist_tracks(self, playlist_id, terr= KKBOXTerritory.TAIWAN):
'''
Fetches new hits playlist by given ID.
:param playlist_id: the playlist ID.
:type playlist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See 'https://docs-en.kkbox.codes/v1.1/reference#newhitsplaylists-playlist_id-tracks'
'''
url = 'https://api.kkbox.com/v1.1/new-hits-playlists/%s/tracks' % playlist_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class KKBOXNewHitsPlaylistFetcher(Fetcher):
'''
List all new hits playlists and fetch tracks for specific new hit playlist.
See 'https://docs-en.kkbox.codes/v1.1/reference#new-hits-playlists'.
'''
@assert_access_token
def fetch_all_new_hits_playlists(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches all new hits playlists.
:param terr: the current territory.
:return: API response.
:rtype: dict
See 'https://docs-en.kkbox.codes/v1.1/reference#newhitsplaylists'
'''
pass
@assert_access_token
def fetch_new_hits_playlist(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches new hits playlist by given ID.
:param playlist_id: the playlist ID.
:type playlist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See 'https://docs-en.kkbox.codes/v1.1/reference#newhitsplaylists-playlist_id'
'''
pass
@assert_access_token
def fetch_new_hits_playlist_tracks(self, playlist_id, terr= KKBOXTerritory.TAIWAN):
'''
Fetches new hits playlist by given ID.
:param playlist_id: the playlist ID.
:type playlist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See 'https://docs-en.kkbox.codes/v1.1/reference#newhitsplaylists-playlist_id-tracks'
'''
pass
| 7 | 4 | 14 | 2 | 4 | 8 | 1 | 1.81 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 7 | 54 | 9 | 16 | 10 | 9 | 29 | 13 | 7 | 9 | 1 | 1 | 0 | 3 |
140,896 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/kkbox_developer_sdk/feature_playlist_category_fetcher.py
|
kkbox_developer_sdk.feature_playlist_category_fetcher.KKBOXFeaturePlaylistCategoryFetcher
|
class KKBOXFeaturePlaylistCategoryFetcher(Fetcher):
'''
List feature playlist categories and list feature playlists for a specific category.
See `https://docs-en.kkbox.codes/v1.1/reference#featured-playlist-categories`.
'''
@assert_access_token
def fetch_categories_of_feature_playlist(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches categories of featured playlist.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#featuredplaylistcategories`.
'''
url = 'https://api.kkbox.com/v1.1/featured-playlist-categories'
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_feature_playlist_by_category(self, category_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches featured playlist by given category ID.
:param category: the category.
:type category: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#featuredplaylistcategories-category_id`.
'''
url = 'https://api.kkbox.com/v1.1/featured-playlist-categories/%s' % category_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
@assert_access_token
def fetch_playlists_of_feature_playlist_category(self, category_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches playlists of featured playlist category by given ID.
:param category: the category.
:type category: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#featuredplaylistcategories-category_id-playlists`.
'''
url = 'https://api.kkbox.com/v1.1/featured-playlist-categories/%s/playlists' % category_id
url += '?' + url_parse.urlencode({'territory': terr})
return self.http._post_data(url, None, self.http._headers_with_access_token())
|
class KKBOXFeaturePlaylistCategoryFetcher(Fetcher):
'''
List feature playlist categories and list feature playlists for a specific category.
See `https://docs-en.kkbox.codes/v1.1/reference#featured-playlist-categories`.
'''
@assert_access_token
def fetch_categories_of_feature_playlist(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches categories of featured playlist.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#featuredplaylistcategories`.
'''
pass
@assert_access_token
def fetch_feature_playlist_by_category(self, category_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches featured playlist by given category ID.
:param category: the category.
:type category: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#featuredplaylistcategories-category_id`.
'''
pass
@assert_access_token
def fetch_playlists_of_feature_playlist_category(self, category_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches playlists of featured playlist category by given ID.
:param category: the category.
:type category: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#featuredplaylistcategories-category_id-playlists`.
'''
pass
| 7 | 4 | 14 | 2 | 4 | 8 | 1 | 1.81 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 7 | 54 | 9 | 16 | 10 | 9 | 29 | 13 | 7 | 9 | 1 | 1 | 0 | 3 |
140,897 |
KKBOX/OpenAPI-Python
|
KKBOX_OpenAPI-Python/test/readMeTest.py
|
readMeTest.TestReadMe
|
class TestReadMe(unittest.TestCase):
def testReadMeExample(self):
from kkbox_developer_sdk.auth_flow import KKBOXOAuth
from client import ClientInfo
auth = KKBOXOAuth(ClientInfo.client_id, ClientInfo.client_secret)
token = auth.fetch_access_token_by_client_credentials()
from kkbox_developer_sdk.api import KKBOXAPI
kkboxapi = KKBOXAPI(token)
artist_id = '8q3_xzjl89Yakn_7GB'
artist = kkboxapi.artist_fetcher.fetch_artist(artist_id)
assert(artist != None)
|
class TestReadMe(unittest.TestCase):
def testReadMeExample(self):
pass
| 2 | 0 | 10 | 0 | 10 | 0 | 1 | 0 | 1 | 2 | 2 | 0 | 1 | 0 | 1 | 73 | 11 | 0 | 11 | 10 | 6 | 0 | 11 | 10 | 6 | 1 | 2 | 0 | 1 |
140,898 |
KLab/Flask-PyMemcache
|
tests/test_flask_pymemcache.py
|
test_flask_pymemcache.TestFlaskPyMemcache
|
class TestFlaskPyMemcache(TestCase):
def test_simple(self):
pymc = pymemcache.client.Client(("localhost", 11211))
memcache = flask_pymemcache.FlaskPyMemcache()
app = flask.Flask(__name__)
app.config["PYMEMCACHE"] = {
"server": ("localhost", 11211),
"key_prefix": b"px",
"close_on_teardown": False,
}
memcache.init_app(app)
with app.app_context():
memcache.client.set(b"foo", b"bar")
with app.app_context():
assert memcache.client.get(b"foo") == b"bar"
assert pymc.get(b"pxfoo") == b"bar"
def test_pool(self):
memcache = flask_pymemcache.FlaskPyMemcache()
app = flask.Flask(__name__)
app.config["PYMEMCACHE"] = {
"server": ("localhost", 11211),
"key_prefix": b"px",
"close_on_teardown": False,
}
memcache.init_app(app, client_class=pymemcache.PooledClient)
with app.app_context():
assert memcache.client.get(b"foo") is None
assert isinstance(memcache.client, pymemcache.PooledClient)
|
class TestFlaskPyMemcache(TestCase):
def test_simple(self):
pass
def test_pool(self):
pass
| 3 | 0 | 16 | 2 | 14 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 74 | 33 | 5 | 28 | 8 | 25 | 0 | 20 | 8 | 17 | 1 | 2 | 1 | 2 |
140,899 |
KLab/Flask-PyMemcache
|
src/flask_pymemcache.py
|
flask_pymemcache.FlaskPyMemcache
|
class FlaskPyMemcache:
def __init__(self, app=None, conf_key=None, client_class=None) -> None:
"""
:type app: flask.Flask
:parm str conf_key: Key of flask config.
"""
self.conf_key = conf_key
if app is not None:
self.init_app(app, conf_key, client_class)
def init_app(self, app, conf_key=None, client_class=None) -> None:
"""
:type app: flask.Flask
:parm str conf_key: Key of flask config.
"""
conf_key = conf_key or self.conf_key or "PYMEMCACHE"
self.conf_key = conf_key
conf = app.config[conf_key]
if not isinstance(conf, dict):
raise TypeError("Flask-PyMemcache conf should be dict")
close_on_teardown = conf.pop("close_on_teardown", False)
if isinstance(conf["server"], list):
conf["servers"] = conf.pop("server")
client = (client_class or pymemcache.HashClient)(**conf)
elif isinstance(conf["server"], tuple):
client = (client_class or pymemcache.Client)(**conf)
else:
raise TypeError(
"Flask-PyMemcache conf['server'] should be tuple or list of tuples"
)
app.extensions.setdefault("pymemcache", {})
app.extensions["pymemcache"][self] = client
if close_on_teardown:
@app.teardown_appcontext
def close_connection(exc=None):
client.close()
@property
def client(self) -> pymemcache.Client:
return flask.current_app.extensions["pymemcache"][self]
|
class FlaskPyMemcache:
def __init__(self, app=None, conf_key=None, client_class=None) -> None:
'''
:type app: flask.Flask
:parm str conf_key: Key of flask config.
'''
pass
def init_app(self, app, conf_key=None, client_class=None) -> None:
'''
:type app: flask.Flask
:parm str conf_key: Key of flask config.
'''
pass
@app.teardown_appcontext
def close_connection(exc=None):
pass
@property
def client(self) -> pymemcache.Client:
pass
| 7 | 2 | 11 | 1 | 8 | 2 | 2 | 0.27 | 0 | 4 | 0 | 0 | 3 | 1 | 3 | 3 | 45 | 7 | 30 | 11 | 23 | 8 | 24 | 9 | 19 | 5 | 0 | 1 | 9 |
140,900 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kaggle/api/kaggle_api_extended.py
|
src.kaggle.api.kaggle_api_extended.DirectoryArchive
|
class DirectoryArchive(object):
def __init__(self, fullpath, format):
self._fullpath = fullpath
self._format = format
self.name = None
self.path = None
def __enter__(self):
self._temp_dir = tempfile.mkdtemp()
_, dir_name = os.path.split(self._fullpath)
self.path = shutil.make_archive(
os.path.join(self._temp_dir, dir_name), self._format, self._fullpath)
_, self.name = os.path.split(self.path)
return self
def __exit__(self, *args):
shutil.rmtree(self._temp_dir)
|
class DirectoryArchive(object):
def __init__(self, fullpath, format):
pass
def __enter__(self):
pass
def __exit__(self, *args):
pass
| 4 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 5 | 3 | 3 | 18 | 3 | 15 | 10 | 11 | 0 | 14 | 10 | 10 | 1 | 1 | 0 | 3 |
140,901 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kaggle_object.py
|
src.kagglesdk.kaggle_object.ListSerializer
|
class ListSerializer(ObjectSerializer):
def __init__(self, item_serializer: ObjectSerializer):
"""
Lists are serialized based on the type they contain. Since objects are generated from proto files, a list always
contains objects of the same type, which is serialized/deserialized using "item_serializer".
"""
ObjectSerializer.__init__(self,
lambda cls, l, ignore_defaults: [item_serializer.to_dict_value(cls, v, ignore_defaults) for v in l],
lambda cls, l: [item_serializer.from_dict_value(cls, v) for v in l])
|
class ListSerializer(ObjectSerializer):
def __init__(self, item_serializer: ObjectSerializer):
'''
Lists are serialized based on the type they contain. Since objects are generated from proto files, a list always
contains objects of the same type, which is serialized/deserialized using "item_serializer".
'''
pass
| 2 | 1 | 8 | 0 | 4 | 4 | 1 | 0.8 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 2 | 9 | 0 | 5 | 2 | 3 | 4 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
140,902 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kaggle_object.py
|
src.kagglesdk.kaggle_object.MapSerializer
|
class MapSerializer(ObjectSerializer):
def __init__(self, item_serializer: ObjectSerializer):
"""
Maps are serialized based on type of their values. Since maps keys are always predefined types, we don't need a
serializer for them.
"""
ObjectSerializer.__init__(self,
lambda cls, d, ignore_defaults: {k: item_serializer.to_dict_value(cls, v, ignore_defaults) for k, v in d.items()},
lambda cls, d: {k: item_serializer.from_dict_value(cls, v) for k, v in d.items()})
|
class MapSerializer(ObjectSerializer):
def __init__(self, item_serializer: ObjectSerializer):
'''
Maps are serialized based on type of their values. Since maps keys are always predefined types, we don't need a
serializer for them.
'''
pass
| 2 | 1 | 8 | 0 | 4 | 4 | 1 | 0.8 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 2 | 9 | 0 | 5 | 2 | 3 | 4 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
140,903 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kaggle_object.py
|
src.kagglesdk.kaggle_object.ObjectSerializer
|
class ObjectSerializer(object):
def __init__(self, to_dict_value, from_dict_value):
self.to_dict_value = to_dict_value
self.from_dict_value = from_dict_value
|
class ObjectSerializer(object):
def __init__(self, to_dict_value, from_dict_value):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 8 | 1 | 2 | 1 | 1 | 4 | 0 | 4 | 4 | 2 | 0 | 4 | 4 | 2 | 1 | 1 | 0 | 1 |
140,904 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kaggle_object.py
|
src.kagglesdk.kaggle_object.PredefinedSerializer
|
class PredefinedSerializer(ObjectSerializer):
def __init__(self):
"""Predefined objects such as int, float etc are serialized/deserialized directly."""
ObjectSerializer.__init__(self, lambda cls, v, _: v, lambda cls, v: v)
|
class PredefinedSerializer(ObjectSerializer):
def __init__(self):
'''Predefined objects such as int, float etc are serialized/deserialized directly.'''
pass
| 2 | 1 | 3 | 0 | 2 | 1 | 1 | 0.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 2 | 4 | 0 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
140,905 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kaggle_object.py
|
src.kagglesdk.kaggle_object.TimeDeltaSerializer
|
class TimeDeltaSerializer(ObjectSerializer):
def __init__(self):
"""Time deltas are serialized/deserialized as a string in "mm:ss" format"""
ObjectSerializer.__init__(self,
lambda cls, t, _: TimeDeltaSerializer._to_dict_value(t),
lambda cls, v: TimeDeltaSerializer._from_dict_value(v))
@staticmethod
def _to_dict_value(delta):
seconds = int(delta.total_seconds())
minutes = seconds // 60
seconds -= minutes * 60
return '{}:{:02}'.format(int(minutes), int(seconds))
@staticmethod
def _from_dict_value(value):
(minutes, seconds) = value.split(':')
return timedelta(minutes=int(minutes), seconds=int(seconds))
|
class TimeDeltaSerializer(ObjectSerializer):
def __init__(self):
'''Time deltas are serialized/deserialized as a string in "mm:ss" format'''
pass
@staticmethod
def _to_dict_value(delta):
pass
@staticmethod
def _from_dict_value(value):
pass
| 6 | 1 | 4 | 0 | 4 | 0 | 1 | 0.07 | 1 | 2 | 0 | 0 | 1 | 0 | 3 | 4 | 18 | 2 | 15 | 9 | 9 | 1 | 11 | 7 | 7 | 1 | 2 | 0 | 3 |
140,906 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/services/kernels_api_service.py
|
src.kagglesdk.kernels.services.kernels_api_service.KernelsApiClient
|
class KernelsApiClient(object):
def __init__(self, client: KaggleHttpClient):
self._client = client
def list_kernels(self, request: ApiListKernelsRequest = None) -> ApiListKernelsResponse:
r"""
Args:
request (ApiListKernelsRequest):
The request object; initialized to empty instance if not specified.
"""
if request is None:
request = ApiListKernelsRequest()
return self._client.call("kernels.KernelsApiService", "ApiListKernels", request, ApiListKernelsResponse)
def list_kernel_files(self, request: ApiListKernelFilesRequest = None) -> ApiListKernelFilesResponse:
r"""
Args:
request (ApiListKernelFilesRequest):
The request object; initialized to empty instance if not specified.
"""
if request is None:
request = ApiListKernelFilesRequest()
return self._client.call("kernels.KernelsApiService", "ApiListKernelFiles", request, ApiListKernelFilesResponse)
def get_kernel(self, request: ApiGetKernelRequest = None) -> ApiGetKernelResponse:
r"""
Args:
request (ApiGetKernelRequest):
The request object; initialized to empty instance if not specified.
"""
if request is None:
request = ApiGetKernelRequest()
return self._client.call("kernels.KernelsApiService", "ApiGetKernel", request, ApiGetKernelResponse)
def save_kernel(self, request: ApiSaveKernelRequest = None) -> ApiSaveKernelResponse:
r"""
Args:
request (ApiSaveKernelRequest):
The request object; initialized to empty instance if not specified.
"""
if request is None:
request = ApiSaveKernelRequest()
return self._client.call("kernels.KernelsApiService", "ApiSaveKernel", request, ApiSaveKernelResponse)
def list_kernel_session_output(self, request: ApiListKernelSessionOutputRequest = None) -> ApiListKernelSessionOutputResponse:
r"""
Args:
request (ApiListKernelSessionOutputRequest):
The request object; initialized to empty instance if not specified.
"""
if request is None:
request = ApiListKernelSessionOutputRequest()
return self._client.call("kernels.KernelsApiService", "ApiListKernelSessionOutput", request, ApiListKernelSessionOutputResponse)
def get_kernel_session_status(self, request: ApiGetKernelSessionStatusRequest = None) -> ApiGetKernelSessionStatusResponse:
r"""
Args:
request (ApiGetKernelSessionStatusRequest):
The request object; initialized to empty instance if not specified.
"""
if request is None:
request = ApiGetKernelSessionStatusRequest()
return self._client.call("kernels.KernelsApiService", "ApiGetKernelSessionStatus", request, ApiGetKernelSessionStatusResponse)
def download_kernel_output(self, request: ApiDownloadKernelOutputRequest = None) -> HttpRedirect:
r"""
Meant for use by Kaggle Hub (http bindings and terminology align with that)
Args:
request (ApiDownloadKernelOutputRequest):
The request object; initialized to empty instance if not specified.
"""
if request is None:
request = ApiDownloadKernelOutputRequest()
return self._client.call("kernels.KernelsApiService", "ApiDownloadKernelOutput", request, HttpRedirect)
def download_kernel_output_zip(self, request: ApiDownloadKernelOutputZipRequest = None) -> FileDownload:
r"""
Meant for use by Kaggle Hub (and DownloadKernelOutput above)
Args:
request (ApiDownloadKernelOutputZipRequest):
The request object; initialized to empty instance if not specified.
"""
if request is None:
request = ApiDownloadKernelOutputZipRequest()
return self._client.call("kernels.KernelsApiService", "ApiDownloadKernelOutputZip", request, FileDownload)
|
class KernelsApiClient(object):
def __init__(self, client: KaggleHttpClient):
pass
def list_kernels(self, request: ApiListKernelsRequest = None) -> ApiListKernelsResponse:
'''
Args:
request (ApiListKernelsRequest):
The request object; initialized to empty instance if not specified.
'''
pass
def list_kernel_files(self, request: ApiListKernelFilesRequest = None) -> ApiListKernelFilesResponse:
'''
Args:
request (ApiListKernelFilesRequest):
The request object; initialized to empty instance if not specified.
'''
pass
def get_kernel(self, request: ApiGetKernelRequest = None) -> ApiGetKernelResponse:
'''
Args:
request (ApiGetKernelRequest):
The request object; initialized to empty instance if not specified.
'''
pass
def save_kernel(self, request: ApiSaveKernelRequest = None) -> ApiSaveKernelResponse:
'''
Args:
request (ApiSaveKernelRequest):
The request object; initialized to empty instance if not specified.
'''
pass
def list_kernel_session_output(self, request: ApiListKernelSessionOutputRequest = None) -> ApiListKernelSessionOutputResponse:
'''
Args:
request (ApiListKernelSessionOutputRequest):
The request object; initialized to empty instance if not specified.
'''
pass
def get_kernel_session_status(self, request: ApiGetKernelSessionStatusRequest = None) -> ApiGetKernelSessionStatusResponse:
'''
Args:
request (ApiGetKernelSessionStatusRequest):
The request object; initialized to empty instance if not specified.
'''
pass
def download_kernel_output(self, request: ApiDownloadKernelOutputRequest = None) -> HttpRedirect:
'''
Meant for use by Kaggle Hub (http bindings and terminology align with that)
Args:
request (ApiDownloadKernelOutputRequest):
The request object; initialized to empty instance if not specified.
'''
pass
def download_kernel_output_zip(self, request: ApiDownloadKernelOutputZipRequest = None) -> FileDownload:
'''
Meant for use by Kaggle Hub (and DownloadKernelOutput above)
Args:
request (ApiDownloadKernelOutputZipRequest):
The request object; initialized to empty instance if not specified.
'''
pass
| 10 | 8 | 10 | 2 | 4 | 5 | 2 | 1.2 | 1 | 17 | 17 | 0 | 9 | 1 | 9 | 9 | 104 | 27 | 35 | 11 | 25 | 42 | 35 | 11 | 25 | 2 | 1 | 1 | 17 |
140,907 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiDownloadKernelOutputRequest
|
class ApiDownloadKernelOutputRequest(KaggleObject):
r"""
Attributes:
owner_slug (str)
kernel_slug (str)
file_path (str)
Relative path to a specific file inside the databundle.
version_number (int)
"""
def __init__(self):
self._owner_slug = ""
self._kernel_slug = ""
self._file_path = None
self._version_number = None
self._freeze()
@property
def owner_slug(self) -> str:
return self._owner_slug
@owner_slug.setter
def owner_slug(self, owner_slug: str):
if owner_slug is None:
del self.owner_slug
return
if not isinstance(owner_slug, str):
raise TypeError('owner_slug must be of type str')
self._owner_slug = owner_slug
@property
def kernel_slug(self) -> str:
return self._kernel_slug
@kernel_slug.setter
def kernel_slug(self, kernel_slug: str):
if kernel_slug is None:
del self.kernel_slug
return
if not isinstance(kernel_slug, str):
raise TypeError('kernel_slug must be of type str')
self._kernel_slug = kernel_slug
@property
def file_path(self) -> str:
"""Relative path to a specific file inside the databundle."""
return self._file_path or ""
@file_path.setter
def file_path(self, file_path: str):
if file_path is None:
del self.file_path
return
if not isinstance(file_path, str):
raise TypeError('file_path must be of type str')
self._file_path = file_path
@property
def version_number(self) -> int:
return self._version_number or 0
@version_number.setter
def version_number(self, version_number: int):
if version_number is None:
del self.version_number
return
if not isinstance(version_number, int):
raise TypeError('version_number must be of type int')
self._version_number = version_number
def endpoint(self):
if self.file_path:
path = '/api/v1/kernels/output/download/{owner_slug}/{kernel_slug}/{file_path}'
else:
path = '/api/v1/kernels/output/download/{owner_slug}/{kernel_slug}'
return path.format_map(self.to_field_map(self))
@staticmethod
def endpoint_path():
return '/api/v1/kernels/output/download/{owner_slug}/{kernel_slug}'
|
class ApiDownloadKernelOutputRequest(KaggleObject):
'''
Attributes:
owner_slug (str)
kernel_slug (str)
file_path (str)
Relative path to a specific file inside the databundle.
version_number (int)
'''
def __init__(self):
pass
@property
def owner_slug(self) -> str:
pass
@owner_slug.setter
def owner_slug(self) -> str:
pass
@property
def kernel_slug(self) -> str:
pass
@kernel_slug.setter
def kernel_slug(self) -> str:
pass
@property
def file_path(self) -> str:
'''Relative path to a specific file inside the databundle.'''
pass
@file_path.setter
def file_path(self) -> str:
pass
@property
def version_number(self) -> int:
pass
@version_number.setter
def version_number(self) -> int:
pass
def endpoint(self):
pass
@staticmethod
def endpoint_path():
pass
| 21 | 2 | 5 | 0 | 5 | 0 | 2 | 0.15 | 1 | 3 | 0 | 0 | 10 | 4 | 11 | 28 | 80 | 11 | 60 | 26 | 39 | 9 | 50 | 17 | 38 | 3 | 2 | 1 | 20 |
140,908 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiDownloadKernelOutputZipRequest
|
class ApiDownloadKernelOutputZipRequest(KaggleObject):
r"""
Attributes:
kernel_session_id (int)
"""
def __init__(self):
self._kernel_session_id = 0
self._freeze()
@property
def kernel_session_id(self) -> int:
return self._kernel_session_id
@kernel_session_id.setter
def kernel_session_id(self, kernel_session_id: int):
if kernel_session_id is None:
del self.kernel_session_id
return
if not isinstance(kernel_session_id, int):
raise TypeError('kernel_session_id must be of type int')
self._kernel_session_id = kernel_session_id
def endpoint(self):
path = '/api/v1/kernels/output/download_zip/{kernel_session_id}'
return path.format_map(self.to_field_map(self))
@staticmethod
def endpoint_path():
return '/api/v1/kernels/output/download_zip/{kernel_session_id}'
|
class ApiDownloadKernelOutputZipRequest(KaggleObject):
'''
Attributes:
kernel_session_id (int)
'''
def __init__(self):
pass
@property
def kernel_session_id(self) -> int:
pass
@kernel_session_id.setter
def kernel_session_id(self) -> int:
pass
def endpoint(self):
pass
@staticmethod
def endpoint_path():
pass
| 9 | 1 | 3 | 0 | 3 | 0 | 1 | 0.19 | 1 | 2 | 0 | 0 | 4 | 1 | 5 | 22 | 30 | 5 | 21 | 11 | 12 | 4 | 18 | 8 | 12 | 3 | 2 | 1 | 7 |
140,909 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiGetKernelRequest
|
class ApiGetKernelRequest(KaggleObject):
r"""
Attributes:
user_name (str)
kernel_slug (str)
"""
def __init__(self):
self._user_name = ""
self._kernel_slug = ""
self._freeze()
@property
def user_name(self) -> str:
return self._user_name
@user_name.setter
def user_name(self, user_name: str):
if user_name is None:
del self.user_name
return
if not isinstance(user_name, str):
raise TypeError('user_name must be of type str')
self._user_name = user_name
@property
def kernel_slug(self) -> str:
return self._kernel_slug
@kernel_slug.setter
def kernel_slug(self, kernel_slug: str):
if kernel_slug is None:
del self.kernel_slug
return
if not isinstance(kernel_slug, str):
raise TypeError('kernel_slug must be of type str')
self._kernel_slug = kernel_slug
def endpoint(self):
path = '/api/v1/kernels/pull'
return path.format_map(self.to_field_map(self))
|
class ApiGetKernelRequest(KaggleObject):
'''
Attributes:
user_name (str)
kernel_slug (str)
'''
def __init__(self):
pass
@property
def user_name(self) -> str:
pass
@user_name.setter
def user_name(self) -> str:
pass
@property
def kernel_slug(self) -> str:
pass
@kernel_slug.setter
def kernel_slug(self) -> str:
pass
def endpoint(self):
pass
| 11 | 1 | 4 | 0 | 4 | 0 | 2 | 0.17 | 1 | 2 | 0 | 0 | 6 | 2 | 6 | 23 | 41 | 6 | 30 | 14 | 19 | 5 | 26 | 10 | 19 | 3 | 2 | 1 | 10 |
140,910 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiGetKernelResponse
|
class ApiGetKernelResponse(KaggleObject):
r"""
Attributes:
metadata (ApiKernelMetadata)
blob (ApiKernelBlob)
"""
def __init__(self):
self._metadata = None
self._blob = None
self._freeze()
@property
def metadata(self) -> Optional['ApiKernelMetadata']:
return self._metadata
@metadata.setter
def metadata(self, metadata: Optional['ApiKernelMetadata']):
if metadata is None:
del self.metadata
return
if not isinstance(metadata, ApiKernelMetadata):
raise TypeError('metadata must be of type ApiKernelMetadata')
self._metadata = metadata
@property
def blob(self) -> Optional['ApiKernelBlob']:
return self._blob
@blob.setter
def blob(self, blob: Optional['ApiKernelBlob']):
if blob is None:
del self.blob
return
if not isinstance(blob, ApiKernelBlob):
raise TypeError('blob must be of type ApiKernelBlob')
self._blob = blob
|
class ApiGetKernelResponse(KaggleObject):
'''
Attributes:
metadata (ApiKernelMetadata)
blob (ApiKernelBlob)
'''
def __init__(self):
pass
@property
def metadata(self) -> Optional['ApiKernelMetadata']:
pass
@metadata.setter
def metadata(self) -> Optional['ApiKernelMetadata']:
pass
@property
def blob(self) -> Optional['ApiKernelBlob']:
pass
@blob.setter
def blob(self) -> Optional['ApiKernelBlob']:
pass
| 10 | 1 | 4 | 0 | 4 | 0 | 2 | 0.19 | 1 | 3 | 2 | 0 | 5 | 2 | 5 | 22 | 37 | 5 | 27 | 12 | 17 | 5 | 23 | 8 | 17 | 3 | 2 | 1 | 9 |
140,911 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiGetKernelSessionStatusRequest
|
class ApiGetKernelSessionStatusRequest(KaggleObject):
r"""
Attributes:
user_name (str)
kernel_slug (str)
"""
def __init__(self):
self._user_name = ""
self._kernel_slug = ""
self._freeze()
@property
def user_name(self) -> str:
return self._user_name
@user_name.setter
def user_name(self, user_name: str):
if user_name is None:
del self.user_name
return
if not isinstance(user_name, str):
raise TypeError('user_name must be of type str')
self._user_name = user_name
@property
def kernel_slug(self) -> str:
return self._kernel_slug
@kernel_slug.setter
def kernel_slug(self, kernel_slug: str):
if kernel_slug is None:
del self.kernel_slug
return
if not isinstance(kernel_slug, str):
raise TypeError('kernel_slug must be of type str')
self._kernel_slug = kernel_slug
def endpoint(self):
path = '/api/v1/kernels/status'
return path.format_map(self.to_field_map(self))
|
class ApiGetKernelSessionStatusRequest(KaggleObject):
'''
Attributes:
user_name (str)
kernel_slug (str)
'''
def __init__(self):
pass
@property
def user_name(self) -> str:
pass
@user_name.setter
def user_name(self) -> str:
pass
@property
def kernel_slug(self) -> str:
pass
@kernel_slug.setter
def kernel_slug(self) -> str:
pass
def endpoint(self):
pass
| 11 | 1 | 4 | 0 | 4 | 0 | 2 | 0.17 | 1 | 2 | 0 | 0 | 6 | 2 | 6 | 23 | 41 | 6 | 30 | 14 | 19 | 5 | 26 | 10 | 19 | 3 | 2 | 1 | 10 |
140,912 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiGetKernelSessionStatusResponse
|
class ApiGetKernelSessionStatusResponse(KaggleObject):
r"""
Attributes:
status (KernelWorkerStatus)
failure_message (str)
"""
def __init__(self):
self._status = KernelWorkerStatus.QUEUED
self._failure_message = None
self._freeze()
@property
def status(self) -> 'KernelWorkerStatus':
return self._status
@status.setter
def status(self, status: 'KernelWorkerStatus'):
if status is None:
del self.status
return
if not isinstance(status, KernelWorkerStatus):
raise TypeError('status must be of type KernelWorkerStatus')
self._status = status
@property
def failure_message(self) -> str:
return self._failure_message or ""
@failure_message.setter
def failure_message(self, failure_message: str):
if failure_message is None:
del self.failure_message
return
if not isinstance(failure_message, str):
raise TypeError('failure_message must be of type str')
self._failure_message = failure_message
@property
def failureMessage(self):
return self.failure_message
|
class ApiGetKernelSessionStatusResponse(KaggleObject):
'''
Attributes:
status (KernelWorkerStatus)
failure_message (str)
'''
def __init__(self):
pass
@property
def status(self) -> 'KernelWorkerStatus':
pass
@status.setter
def status(self) -> 'KernelWorkerStatus':
pass
@property
def failure_message(self) -> str:
pass
@failure_message.setter
def failure_message(self) -> str:
pass
@property
def failureMessage(self):
pass
| 12 | 1 | 4 | 0 | 4 | 0 | 2 | 0.17 | 1 | 3 | 1 | 0 | 6 | 2 | 6 | 23 | 41 | 6 | 30 | 14 | 18 | 5 | 25 | 9 | 18 | 3 | 2 | 1 | 10 |
140,913 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiKernelBlob
|
class ApiKernelBlob(KaggleObject):
r"""
Attributes:
source (str)
language (str)
kernel_type (str)
slug (str)
"""
def __init__(self):
self._source = None
self._language = None
self._kernel_type = None
self._slug = None
self._freeze()
@property
def source(self) -> str:
return self._source or ""
@source.setter
def source(self, source: str):
if source is None:
del self.source
return
if not isinstance(source, str):
raise TypeError('source must be of type str')
self._source = source
@property
def language(self) -> str:
return self._language or ""
@language.setter
def language(self, language: str):
if language is None:
del self.language
return
if not isinstance(language, str):
raise TypeError('language must be of type str')
self._language = language
@property
def kernel_type(self) -> str:
return self._kernel_type or ""
@kernel_type.setter
def kernel_type(self, kernel_type: str):
if kernel_type is None:
del self.kernel_type
return
if not isinstance(kernel_type, str):
raise TypeError('kernel_type must be of type str')
self._kernel_type = kernel_type
@property
def slug(self) -> str:
return self._slug or ""
@slug.setter
def slug(self, slug: str):
if slug is None:
del self.slug
return
if not isinstance(slug, str):
raise TypeError('slug must be of type str')
self._slug = slug
|
class ApiKernelBlob(KaggleObject):
'''
Attributes:
source (str)
language (str)
kernel_type (str)
slug (str)
'''
def __init__(self):
pass
@property
def source(self) -> str:
pass
@source.setter
def source(self) -> str:
pass
@property
def language(self) -> str:
pass
@language.setter
def language(self) -> str:
pass
@property
def kernel_type(self) -> str:
pass
@kernel_type.setter
def kernel_type(self) -> str:
pass
@property
def slug(self) -> str:
pass
@slug.setter
def slug(self) -> str:
pass
| 18 | 1 | 5 | 0 | 5 | 0 | 2 | 0.14 | 1 | 2 | 0 | 0 | 9 | 4 | 9 | 26 | 67 | 9 | 51 | 22 | 33 | 7 | 43 | 14 | 33 | 3 | 2 | 1 | 17 |
140,914 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiKernelMetadata
|
class ApiKernelMetadata(KaggleObject):
r"""
Attributes:
id (int)
ref (str)
title (str)
author (str)
slug (str)
last_run_time (datetime)
language (str)
kernel_type (str)
is_private (bool)
enable_gpu (bool)
enable_tpu (bool)
enable_internet (bool)
category_ids (str)
dataset_data_sources (str)
kernel_data_sources (str)
competition_data_sources (str)
model_data_sources (str)
total_votes (int)
current_version_number (int)
"""
def __init__(self):
self._id = 0
self._ref = ""
self._title = ""
self._author = ""
self._slug = ""
self._last_run_time = None
self._language = None
self._kernel_type = None
self._is_private = None
self._enable_gpu = None
self._enable_tpu = None
self._enable_internet = None
self._category_ids = []
self._dataset_data_sources = []
self._kernel_data_sources = []
self._competition_data_sources = []
self._model_data_sources = []
self._total_votes = 0
self._current_version_number = None
self._freeze()
@property
def id(self) -> int:
return self._id
@id.setter
def id(self, id: int):
if id is None:
del self.id
return
if not isinstance(id, int):
raise TypeError('id must be of type int')
self._id = id
@property
def ref(self) -> str:
return self._ref
@ref.setter
def ref(self, ref: str):
if ref is None:
del self.ref
return
if not isinstance(ref, str):
raise TypeError('ref must be of type str')
self._ref = ref
@property
def title(self) -> str:
return self._title
@title.setter
def title(self, title: str):
if title is None:
del self.title
return
if not isinstance(title, str):
raise TypeError('title must be of type str')
self._title = title
@property
def author(self) -> str:
return self._author
@author.setter
def author(self, author: str):
if author is None:
del self.author
return
if not isinstance(author, str):
raise TypeError('author must be of type str')
self._author = author
@property
def slug(self) -> str:
return self._slug
@slug.setter
def slug(self, slug: str):
if slug is None:
del self.slug
return
if not isinstance(slug, str):
raise TypeError('slug must be of type str')
self._slug = slug
@property
def last_run_time(self) -> datetime:
return self._last_run_time
@last_run_time.setter
def last_run_time(self, last_run_time: datetime):
if last_run_time is None:
del self.last_run_time
return
if not isinstance(last_run_time, datetime):
raise TypeError('last_run_time must be of type datetime')
self._last_run_time = last_run_time
@property
def language(self) -> str:
return self._language or ""
@language.setter
def language(self, language: str):
if language is None:
del self.language
return
if not isinstance(language, str):
raise TypeError('language must be of type str')
self._language = language
@property
def kernel_type(self) -> str:
return self._kernel_type or ""
@kernel_type.setter
def kernel_type(self, kernel_type: str):
if kernel_type is None:
del self.kernel_type
return
if not isinstance(kernel_type, str):
raise TypeError('kernel_type must be of type str')
self._kernel_type = kernel_type
@property
def is_private(self) -> bool:
return self._is_private or False
@is_private.setter
def is_private(self, is_private: bool):
if is_private is None:
del self.is_private
return
if not isinstance(is_private, bool):
raise TypeError('is_private must be of type bool')
self._is_private = is_private
@property
def enable_gpu(self) -> bool:
return self._enable_gpu or False
@enable_gpu.setter
def enable_gpu(self, enable_gpu: bool):
if enable_gpu is None:
del self.enable_gpu
return
if not isinstance(enable_gpu, bool):
raise TypeError('enable_gpu must be of type bool')
self._enable_gpu = enable_gpu
@property
def enable_tpu(self) -> bool:
return self._enable_tpu or False
@enable_tpu.setter
def enable_tpu(self, enable_tpu: bool):
if enable_tpu is None:
del self.enable_tpu
return
if not isinstance(enable_tpu, bool):
raise TypeError('enable_tpu must be of type bool')
self._enable_tpu = enable_tpu
@property
def enable_internet(self) -> bool:
return self._enable_internet or False
@enable_internet.setter
def enable_internet(self, enable_internet: bool):
if enable_internet is None:
del self.enable_internet
return
if not isinstance(enable_internet, bool):
raise TypeError('enable_internet must be of type bool')
self._enable_internet = enable_internet
@property
def category_ids(self) -> Optional[List[str]]:
return self._category_ids
@category_ids.setter
def category_ids(self, category_ids: Optional[List[str]]):
if category_ids is None:
del self.category_ids
return
if not isinstance(category_ids, list):
raise TypeError('category_ids must be of type list')
if not all([isinstance(t, str) for t in category_ids]):
raise TypeError('category_ids must contain only items of type str')
self._category_ids = category_ids
@property
def dataset_data_sources(self) -> Optional[List[str]]:
return self._dataset_data_sources
@dataset_data_sources.setter
def dataset_data_sources(self, dataset_data_sources: Optional[List[str]]):
if dataset_data_sources is None:
del self.dataset_data_sources
return
if not isinstance(dataset_data_sources, list):
raise TypeError('dataset_data_sources must be of type list')
if not all([isinstance(t, str) for t in dataset_data_sources]):
raise TypeError('dataset_data_sources must contain only items of type str')
self._dataset_data_sources = dataset_data_sources
@property
def kernel_data_sources(self) -> Optional[List[str]]:
return self._kernel_data_sources
@kernel_data_sources.setter
def kernel_data_sources(self, kernel_data_sources: Optional[List[str]]):
if kernel_data_sources is None:
del self.kernel_data_sources
return
if not isinstance(kernel_data_sources, list):
raise TypeError('kernel_data_sources must be of type list')
if not all([isinstance(t, str) for t in kernel_data_sources]):
raise TypeError('kernel_data_sources must contain only items of type str')
self._kernel_data_sources = kernel_data_sources
@property
def competition_data_sources(self) -> Optional[List[str]]:
return self._competition_data_sources
@competition_data_sources.setter
def competition_data_sources(self, competition_data_sources: Optional[List[str]]):
if competition_data_sources is None:
del self.competition_data_sources
return
if not isinstance(competition_data_sources, list):
raise TypeError('competition_data_sources must be of type list')
if not all([isinstance(t, str) for t in competition_data_sources]):
raise TypeError('competition_data_sources must contain only items of type str')
self._competition_data_sources = competition_data_sources
@property
def model_data_sources(self) -> Optional[List[str]]:
return self._model_data_sources
@model_data_sources.setter
def model_data_sources(self, model_data_sources: Optional[List[str]]):
if model_data_sources is None:
del self.model_data_sources
return
if not isinstance(model_data_sources, list):
raise TypeError('model_data_sources must be of type list')
if not all([isinstance(t, str) for t in model_data_sources]):
raise TypeError('model_data_sources must contain only items of type str')
self._model_data_sources = model_data_sources
@property
def total_votes(self) -> int:
return self._total_votes
@total_votes.setter
def total_votes(self, total_votes: int):
if total_votes is None:
del self.total_votes
return
if not isinstance(total_votes, int):
raise TypeError('total_votes must be of type int')
self._total_votes = total_votes
@property
def current_version_number(self) -> int:
return self._current_version_number or 0
@current_version_number.setter
def current_version_number(self, current_version_number: int):
if current_version_number is None:
del self.current_version_number
return
if not isinstance(current_version_number, int):
raise TypeError('current_version_number must be of type int')
self._current_version_number = current_version_number
|
class ApiKernelMetadata(KaggleObject):
'''
Attributes:
id (int)
ref (str)
title (str)
author (str)
slug (str)
last_run_time (datetime)
language (str)
kernel_type (str)
is_private (bool)
enable_gpu (bool)
enable_tpu (bool)
enable_internet (bool)
category_ids (str)
dataset_data_sources (str)
kernel_data_sources (str)
competition_data_sources (str)
model_data_sources (str)
total_votes (int)
current_version_number (int)
'''
def __init__(self):
pass
@property
def id(self) -> int:
pass
@id.setter
def id(self) -> int:
pass
@property
def ref(self) -> str:
pass
@ref.setter
def ref(self) -> str:
pass
@property
def title(self) -> str:
pass
@title.setter
def title(self) -> str:
pass
@property
def author(self) -> str:
pass
@author.setter
def author(self) -> str:
pass
@property
def slug(self) -> str:
pass
@slug.setter
def slug(self) -> str:
pass
@property
def last_run_time(self) -> datetime:
pass
@last_run_time.setter
def last_run_time(self) -> datetime:
pass
@property
def language(self) -> str:
pass
@language.setter
def language(self) -> str:
pass
@property
def kernel_type(self) -> str:
pass
@kernel_type.setter
def kernel_type(self) -> str:
pass
@property
def is_private(self) -> bool:
pass
@is_private.setter
def is_private(self) -> bool:
pass
@property
def enable_gpu(self) -> bool:
pass
@enable_gpu.setter
def enable_gpu(self) -> bool:
pass
@property
def enable_tpu(self) -> bool:
pass
@enable_tpu.setter
def enable_tpu(self) -> bool:
pass
@property
def enable_internet(self) -> bool:
pass
@enable_internet.setter
def enable_internet(self) -> bool:
pass
@property
def category_ids(self) -> Optional[List[str]]:
pass
@category_ids.setter
def category_ids(self) -> Optional[List[str]]:
pass
@property
def dataset_data_sources(self) -> Optional[List[str]]:
pass
@dataset_data_sources.setter
def dataset_data_sources(self) -> Optional[List[str]]:
pass
@property
def kernel_data_sources(self) -> Optional[List[str]]:
pass
@kernel_data_sources.setter
def kernel_data_sources(self) -> Optional[List[str]]:
pass
@property
def competition_data_sources(self) -> Optional[List[str]]:
pass
@competition_data_sources.setter
def competition_data_sources(self) -> Optional[List[str]]:
pass
@property
def model_data_sources(self) -> Optional[List[str]]:
pass
@model_data_sources.setter
def model_data_sources(self) -> Optional[List[str]]:
pass
@property
def total_votes(self) -> int:
pass
@total_votes.setter
def total_votes(self) -> int:
pass
@property
def current_version_number(self) -> int:
pass
@current_version_number.setter
def current_version_number(self) -> int:
pass
| 78 | 1 | 5 | 0 | 5 | 0 | 2 | 0.09 | 1 | 6 | 0 | 0 | 39 | 19 | 39 | 56 | 302 | 39 | 241 | 97 | 163 | 22 | 203 | 59 | 163 | 4 | 2 | 1 | 82 |
140,915 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiKernelSessionOutputFile
|
class ApiKernelSessionOutputFile(KaggleObject):
r"""
Attributes:
url (str)
file_name (str)
"""
def __init__(self):
self._url = None
self._file_name = None
self._freeze()
@property
def url(self) -> str:
return self._url or ""
@url.setter
def url(self, url: str):
if url is None:
del self.url
return
if not isinstance(url, str):
raise TypeError('url must be of type str')
self._url = url
@property
def file_name(self) -> str:
return self._file_name or ""
@file_name.setter
def file_name(self, file_name: str):
if file_name is None:
del self.file_name
return
if not isinstance(file_name, str):
raise TypeError('file_name must be of type str')
self._file_name = file_name
|
class ApiKernelSessionOutputFile(KaggleObject):
'''
Attributes:
url (str)
file_name (str)
'''
def __init__(self):
pass
@property
def url(self) -> str:
pass
@url.setter
def url(self) -> str:
pass
@property
def file_name(self) -> str:
pass
@file_name.setter
def file_name(self) -> str:
pass
| 10 | 1 | 4 | 0 | 4 | 0 | 2 | 0.19 | 1 | 2 | 0 | 0 | 5 | 2 | 5 | 22 | 37 | 5 | 27 | 12 | 17 | 5 | 23 | 8 | 17 | 3 | 2 | 1 | 9 |
140,916 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiListKernelFilesItem
|
class ApiListKernelFilesItem(KaggleObject):
r"""
Attributes:
name (str)
size (int)
creation_date (str)
"""
def __init__(self):
self._name = ""
self._size = 0
self._creation_date = ""
self._freeze()
@property
def name(self) -> str:
return self._name
@name.setter
def name(self, name: str):
if name is None:
del self.name
return
if not isinstance(name, str):
raise TypeError('name must be of type str')
self._name = name
@property
def size(self) -> int:
return self._size
@size.setter
def size(self, size: int):
if size is None:
del self.size
return
if not isinstance(size, int):
raise TypeError('size must be of type int')
self._size = size
@property
def creation_date(self) -> str:
return self._creation_date
@creation_date.setter
def creation_date(self, creation_date: str):
if creation_date is None:
del self.creation_date
return
if not isinstance(creation_date, str):
raise TypeError('creation_date must be of type str')
self._creation_date = creation_date
|
class ApiListKernelFilesItem(KaggleObject):
'''
Attributes:
name (str)
size (int)
creation_date (str)
'''
def __init__(self):
pass
@property
def name(self) -> str:
pass
@name.setter
def name(self) -> str:
pass
@property
def size(self) -> int:
pass
@size.setter
def size(self) -> int:
pass
@property
def creation_date(self) -> str:
pass
@creation_date.setter
def creation_date(self) -> str:
pass
| 14 | 1 | 5 | 0 | 5 | 0 | 2 | 0.15 | 1 | 3 | 0 | 0 | 7 | 3 | 7 | 24 | 52 | 7 | 39 | 17 | 25 | 6 | 33 | 11 | 25 | 3 | 2 | 1 | 13 |
140,917 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiListKernelFilesRequest
|
class ApiListKernelFilesRequest(KaggleObject):
r"""
Attributes:
user_name (str)
kernel_slug (str)
page_size (int)
page_token (str)
"""
def __init__(self):
self._user_name = ""
self._kernel_slug = ""
self._page_size = None
self._page_token = None
self._freeze()
@property
def user_name(self) -> str:
return self._user_name
@user_name.setter
def user_name(self, user_name: str):
if user_name is None:
del self.user_name
return
if not isinstance(user_name, str):
raise TypeError('user_name must be of type str')
self._user_name = user_name
@property
def kernel_slug(self) -> str:
return self._kernel_slug
@kernel_slug.setter
def kernel_slug(self, kernel_slug: str):
if kernel_slug is None:
del self.kernel_slug
return
if not isinstance(kernel_slug, str):
raise TypeError('kernel_slug must be of type str')
self._kernel_slug = kernel_slug
@property
def page_size(self) -> int:
return self._page_size or 0
@page_size.setter
def page_size(self, page_size: int):
if page_size is None:
del self.page_size
return
if not isinstance(page_size, int):
raise TypeError('page_size must be of type int')
self._page_size = page_size
@property
def page_token(self) -> str:
return self._page_token or ""
@page_token.setter
def page_token(self, page_token: str):
if page_token is None:
del self.page_token
return
if not isinstance(page_token, str):
raise TypeError('page_token must be of type str')
self._page_token = page_token
def endpoint(self):
path = '/api/v1/kernels/files'
return path.format_map(self.to_field_map(self))
|
class ApiListKernelFilesRequest(KaggleObject):
'''
Attributes:
user_name (str)
kernel_slug (str)
page_size (int)
page_token (str)
'''
def __init__(self):
pass
@property
def user_name(self) -> str:
pass
@user_name.setter
def user_name(self) -> str:
pass
@property
def kernel_slug(self) -> str:
pass
@kernel_slug.setter
def kernel_slug(self) -> str:
pass
@property
def page_size(self) -> int:
pass
@page_size.setter
def page_size(self) -> int:
pass
@property
def page_token(self) -> str:
pass
@page_token.setter
def page_token(self) -> str:
pass
def endpoint(self):
pass
| 19 | 1 | 5 | 0 | 5 | 0 | 2 | 0.13 | 1 | 3 | 0 | 0 | 10 | 4 | 10 | 27 | 71 | 10 | 54 | 24 | 35 | 7 | 46 | 16 | 35 | 3 | 2 | 1 | 18 |
140,918 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiListKernelFilesResponse
|
class ApiListKernelFilesResponse(KaggleObject):
r"""
Attributes:
files (ApiListKernelFilesItem)
next_page_token (str)
"""
def __init__(self):
self._files = []
self._next_page_token = None
self._freeze()
@property
def files(self) -> Optional[List[Optional['ApiListKernelFilesItem']]]:
return self._files
@files.setter
def files(self, files: Optional[List[Optional['ApiListKernelFilesItem']]]):
if files is None:
del self.files
return
if not isinstance(files, list):
raise TypeError('files must be of type list')
if not all([isinstance(t, ApiListKernelFilesItem) for t in files]):
raise TypeError('files must contain only items of type ApiListKernelFilesItem')
self._files = files
@property
def next_page_token(self) -> str:
return self._next_page_token or ""
@next_page_token.setter
def next_page_token(self, next_page_token: str):
if next_page_token is None:
del self.next_page_token
return
if not isinstance(next_page_token, str):
raise TypeError('next_page_token must be of type str')
self._next_page_token = next_page_token
@property
def nextPageToken(self):
return self.next_page_token
|
class ApiListKernelFilesResponse(KaggleObject):
'''
Attributes:
files (ApiListKernelFilesItem)
next_page_token (str)
'''
def __init__(self):
pass
@property
def files(self) -> Optional[List[Optional['ApiListKernelFilesItem']]]:
pass
@files.setter
def files(self) -> Optional[List[Optional['ApiListKernelFilesItem']]]:
pass
@property
def next_page_token(self) -> str:
pass
@next_page_token.setter
def next_page_token(self) -> str:
pass
@property
def nextPageToken(self):
pass
| 12 | 1 | 4 | 0 | 4 | 0 | 2 | 0.16 | 1 | 4 | 1 | 0 | 6 | 2 | 6 | 23 | 43 | 6 | 32 | 14 | 20 | 5 | 27 | 9 | 20 | 4 | 2 | 1 | 11 |
140,919 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiListKernelSessionOutputRequest
|
class ApiListKernelSessionOutputRequest(KaggleObject):
r"""
Attributes:
user_name (str)
kernel_slug (str)
page_size (int)
page_token (str)
"""
def __init__(self):
self._user_name = ""
self._kernel_slug = ""
self._page_size = None
self._page_token = None
self._freeze()
@property
def user_name(self) -> str:
return self._user_name
@user_name.setter
def user_name(self, user_name: str):
if user_name is None:
del self.user_name
return
if not isinstance(user_name, str):
raise TypeError('user_name must be of type str')
self._user_name = user_name
@property
def kernel_slug(self) -> str:
return self._kernel_slug
@kernel_slug.setter
def kernel_slug(self, kernel_slug: str):
if kernel_slug is None:
del self.kernel_slug
return
if not isinstance(kernel_slug, str):
raise TypeError('kernel_slug must be of type str')
self._kernel_slug = kernel_slug
@property
def page_size(self) -> int:
return self._page_size or 0
@page_size.setter
def page_size(self, page_size: int):
if page_size is None:
del self.page_size
return
if not isinstance(page_size, int):
raise TypeError('page_size must be of type int')
self._page_size = page_size
@property
def page_token(self) -> str:
return self._page_token or ""
@page_token.setter
def page_token(self, page_token: str):
if page_token is None:
del self.page_token
return
if not isinstance(page_token, str):
raise TypeError('page_token must be of type str')
self._page_token = page_token
def endpoint(self):
path = '/api/v1/kernels/output'
return path.format_map(self.to_field_map(self))
|
class ApiListKernelSessionOutputRequest(KaggleObject):
'''
Attributes:
user_name (str)
kernel_slug (str)
page_size (int)
page_token (str)
'''
def __init__(self):
pass
@property
def user_name(self) -> str:
pass
@user_name.setter
def user_name(self) -> str:
pass
@property
def kernel_slug(self) -> str:
pass
@kernel_slug.setter
def kernel_slug(self) -> str:
pass
@property
def page_size(self) -> int:
pass
@page_size.setter
def page_size(self) -> int:
pass
@property
def page_token(self) -> str:
pass
@page_token.setter
def page_token(self) -> str:
pass
def endpoint(self):
pass
| 19 | 1 | 5 | 0 | 5 | 0 | 2 | 0.13 | 1 | 3 | 0 | 0 | 10 | 4 | 10 | 27 | 71 | 10 | 54 | 24 | 35 | 7 | 46 | 16 | 35 | 3 | 2 | 1 | 18 |
140,920 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiListKernelSessionOutputResponse
|
class ApiListKernelSessionOutputResponse(KaggleObject):
r"""
Attributes:
files (ApiKernelSessionOutputFile)
log (str)
next_page_token (str)
"""
def __init__(self):
self._files = []
self._log = None
self._next_page_token = None
self._freeze()
@property
def files(self) -> Optional[List[Optional['ApiKernelSessionOutputFile']]]:
return self._files
@files.setter
def files(self, files: Optional[List[Optional['ApiKernelSessionOutputFile']]]):
if files is None:
del self.files
return
if not isinstance(files, list):
raise TypeError('files must be of type list')
if not all([isinstance(t, ApiKernelSessionOutputFile) for t in files]):
raise TypeError('files must contain only items of type ApiKernelSessionOutputFile')
self._files = files
@property
def log(self) -> str:
return self._log or ""
@log.setter
def log(self, log: str):
if log is None:
del self.log
return
if not isinstance(log, str):
raise TypeError('log must be of type str')
self._log = log
@property
def next_page_token(self) -> str:
return self._next_page_token or ""
@next_page_token.setter
def next_page_token(self, next_page_token: str):
if next_page_token is None:
del self.next_page_token
return
if not isinstance(next_page_token, str):
raise TypeError('next_page_token must be of type str')
self._next_page_token = next_page_token
@property
def nextPageToken(self):
return self.next_page_token
|
class ApiListKernelSessionOutputResponse(KaggleObject):
'''
Attributes:
files (ApiKernelSessionOutputFile)
log (str)
next_page_token (str)
'''
def __init__(self):
pass
@property
def files(self) -> Optional[List[Optional['ApiKernelSessionOutputFile']]]:
pass
@files.setter
def files(self) -> Optional[List[Optional['ApiKernelSessionOutputFile']]]:
pass
@property
def log(self) -> str:
pass
@log.setter
def log(self) -> str:
pass
@property
def next_page_token(self) -> str:
pass
@next_page_token.setter
def next_page_token(self) -> str:
pass
@property
def nextPageToken(self):
pass
| 16 | 1 | 5 | 0 | 5 | 0 | 2 | 0.14 | 1 | 4 | 1 | 0 | 8 | 3 | 8 | 25 | 58 | 8 | 44 | 19 | 28 | 6 | 37 | 12 | 28 | 4 | 2 | 1 | 15 |
140,921 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiListKernelsRequest
|
class ApiListKernelsRequest(KaggleObject):
r"""
Attributes:
competition (str)
Display kernels using the specified competition.
dataset (str)
Display kernels using the specified dataset.
parent_kernel (str)
Display kernels that have forked the specified kernel.
group (KernelsListViewType)
Display your kernels, collaborated, bookmarked or upvoted kernels.
kernel_type (str)
Display kernels of a specific type.
language (str)
Display kernels in a specific language. One of 'all', 'python', 'r',
'sqlite' and 'julia'.
output_type (str)
Display kernels with a specific output type. One of 'all', 'visualization'
and 'notebook'.
search (str)
Display kernels matching the specified search terms.
sort_by (KernelsListSortType)
Sort the results (default is 'hotness'). 'relevance' only works if there is
a search query.
user (str)
Display kernels by a particular user or group.
page (int)
Page number (default is 1).
page_size (int)
Page size, i.e., maximum number of results to return.
"""
def __init__(self):
self._competition = None
self._dataset = None
self._parent_kernel = None
self._group = KernelsListViewType.KERNELS_LIST_VIEW_TYPE_UNSPECIFIED
self._kernel_type = None
self._language = None
self._output_type = None
self._search = None
self._sort_by = KernelsListSortType.HOTNESS
self._user = None
self._page = None
self._page_size = None
self._freeze()
@property
def competition(self) -> str:
"""Display kernels using the specified competition."""
return self._competition or ""
@competition.setter
def competition(self, competition: str):
if competition is None:
del self.competition
return
if not isinstance(competition, str):
raise TypeError('competition must be of type str')
self._competition = competition
@property
def dataset(self) -> str:
"""Display kernels using the specified dataset."""
return self._dataset or ""
@dataset.setter
def dataset(self, dataset: str):
if dataset is None:
del self.dataset
return
if not isinstance(dataset, str):
raise TypeError('dataset must be of type str')
self._dataset = dataset
@property
def parent_kernel(self) -> str:
"""Display kernels that have forked the specified kernel."""
return self._parent_kernel or ""
@parent_kernel.setter
def parent_kernel(self, parent_kernel: str):
if parent_kernel is None:
del self.parent_kernel
return
if not isinstance(parent_kernel, str):
raise TypeError('parent_kernel must be of type str')
self._parent_kernel = parent_kernel
@property
def group(self) -> 'KernelsListViewType':
"""Display your kernels, collaborated, bookmarked or upvoted kernels."""
return self._group
@group.setter
def group(self, group: 'KernelsListViewType'):
if group is None:
del self.group
return
if not isinstance(group, KernelsListViewType):
raise TypeError('group must be of type KernelsListViewType')
self._group = group
@property
def kernel_type(self) -> str:
"""Display kernels of a specific type."""
return self._kernel_type or ""
@kernel_type.setter
def kernel_type(self, kernel_type: str):
if kernel_type is None:
del self.kernel_type
return
if not isinstance(kernel_type, str):
raise TypeError('kernel_type must be of type str')
self._kernel_type = kernel_type
@property
def language(self) -> str:
r"""
Display kernels in a specific language. One of 'all', 'python', 'r',
'sqlite' and 'julia'.
"""
return self._language or ""
@language.setter
def language(self, language: str):
if language is None:
del self.language
return
if not isinstance(language, str):
raise TypeError('language must be of type str')
self._language = language
@property
def output_type(self) -> str:
r"""
Display kernels with a specific output type. One of 'all', 'visualization'
and 'notebook'.
"""
return self._output_type or ""
@output_type.setter
def output_type(self, output_type: str):
if output_type is None:
del self.output_type
return
if not isinstance(output_type, str):
raise TypeError('output_type must be of type str')
self._output_type = output_type
@property
def search(self) -> str:
"""Display kernels matching the specified search terms."""
return self._search or ""
@search.setter
def search(self, search: str):
if search is None:
del self.search
return
if not isinstance(search, str):
raise TypeError('search must be of type str')
self._search = search
@property
def sort_by(self) -> 'KernelsListSortType':
r"""
Sort the results (default is 'hotness'). 'relevance' only works if there is
a search query.
"""
return self._sort_by
@sort_by.setter
def sort_by(self, sort_by: 'KernelsListSortType'):
if sort_by is None:
del self.sort_by
return
if not isinstance(sort_by, KernelsListSortType):
raise TypeError('sort_by must be of type KernelsListSortType')
self._sort_by = sort_by
@property
def user(self) -> str:
"""Display kernels by a particular user or group."""
return self._user or ""
@user.setter
def user(self, user: str):
if user is None:
del self.user
return
if not isinstance(user, str):
raise TypeError('user must be of type str')
self._user = user
@property
def page(self) -> int:
"""Page number (default is 1)."""
return self._page or 0
@page.setter
def page(self, page: int):
if page is None:
del self.page
return
if not isinstance(page, int):
raise TypeError('page must be of type int')
self._page = page
@property
def page_size(self) -> int:
"""Page size, i.e., maximum number of results to return."""
return self._page_size or 0
@page_size.setter
def page_size(self, page_size: int):
if page_size is None:
del self.page_size
return
if not isinstance(page_size, int):
raise TypeError('page_size must be of type int')
self._page_size = page_size
def endpoint(self):
path = '/api/v1/kernels/list'
return path.format_map(self.to_field_map(self))
|
class ApiListKernelsRequest(KaggleObject):
'''
Attributes:
competition (str)
Display kernels using the specified competition.
dataset (str)
Display kernels using the specified dataset.
parent_kernel (str)
Display kernels that have forked the specified kernel.
group (KernelsListViewType)
Display your kernels, collaborated, bookmarked or upvoted kernels.
kernel_type (str)
Display kernels of a specific type.
language (str)
Display kernels in a specific language. One of 'all', 'python', 'r',
'sqlite' and 'julia'.
output_type (str)
Display kernels with a specific output type. One of 'all', 'visualization'
and 'notebook'.
search (str)
Display kernels matching the specified search terms.
sort_by (KernelsListSortType)
Sort the results (default is 'hotness'). 'relevance' only works if there is
a search query.
user (str)
Display kernels by a particular user or group.
page (int)
Page number (default is 1).
page_size (int)
Page size, i.e., maximum number of results to return.
'''
def __init__(self):
pass
@property
def competition(self) -> str:
'''Display kernels using the specified competition.'''
pass
@competition.setter
def competition(self) -> str:
pass
@property
def dataset(self) -> str:
'''Display kernels using the specified dataset.'''
pass
@dataset.setter
def dataset(self) -> str:
pass
@property
def parent_kernel(self) -> str:
'''Display kernels that have forked the specified kernel.'''
pass
@parent_kernel.setter
def parent_kernel(self) -> str:
pass
@property
def group(self) -> 'KernelsListViewType':
'''Display your kernels, collaborated, bookmarked or upvoted kernels.'''
pass
@group.setter
def group(self) -> 'KernelsListViewType':
pass
@property
def kernel_type(self) -> str:
'''Display kernels of a specific type.'''
pass
@kernel_type.setter
def kernel_type(self) -> str:
pass
@property
def language(self) -> str:
'''
Display kernels in a specific language. One of 'all', 'python', 'r',
'sqlite' and 'julia'.
'''
pass
@language.setter
def language(self) -> str:
pass
@property
def output_type(self) -> str:
'''
Display kernels with a specific output type. One of 'all', 'visualization'
and 'notebook'.
'''
pass
@output_type.setter
def output_type(self) -> str:
pass
@property
def search(self) -> str:
'''Display kernels matching the specified search terms.'''
pass
@search.setter
def search(self) -> str:
pass
@property
def sort_by(self) -> 'KernelsListSortType':
'''
Sort the results (default is 'hotness'). 'relevance' only works if there is
a search query.
'''
pass
@sort_by.setter
def sort_by(self) -> 'KernelsListSortType':
pass
@property
def user(self) -> str:
'''Display kernels by a particular user or group.'''
pass
@user.setter
def user(self) -> str:
pass
@property
def page(self) -> int:
'''Page number (default is 1).'''
pass
@page.setter
def page(self) -> int:
pass
@property
def page_size(self) -> int:
'''Page size, i.e., maximum number of results to return.'''
pass
@page_size.setter
def page_size(self) -> int:
pass
def endpoint(self):
pass
| 51 | 13 | 6 | 0 | 5 | 1 | 2 | 0.34 | 1 | 5 | 2 | 0 | 26 | 12 | 26 | 43 | 227 | 26 | 150 | 64 | 99 | 51 | 126 | 40 | 99 | 3 | 2 | 1 | 50 |
140,922 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiListKernelsResponse
|
class ApiListKernelsResponse(KaggleObject):
r"""
Attributes:
kernels (ApiKernelMetadata)
"""
def __init__(self):
self._kernels = []
self._freeze()
@property
def kernels(self) -> Optional[List[Optional['ApiKernelMetadata']]]:
return self._kernels
@kernels.setter
def kernels(self, kernels: Optional[List[Optional['ApiKernelMetadata']]]):
if kernels is None:
del self.kernels
return
if not isinstance(kernels, list):
raise TypeError('kernels must be of type list')
if not all([isinstance(t, ApiKernelMetadata) for t in kernels]):
raise TypeError('kernels must contain only items of type ApiKernelMetadata')
self._kernels = kernels
@classmethod
def prepare_from(cls, http_response):
return cls.from_dict({'kernels': json.loads(http_response.text)})
|
class ApiListKernelsResponse(KaggleObject):
'''
Attributes:
kernels (ApiKernelMetadata)
'''
def __init__(self):
pass
@property
def kernels(self) -> Optional[List[Optional['ApiKernelMetadata']]]:
pass
@kernels.setter
def kernels(self) -> Optional[List[Optional['ApiKernelMetadata']]]:
pass
@classmethod
def prepare_from(cls, http_response):
pass
| 8 | 1 | 4 | 0 | 4 | 0 | 2 | 0.2 | 1 | 3 | 1 | 0 | 3 | 1 | 4 | 21 | 28 | 4 | 20 | 9 | 12 | 4 | 17 | 6 | 12 | 4 | 2 | 1 | 7 |
140,923 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiSaveKernelRequest
|
class ApiSaveKernelRequest(KaggleObject):
r"""
Attributes:
id (int)
The kernel's unique ID number. One of `id` and `slug` are required. If both
are specified, `id` will be preferred.
slug (str)
The full slug of the kernel to push to, in the format
`{username}/{kernel-slug}`. The kernel slug must be the title lowercased
with dashes (`-`) replacing spaces. One of `id` and `slug` are required. If
both are specified, `id` will be preferred.
new_title (str)
The title to be set on the kernel.
text (str)
The kernel's source code.
language (str)
The language that the kernel is written in. One of 'python', 'r' and
'rmarkdown'.
kernel_type (str)
The type of kernel. Cannot be changed once the kernel has been created.
dataset_data_sources (str)
A list of dataset data sources that the kernel should use. Each dataset is
specified as
`{username}/{dataset-slug}`.
kernel_data_sources (str)
A list of kernel data sources that the kernel should use. Each dataset is
specified as
`{username}/{kernel-slug}`.
competition_data_sources (str)
A list of competition data sources that the kernel should use
category_ids (str)
A list of tag IDs to associated with the kernel.
is_private (bool)
Whether or not the kernel should be private.
enable_gpu (bool)
Whether or not the kernel should run on a GPU.
enable_tpu (bool)
Whether or not the kernel should run on a TPU.
enable_internet (bool)
Whether or not the kernel should be able to access the internet.
docker_image_pinning_type (str)
Which docker image to use for executing new versions going forward.
model_data_sources (str)
A list of model data sources that the kernel should use.
Each model is specified as (for the latest version):
`{username}/{model-slug}/{framework}/{variation-slug}`
Or versioned:
`{username}/{model-slug}/{framework}/{variation-slug}/{version-number}`
session_timeout_seconds (int)
If specified, terminate the kernel session after this many seconds of
runtime, which must be lower than the global maximum.
"""
def __init__(self):
self._id = None
self._slug = None
self._new_title = None
self._text = None
self._language = None
self._kernel_type = None
self._dataset_data_sources = []
self._kernel_data_sources = []
self._competition_data_sources = []
self._category_ids = []
self._is_private = None
self._enable_gpu = None
self._enable_tpu = None
self._enable_internet = None
self._docker_image_pinning_type = None
self._model_data_sources = []
self._session_timeout_seconds = None
self._freeze()
@property
def id(self) -> int:
r"""
The kernel's unique ID number. One of `id` and `slug` are required. If both
are specified, `id` will be preferred.
"""
return self._id or 0
@id.setter
def id(self, id: int):
if id is None:
del self.id
return
if not isinstance(id, int):
raise TypeError('id must be of type int')
self._id = id
@property
def slug(self) -> str:
r"""
The full slug of the kernel to push to, in the format
`{username}/{kernel-slug}`. The kernel slug must be the title lowercased
with dashes (`-`) replacing spaces. One of `id` and `slug` are required. If
both are specified, `id` will be preferred.
"""
return self._slug or ""
@slug.setter
def slug(self, slug: str):
if slug is None:
del self.slug
return
if not isinstance(slug, str):
raise TypeError('slug must be of type str')
self._slug = slug
@property
def new_title(self) -> str:
"""The title to be set on the kernel."""
return self._new_title or ""
@new_title.setter
def new_title(self, new_title: str):
if new_title is None:
del self.new_title
return
if not isinstance(new_title, str):
raise TypeError('new_title must be of type str')
self._new_title = new_title
@property
def text(self) -> str:
"""The kernel's source code."""
return self._text or ""
@text.setter
def text(self, text: str):
if text is None:
del self.text
return
if not isinstance(text, str):
raise TypeError('text must be of type str')
self._text = text
@property
def language(self) -> str:
r"""
The language that the kernel is written in. One of 'python', 'r' and
'rmarkdown'.
"""
return self._language or ""
@language.setter
def language(self, language: str):
if language is None:
del self.language
return
if not isinstance(language, str):
raise TypeError('language must be of type str')
self._language = language
@property
def kernel_type(self) -> str:
"""The type of kernel. Cannot be changed once the kernel has been created."""
return self._kernel_type or ""
@kernel_type.setter
def kernel_type(self, kernel_type: str):
if kernel_type is None:
del self.kernel_type
return
if not isinstance(kernel_type, str):
raise TypeError('kernel_type must be of type str')
self._kernel_type = kernel_type
@property
def dataset_data_sources(self) -> Optional[List[str]]:
r"""
A list of dataset data sources that the kernel should use. Each dataset is
specified as
`{username}/{dataset-slug}`.
"""
return self._dataset_data_sources
@dataset_data_sources.setter
def dataset_data_sources(self, dataset_data_sources: Optional[List[str]]):
if dataset_data_sources is None:
del self.dataset_data_sources
return
if not isinstance(dataset_data_sources, list):
raise TypeError('dataset_data_sources must be of type list')
if not all([isinstance(t, str) for t in dataset_data_sources]):
raise TypeError('dataset_data_sources must contain only items of type str')
self._dataset_data_sources = dataset_data_sources
@property
def kernel_data_sources(self) -> Optional[List[str]]:
r"""
A list of kernel data sources that the kernel should use. Each dataset is
specified as
`{username}/{kernel-slug}`.
"""
return self._kernel_data_sources
@kernel_data_sources.setter
def kernel_data_sources(self, kernel_data_sources: Optional[List[str]]):
if kernel_data_sources is None:
del self.kernel_data_sources
return
if not isinstance(kernel_data_sources, list):
raise TypeError('kernel_data_sources must be of type list')
if not all([isinstance(t, str) for t in kernel_data_sources]):
raise TypeError('kernel_data_sources must contain only items of type str')
self._kernel_data_sources = kernel_data_sources
@property
def competition_data_sources(self) -> Optional[List[str]]:
"""A list of competition data sources that the kernel should use"""
return self._competition_data_sources
@competition_data_sources.setter
def competition_data_sources(self, competition_data_sources: Optional[List[str]]):
if competition_data_sources is None:
del self.competition_data_sources
return
if not isinstance(competition_data_sources, list):
raise TypeError('competition_data_sources must be of type list')
if not all([isinstance(t, str) for t in competition_data_sources]):
raise TypeError('competition_data_sources must contain only items of type str')
self._competition_data_sources = competition_data_sources
@property
def category_ids(self) -> Optional[List[str]]:
"""A list of tag IDs to associated with the kernel."""
return self._category_ids
@category_ids.setter
def category_ids(self, category_ids: Optional[List[str]]):
if category_ids is None:
del self.category_ids
return
if not isinstance(category_ids, list):
raise TypeError('category_ids must be of type list')
if not all([isinstance(t, str) for t in category_ids]):
raise TypeError('category_ids must contain only items of type str')
self._category_ids = category_ids
@property
def is_private(self) -> bool:
"""Whether or not the kernel should be private."""
return self._is_private or False
@is_private.setter
def is_private(self, is_private: bool):
if is_private is None:
del self.is_private
return
if not isinstance(is_private, bool):
raise TypeError('is_private must be of type bool')
self._is_private = is_private
@property
def enable_gpu(self) -> bool:
"""Whether or not the kernel should run on a GPU."""
return self._enable_gpu or False
@enable_gpu.setter
def enable_gpu(self, enable_gpu: bool):
if enable_gpu is None:
del self.enable_gpu
return
if not isinstance(enable_gpu, bool):
raise TypeError('enable_gpu must be of type bool')
self._enable_gpu = enable_gpu
@property
def enable_tpu(self) -> bool:
"""Whether or not the kernel should run on a TPU."""
return self._enable_tpu or False
@enable_tpu.setter
def enable_tpu(self, enable_tpu: bool):
if enable_tpu is None:
del self.enable_tpu
return
if not isinstance(enable_tpu, bool):
raise TypeError('enable_tpu must be of type bool')
self._enable_tpu = enable_tpu
@property
def enable_internet(self) -> bool:
"""Whether or not the kernel should be able to access the internet."""
return self._enable_internet or False
@enable_internet.setter
def enable_internet(self, enable_internet: bool):
if enable_internet is None:
del self.enable_internet
return
if not isinstance(enable_internet, bool):
raise TypeError('enable_internet must be of type bool')
self._enable_internet = enable_internet
@property
def docker_image_pinning_type(self) -> str:
"""Which docker image to use for executing new versions going forward."""
return self._docker_image_pinning_type or ""
@docker_image_pinning_type.setter
def docker_image_pinning_type(self, docker_image_pinning_type: str):
if docker_image_pinning_type is None:
del self.docker_image_pinning_type
return
if not isinstance(docker_image_pinning_type, str):
raise TypeError('docker_image_pinning_type must be of type str')
self._docker_image_pinning_type = docker_image_pinning_type
@property
def model_data_sources(self) -> Optional[List[str]]:
r"""
A list of model data sources that the kernel should use.
Each model is specified as (for the latest version):
`{username}/{model-slug}/{framework}/{variation-slug}`
Or versioned:
`{username}/{model-slug}/{framework}/{variation-slug}/{version-number}`
"""
return self._model_data_sources
@model_data_sources.setter
def model_data_sources(self, model_data_sources: Optional[List[str]]):
if model_data_sources is None:
del self.model_data_sources
return
if not isinstance(model_data_sources, list):
raise TypeError('model_data_sources must be of type list')
if not all([isinstance(t, str) for t in model_data_sources]):
raise TypeError('model_data_sources must contain only items of type str')
self._model_data_sources = model_data_sources
@property
def session_timeout_seconds(self) -> int:
r"""
If specified, terminate the kernel session after this many seconds of
runtime, which must be lower than the global maximum.
"""
return self._session_timeout_seconds or 0
@session_timeout_seconds.setter
def session_timeout_seconds(self, session_timeout_seconds: int):
if session_timeout_seconds is None:
del self.session_timeout_seconds
return
if not isinstance(session_timeout_seconds, int):
raise TypeError('session_timeout_seconds must be of type int')
self._session_timeout_seconds = session_timeout_seconds
def endpoint(self):
path = '/api/v1/kernels/push'
return path.format_map(self.to_field_map(self))
@staticmethod
def method():
return 'POST'
@staticmethod
def body_fields():
return '*'
|
class ApiSaveKernelRequest(KaggleObject):
'''
Attributes:
id (int)
The kernel's unique ID number. One of `id` and `slug` are required. If both
are specified, `id` will be preferred.
slug (str)
The full slug of the kernel to push to, in the format
`{username}/{kernel-slug}`. The kernel slug must be the title lowercased
with dashes (`-`) replacing spaces. One of `id` and `slug` are required. If
both are specified, `id` will be preferred.
new_title (str)
The title to be set on the kernel.
text (str)
The kernel's source code.
language (str)
The language that the kernel is written in. One of 'python', 'r' and
'rmarkdown'.
kernel_type (str)
The type of kernel. Cannot be changed once the kernel has been created.
dataset_data_sources (str)
A list of dataset data sources that the kernel should use. Each dataset is
specified as
`{username}/{dataset-slug}`.
kernel_data_sources (str)
A list of kernel data sources that the kernel should use. Each dataset is
specified as
`{username}/{kernel-slug}`.
competition_data_sources (str)
A list of competition data sources that the kernel should use
category_ids (str)
A list of tag IDs to associated with the kernel.
is_private (bool)
Whether or not the kernel should be private.
enable_gpu (bool)
Whether or not the kernel should run on a GPU.
enable_tpu (bool)
Whether or not the kernel should run on a TPU.
enable_internet (bool)
Whether or not the kernel should be able to access the internet.
docker_image_pinning_type (str)
Which docker image to use for executing new versions going forward.
model_data_sources (str)
A list of model data sources that the kernel should use.
Each model is specified as (for the latest version):
`{username}/{model-slug}/{framework}/{variation-slug}`
Or versioned:
`{username}/{model-slug}/{framework}/{variation-slug}/{version-number}`
session_timeout_seconds (int)
If specified, terminate the kernel session after this many seconds of
runtime, which must be lower than the global maximum.
'''
def __init__(self):
pass
@property
def id(self) -> int:
'''
The kernel's unique ID number. One of `id` and `slug` are required. If both
are specified, `id` will be preferred.
'''
pass
@id.setter
def id(self) -> int:
pass
@property
def slug(self) -> str:
'''
The full slug of the kernel to push to, in the format
`{username}/{kernel-slug}`. The kernel slug must be the title lowercased
with dashes (`-`) replacing spaces. One of `id` and `slug` are required. If
both are specified, `id` will be preferred.
'''
pass
@slug.setter
def slug(self) -> str:
pass
@property
def new_title(self) -> str:
'''The title to be set on the kernel.'''
pass
@new_title.setter
def new_title(self) -> str:
pass
@property
def text(self) -> str:
'''The kernel's source code.'''
pass
@text.setter
def text(self) -> str:
pass
@property
def language(self) -> str:
'''
The language that the kernel is written in. One of 'python', 'r' and
'rmarkdown'.
'''
pass
@language.setter
def language(self) -> str:
pass
@property
def kernel_type(self) -> str:
'''The type of kernel. Cannot be changed once the kernel has been created.'''
pass
@kernel_type.setter
def kernel_type(self) -> str:
pass
@property
def dataset_data_sources(self) -> Optional[List[str]]:
'''
A list of dataset data sources that the kernel should use. Each dataset is
specified as
`{username}/{dataset-slug}`.
'''
pass
@dataset_data_sources.setter
def dataset_data_sources(self) -> Optional[List[str]]:
pass
@property
def kernel_data_sources(self) -> Optional[List[str]]:
'''
A list of kernel data sources that the kernel should use. Each dataset is
specified as
`{username}/{kernel-slug}`.
'''
pass
@kernel_data_sources.setter
def kernel_data_sources(self) -> Optional[List[str]]:
pass
@property
def competition_data_sources(self) -> Optional[List[str]]:
'''A list of competition data sources that the kernel should use'''
pass
@competition_data_sources.setter
def competition_data_sources(self) -> Optional[List[str]]:
pass
@property
def category_ids(self) -> Optional[List[str]]:
'''A list of tag IDs to associated with the kernel.'''
pass
@category_ids.setter
def category_ids(self) -> Optional[List[str]]:
pass
@property
def is_private(self) -> bool:
'''Whether or not the kernel should be private.'''
pass
@is_private.setter
def is_private(self) -> bool:
pass
@property
def enable_gpu(self) -> bool:
'''Whether or not the kernel should run on a GPU.'''
pass
@enable_gpu.setter
def enable_gpu(self) -> bool:
pass
@property
def enable_tpu(self) -> bool:
'''Whether or not the kernel should run on a TPU.'''
pass
@enable_tpu.setter
def enable_tpu(self) -> bool:
pass
@property
def enable_internet(self) -> bool:
'''Whether or not the kernel should be able to access the internet.'''
pass
@enable_internet.setter
def enable_internet(self) -> bool:
pass
@property
def docker_image_pinning_type(self) -> str:
'''Which docker image to use for executing new versions going forward.'''
pass
@docker_image_pinning_type.setter
def docker_image_pinning_type(self) -> str:
pass
@property
def model_data_sources(self) -> Optional[List[str]]:
'''
A list of model data sources that the kernel should use.
Each model is specified as (for the latest version):
`{username}/{model-slug}/{framework}/{variation-slug}`
Or versioned:
`{username}/{model-slug}/{framework}/{variation-slug}/{version-number}`
'''
pass
@model_data_sources.setter
def model_data_sources(self) -> Optional[List[str]]:
pass
@property
def session_timeout_seconds(self) -> int:
'''
If specified, terminate the kernel session after this many seconds of
runtime, which must be lower than the global maximum.
'''
pass
@session_timeout_seconds.setter
def session_timeout_seconds(self) -> int:
pass
def endpoint(self):
pass
@staticmethod
def method():
pass
@staticmethod
def body_fields():
pass
| 75 | 18 | 6 | 0 | 5 | 1 | 2 | 0.42 | 1 | 5 | 0 | 0 | 36 | 17 | 38 | 55 | 361 | 39 | 226 | 93 | 151 | 96 | 190 | 57 | 151 | 4 | 2 | 1 | 77 |
140,924 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_api_service.py
|
src.kagglesdk.kernels.types.kernels_api_service.ApiSaveKernelResponse
|
class ApiSaveKernelResponse(KaggleObject):
r"""
Attributes:
ref (str)
url (str)
version_number (int)
error (str)
invalid_tags (str)
invalid_dataset_sources (str)
invalid_competition_sources (str)
invalid_kernel_sources (str)
invalid_model_sources (str)
"""
def __init__(self):
self._ref = ""
self._url = ""
self._version_number = None
self._error = None
self._invalid_tags = []
self._invalid_dataset_sources = []
self._invalid_competition_sources = []
self._invalid_kernel_sources = []
self._invalid_model_sources = []
self._freeze()
@property
def ref(self) -> str:
return self._ref
@ref.setter
def ref(self, ref: str):
if ref is None:
del self.ref
return
if not isinstance(ref, str):
raise TypeError('ref must be of type str')
self._ref = ref
@property
def url(self) -> str:
return self._url
@url.setter
def url(self, url: str):
if url is None:
del self.url
return
if not isinstance(url, str):
raise TypeError('url must be of type str')
self._url = url
@property
def version_number(self) -> int:
return self._version_number or 0
@version_number.setter
def version_number(self, version_number: int):
if version_number is None:
del self.version_number
return
if not isinstance(version_number, int):
raise TypeError('version_number must be of type int')
self._version_number = version_number
@property
def error(self) -> str:
return self._error or ""
@error.setter
def error(self, error: str):
if error is None:
del self.error
return
if not isinstance(error, str):
raise TypeError('error must be of type str')
self._error = error
@property
def invalid_tags(self) -> Optional[List[str]]:
return self._invalid_tags
@invalid_tags.setter
def invalid_tags(self, invalid_tags: Optional[List[str]]):
if invalid_tags is None:
del self.invalid_tags
return
if not isinstance(invalid_tags, list):
raise TypeError('invalid_tags must be of type list')
if not all([isinstance(t, str) for t in invalid_tags]):
raise TypeError('invalid_tags must contain only items of type str')
self._invalid_tags = invalid_tags
@property
def invalid_dataset_sources(self) -> Optional[List[str]]:
return self._invalid_dataset_sources
@invalid_dataset_sources.setter
def invalid_dataset_sources(self, invalid_dataset_sources: Optional[List[str]]):
if invalid_dataset_sources is None:
del self.invalid_dataset_sources
return
if not isinstance(invalid_dataset_sources, list):
raise TypeError('invalid_dataset_sources must be of type list')
if not all([isinstance(t, str) for t in invalid_dataset_sources]):
raise TypeError('invalid_dataset_sources must contain only items of type str')
self._invalid_dataset_sources = invalid_dataset_sources
@property
def invalid_competition_sources(self) -> Optional[List[str]]:
return self._invalid_competition_sources
@invalid_competition_sources.setter
def invalid_competition_sources(self, invalid_competition_sources: Optional[List[str]]):
if invalid_competition_sources is None:
del self.invalid_competition_sources
return
if not isinstance(invalid_competition_sources, list):
raise TypeError('invalid_competition_sources must be of type list')
if not all([isinstance(t, str) for t in invalid_competition_sources]):
raise TypeError('invalid_competition_sources must contain only items of type str')
self._invalid_competition_sources = invalid_competition_sources
@property
def invalid_kernel_sources(self) -> Optional[List[str]]:
return self._invalid_kernel_sources
@invalid_kernel_sources.setter
def invalid_kernel_sources(self, invalid_kernel_sources: Optional[List[str]]):
if invalid_kernel_sources is None:
del self.invalid_kernel_sources
return
if not isinstance(invalid_kernel_sources, list):
raise TypeError('invalid_kernel_sources must be of type list')
if not all([isinstance(t, str) for t in invalid_kernel_sources]):
raise TypeError('invalid_kernel_sources must contain only items of type str')
self._invalid_kernel_sources = invalid_kernel_sources
@property
def invalid_model_sources(self) -> Optional[List[str]]:
return self._invalid_model_sources
@invalid_model_sources.setter
def invalid_model_sources(self, invalid_model_sources: Optional[List[str]]):
if invalid_model_sources is None:
del self.invalid_model_sources
return
if not isinstance(invalid_model_sources, list):
raise TypeError('invalid_model_sources must be of type list')
if not all([isinstance(t, str) for t in invalid_model_sources]):
raise TypeError('invalid_model_sources must contain only items of type str')
self._invalid_model_sources = invalid_model_sources
@property
def versionNumber(self):
return self.version_number
@property
def invalidTags(self):
return self.invalid_tags
@property
def invalidDatasetSources(self):
return self.invalid_dataset_sources
@property
def invalidCompetitionSources(self):
return self.invalid_competition_sources
@property
def invalidKernelSources(self):
return self.invalid_kernel_sources
@property
def invalidModelSources(self):
return self.invalid_model_sources
|
class ApiSaveKernelResponse(KaggleObject):
'''
Attributes:
ref (str)
url (str)
version_number (int)
error (str)
invalid_tags (str)
invalid_dataset_sources (str)
invalid_competition_sources (str)
invalid_kernel_sources (str)
invalid_model_sources (str)
'''
def __init__(self):
pass
@property
def ref(self) -> str:
pass
@ref.setter
def ref(self) -> str:
pass
@property
def url(self) -> str:
pass
@url.setter
def url(self) -> str:
pass
@property
def version_number(self) -> int:
pass
@version_number.setter
def version_number(self) -> int:
pass
@property
def error(self) -> str:
pass
@error.setter
def error(self) -> str:
pass
@property
def invalid_tags(self) -> Optional[List[str]]:
pass
@invalid_tags.setter
def invalid_tags(self) -> Optional[List[str]]:
pass
@property
def invalid_dataset_sources(self) -> Optional[List[str]]:
pass
@invalid_dataset_sources.setter
def invalid_dataset_sources(self) -> Optional[List[str]]:
pass
@property
def invalid_competition_sources(self) -> Optional[List[str]]:
pass
@invalid_competition_sources.setter
def invalid_competition_sources(self) -> Optional[List[str]]:
pass
@property
def invalid_kernel_sources(self) -> Optional[List[str]]:
pass
@invalid_kernel_sources.setter
def invalid_kernel_sources(self) -> Optional[List[str]]:
pass
@property
def invalid_model_sources(self) -> Optional[List[str]]:
pass
@invalid_model_sources.setter
def invalid_model_sources(self) -> Optional[List[str]]:
pass
@property
def versionNumber(self):
pass
@property
def invalidTags(self):
pass
@property
def invalidDatasetSources(self):
pass
@property
def invalidCompetitionSources(self):
pass
@property
def invalidKernelSources(self):
pass
@property
def invalidModelSources(self):
pass
| 50 | 1 | 5 | 0 | 5 | 0 | 2 | 0.09 | 1 | 4 | 0 | 0 | 25 | 9 | 25 | 42 | 176 | 25 | 139 | 59 | 89 | 12 | 115 | 35 | 89 | 4 | 2 | 1 | 48 |
140,925 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kaggle_object.py
|
src.kagglesdk.kaggle_object.KaggleObjectSerializer
|
class KaggleObjectSerializer(ObjectSerializer):
def __init__(self):
"""
Kaggle objects (i.e., proto-generated types that inherit from KaggleObject) have custom "to_dict" and "from_dict"
methods that serialize/deserialize them to/from dictionaries.
"""
ObjectSerializer.__init__(self,
# "v" is an instance of a KaggleObject. For example: "req = ListCompetitionsRequest()".
# So "req.to_dict()" returns a dictionary with keys as json field names. Example:
# '{"pageSize": 10, "page": 2}'
lambda cls, v, ignore_defaults: cls.to_dict(v, ignore_defaults),
# "cls" is the type of a KaggleObject. For example: ListCompetitionsRequest. All
# generated Kaggle objects have "from_dict" class method that takes a dict to create a
# new instance of the object. See "KaggleObject" class definition below.
lambda cls, v: cls.from_dict(v))
|
class KaggleObjectSerializer(ObjectSerializer):
def __init__(self):
'''
Kaggle objects (i.e., proto-generated types that inherit from KaggleObject) have custom "to_dict" and "from_dict"
methods that serialize/deserialize them to/from dictionaries.
'''
pass
| 2 | 1 | 14 | 0 | 4 | 10 | 1 | 2 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 2 | 15 | 0 | 5 | 2 | 3 | 10 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
140,926 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kaggle_object.py
|
src.kagglesdk.kaggle_object.KaggleObject
|
class KaggleObject(object):
def endpoint(self):
raise 'Error: endpoint must be defined by the request object'
@staticmethod
def endpoint_path():
return None
@staticmethod
def body_fields():
return None
@classmethod
def prepare_from(cls, http_response):
return cls.from_json(http_response.text)
@staticmethod
def method():
return "GET"
def _freeze(self):
self._is_frozen = True
def __setattr__(self, key, value):
if hasattr(self, '_is_frozen') and not hasattr(self, key):
raise AttributeError(f'Unknown field for {self.__class__.__name__}: {key}')
object.__setattr__(self, key, value)
def to_dict(self, ignore_defaults=True):
kv_pairs = [(field.json_name, field.get_as_dict_item(self, ignore_defaults)) for field in self._fields]
return {k: v for (k, v) in kv_pairs if not ignore_defaults or v is not None}
@staticmethod
def to_field_map(self, ignore_defaults=True):
kv_pairs = [(field.field_name, field.get_as_dict_item(self, ignore_defaults)) for field in self._fields]
return {k: v for (k, v) in kv_pairs if not ignore_defaults or v is not None}
@classmethod
def from_dict(cls, json_dict):
instance = cls()
for field in cls._fields:
field.set_from_dict(instance, json_dict)
return instance
@classmethod
def from_json(cls, json_str):
return cls.from_dict(json.loads(json_str))
@staticmethod
def to_json(self, ignore_defaults=True):
return json.dumps(KaggleObject.to_dict(self, ignore_defaults))
def __str__(self):
return KaggleObject.to_json(self, ignore_defaults=False)
def __repr__(self):
return KaggleObject.to_json(self, ignore_defaults=False)
def __contains__(self, field_name):
field = self._get_field(field_name)
value = getattr(self, field.private_field_name)
if field.optional:
return value is not None
else:
return value != field.default_value
def __delattr__(self, field_name):
field = self._get_field(field_name)
setattr(self, field.private_field_name, field.default_value)
def _get_field(self, field_name):
field = next((f for f in self._fields if f.field_name == field_name), None)
if field is None:
raise ValueError(f'Protocol message {self.__class__.__name__} has no "{field_name}" field.')
return field
|
class KaggleObject(object):
def endpoint(self):
pass
@staticmethod
def endpoint_path():
pass
@staticmethod
def body_fields():
pass
@classmethod
def prepare_from(cls, http_response):
pass
@staticmethod
def method():
pass
def _freeze(self):
pass
def __setattr__(self, key, value):
pass
def to_dict(self, ignore_defaults=True):
pass
@staticmethod
def to_field_map(self, ignore_defaults=True):
pass
@classmethod
def from_dict(cls, json_dict):
pass
@classmethod
def from_json(cls, json_str):
pass
@staticmethod
def to_json(self, ignore_defaults=True):
pass
def __str__(self):
pass
def __repr__(self):
pass
def __contains__(self, field_name):
pass
def __delattr__(self, field_name):
pass
def _get_field(self, field_name):
pass
| 26 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 9 | 1 | 17 | 17 | 75 | 16 | 59 | 35 | 33 | 0 | 50 | 27 | 32 | 2 | 1 | 1 | 21 |
140,927 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kaggle_object.py
|
src.kagglesdk.kaggle_object.FieldMetadata
|
class FieldMetadata(object):
def __init__(self, json_name, field_name, private_field_name, field_type, default_value, serializer, optional=False):
self.json_name = json_name
self.field_name = field_name
self.private_field_name = private_field_name
self.field_type = field_type
self.default_value = default_value
self.serializer = serializer
self.optional = optional
def get_as_dict_item(self, instance, ignore_defaults=True):
value = getattr(instance, self.private_field_name)
if ignore_defaults and value == self.default_value:
return None
if value is None:
return None
return self.serializer.to_dict_value(self.field_type, value, ignore_defaults)
def set_from_dict(self, instance, json_dict):
if self.json_name not in json_dict:
return # Ignore unknown fields
value = json_dict[self.json_name]
if value == self.default_value:
return # Ignore default values
try:
setattr(instance, self.private_field_name, self.serializer.from_dict_value(self.field_type, value))
except Exception as e:
raise
|
class FieldMetadata(object):
def __init__(self, json_name, field_name, private_field_name, field_type, default_value, serializer, optional=False):
pass
def get_as_dict_item(self, instance, ignore_defaults=True):
pass
def set_from_dict(self, instance, json_dict):
pass
| 4 | 0 | 8 | 0 | 8 | 1 | 3 | 0.08 | 1 | 1 | 0 | 0 | 3 | 7 | 3 | 3 | 28 | 2 | 26 | 14 | 22 | 2 | 26 | 13 | 22 | 4 | 1 | 1 | 8 |
140,928 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kaggle_object.py
|
src.kagglesdk.kaggle_object.FieldMaskSerializer
|
class FieldMaskSerializer(ObjectSerializer):
def __init__(self):
"""Field masks are serialized/deserialized as a string that contains a list of paths with a comma delimiter"""
ObjectSerializer.__init__(self,
lambda cls, m, _: m.ToJsonString(),
lambda cls, v: FieldMaskSerializer._from_joined_paths(v))
@staticmethod
def _from_joined_paths(joined_paths):
mask = FieldMask()
mask.FromJsonString(joined_paths)
return mask
|
class FieldMaskSerializer(ObjectSerializer):
def __init__(self):
'''Field masks are serialized/deserialized as a string that contains a list of paths with a comma delimiter'''
pass
@staticmethod
def _from_joined_paths(joined_paths):
pass
| 4 | 1 | 5 | 0 | 4 | 1 | 1 | 0.1 | 1 | 0 | 0 | 0 | 1 | 0 | 2 | 3 | 12 | 1 | 10 | 5 | 6 | 1 | 7 | 4 | 4 | 1 | 2 | 0 | 2 |
140,929 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_enums.py
|
src.kagglesdk.datasets.types.dataset_enums.DatabundleVersionStatus
|
class DatabundleVersionStatus(enum.Enum):
NOT_YET_PERSISTED = 0
BLOBS_RECEIVED = 1
BLOBS_DECOMPRESSED = 2
BLOBS_COPIED_TO_SDS = 3
INDIVIDUAL_BLOBS_COMPRESSED = 4
READY = 5
FAILED = 6
DELETED = 7
REPROCESSING = 8
|
class DatabundleVersionStatus(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 10 | 0 | 10 | 10 | 9 | 0 | 10 | 10 | 9 | 0 | 4 | 0 | 0 |
140,930 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_enums.py
|
src.kagglesdk.datasets.types.dataset_enums.DatasetFileTypeGroup
|
class DatasetFileTypeGroup(enum.Enum):
r"""
This enum drives acceptable values from the python API, so avoid changing
enum member names if possible
"""
DATASET_FILE_TYPE_GROUP_ALL = 0
DATASET_FILE_TYPE_GROUP_CSV = 1
DATASET_FILE_TYPE_GROUP_SQLITE = 2
DATASET_FILE_TYPE_GROUP_JSON = 3
DATASET_FILE_TYPE_GROUP_BIG_QUERY = 4
|
class DatasetFileTypeGroup(enum.Enum):
'''
This enum drives acceptable values from the python API, so avoid changing
enum member names if possible
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.67 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 10 | 0 | 6 | 6 | 5 | 4 | 6 | 6 | 5 | 0 | 4 | 0 | 0 |
140,931 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_enums.py
|
src.kagglesdk.datasets.types.dataset_enums.DatasetLicenseGroup
|
class DatasetLicenseGroup(enum.Enum):
r"""
This enum drives acceptable values from the python API, so avoid changing
enum member names if possible
"""
DATASET_LICENSE_GROUP_ALL = 0
DATASET_LICENSE_GROUP_CC = 1
DATASET_LICENSE_GROUP_GPL = 2
DATASET_LICENSE_GROUP_ODB = 3
DATASET_LICENSE_GROUP_OTHER = 4
|
class DatasetLicenseGroup(enum.Enum):
'''
This enum drives acceptable values from the python API, so avoid changing
enum member names if possible
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.67 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 10 | 0 | 6 | 6 | 5 | 4 | 6 | 6 | 5 | 0 | 4 | 0 | 0 |
140,932 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_enums.py
|
src.kagglesdk.datasets.types.dataset_enums.DatasetSelectionGroup
|
class DatasetSelectionGroup(enum.Enum):
DATASET_SELECTION_GROUP_PUBLIC = 0
DATASET_SELECTION_GROUP_MY = 1
DATASET_SELECTION_GROUP_USER = 2
DATASET_SELECTION_GROUP_USER_SHARED_WITH_ME = 3
DATASET_SELECTION_GROUP_UPVOTED = 4
DATASET_SELECTION_GROUP_MY_PRIVATE = 5
DATASET_SELECTION_GROUP_MY_PUBLIC = 10
DATASET_SELECTION_GROUP_ORGANIZATION = 6
DATASET_SELECTION_GROUP_BOOKMARKED = 11
DATASET_SELECTION_GROUP_COLLABORATION = 12
DATASET_SELECTION_GROUP_SHARED_WITH_USER = 13
DATASET_SELECTION_GROUP_FEATURED = 7
"""Old"""
DATASET_SELECTION_GROUP_ALL = 8
DATASET_SELECTION_GROUP_UNFEATURED = 9
|
class DatasetSelectionGroup(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.07 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 16 | 0 | 15 | 15 | 14 | 1 | 15 | 15 | 14 | 0 | 4 | 0 | 0 |
140,933 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_enums.py
|
src.kagglesdk.datasets.types.dataset_enums.DatasetSizeGroup
|
class DatasetSizeGroup(enum.Enum):
r"""
This enum drives acceptable values from the python API, so avoid changing
enum member names if possible
"""
DATASET_SIZE_GROUP_ALL = 0
DATASET_SIZE_GROUP_SMALL = 1
DATASET_SIZE_GROUP_MEDIUM = 2
DATASET_SIZE_GROUP_LARGE = 3
|
class DatasetSizeGroup(enum.Enum):
'''
This enum drives acceptable values from the python API, so avoid changing
enum member names if possible
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.8 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 9 | 0 | 5 | 5 | 4 | 4 | 5 | 5 | 4 | 0 | 4 | 0 | 0 |
140,934 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_enums.py
|
src.kagglesdk.datasets.types.dataset_enums.DatasetSortBy
|
class DatasetSortBy(enum.Enum):
r"""
This enum drives acceptable values from the python API, so avoid changing
enum member names if possible
"""
DATASET_SORT_BY_HOTTEST = 0
DATASET_SORT_BY_VOTES = 1
DATASET_SORT_BY_UPDATED = 2
DATASET_SORT_BY_ACTIVE = 3
"""Deprecated"""
DATASET_SORT_BY_PUBLISHED = 4
DATASET_SORT_BY_RELEVANCE = 5
"""Old world"""
DATASET_SORT_BY_LAST_VIEWED = 6
DATASET_SORT_BY_USABILITY = 7
|
class DatasetSortBy(enum.Enum):
'''
This enum drives acceptable values from the python API, so avoid changing
enum member names if possible
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.67 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 15 | 0 | 9 | 9 | 8 | 6 | 9 | 9 | 8 | 0 | 4 | 0 | 0 |
140,935 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_enums.py
|
src.kagglesdk.datasets.types.dataset_enums.DatasetViewedGroup
|
class DatasetViewedGroup(enum.Enum):
DATASET_VIEWED_GROUP_UNSPECIFIED = 0
DATASET_VIEWED_GROUP_VIEWED = 1
|
class DatasetViewedGroup(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 4 | 0 | 0 |
140,936 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_types.py
|
src.kagglesdk.datasets.types.dataset_types.DatasetCollaborator
|
class DatasetCollaborator(KaggleObject):
r"""
Attributes:
username (str)
group_slug (str)
role (CollaboratorType)
"""
def __init__(self):
self._username = None
self._group_slug = None
self._role = CollaboratorType.COLLABORATOR_TYPE_UNSPECIFIED
self._freeze()
@property
def username(self) -> str:
return self._username or ""
@username.setter
def username(self, username: str):
if username is None:
del self.username
return
if not isinstance(username, str):
raise TypeError('username must be of type str')
del self.group_slug
self._username = username
@property
def group_slug(self) -> str:
return self._group_slug or ""
@group_slug.setter
def group_slug(self, group_slug: str):
if group_slug is None:
del self.group_slug
return
if not isinstance(group_slug, str):
raise TypeError('group_slug must be of type str')
del self.username
self._group_slug = group_slug
@property
def role(self) -> 'CollaboratorType':
return self._role
@role.setter
def role(self, role: 'CollaboratorType'):
if role is None:
del self.role
return
if not isinstance(role, CollaboratorType):
raise TypeError('role must be of type CollaboratorType')
self._role = role
|
class DatasetCollaborator(KaggleObject):
'''
Attributes:
username (str)
group_slug (str)
role (CollaboratorType)
'''
def __init__(self):
pass
@property
def username(self) -> str:
pass
@username.setter
def username(self) -> str:
pass
@property
def group_slug(self) -> str:
pass
@group_slug.setter
def group_slug(self) -> str:
pass
@property
def role(self) -> 'CollaboratorType':
pass
@role.setter
def role(self) -> 'CollaboratorType':
pass
| 14 | 1 | 5 | 0 | 5 | 0 | 2 | 0.15 | 1 | 3 | 1 | 0 | 7 | 3 | 7 | 24 | 54 | 7 | 41 | 17 | 27 | 6 | 35 | 11 | 27 | 3 | 2 | 1 | 13 |
140,937 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_types.py
|
src.kagglesdk.datasets.types.dataset_types.DatasetInfo
|
class DatasetInfo(KaggleObject):
r"""
Attributes:
dataset_id (int)
dataset_slug (str)
owner_user (str)
usability_rating (float)
total_views (int)
total_votes (int)
total_downloads (int)
title (str)
Copy/paste from DatasetSettings below. Can't use composition because
that'd be a backwards-incompatible change for the Python Api.
subtitle (str)
description (str)
is_private (bool)
keywords (str)
licenses (SettingsLicense)
collaborators (DatasetCollaborator)
data (DatasetSettingsFile)
"""
def __init__(self):
self._dataset_id = 0
self._dataset_slug = None
self._owner_user = None
self._usability_rating = None
self._total_views = 0
self._total_votes = 0
self._total_downloads = 0
self._title = None
self._subtitle = None
self._description = None
self._is_private = False
self._keywords = []
self._licenses = []
self._collaborators = []
self._data = []
self._freeze()
@property
def dataset_id(self) -> int:
return self._dataset_id
@dataset_id.setter
def dataset_id(self, dataset_id: int):
if dataset_id is None:
del self.dataset_id
return
if not isinstance(dataset_id, int):
raise TypeError('dataset_id must be of type int')
self._dataset_id = dataset_id
@property
def dataset_slug(self) -> str:
return self._dataset_slug or ""
@dataset_slug.setter
def dataset_slug(self, dataset_slug: str):
if dataset_slug is None:
del self.dataset_slug
return
if not isinstance(dataset_slug, str):
raise TypeError('dataset_slug must be of type str')
self._dataset_slug = dataset_slug
@property
def owner_user(self) -> str:
return self._owner_user or ""
@owner_user.setter
def owner_user(self, owner_user: str):
if owner_user is None:
del self.owner_user
return
if not isinstance(owner_user, str):
raise TypeError('owner_user must be of type str')
self._owner_user = owner_user
@property
def usability_rating(self) -> float:
return self._usability_rating or 0.0
@usability_rating.setter
def usability_rating(self, usability_rating: float):
if usability_rating is None:
del self.usability_rating
return
if not isinstance(usability_rating, float):
raise TypeError('usability_rating must be of type float')
self._usability_rating = usability_rating
@property
def total_views(self) -> int:
return self._total_views
@total_views.setter
def total_views(self, total_views: int):
if total_views is None:
del self.total_views
return
if not isinstance(total_views, int):
raise TypeError('total_views must be of type int')
self._total_views = total_views
@property
def total_votes(self) -> int:
return self._total_votes
@total_votes.setter
def total_votes(self, total_votes: int):
if total_votes is None:
del self.total_votes
return
if not isinstance(total_votes, int):
raise TypeError('total_votes must be of type int')
self._total_votes = total_votes
@property
def total_downloads(self) -> int:
return self._total_downloads
@total_downloads.setter
def total_downloads(self, total_downloads: int):
if total_downloads is None:
del self.total_downloads
return
if not isinstance(total_downloads, int):
raise TypeError('total_downloads must be of type int')
self._total_downloads = total_downloads
@property
def title(self) -> str:
r"""
Copy/paste from DatasetSettings below. Can't use composition because
that'd be a backwards-incompatible change for the Python Api.
"""
return self._title or ""
@title.setter
def title(self, title: str):
if title is None:
del self.title
return
if not isinstance(title, str):
raise TypeError('title must be of type str')
self._title = title
@property
def subtitle(self) -> str:
return self._subtitle or ""
@subtitle.setter
def subtitle(self, subtitle: str):
if subtitle is None:
del self.subtitle
return
if not isinstance(subtitle, str):
raise TypeError('subtitle must be of type str')
self._subtitle = subtitle
@property
def description(self) -> str:
return self._description or ""
@description.setter
def description(self, description: str):
if description is None:
del self.description
return
if not isinstance(description, str):
raise TypeError('description must be of type str')
self._description = description
@property
def is_private(self) -> bool:
return self._is_private
@is_private.setter
def is_private(self, is_private: bool):
if is_private is None:
del self.is_private
return
if not isinstance(is_private, bool):
raise TypeError('is_private must be of type bool')
self._is_private = is_private
@property
def keywords(self) -> Optional[List[str]]:
return self._keywords
@keywords.setter
def keywords(self, keywords: Optional[List[str]]):
if keywords is None:
del self.keywords
return
if not isinstance(keywords, list):
raise TypeError('keywords must be of type list')
if not all([isinstance(t, str) for t in keywords]):
raise TypeError('keywords must contain only items of type str')
self._keywords = keywords
@property
def licenses(self) -> Optional[List[Optional['SettingsLicense']]]:
return self._licenses
@licenses.setter
def licenses(self, licenses: Optional[List[Optional['SettingsLicense']]]):
if licenses is None:
del self.licenses
return
if not isinstance(licenses, list):
raise TypeError('licenses must be of type list')
if not all([isinstance(t, SettingsLicense) for t in licenses]):
raise TypeError('licenses must contain only items of type SettingsLicense')
self._licenses = licenses
@property
def collaborators(self) -> Optional[List[Optional['DatasetCollaborator']]]:
return self._collaborators
@collaborators.setter
def collaborators(self, collaborators: Optional[List[Optional['DatasetCollaborator']]]):
if collaborators is None:
del self.collaborators
return
if not isinstance(collaborators, list):
raise TypeError('collaborators must be of type list')
if not all([isinstance(t, DatasetCollaborator) for t in collaborators]):
raise TypeError('collaborators must contain only items of type DatasetCollaborator')
self._collaborators = collaborators
@property
def data(self) -> Optional[List[Optional['DatasetSettingsFile']]]:
return self._data
@data.setter
def data(self, data: Optional[List[Optional['DatasetSettingsFile']]]):
if data is None:
del self.data
return
if not isinstance(data, list):
raise TypeError('data must be of type list')
if not all([isinstance(t, DatasetSettingsFile) for t in data]):
raise TypeError('data must contain only items of type DatasetSettingsFile')
self._data = data
|
class DatasetInfo(KaggleObject):
'''
Attributes:
dataset_id (int)
dataset_slug (str)
owner_user (str)
usability_rating (float)
total_views (int)
total_votes (int)
total_downloads (int)
title (str)
Copy/paste from DatasetSettings below. Can't use composition because
that'd be a backwards-incompatible change for the Python Api.
subtitle (str)
description (str)
is_private (bool)
keywords (str)
licenses (SettingsLicense)
collaborators (DatasetCollaborator)
data (DatasetSettingsFile)
'''
def __init__(self):
pass
@property
def dataset_id(self) -> int:
pass
@dataset_id.setter
def dataset_id(self) -> int:
pass
@property
def dataset_slug(self) -> str:
pass
@dataset_slug.setter
def dataset_slug(self) -> str:
pass
@property
def owner_user(self) -> str:
pass
@owner_user.setter
def owner_user(self) -> str:
pass
@property
def usability_rating(self) -> float:
pass
@usability_rating.setter
def usability_rating(self) -> float:
pass
@property
def total_views(self) -> int:
pass
@total_views.setter
def total_views(self) -> int:
pass
@property
def total_votes(self) -> int:
pass
@total_votes.setter
def total_votes(self) -> int:
pass
@property
def total_downloads(self) -> int:
pass
@total_downloads.setter
def total_downloads(self) -> int:
pass
@property
def title(self) -> str:
'''
Copy/paste from DatasetSettings below. Can't use composition because
that'd be a backwards-incompatible change for the Python Api.
'''
pass
@title.setter
def title(self) -> str:
pass
@property
def subtitle(self) -> str:
pass
@subtitle.setter
def subtitle(self) -> str:
pass
@property
def description(self) -> str:
pass
@description.setter
def description(self) -> str:
pass
@property
def is_private(self) -> bool:
pass
@is_private.setter
def is_private(self) -> bool:
pass
@property
def keywords(self) -> Optional[List[str]]:
pass
@keywords.setter
def keywords(self) -> Optional[List[str]]:
pass
@property
def licenses(self) -> Optional[List[Optional['SettingsLicense']]]:
pass
@licenses.setter
def licenses(self) -> Optional[List[Optional['SettingsLicense']]]:
pass
@property
def collaborators(self) -> Optional[List[Optional['DatasetCollaborator']]]:
pass
@collaborators.setter
def collaborators(self) -> Optional[List[Optional['DatasetCollaborator']]]:
pass
@property
def dataset_id(self) -> int:
pass
@data.setter
def dataset_id(self) -> int:
pass
| 62 | 2 | 5 | 0 | 5 | 0 | 2 | 0.13 | 1 | 9 | 3 | 0 | 31 | 15 | 31 | 48 | 246 | 31 | 191 | 77 | 129 | 24 | 161 | 47 | 129 | 4 | 2 | 1 | 65 |
140,938 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_types.py
|
src.kagglesdk.datasets.types.dataset_types.DatasetSettings
|
class DatasetSettings(KaggleObject):
r"""
Attributes:
title (str)
subtitle (str)
description (str)
is_private (bool)
keywords (str)
licenses (SettingsLicense)
collaborators (DatasetCollaborator)
data (DatasetSettingsFile)
"""
def __init__(self):
self._title = None
self._subtitle = None
self._description = None
self._is_private = False
self._keywords = []
self._licenses = []
self._collaborators = []
self._data = []
self._freeze()
@property
def title(self) -> str:
return self._title or ""
@title.setter
def title(self, title: str):
if title is None:
del self.title
return
if not isinstance(title, str):
raise TypeError('title must be of type str')
self._title = title
@property
def subtitle(self) -> str:
return self._subtitle or ""
@subtitle.setter
def subtitle(self, subtitle: str):
if subtitle is None:
del self.subtitle
return
if not isinstance(subtitle, str):
raise TypeError('subtitle must be of type str')
self._subtitle = subtitle
@property
def description(self) -> str:
return self._description or ""
@description.setter
def description(self, description: str):
if description is None:
del self.description
return
if not isinstance(description, str):
raise TypeError('description must be of type str')
self._description = description
@property
def is_private(self) -> bool:
return self._is_private
@is_private.setter
def is_private(self, is_private: bool):
if is_private is None:
del self.is_private
return
if not isinstance(is_private, bool):
raise TypeError('is_private must be of type bool')
self._is_private = is_private
@property
def keywords(self) -> Optional[List[str]]:
return self._keywords
@keywords.setter
def keywords(self, keywords: Optional[List[str]]):
if keywords is None:
del self.keywords
return
if not isinstance(keywords, list):
raise TypeError('keywords must be of type list')
if not all([isinstance(t, str) for t in keywords]):
raise TypeError('keywords must contain only items of type str')
self._keywords = keywords
@property
def licenses(self) -> Optional[List[Optional['SettingsLicense']]]:
return self._licenses
@licenses.setter
def licenses(self, licenses: Optional[List[Optional['SettingsLicense']]]):
if licenses is None:
del self.licenses
return
if not isinstance(licenses, list):
raise TypeError('licenses must be of type list')
if not all([isinstance(t, SettingsLicense) for t in licenses]):
raise TypeError('licenses must contain only items of type SettingsLicense')
self._licenses = licenses
@property
def collaborators(self) -> Optional[List[Optional['DatasetCollaborator']]]:
return self._collaborators
@collaborators.setter
def collaborators(self, collaborators: Optional[List[Optional['DatasetCollaborator']]]):
if collaborators is None:
del self.collaborators
return
if not isinstance(collaborators, list):
raise TypeError('collaborators must be of type list')
if not all([isinstance(t, DatasetCollaborator) for t in collaborators]):
raise TypeError('collaborators must contain only items of type DatasetCollaborator')
self._collaborators = collaborators
@property
def data(self) -> Optional[List[Optional['DatasetSettingsFile']]]:
return self._data
@data.setter
def data(self, data: Optional[List[Optional['DatasetSettingsFile']]]):
if data is None:
del self.data
return
if not isinstance(data, list):
raise TypeError('data must be of type list')
if not all([isinstance(t, DatasetSettingsFile) for t in data]):
raise TypeError('data must contain only items of type DatasetSettingsFile')
self._data = data
|
class DatasetSettings(KaggleObject):
'''
Attributes:
title (str)
subtitle (str)
description (str)
is_private (bool)
keywords (str)
licenses (SettingsLicense)
collaborators (DatasetCollaborator)
data (DatasetSettingsFile)
'''
def __init__(self):
pass
@property
def title(self) -> str:
pass
@title.setter
def title(self) -> str:
pass
@property
def subtitle(self) -> str:
pass
@subtitle.setter
def subtitle(self) -> str:
pass
@property
def description(self) -> str:
pass
@description.setter
def description(self) -> str:
pass
@property
def is_private(self) -> bool:
pass
@is_private.setter
def is_private(self) -> bool:
pass
@property
def keywords(self) -> Optional[List[str]]:
pass
@keywords.setter
def keywords(self) -> Optional[List[str]]:
pass
@property
def licenses(self) -> Optional[List[Optional['SettingsLicense']]]:
pass
@licenses.setter
def licenses(self) -> Optional[List[Optional['SettingsLicense']]]:
pass
@property
def collaborators(self) -> Optional[List[Optional['DatasetCollaborator']]]:
pass
@collaborators.setter
def collaborators(self) -> Optional[List[Optional['DatasetCollaborator']]]:
pass
@property
def data(self) -> Optional[List[Optional['DatasetSettingsFile']]]:
pass
@data.setter
def data(self) -> Optional[List[Optional['DatasetSettingsFile']]]:
pass
| 34 | 1 | 5 | 0 | 5 | 0 | 2 | 0.1 | 1 | 7 | 3 | 0 | 17 | 8 | 17 | 34 | 135 | 17 | 107 | 42 | 73 | 11 | 91 | 26 | 73 | 4 | 2 | 1 | 37 |
140,939 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_types.py
|
src.kagglesdk.datasets.types.dataset_types.DatasetSettingsFile
|
class DatasetSettingsFile(KaggleObject):
r"""
Attributes:
name (str)
description (str)
total_bytes (int)
columns (DatasetSettingsFileColumn)
"""
def __init__(self):
self._name = ""
self._description = None
self._total_bytes = 0
self._columns = []
self._freeze()
@property
def name(self) -> str:
return self._name
@name.setter
def name(self, name: str):
if name is None:
del self.name
return
if not isinstance(name, str):
raise TypeError('name must be of type str')
self._name = name
@property
def description(self) -> str:
return self._description or ""
@description.setter
def description(self, description: str):
if description is None:
del self.description
return
if not isinstance(description, str):
raise TypeError('description must be of type str')
self._description = description
@property
def total_bytes(self) -> int:
return self._total_bytes
@total_bytes.setter
def total_bytes(self, total_bytes: int):
if total_bytes is None:
del self.total_bytes
return
if not isinstance(total_bytes, int):
raise TypeError('total_bytes must be of type int')
self._total_bytes = total_bytes
@property
def columns(self) -> Optional[List[Optional['DatasetSettingsFileColumn']]]:
return self._columns
@columns.setter
def columns(self, columns: Optional[List[Optional['DatasetSettingsFileColumn']]]):
if columns is None:
del self.columns
return
if not isinstance(columns, list):
raise TypeError('columns must be of type list')
if not all([isinstance(t, DatasetSettingsFileColumn) for t in columns]):
raise TypeError('columns must contain only items of type DatasetSettingsFileColumn')
self._columns = columns
|
class DatasetSettingsFile(KaggleObject):
'''
Attributes:
name (str)
description (str)
total_bytes (int)
columns (DatasetSettingsFileColumn)
'''
def __init__(self):
pass
@property
def name(self) -> str:
pass
@name.setter
def name(self) -> str:
pass
@property
def description(self) -> str:
pass
@description.setter
def description(self) -> str:
pass
@property
def total_bytes(self) -> int:
pass
@total_bytes.setter
def total_bytes(self) -> int:
pass
@property
def columns(self) -> Optional[List[Optional['DatasetSettingsFileColumn']]]:
pass
@columns.setter
def columns(self) -> Optional[List[Optional['DatasetSettingsFileColumn']]]:
pass
| 18 | 1 | 5 | 0 | 5 | 0 | 2 | 0.13 | 1 | 5 | 1 | 0 | 9 | 4 | 9 | 26 | 69 | 9 | 53 | 22 | 35 | 7 | 45 | 14 | 35 | 4 | 2 | 1 | 18 |
140,940 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_types.py
|
src.kagglesdk.datasets.types.dataset_types.DatasetSettingsFileColumn
|
class DatasetSettingsFileColumn(KaggleObject):
r"""
Attributes:
name (str)
description (str)
type (str)
"""
def __init__(self):
self._name = ""
self._description = None
self._type = None
self._freeze()
@property
def name(self) -> str:
return self._name
@name.setter
def name(self, name: str):
if name is None:
del self.name
return
if not isinstance(name, str):
raise TypeError('name must be of type str')
self._name = name
@property
def description(self) -> str:
return self._description or ""
@description.setter
def description(self, description: str):
if description is None:
del self.description
return
if not isinstance(description, str):
raise TypeError('description must be of type str')
self._description = description
@property
def type(self) -> str:
return self._type or ""
@type.setter
def type(self, type: str):
if type is None:
del self.type
return
if not isinstance(type, str):
raise TypeError('type must be of type str')
self._type = type
|
class DatasetSettingsFileColumn(KaggleObject):
'''
Attributes:
name (str)
description (str)
type (str)
'''
def __init__(self):
pass
@property
def name(self) -> str:
pass
@name.setter
def name(self) -> str:
pass
@property
def description(self) -> str:
pass
@description.setter
def description(self) -> str:
pass
@property
def type(self) -> str:
pass
@type.setter
def type(self) -> str:
pass
| 14 | 1 | 5 | 0 | 5 | 0 | 2 | 0.15 | 1 | 2 | 0 | 0 | 7 | 3 | 7 | 24 | 52 | 7 | 39 | 17 | 25 | 6 | 33 | 11 | 25 | 3 | 2 | 1 | 13 |
140,941 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/kernels/types/kernels_enums.py
|
src.kagglesdk.kernels.types.kernels_enums.KernelWorkerStatus
|
class KernelWorkerStatus(enum.Enum):
QUEUED = 0
RUNNING = 1
COMPLETE = 2
ERROR = 3
CANCEL_REQUESTED = 4
CANCEL_ACKNOWLEDGED = 5
NEW_SCRIPT = 6
|
class KernelWorkerStatus(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 8 | 0 | 8 | 8 | 7 | 0 | 8 | 8 | 7 | 0 | 4 | 0 | 0 |
140,942 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/datasets/types/dataset_types.py
|
src.kagglesdk.datasets.types.dataset_types.SettingsLicense
|
class SettingsLicense(KaggleObject):
r"""
Attributes:
name (str)
"""
def __init__(self):
self._name = None
self._freeze()
@property
def name(self) -> str:
return self._name or ""
@name.setter
def name(self, name: str):
if name is None:
del self.name
return
if not isinstance(name, str):
raise TypeError('name must be of type str')
self._name = name
|
class SettingsLicense(KaggleObject):
'''
Attributes:
name (str)
'''
def __init__(self):
pass
@property
def name(self) -> str:
pass
@name.setter
def name(self) -> str:
pass
| 6 | 1 | 4 | 0 | 4 | 0 | 2 | 0.27 | 1 | 2 | 0 | 0 | 3 | 1 | 3 | 20 | 22 | 3 | 15 | 7 | 9 | 4 | 13 | 5 | 9 | 3 | 2 | 1 | 5 |
140,943 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/education/types/education_api_service.py
|
src.kagglesdk.education.types.education_api_service.ApiTrackExerciseInteractionRequest
|
class ApiTrackExerciseInteractionRequest(KaggleObject):
r"""
This is copied from TrackExerciseInteractionRequest in
education_service.proto, which will eventually be deprecated. In the
meantime, make sure to keep these in sync.
NOTE: there's one small rename from `fork_parent_script_version_id` to
`fork_parent_kernel_session_id`.
Attributes:
exception_class (str)
failure_message (str)
interaction_type (LearnExerciseInteractionType)
learn_tools_version (str)
fork_parent_kernel_session_id (int)
outcome_type (LearnExerciseOutcomeType)
question_id (str)
question_type (LearnExerciseQuestionType)
trace (str)
value_towards_completion (float)
"""
def __init__(self):
self._exception_class = ""
self._failure_message = ""
self._interaction_type = LearnExerciseInteractionType.LEARN_EXERCISE_INTERACTION_TYPE_UNSPECIFIED
self._learn_tools_version = ""
self._fork_parent_kernel_session_id = 0
self._outcome_type = LearnExerciseOutcomeType.LEARN_EXERCISE_OUTCOME_TYPE_UNSPECIFIED
self._question_id = ""
self._question_type = LearnExerciseQuestionType.LEARN_EXERCISE_QUESTION_TYPE_UNSPECIFIED
self._trace = ""
self._value_towards_completion = None
self._freeze()
@property
def exception_class(self) -> str:
return self._exception_class
@exception_class.setter
def exception_class(self, exception_class: str):
if exception_class is None:
del self.exception_class
return
if not isinstance(exception_class, str):
raise TypeError('exception_class must be of type str')
self._exception_class = exception_class
@property
def failure_message(self) -> str:
return self._failure_message
@failure_message.setter
def failure_message(self, failure_message: str):
if failure_message is None:
del self.failure_message
return
if not isinstance(failure_message, str):
raise TypeError('failure_message must be of type str')
self._failure_message = failure_message
@property
def interaction_type(self) -> 'LearnExerciseInteractionType':
return self._interaction_type
@interaction_type.setter
def interaction_type(self, interaction_type: 'LearnExerciseInteractionType'):
if interaction_type is None:
del self.interaction_type
return
if not isinstance(interaction_type, LearnExerciseInteractionType):
raise TypeError('interaction_type must be of type LearnExerciseInteractionType')
self._interaction_type = interaction_type
@property
def learn_tools_version(self) -> str:
return self._learn_tools_version
@learn_tools_version.setter
def learn_tools_version(self, learn_tools_version: str):
if learn_tools_version is None:
del self.learn_tools_version
return
if not isinstance(learn_tools_version, str):
raise TypeError('learn_tools_version must be of type str')
self._learn_tools_version = learn_tools_version
@property
def fork_parent_kernel_session_id(self) -> int:
return self._fork_parent_kernel_session_id
@fork_parent_kernel_session_id.setter
def fork_parent_kernel_session_id(self, fork_parent_kernel_session_id: int):
if fork_parent_kernel_session_id is None:
del self.fork_parent_kernel_session_id
return
if not isinstance(fork_parent_kernel_session_id, int):
raise TypeError('fork_parent_kernel_session_id must be of type int')
self._fork_parent_kernel_session_id = fork_parent_kernel_session_id
@property
def outcome_type(self) -> 'LearnExerciseOutcomeType':
return self._outcome_type
@outcome_type.setter
def outcome_type(self, outcome_type: 'LearnExerciseOutcomeType'):
if outcome_type is None:
del self.outcome_type
return
if not isinstance(outcome_type, LearnExerciseOutcomeType):
raise TypeError('outcome_type must be of type LearnExerciseOutcomeType')
self._outcome_type = outcome_type
@property
def question_id(self) -> str:
return self._question_id
@question_id.setter
def question_id(self, question_id: str):
if question_id is None:
del self.question_id
return
if not isinstance(question_id, str):
raise TypeError('question_id must be of type str')
self._question_id = question_id
@property
def question_type(self) -> 'LearnExerciseQuestionType':
return self._question_type
@question_type.setter
def question_type(self, question_type: 'LearnExerciseQuestionType'):
if question_type is None:
del self.question_type
return
if not isinstance(question_type, LearnExerciseQuestionType):
raise TypeError('question_type must be of type LearnExerciseQuestionType')
self._question_type = question_type
@property
def trace(self) -> str:
return self._trace
@trace.setter
def trace(self, trace: str):
if trace is None:
del self.trace
return
if not isinstance(trace, str):
raise TypeError('trace must be of type str')
self._trace = trace
@property
def value_towards_completion(self) -> float:
return self._value_towards_completion or 0.0
@value_towards_completion.setter
def value_towards_completion(self, value_towards_completion: float):
if value_towards_completion is None:
del self.value_towards_completion
return
if not isinstance(value_towards_completion, float):
raise TypeError('value_towards_completion must be of type float')
self._value_towards_completion = value_towards_completion
def endpoint(self):
path = '/api/v1/learn/track'
return path.format_map(self.to_field_map(self))
@staticmethod
def method():
return 'POST'
@staticmethod
def body_fields():
return '*'
|
class ApiTrackExerciseInteractionRequest(KaggleObject):
'''
This is copied from TrackExerciseInteractionRequest in
education_service.proto, which will eventually be deprecated. In the
meantime, make sure to keep these in sync.
NOTE: there's one small rename from `fork_parent_script_version_id` to
`fork_parent_kernel_session_id`.
Attributes:
exception_class (str)
failure_message (str)
interaction_type (LearnExerciseInteractionType)
learn_tools_version (str)
fork_parent_kernel_session_id (int)
outcome_type (LearnExerciseOutcomeType)
question_id (str)
question_type (LearnExerciseQuestionType)
trace (str)
value_towards_completion (float)
'''
def __init__(self):
pass
@property
def exception_class(self) -> str:
pass
@exception_class.setter
def exception_class(self) -> str:
pass
@property
def failure_message(self) -> str:
pass
@failure_message.setter
def failure_message(self) -> str:
pass
@property
def interaction_type(self) -> 'LearnExerciseInteractionType':
pass
@interaction_type.setter
def interaction_type(self) -> 'LearnExerciseInteractionType':
pass
@property
def learn_tools_version(self) -> str:
pass
@learn_tools_version.setter
def learn_tools_version(self) -> str:
pass
@property
def fork_parent_kernel_session_id(self) -> int:
pass
@fork_parent_kernel_session_id.setter
def fork_parent_kernel_session_id(self) -> int:
pass
@property
def outcome_type(self) -> 'LearnExerciseOutcomeType':
pass
@outcome_type.setter
def outcome_type(self) -> 'LearnExerciseOutcomeType':
pass
@property
def question_id(self) -> str:
pass
@question_id.setter
def question_id(self) -> str:
pass
@property
def question_type(self) -> 'LearnExerciseQuestionType':
pass
@question_type.setter
def question_type(self) -> 'LearnExerciseQuestionType':
pass
@property
def trace(self) -> str:
pass
@trace.setter
def trace(self) -> str:
pass
@property
def value_towards_completion(self) -> float:
pass
@value_towards_completion.setter
def value_towards_completion(self) -> float:
pass
def endpoint(self):
pass
@staticmethod
def method():
pass
@staticmethod
def body_fields():
pass
| 47 | 1 | 5 | 0 | 5 | 0 | 2 | 0.14 | 1 | 7 | 3 | 0 | 22 | 10 | 24 | 41 | 177 | 27 | 132 | 58 | 85 | 18 | 110 | 36 | 85 | 3 | 2 | 1 | 44 |
140,944 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/education/types/education_api_service.py
|
src.kagglesdk.education.types.education_api_service.ApiTrackExerciseInteractionResponse
|
class ApiTrackExerciseInteractionResponse(KaggleObject):
r"""
This is copied from TrackExerciseInteractionResponse in
education_service.proto, which will eventually be deprecated. In the
meantime, make sure to keep these in sync.
Attributes:
nudge (LearnNudge)
show_login_prompt (bool)
"""
def __init__(self):
self._nudge = None
self._show_login_prompt = False
self._freeze()
@property
def nudge(self) -> Optional['LearnNudge']:
return self._nudge
@nudge.setter
def nudge(self, nudge: Optional['LearnNudge']):
if nudge is None:
del self.nudge
return
if not isinstance(nudge, LearnNudge):
raise TypeError('nudge must be of type LearnNudge')
self._nudge = nudge
@property
def show_login_prompt(self) -> bool:
return self._show_login_prompt
@show_login_prompt.setter
def show_login_prompt(self, show_login_prompt: bool):
if show_login_prompt is None:
del self.show_login_prompt
return
if not isinstance(show_login_prompt, bool):
raise TypeError('show_login_prompt must be of type bool')
self._show_login_prompt = show_login_prompt
@property
def showLoginPrompt(self):
return self.show_login_prompt
|
class ApiTrackExerciseInteractionResponse(KaggleObject):
'''
This is copied from TrackExerciseInteractionResponse in
education_service.proto, which will eventually be deprecated. In the
meantime, make sure to keep these in sync.
Attributes:
nudge (LearnNudge)
show_login_prompt (bool)
'''
def __init__(self):
pass
@property
def nudge(self) -> Optional['LearnNudge']:
pass
@nudge.setter
def nudge(self) -> Optional['LearnNudge']:
pass
@property
def show_login_prompt(self) -> bool:
pass
@show_login_prompt.setter
def show_login_prompt(self) -> bool:
pass
@property
def showLoginPrompt(self):
pass
| 12 | 1 | 4 | 0 | 4 | 0 | 2 | 0.27 | 1 | 3 | 1 | 0 | 6 | 2 | 6 | 23 | 45 | 7 | 30 | 14 | 18 | 8 | 25 | 9 | 18 | 3 | 2 | 1 | 10 |
140,945 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/education/types/education_service.py
|
src.kagglesdk.education.types.education_service.LearnExerciseInteractionType
|
class LearnExerciseInteractionType(enum.Enum):
LEARN_EXERCISE_INTERACTION_TYPE_UNSPECIFIED = 0
CHECK = 1
HINT = 2
SOLUTION = 3
|
class LearnExerciseInteractionType(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 5 | 0 | 5 | 5 | 4 | 0 | 5 | 5 | 4 | 0 | 4 | 0 | 0 |
140,946 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/education/types/education_service.py
|
src.kagglesdk.education.types.education_service.LearnExerciseOutcomeType
|
class LearnExerciseOutcomeType(enum.Enum):
LEARN_EXERCISE_OUTCOME_TYPE_UNSPECIFIED = 0
PASS = 1
FAIL = 2
EXCEPTION = 3
UNATTEMPTED = 4
|
class LearnExerciseOutcomeType(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 6 | 0 | 6 | 6 | 5 | 0 | 6 | 6 | 5 | 0 | 4 | 0 | 0 |
140,947 |
Kaggle/kaggle-api
|
Kaggle_kaggle-api/src/kagglesdk/education/types/education_service.py
|
src.kagglesdk.education.types.education_service.LearnExerciseQuestionType
|
class LearnExerciseQuestionType(enum.Enum):
LEARN_EXERCISE_QUESTION_TYPE_UNSPECIFIED = 0
EQUALITY_CHECK_PROBLEM = 1
CODING_PROBLEM = 2
FUNCTION_PROBLEM = 3
THOUGHT_EXPERIMENT = 4
|
class LearnExerciseQuestionType(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 6 | 0 | 6 | 6 | 5 | 0 | 6 | 6 | 5 | 0 | 4 | 0 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.